"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/domain/delegates/threads/upsert.ts
var upsert_exports = {};
__export(upsert_exports, {
  upsertThread: () => upsertThread
});
module.exports = __toCommonJS(upsert_exports);
async function upsertThread(messages, appId, client, id) {
  console.log(`upsertThread threadId: ${id}`);
  const token = await client.auth.signIn();
  const apiKey = token.access_token;
  const url = `${client.url}/api/v2/ontologies/${client.ontologyRid}/actions/upsert-thread/apply`;
  const headers = {
    Authorization: `Bearer ${apiKey}`,
    "Content-Type": "application/json"
  };
  const body = JSON.stringify({
    parameters: {
      id,
      messages,
      appId
    },
    options: {
      returnEdits: "ALL"
    }
  });
  const apiResult = await fetch(url, {
    method: "POST",
    headers,
    body
  });
  const result = await apiResult.json();
  if (!result.edits || result.edits.edits.length === 0) {
    throw new Error("Failed to upsert thread message to the ontology.");
  }
  console.log(`upsert thread action returned: ${result?.edits?.edits?.[0]}`);
  const threadId = result.edits.edits[0].primaryKey;
  const getUrl = `${client.url}/api/v2/ontologies/${client.ontologyRid}/objects/Threads/${threadId}`;
  const machineFetchResults = await fetch(getUrl, {
    method: "GET",
    headers
  });
  const thread = await machineFetchResults.json();
  console.log(`the thread execution ontology returned: ${JSON.stringify(thread)}`);
  return thread;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  upsertThread
});
