open-agents-ai 0.185.78 → 0.185.79

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +490 -243
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -11957,8 +11957,8 @@ async function loadTranscribeCli() {
11957
11957
  const nvmBase = join19(homedir7(), ".nvm", "versions", "node");
11958
11958
  if (existsSync16(nvmBase)) {
11959
11959
  try {
11960
- const { readdirSync: readdirSync24 } = await import("node:fs");
11961
- for (const ver of readdirSync24(nvmBase)) {
11960
+ const { readdirSync: readdirSync25 } = await import("node:fs");
11961
+ for (const ver of readdirSync25(nvmBase)) {
11962
11962
  const tcPath = join19(nvmBase, ver, "lib", "node_modules", "transcribe-cli");
11963
11963
  if (existsSync16(join19(tcPath, "dist", "index.js"))) {
11964
11964
  const { createRequire: createRequire6 } = await import("node:module");
@@ -13820,11 +13820,11 @@ print("__SESSION__" + json.dumps(_session) + "__SESSION__")
13820
13820
  * what was previously computed. */
13821
13821
  async loadSessionInfo() {
13822
13822
  try {
13823
- const { readFileSync: readFileSync47, existsSync: existsSync59 } = await import("node:fs");
13823
+ const { readFileSync: readFileSync48, existsSync: existsSync60 } = await import("node:fs");
13824
13824
  const sessionPath = join22(this.cwd, ".oa", "rlm", "session.json");
13825
- if (!existsSync59(sessionPath))
13825
+ if (!existsSync60(sessionPath))
13826
13826
  return null;
13827
- return JSON.parse(readFileSync47(sessionPath, "utf8"));
13827
+ return JSON.parse(readFileSync48(sessionPath, "utf8"));
13828
13828
  } catch {
13829
13829
  return null;
13830
13830
  }
@@ -14001,10 +14001,10 @@ var init_memory_metabolism = __esm({
14001
14001
  const trajDir = join23(this.cwd, ".oa", "rlm-trajectories");
14002
14002
  let lessons = [];
14003
14003
  try {
14004
- const { readdirSync: readdirSync24, readFileSync: readFileSync47 } = await import("node:fs");
14005
- const files = readdirSync24(trajDir).filter((f) => f.endsWith(".jsonl")).sort().reverse().slice(0, 3);
14004
+ const { readdirSync: readdirSync25, readFileSync: readFileSync48 } = await import("node:fs");
14005
+ const files = readdirSync25(trajDir).filter((f) => f.endsWith(".jsonl")).sort().reverse().slice(0, 3);
14006
14006
  for (const file of files) {
14007
- const lines = readFileSync47(join23(trajDir, file), "utf8").split("\n").filter((l) => l.trim());
14007
+ const lines = readFileSync48(join23(trajDir, file), "utf8").split("\n").filter((l) => l.trim());
14008
14008
  for (const line of lines) {
14009
14009
  try {
14010
14010
  const entry = JSON.parse(line);
@@ -14388,14 +14388,14 @@ ${issues.map((i) => ` - ${i}`).join("\n")}` : " No issues found."),
14388
14388
  * Optionally filter by task type for phase-aware context (FSM paper insight).
14389
14389
  */
14390
14390
  getTopMemoriesSync(k = 5, taskType) {
14391
- const { readFileSync: readFileSync47, existsSync: existsSync59 } = __require("node:fs");
14391
+ const { readFileSync: readFileSync48, existsSync: existsSync60 } = __require("node:fs");
14392
14392
  const metaDir = join23(this.cwd, ".oa", "memory", "metabolism");
14393
14393
  const storeFile = join23(metaDir, "store.json");
14394
- if (!existsSync59(storeFile))
14394
+ if (!existsSync60(storeFile))
14395
14395
  return "";
14396
14396
  let store2 = [];
14397
14397
  try {
14398
- store2 = JSON.parse(readFileSync47(storeFile, "utf8"));
14398
+ store2 = JSON.parse(readFileSync48(storeFile, "utf8"));
14399
14399
  } catch {
14400
14400
  return "";
14401
14401
  }
@@ -14417,14 +14417,14 @@ ${issues.map((i) => ` - ${i}`).join("\n")}` : " No issues found."),
14417
14417
  /** Update memory scores based on task outcome. Called after task completion.
14418
14418
  * Memories used in successful tasks get boosted. Memories present during failures get decayed. */
14419
14419
  updateFromOutcomeSync(surfacedMemoryText, succeeded) {
14420
- const { readFileSync: readFileSync47, writeFileSync: writeFileSync31, existsSync: existsSync59, mkdirSync: mkdirSync33 } = __require("node:fs");
14420
+ const { readFileSync: readFileSync48, writeFileSync: writeFileSync31, existsSync: existsSync60, mkdirSync: mkdirSync33 } = __require("node:fs");
14421
14421
  const metaDir = join23(this.cwd, ".oa", "memory", "metabolism");
14422
14422
  const storeFile = join23(metaDir, "store.json");
14423
- if (!existsSync59(storeFile))
14423
+ if (!existsSync60(storeFile))
14424
14424
  return;
14425
14425
  let store2 = [];
14426
14426
  try {
14427
- store2 = JSON.parse(readFileSync47(storeFile, "utf8"));
14427
+ store2 = JSON.parse(readFileSync48(storeFile, "utf8"));
14428
14428
  } catch {
14429
14429
  return;
14430
14430
  }
@@ -14871,13 +14871,13 @@ Recommendation: Strategy ${scored[0].index + 1} scores highest.`;
14871
14871
  // Per EvoSkill (arXiv:2603.02766): retrieve relevant strategies from archive.
14872
14872
  /** Retrieve top-K strategies for context injection. Returns "" if none. */
14873
14873
  getRelevantStrategiesSync(k = 3, taskType) {
14874
- const { readFileSync: readFileSync47, existsSync: existsSync59 } = __require("node:fs");
14874
+ const { readFileSync: readFileSync48, existsSync: existsSync60 } = __require("node:fs");
14875
14875
  const archiveFile = join25(this.cwd, ".oa", "arche", "variants.json");
14876
- if (!existsSync59(archiveFile))
14876
+ if (!existsSync60(archiveFile))
14877
14877
  return "";
14878
14878
  let variants = [];
14879
14879
  try {
14880
- variants = JSON.parse(readFileSync47(archiveFile, "utf8"));
14880
+ variants = JSON.parse(readFileSync48(archiveFile, "utf8"));
14881
14881
  } catch {
14882
14882
  return "";
14883
14883
  }
@@ -14895,13 +14895,13 @@ Recommendation: Strategy ${scored[0].index + 1} scores highest.`;
14895
14895
  }
14896
14896
  /** Archive a strategy variant synchronously (for task completion path) */
14897
14897
  archiveVariantSync(strategy, outcome, tags = []) {
14898
- const { readFileSync: readFileSync47, writeFileSync: writeFileSync31, existsSync: existsSync59, mkdirSync: mkdirSync33 } = __require("node:fs");
14898
+ const { readFileSync: readFileSync48, writeFileSync: writeFileSync31, existsSync: existsSync60, mkdirSync: mkdirSync33 } = __require("node:fs");
14899
14899
  const dir = join25(this.cwd, ".oa", "arche");
14900
14900
  const archiveFile = join25(dir, "variants.json");
14901
14901
  let variants = [];
14902
14902
  try {
14903
- if (existsSync59(archiveFile))
14904
- variants = JSON.parse(readFileSync47(archiveFile, "utf8"));
14903
+ if (existsSync60(archiveFile))
14904
+ variants = JSON.parse(readFileSync48(archiveFile, "utf8"));
14905
14905
  } catch {
14906
14906
  }
14907
14907
  variants.push({
@@ -27423,8 +27423,8 @@ ${marker}` : marker);
27423
27423
  return;
27424
27424
  try {
27425
27425
  const { mkdirSync: mkdirSync33, writeFileSync: writeFileSync31 } = __require("node:fs");
27426
- const { join: join79 } = __require("node:path");
27427
- const sessionDir = join79(this._workingDirectory, ".oa", "session", this._sessionId);
27426
+ const { join: join80 } = __require("node:path");
27427
+ const sessionDir = join80(this._workingDirectory, ".oa", "session", this._sessionId);
27428
27428
  mkdirSync33(sessionDir, { recursive: true });
27429
27429
  const checkpoint = {
27430
27430
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -27437,7 +27437,7 @@ ${marker}` : marker);
27437
27437
  memexEntryCount: this._memexArchive.size,
27438
27438
  fileRegistrySize: this._fileRegistry.size
27439
27439
  };
27440
- writeFileSync31(join79(sessionDir, "checkpoint.json"), JSON.stringify(checkpoint, null, 2));
27440
+ writeFileSync31(join80(sessionDir, "checkpoint.json"), JSON.stringify(checkpoint, null, 2));
27441
27441
  } catch {
27442
27442
  }
27443
27443
  }
@@ -28575,17 +28575,17 @@ ${transcript}`
28575
28575
  let resizedBase64 = null;
28576
28576
  try {
28577
28577
  const { execSync: execSync36 } = await import("node:child_process");
28578
- const { writeFileSync: writeFileSync31, readFileSync: readFileSync47, unlinkSync: unlinkSync13 } = await import("node:fs");
28579
- const { join: join79 } = await import("node:path");
28578
+ const { writeFileSync: writeFileSync31, readFileSync: readFileSync48, unlinkSync: unlinkSync13 } = await import("node:fs");
28579
+ const { join: join80 } = await import("node:path");
28580
28580
  const { tmpdir: tmpdir11 } = await import("node:os");
28581
- const tmpIn = join79(tmpdir11(), `oa_img_in_${Date.now()}.png`);
28582
- const tmpOut = join79(tmpdir11(), `oa_img_out_${Date.now()}.jpg`);
28581
+ const tmpIn = join80(tmpdir11(), `oa_img_in_${Date.now()}.png`);
28582
+ const tmpOut = join80(tmpdir11(), `oa_img_out_${Date.now()}.jpg`);
28583
28583
  writeFileSync31(tmpIn, buffer);
28584
28584
  const pyBin = process.platform === "win32" ? "python" : "python3";
28585
28585
  const escapedIn = tmpIn.replace(/\\/g, "\\\\");
28586
28586
  const escapedOut = tmpOut.replace(/\\/g, "\\\\");
28587
28587
  execSync36(`${pyBin} -c "from PIL import Image; img = Image.open('${escapedIn}'); img.thumbnail((512, 512), Image.LANCZOS); img = img.convert('RGB'); img.save('${escapedOut}', 'JPEG', quality=75)"`, { timeout: 1e4, stdio: "pipe" });
28588
- const resizedBuf = readFileSync47(tmpOut);
28588
+ const resizedBuf = readFileSync48(tmpOut);
28589
28589
  resizedBase64 = `data:image/jpeg;base64,${resizedBuf.toString("base64")}`;
28590
28590
  try {
28591
28591
  unlinkSync13(tmpIn);
@@ -30716,8 +30716,8 @@ var init_listen = __esm({
30716
30716
  const nvmBase = join48(homedir11(), ".nvm", "versions", "node");
30717
30717
  if (existsSync32(nvmBase)) {
30718
30718
  try {
30719
- const { readdirSync: readdirSync24 } = await import("node:fs");
30720
- for (const ver of readdirSync24(nvmBase)) {
30719
+ const { readdirSync: readdirSync25 } = await import("node:fs");
30720
+ for (const ver of readdirSync25(nvmBase)) {
30721
30721
  const tcPath = join48(nvmBase, ver, "lib", "node_modules", "transcribe-cli");
30722
30722
  if (existsSync32(join48(tcPath, "dist", "index.js"))) {
30723
30723
  const { createRequire: createRequire6 } = await import("node:module");
@@ -39557,26 +39557,26 @@ async function fetchOpenAIModels(baseUrl, apiKey) {
39557
39557
  async function fetchPeerModels(peerId, authKey) {
39558
39558
  try {
39559
39559
  const { NexusTool: NexusTool2 } = await Promise.resolve().then(() => (init_dist2(), dist_exports));
39560
- const { existsSync: existsSync59, readFileSync: readFileSync47 } = await import("node:fs");
39561
- const { join: join79 } = await import("node:path");
39560
+ const { existsSync: existsSync60, readFileSync: readFileSync48 } = await import("node:fs");
39561
+ const { join: join80 } = await import("node:path");
39562
39562
  const cwd4 = process.cwd();
39563
39563
  const nexusTool = new NexusTool2(cwd4);
39564
39564
  const nexusDir = nexusTool.getNexusDir();
39565
39565
  let isLocalPeer = false;
39566
39566
  try {
39567
- const statusPath = join79(nexusDir, "status.json");
39568
- if (existsSync59(statusPath)) {
39569
- const status = JSON.parse(readFileSync47(statusPath, "utf8"));
39567
+ const statusPath = join80(nexusDir, "status.json");
39568
+ if (existsSync60(statusPath)) {
39569
+ const status = JSON.parse(readFileSync48(statusPath, "utf8"));
39570
39570
  if (status.peerId === peerId)
39571
39571
  isLocalPeer = true;
39572
39572
  }
39573
39573
  } catch {
39574
39574
  }
39575
39575
  if (isLocalPeer) {
39576
- const pricingPath = join79(nexusDir, "pricing.json");
39577
- if (existsSync59(pricingPath)) {
39576
+ const pricingPath = join80(nexusDir, "pricing.json");
39577
+ if (existsSync60(pricingPath)) {
39578
39578
  try {
39579
- const pricing = JSON.parse(readFileSync47(pricingPath, "utf8"));
39579
+ const pricing = JSON.parse(readFileSync48(pricingPath, "utf8"));
39580
39580
  const localModels = (pricing.models || []).map((m) => ({
39581
39581
  name: m.model || "unknown",
39582
39582
  size: m.parameterSize || "",
@@ -39590,10 +39590,10 @@ async function fetchPeerModels(peerId, authKey) {
39590
39590
  }
39591
39591
  }
39592
39592
  }
39593
- const cachePath = join79(nexusDir, "peer-models-cache.json");
39594
- if (existsSync59(cachePath)) {
39593
+ const cachePath = join80(nexusDir, "peer-models-cache.json");
39594
+ if (existsSync60(cachePath)) {
39595
39595
  try {
39596
- const cache4 = JSON.parse(readFileSync47(cachePath, "utf8"));
39596
+ const cache4 = JSON.parse(readFileSync48(cachePath, "utf8"));
39597
39597
  if (cache4.peerId === peerId && cache4.models?.length > 0) {
39598
39598
  const age = Date.now() - new Date(cache4.cachedAt).getTime();
39599
39599
  if (age < 5 * 60 * 1e3) {
@@ -39708,10 +39708,10 @@ async function fetchPeerModels(peerId, authKey) {
39708
39708
  } catch {
39709
39709
  }
39710
39710
  if (isLocalPeer) {
39711
- const pricingPath = join79(nexusDir, "pricing.json");
39712
- if (existsSync59(pricingPath)) {
39711
+ const pricingPath = join80(nexusDir, "pricing.json");
39712
+ if (existsSync60(pricingPath)) {
39713
39713
  try {
39714
- const pricing = JSON.parse(readFileSync47(pricingPath, "utf8"));
39714
+ const pricing = JSON.parse(readFileSync48(pricingPath, "utf8"));
39715
39715
  return (pricing.models || []).map((m) => ({
39716
39716
  name: m.model || "unknown",
39717
39717
  size: m.parameterSize || "",
@@ -52966,8 +52966,8 @@ async function handlePeerEndpoint(peerId, authKey, ctx, local) {
52966
52966
  if (models.length > 0) {
52967
52967
  try {
52968
52968
  const { writeFileSync: writeFileSync31, mkdirSync: mkdirSync33 } = await import("node:fs");
52969
- const { join: join79, dirname: dirname24 } = await import("node:path");
52970
- const cachePath = join79(ctx.repoRoot || process.cwd(), ".oa", "nexus", "peer-models-cache.json");
52969
+ const { join: join80, dirname: dirname24 } = await import("node:path");
52970
+ const cachePath = join80(ctx.repoRoot || process.cwd(), ".oa", "nexus", "peer-models-cache.json");
52971
52971
  mkdirSync33(dirname24(cachePath), { recursive: true });
52972
52972
  writeFileSync31(cachePath, JSON.stringify({
52973
52973
  peerId,
@@ -53168,17 +53168,17 @@ async function handleUpdate(subcommand, ctx) {
53168
53168
  try {
53169
53169
  const { createRequire: createRequire6 } = await import("node:module");
53170
53170
  const { fileURLToPath: fileURLToPath16 } = await import("node:url");
53171
- const { dirname: dirname24, join: join79 } = await import("node:path");
53172
- const { existsSync: existsSync59 } = await import("node:fs");
53171
+ const { dirname: dirname24, join: join80 } = await import("node:path");
53172
+ const { existsSync: existsSync60 } = await import("node:fs");
53173
53173
  const req = createRequire6(import.meta.url);
53174
53174
  const thisDir = dirname24(fileURLToPath16(import.meta.url));
53175
53175
  const candidates = [
53176
- join79(thisDir, "..", "package.json"),
53177
- join79(thisDir, "..", "..", "package.json"),
53178
- join79(thisDir, "..", "..", "..", "package.json")
53176
+ join80(thisDir, "..", "package.json"),
53177
+ join80(thisDir, "..", "..", "package.json"),
53178
+ join80(thisDir, "..", "..", "..", "package.json")
53179
53179
  ];
53180
53180
  for (const pkgPath of candidates) {
53181
- if (existsSync59(pkgPath)) {
53181
+ if (existsSync60(pkgPath)) {
53182
53182
  const pkg = req(pkgPath);
53183
53183
  if (pkg.name === "open-agents-ai" || pkg.name === "@open-agents/cli") {
53184
53184
  currentVersion = pkg.version ?? "0.0.0";
@@ -54151,11 +54151,11 @@ function loadMemoryDir(memDir, scope) {
54151
54151
  return lines.join("\n");
54152
54152
  }
54153
54153
  function loadSessionHistory(repoRoot) {
54154
- const sessions = loadRecentSessions(repoRoot, 5);
54155
- if (sessions.length === 0)
54154
+ const sessions2 = loadRecentSessions(repoRoot, 5);
54155
+ if (sessions2.length === 0)
54156
54156
  return "";
54157
54157
  const lines = ["Recent tasks in this project:"];
54158
- for (const s of sessions) {
54158
+ for (const s of sessions2) {
54159
54159
  if (!s.startedAt || !s.task)
54160
54160
  continue;
54161
54161
  const status = s.completed ? "completed" : "incomplete";
@@ -55490,8 +55490,8 @@ function listBannerDesigns(workDir) {
55490
55490
  if (!existsSync45(dir))
55491
55491
  return [];
55492
55492
  try {
55493
- const { readdirSync: readdirSync24 } = __require("node:fs");
55494
- return readdirSync24(dir).filter((f) => f.endsWith(".json")).map((f) => f.replace(".json", ""));
55493
+ const { readdirSync: readdirSync25 } = __require("node:fs");
55494
+ return readdirSync25(dir).filter((f) => f.endsWith(".json")).map((f) => f.replace(".json", ""));
55495
55495
  } catch {
55496
55496
  return [];
55497
55497
  }
@@ -56039,8 +56039,8 @@ function extractFromManifests(repoRoot, tags) {
56039
56039
  }
56040
56040
  function extractFromSessions(repoRoot, tags) {
56041
56041
  try {
56042
- const sessions = loadRecentSessions(repoRoot, 10);
56043
- for (const session of sessions) {
56042
+ const sessions2 = loadRecentSessions(repoRoot, 10);
56043
+ for (const session of sessions2) {
56044
56044
  if (session.task) {
56045
56045
  const words = session.task.toLowerCase().replace(/[^a-z0-9\s-]/g, " ").split(/\s+/).filter((w) => w.length > 3 && !STOP_WORDS.has(w));
56046
56046
  tags.push(...words.slice(0, 4));
@@ -65617,6 +65617,7 @@ const statusEl = document.getElementById('status');
65617
65617
  let apiKey = localStorage.getItem('oa-api-key') || '';
65618
65618
  let streaming = false;
65619
65619
  let messages = [];
65620
+ let chatSessionId = null; // stateful session for /v1/chat
65620
65621
 
65621
65622
  // Auto-resize textarea
65622
65623
  input.addEventListener('input', () => {
@@ -65722,22 +65723,25 @@ async function sendMessage() {
65722
65723
  let fullContent = '';
65723
65724
 
65724
65725
  try {
65726
+ // Use stateful /v1/chat endpoint (maintains OA identity + context)
65725
65727
  const body = {
65728
+ session_id: chatSessionId,
65726
65729
  model: modelSelect.value,
65727
- messages: [
65728
- ...(sysPrompt ? [{ role: 'system', content: sysPrompt }] : []),
65729
- ...messages,
65730
- ],
65730
+ message: text,
65731
65731
  stream: true,
65732
65732
  max_tokens: 4096,
65733
65733
  };
65734
65734
 
65735
- const response = await fetch('/v1/chat/completions', {
65735
+ const response = await fetch('/v1/chat', {
65736
65736
  method: 'POST',
65737
65737
  headers: headers(),
65738
65738
  body: JSON.stringify(body),
65739
65739
  });
65740
65740
 
65741
+ // Capture session ID from response header
65742
+ const sid = response.headers.get('x-session-id');
65743
+ if (sid) chatSessionId = sid;
65744
+
65741
65745
  const reader = response.body.getReader();
65742
65746
  const decoder = new TextDecoder();
65743
65747
  let buffer = '';
@@ -66259,16 +66263,137 @@ var init_auth_oidc = __esm({
66259
66263
  }
66260
66264
  });
66261
66265
 
66262
- // packages/cli/dist/api/usage-tracker.js
66263
- import { mkdirSync as mkdirSync27, readFileSync as readFileSync42, writeFileSync as writeFileSync25, existsSync as existsSync53 } from "node:fs";
66266
+ // packages/cli/dist/api/chat-session.js
66267
+ import { randomUUID as randomUUID4 } from "node:crypto";
66268
+ import { existsSync as existsSync53, readFileSync as readFileSync42, readdirSync as readdirSync20 } from "node:fs";
66264
66269
  import { join as join70 } from "node:path";
66270
+ function buildSystemPrompt(cwd4) {
66271
+ const parts = [];
66272
+ parts.push("You are Open Agent (OA), an AI coding assistant running locally via Ollama. You have access to the user's workspace and can discuss code, files, and projects. Be helpful, concise, and technically precise. When asked about files or code, describe what you know from the conversation context.");
66273
+ parts.push(`\\nEnvironment: ${process.platform}, Node ${process.version}, CWD: ${cwd4}`);
66274
+ const diaryPath = join70(cwd4, ".oa", "context", "session-diary.md");
66275
+ if (existsSync53(diaryPath)) {
66276
+ try {
66277
+ const diary = readFileSync42(diaryPath, "utf-8").slice(0, 1e3);
66278
+ parts.push(`\\nPrevious session history:\\n${diary}`);
66279
+ } catch {
66280
+ }
66281
+ }
66282
+ const memDir = join70(cwd4, ".oa", "memory");
66283
+ if (existsSync53(memDir)) {
66284
+ try {
66285
+ const files = readdirSync20(memDir).filter((f) => f.endsWith(".json")).slice(0, 5);
66286
+ if (files.length > 0) {
66287
+ parts.push("\\nPersistent memory topics: " + files.map((f) => f.replace(".json", "")).join(", "));
66288
+ for (const f of files.slice(0, 3)) {
66289
+ try {
66290
+ const data = JSON.parse(readFileSync42(join70(memDir, f), "utf-8"));
66291
+ const entries = Object.entries(data).slice(0, 3);
66292
+ if (entries.length > 0) {
66293
+ parts.push(`\\nMemory [${f.replace(".json", "")}]: ` + entries.map(([k, v]) => `${k}: ${String(v.value ?? v).slice(0, 100)}`).join("; "));
66294
+ }
66295
+ } catch {
66296
+ }
66297
+ }
66298
+ }
66299
+ } catch {
66300
+ }
66301
+ }
66302
+ for (const name of ["AGENTS.md", "OA.md", ".open-agents.md"]) {
66303
+ const p = join70(cwd4, name);
66304
+ if (existsSync53(p)) {
66305
+ try {
66306
+ const content = readFileSync42(p, "utf-8").slice(0, 500);
66307
+ parts.push(`\\nProject instructions (${name}):\\n${content}`);
66308
+ } catch {
66309
+ }
66310
+ }
66311
+ }
66312
+ return parts.join("");
66313
+ }
66314
+ function getSession(sessionId, model, cwd4) {
66315
+ if (sessionId && sessions.has(sessionId)) {
66316
+ const s = sessions.get(sessionId);
66317
+ s.lastActivity = Date.now();
66318
+ return s;
66319
+ }
66320
+ const id = sessionId || randomUUID4();
66321
+ const systemPrompt = buildSystemPrompt(cwd4);
66322
+ const session = {
66323
+ id,
66324
+ messages: [{ role: "system", content: systemPrompt }],
66325
+ model,
66326
+ createdAt: Date.now(),
66327
+ lastActivity: Date.now(),
66328
+ tokensIn: 0,
66329
+ tokensOut: 0
66330
+ };
66331
+ sessions.set(id, session);
66332
+ return session;
66333
+ }
66334
+ function addUserMessage(session, content) {
66335
+ session.messages.push({ role: "user", content });
66336
+ session.lastActivity = Date.now();
66337
+ return [...session.messages];
66338
+ }
66339
+ function addAssistantMessage(session, content) {
66340
+ session.messages.push({ role: "assistant", content });
66341
+ session.lastActivity = Date.now();
66342
+ }
66343
+ function trackSessionTokens(session, tokensIn, tokensOut) {
66344
+ session.tokensIn += tokensIn;
66345
+ session.tokensOut += tokensOut;
66346
+ }
66347
+ function listSessions() {
66348
+ return Array.from(sessions.values()).map((s) => ({
66349
+ id: s.id,
66350
+ model: s.model,
66351
+ messages: s.messages.length - 1,
66352
+ // exclude system prompt
66353
+ tokensIn: s.tokensIn,
66354
+ tokensOut: s.tokensOut,
66355
+ lastActivity: new Date(s.lastActivity).toISOString()
66356
+ }));
66357
+ }
66358
+ function compactSession(session, maxMessages = 40) {
66359
+ if (session.messages.length <= maxMessages)
66360
+ return;
66361
+ const system = session.messages[0];
66362
+ const recent = session.messages.slice(-20);
66363
+ const middle = session.messages.slice(1, -20);
66364
+ const summary = `[Earlier conversation: ${middle.length} messages discussed ` + middle.filter((m) => m.role === "user").map((m) => m.content.slice(0, 50)).slice(0, 5).join(", ") + "...]";
66365
+ session.messages = [
66366
+ system,
66367
+ { role: "system", content: summary },
66368
+ ...recent
66369
+ ];
66370
+ }
66371
+ var sessions, SESSION_TTL_MS;
66372
+ var init_chat_session = __esm({
66373
+ "packages/cli/dist/api/chat-session.js"() {
66374
+ "use strict";
66375
+ sessions = /* @__PURE__ */ new Map();
66376
+ SESSION_TTL_MS = 30 * 60 * 1e3;
66377
+ setInterval(() => {
66378
+ const now = Date.now();
66379
+ for (const [id, s] of sessions) {
66380
+ if (now - s.lastActivity > SESSION_TTL_MS)
66381
+ sessions.delete(id);
66382
+ }
66383
+ }, 5 * 60 * 1e3);
66384
+ }
66385
+ });
66386
+
66387
+ // packages/cli/dist/api/usage-tracker.js
66388
+ import { mkdirSync as mkdirSync27, readFileSync as readFileSync43, writeFileSync as writeFileSync25, existsSync as existsSync54 } from "node:fs";
66389
+ import { join as join71 } from "node:path";
66265
66390
  function initUsageTracker(oaDir) {
66266
- const dir = join70(oaDir, "usage");
66391
+ const dir = join71(oaDir, "usage");
66267
66392
  mkdirSync27(dir, { recursive: true });
66268
- usageFile = join70(dir, "token-usage.json");
66393
+ usageFile = join71(dir, "token-usage.json");
66269
66394
  try {
66270
- if (existsSync53(usageFile)) {
66271
- store = JSON.parse(readFileSync42(usageFile, "utf-8"));
66395
+ if (existsSync54(usageFile)) {
66396
+ store = JSON.parse(readFileSync43(usageFile, "utf-8"));
66272
66397
  }
66273
66398
  } catch {
66274
66399
  store = { providers: {}, lastSaved: "" };
@@ -66336,24 +66461,24 @@ var init_usage_tracker = __esm({
66336
66461
  });
66337
66462
 
66338
66463
  // packages/cli/dist/api/profiles.js
66339
- import { existsSync as existsSync54, readFileSync as readFileSync43, writeFileSync as writeFileSync26, mkdirSync as mkdirSync28, readdirSync as readdirSync20, unlinkSync as unlinkSync12 } from "node:fs";
66340
- import { join as join71 } from "node:path";
66464
+ import { existsSync as existsSync55, readFileSync as readFileSync44, writeFileSync as writeFileSync26, mkdirSync as mkdirSync28, readdirSync as readdirSync21, unlinkSync as unlinkSync12 } from "node:fs";
66465
+ import { join as join72 } from "node:path";
66341
66466
  import { homedir as homedir18 } from "node:os";
66342
66467
  import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, randomBytes as randomBytes15, scryptSync as scryptSync3, createHash as createHash5 } from "node:crypto";
66343
66468
  function globalProfileDir() {
66344
- return join71(homedir18(), ".open-agents", "profiles");
66469
+ return join72(homedir18(), ".open-agents", "profiles");
66345
66470
  }
66346
66471
  function projectProfileDir(projectDir) {
66347
- return join71(projectDir || process.cwd(), ".oa", "profiles");
66472
+ return join72(projectDir || process.cwd(), ".oa", "profiles");
66348
66473
  }
66349
66474
  function listProfiles(projectDir) {
66350
66475
  const result = [];
66351
66476
  const seen = /* @__PURE__ */ new Set();
66352
66477
  const projDir = projectProfileDir(projectDir);
66353
- if (existsSync54(projDir)) {
66354
- for (const f of readdirSync20(projDir).filter((f2) => f2.endsWith(".json"))) {
66478
+ if (existsSync55(projDir)) {
66479
+ for (const f of readdirSync21(projDir).filter((f2) => f2.endsWith(".json"))) {
66355
66480
  try {
66356
- const raw = JSON.parse(readFileSync43(join71(projDir, f), "utf8"));
66481
+ const raw = JSON.parse(readFileSync44(join72(projDir, f), "utf8"));
66357
66482
  const name = f.replace(".json", "");
66358
66483
  seen.add(name);
66359
66484
  result.push({
@@ -66367,13 +66492,13 @@ function listProfiles(projectDir) {
66367
66492
  }
66368
66493
  }
66369
66494
  const globDir = globalProfileDir();
66370
- if (existsSync54(globDir)) {
66371
- for (const f of readdirSync20(globDir).filter((f2) => f2.endsWith(".json"))) {
66495
+ if (existsSync55(globDir)) {
66496
+ for (const f of readdirSync21(globDir).filter((f2) => f2.endsWith(".json"))) {
66372
66497
  const name = f.replace(".json", "");
66373
66498
  if (seen.has(name))
66374
66499
  continue;
66375
66500
  try {
66376
- const raw = JSON.parse(readFileSync43(join71(globDir, f), "utf8"));
66501
+ const raw = JSON.parse(readFileSync44(join72(globDir, f), "utf8"));
66377
66502
  result.push({
66378
66503
  name,
66379
66504
  description: raw.description || "",
@@ -66388,12 +66513,12 @@ function listProfiles(projectDir) {
66388
66513
  }
66389
66514
  function loadProfile(name, password, projectDir) {
66390
66515
  const sanitized = name.replace(/[^a-zA-Z0-9_-]/g, "");
66391
- const projPath = join71(projectProfileDir(projectDir), `${sanitized}.json`);
66392
- const globPath = join71(globalProfileDir(), `${sanitized}.json`);
66393
- const filePath = existsSync54(projPath) ? projPath : existsSync54(globPath) ? globPath : null;
66516
+ const projPath = join72(projectProfileDir(projectDir), `${sanitized}.json`);
66517
+ const globPath = join72(globalProfileDir(), `${sanitized}.json`);
66518
+ const filePath = existsSync55(projPath) ? projPath : existsSync55(globPath) ? globPath : null;
66394
66519
  if (!filePath)
66395
66520
  return null;
66396
- const raw = JSON.parse(readFileSync43(filePath, "utf8"));
66521
+ const raw = JSON.parse(readFileSync44(filePath, "utf8"));
66397
66522
  if (raw.encrypted === true) {
66398
66523
  if (!password)
66399
66524
  return null;
@@ -66405,7 +66530,7 @@ function saveProfile(profile, password, scope = "global", projectDir) {
66405
66530
  const dir = scope === "project" ? projectProfileDir(projectDir) : globalProfileDir();
66406
66531
  mkdirSync28(dir, { recursive: true });
66407
66532
  const sanitized = profile.name.replace(/[^a-zA-Z0-9_-]/g, "");
66408
- const filePath = join71(dir, `${sanitized}.json`);
66533
+ const filePath = join72(dir, `${sanitized}.json`);
66409
66534
  profile.modified = (/* @__PURE__ */ new Date()).toISOString();
66410
66535
  if (password) {
66411
66536
  const encrypted = encryptProfile(profile, password);
@@ -66418,8 +66543,8 @@ function saveProfile(profile, password, scope = "global", projectDir) {
66418
66543
  function deleteProfile(name, scope = "global", projectDir) {
66419
66544
  const sanitized = name.replace(/[^a-zA-Z0-9_-]/g, "");
66420
66545
  const dir = scope === "project" ? projectProfileDir(projectDir) : globalProfileDir();
66421
- const filePath = join71(dir, `${sanitized}.json`);
66422
- if (existsSync54(filePath)) {
66546
+ const filePath = join72(dir, `${sanitized}.json`);
66547
+ if (existsSync55(filePath)) {
66423
66548
  unlinkSync12(filePath);
66424
66549
  return true;
66425
66550
  }
@@ -66512,22 +66637,22 @@ import * as http from "node:http";
66512
66637
  import * as https from "node:https";
66513
66638
  import { createRequire as createRequire3 } from "node:module";
66514
66639
  import { fileURLToPath as fileURLToPath13 } from "node:url";
66515
- import { dirname as dirname21, join as join72, resolve as resolve31 } from "node:path";
66640
+ import { dirname as dirname21, join as join73, resolve as resolve31 } from "node:path";
66516
66641
  import { spawn as spawn21 } from "node:child_process";
66517
- import { mkdirSync as mkdirSync29, writeFileSync as writeFileSync27, readFileSync as readFileSync44, readdirSync as readdirSync21, existsSync as existsSync55 } from "node:fs";
66518
- import { randomBytes as randomBytes16, randomUUID as randomUUID4 } from "node:crypto";
66642
+ import { mkdirSync as mkdirSync29, writeFileSync as writeFileSync27, readFileSync as readFileSync45, readdirSync as readdirSync22, existsSync as existsSync56 } from "node:fs";
66643
+ import { randomBytes as randomBytes16, randomUUID as randomUUID5 } from "node:crypto";
66519
66644
  function getVersion3() {
66520
66645
  try {
66521
66646
  const require2 = createRequire3(import.meta.url);
66522
66647
  const thisDir = dirname21(fileURLToPath13(import.meta.url));
66523
66648
  const candidates = [
66524
- join72(thisDir, "..", "package.json"),
66525
- join72(thisDir, "..", "..", "package.json"),
66526
- join72(thisDir, "..", "..", "..", "package.json")
66649
+ join73(thisDir, "..", "package.json"),
66650
+ join73(thisDir, "..", "..", "package.json"),
66651
+ join73(thisDir, "..", "..", "..", "package.json")
66527
66652
  ];
66528
66653
  for (const pkgPath of candidates) {
66529
66654
  try {
66530
- if (!existsSync55(pkgPath))
66655
+ if (!existsSync56(pkgPath))
66531
66656
  continue;
66532
66657
  const pkg = require2(pkgPath);
66533
66658
  if (pkg.name === "open-agents-ai" || pkg.name === "@open-agents/cli" || pkg.name === "@open-agents/monorepo") {
@@ -66828,29 +66953,29 @@ function ollamaStream(ollamaUrl, path, method, body, onData, onEnd, onError) {
66828
66953
  }
66829
66954
  function jobsDir() {
66830
66955
  const root = resolve31(process.cwd());
66831
- const dir = join72(root, ".oa", "jobs");
66956
+ const dir = join73(root, ".oa", "jobs");
66832
66957
  mkdirSync29(dir, { recursive: true });
66833
66958
  return dir;
66834
66959
  }
66835
66960
  function loadJob(id) {
66836
- const file = join72(jobsDir(), `${id}.json`);
66837
- if (!existsSync55(file))
66961
+ const file = join73(jobsDir(), `${id}.json`);
66962
+ if (!existsSync56(file))
66838
66963
  return null;
66839
66964
  try {
66840
- return JSON.parse(readFileSync44(file, "utf-8"));
66965
+ return JSON.parse(readFileSync45(file, "utf-8"));
66841
66966
  } catch {
66842
66967
  return null;
66843
66968
  }
66844
66969
  }
66845
66970
  function listJobs() {
66846
66971
  const dir = jobsDir();
66847
- if (!existsSync55(dir))
66972
+ if (!existsSync56(dir))
66848
66973
  return [];
66849
- const files = readdirSync21(dir).filter((f) => f.endsWith(".json")).sort();
66974
+ const files = readdirSync22(dir).filter((f) => f.endsWith(".json")).sort();
66850
66975
  const jobs = [];
66851
66976
  for (const file of files) {
66852
66977
  try {
66853
- jobs.push(JSON.parse(readFileSync44(join72(dir, file), "utf-8")));
66978
+ jobs.push(JSON.parse(readFileSync45(join73(dir, file), "utf-8")));
66854
66979
  } catch {
66855
66980
  }
66856
66981
  }
@@ -67298,7 +67423,7 @@ async function handleV1Run(req, res) {
67298
67423
  if (workingDir) {
67299
67424
  cwd4 = resolve31(workingDir);
67300
67425
  } else if (isolate) {
67301
- const wsDir = join72(dir, "..", "workspaces", id);
67426
+ const wsDir = join73(dir, "..", "workspaces", id);
67302
67427
  mkdirSync29(wsDir, { recursive: true });
67303
67428
  cwd4 = wsDir;
67304
67429
  } else {
@@ -67371,7 +67496,7 @@ async function handleV1Run(req, res) {
67371
67496
  });
67372
67497
  child.unref();
67373
67498
  job.pid = child.pid ?? 0;
67374
- writeFileSync27(join72(dir, `${id}.json`), JSON.stringify(job, null, 2));
67499
+ writeFileSync27(join73(dir, `${id}.json`), JSON.stringify(job, null, 2));
67375
67500
  runningProcesses.set(id, child);
67376
67501
  if (streamMode) {
67377
67502
  res.writeHead(200, {
@@ -67398,7 +67523,7 @@ async function handleV1Run(req, res) {
67398
67523
  job.status = code === 0 ? "completed" : "failed";
67399
67524
  job.completedAt = (/* @__PURE__ */ new Date()).toISOString();
67400
67525
  try {
67401
- writeFileSync27(join72(dir, `${id}.json`), JSON.stringify(job, null, 2));
67526
+ writeFileSync27(join73(dir, `${id}.json`), JSON.stringify(job, null, 2));
67402
67527
  } catch {
67403
67528
  }
67404
67529
  runningProcesses.delete(id);
@@ -67429,7 +67554,7 @@ async function handleV1Run(req, res) {
67429
67554
  job.completedAt = (/* @__PURE__ */ new Date()).toISOString();
67430
67555
  }
67431
67556
  try {
67432
- writeFileSync27(join72(dir, `${id}.json`), JSON.stringify(job, null, 2));
67557
+ writeFileSync27(join73(dir, `${id}.json`), JSON.stringify(job, null, 2));
67433
67558
  } catch {
67434
67559
  }
67435
67560
  runningProcesses.delete(id);
@@ -67478,7 +67603,7 @@ function handleV1RunsDelete(res, id) {
67478
67603
  job.error = "Aborted via API";
67479
67604
  const dir = jobsDir();
67480
67605
  try {
67481
- writeFileSync27(join72(dir, `${id}.json`), JSON.stringify(job, null, 2));
67606
+ writeFileSync27(join73(dir, `${id}.json`), JSON.stringify(job, null, 2));
67482
67607
  } catch {
67483
67608
  }
67484
67609
  runningProcesses.delete(id);
@@ -67623,7 +67748,7 @@ async function handleRequest(req, res, ollamaUrl, verbose) {
67623
67748
  const urlObj = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
67624
67749
  const pathname = urlObj.pathname;
67625
67750
  const startMs = performance.now();
67626
- const requestId = req.headers["x-request-id"] || randomUUID4();
67751
+ const requestId = req.headers["x-request-id"] || randomUUID5();
67627
67752
  res.setHeader("X-Request-ID", requestId);
67628
67753
  if (method === "OPTIONS") {
67629
67754
  if (!corsHeaders(req, res))
@@ -67698,6 +67823,127 @@ async function handleRequest(req, res, ollamaUrl, verbose) {
67698
67823
  return;
67699
67824
  }
67700
67825
  }
67826
+ if (pathname === "/v1/chat" && method === "POST") {
67827
+ if (!checkAuth(req, res, "run")) {
67828
+ status = 401;
67829
+ return;
67830
+ }
67831
+ const chatBody = await parseJsonBody(req);
67832
+ if (!chatBody?.message || typeof chatBody.message !== "string") {
67833
+ jsonResponse(res, 400, { error: "Missing required field: message" });
67834
+ return;
67835
+ }
67836
+ const sessionId = chatBody.session_id;
67837
+ const model = chatBody.model || loadConfig().model;
67838
+ const session = getSession(sessionId, model, resolve31(process.cwd()));
67839
+ const messages = addUserMessage(session, chatBody.message);
67840
+ compactSession(session);
67841
+ const streamMode = chatBody.stream !== false;
67842
+ const chatRequest = {
67843
+ model: session.model,
67844
+ messages,
67845
+ stream: streamMode,
67846
+ max_tokens: chatBody.max_tokens || 4096
67847
+ };
67848
+ const route = resolveModelEndpoint(session.model);
67849
+ const targetUrl = route?.endpoint?.url || loadConfig().backendUrl;
67850
+ if (streamMode) {
67851
+ res.writeHead(200, {
67852
+ "Content-Type": "text/event-stream",
67853
+ "Cache-Control": "no-cache",
67854
+ "Connection": "keep-alive",
67855
+ "X-Session-ID": session.id
67856
+ });
67857
+ let fullContent = "";
67858
+ try {
67859
+ const url = new URL("/api/chat", targetUrl);
67860
+ const isHttps = url.protocol === "https:";
67861
+ const transport = isHttps ? https : http;
67862
+ const reqBody = JSON.stringify({
67863
+ model: session.model.replace(/^local\//, ""),
67864
+ messages: messages.map((m) => ({ role: m.role, content: m.content })),
67865
+ stream: true
67866
+ });
67867
+ await new Promise((resolve36, reject) => {
67868
+ const proxyReq = transport.request({
67869
+ hostname: url.hostname,
67870
+ port: url.port || (isHttps ? 443 : 80),
67871
+ path: url.pathname,
67872
+ method: "POST",
67873
+ headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(reqBody) }
67874
+ }, (proxyRes) => {
67875
+ let buffer = "";
67876
+ proxyRes.on("data", (chunk) => {
67877
+ buffer += chunk.toString();
67878
+ const lines = buffer.split("\n");
67879
+ buffer = lines.pop() || "";
67880
+ for (const line of lines) {
67881
+ if (!line.trim())
67882
+ continue;
67883
+ try {
67884
+ const parsed = JSON.parse(line);
67885
+ if (parsed.message?.content) {
67886
+ fullContent += parsed.message.content;
67887
+ const sseChunk = {
67888
+ id: `chatcmpl-${session.id.slice(0, 8)}`,
67889
+ object: "chat.completion.chunk",
67890
+ choices: [{ index: 0, delta: { content: parsed.message.content }, finish_reason: null }]
67891
+ };
67892
+ res.write("data: " + JSON.stringify(sseChunk) + "\n\n");
67893
+ }
67894
+ if (parsed.done) {
67895
+ trackSessionTokens(session, parsed.prompt_eval_count ?? 0, parsed.eval_count ?? 0);
67896
+ trackTokens("local", parsed.prompt_eval_count ?? 0, parsed.eval_count ?? 0);
67897
+ metrics.totalTokensIn += parsed.prompt_eval_count ?? 0;
67898
+ metrics.totalTokensOut += parsed.eval_count ?? 0;
67899
+ res.write("data: [DONE]\n\n");
67900
+ }
67901
+ } catch {
67902
+ }
67903
+ }
67904
+ });
67905
+ proxyRes.on("end", resolve36);
67906
+ proxyRes.on("error", reject);
67907
+ });
67908
+ proxyReq.setTimeout(12e4, () => proxyReq.destroy(new Error("Chat stream timeout")));
67909
+ proxyReq.on("error", reject);
67910
+ proxyReq.write(reqBody);
67911
+ proxyReq.end();
67912
+ });
67913
+ } catch (e) {
67914
+ res.write("data: " + JSON.stringify({ error: e.message }) + "\n\n");
67915
+ }
67916
+ addAssistantMessage(session, fullContent);
67917
+ res.end();
67918
+ } else {
67919
+ try {
67920
+ const result = await ollamaRequest(targetUrl, "/api/chat", "POST", JSON.stringify({
67921
+ model: session.model.replace(/^local\//, ""),
67922
+ messages: messages.map((m) => ({ role: m.role, content: m.content })),
67923
+ stream: false
67924
+ }));
67925
+ const parsed = JSON.parse(result.body);
67926
+ const content = parsed.message?.content ?? "";
67927
+ addAssistantMessage(session, content);
67928
+ trackSessionTokens(session, parsed.prompt_eval_count ?? 0, parsed.eval_count ?? 0);
67929
+ trackTokens("local", parsed.prompt_eval_count ?? 0, parsed.eval_count ?? 0);
67930
+ jsonResponse(res, 200, {
67931
+ session_id: session.id,
67932
+ message: { role: "assistant", content },
67933
+ usage: { prompt_tokens: parsed.prompt_eval_count ?? 0, completion_tokens: parsed.eval_count ?? 0 }
67934
+ });
67935
+ } catch (e) {
67936
+ jsonResponse(res, 500, { error: "Chat failed", message: e.message });
67937
+ }
67938
+ }
67939
+ return;
67940
+ }
67941
+ if (pathname === "/v1/chat/sessions" && method === "GET") {
67942
+ if (!checkAuth(req, res, "read"))
67943
+ return;
67944
+ jsonResponse(res, 200, { sessions: listSessions() });
67945
+ return;
67946
+ }
67701
67947
  if (pathname === "/v1/models" && method === "GET") {
67702
67948
  await handleV1Models(res, ollamaUrl);
67703
67949
  return;
@@ -67920,20 +68166,20 @@ function startApiServer(options = {}) {
67920
68166
  const config = loadConfig();
67921
68167
  const ollamaUrl = options.ollamaUrl ?? config.backendUrl;
67922
68168
  const cwd4 = process.cwd();
67923
- initAuditLog(join72(cwd4, ".oa"));
67924
- initUsageTracker(join72(cwd4, ".oa"));
68169
+ initAuditLog(join73(cwd4, ".oa"));
68170
+ initUsageTracker(join73(cwd4, ".oa"));
67925
68171
  const retentionDays = parseInt(process.env["OA_JOB_RETENTION_DAYS"] ?? "30", 10);
67926
68172
  if (retentionDays > 0) {
67927
68173
  try {
67928
- const jobsDir3 = join72(cwd4, ".oa", "jobs");
67929
- if (existsSync55(jobsDir3)) {
68174
+ const jobsDir3 = join73(cwd4, ".oa", "jobs");
68175
+ if (existsSync56(jobsDir3)) {
67930
68176
  const cutoff = Date.now() - retentionDays * 864e5;
67931
- for (const f of readdirSync21(jobsDir3)) {
68177
+ for (const f of readdirSync22(jobsDir3)) {
67932
68178
  if (!f.endsWith(".json"))
67933
68179
  continue;
67934
68180
  try {
67935
- const jobPath = join72(jobsDir3, f);
67936
- const job = JSON.parse(readFileSync44(jobPath, "utf-8"));
68181
+ const jobPath = join73(jobsDir3, f);
68182
+ const job = JSON.parse(readFileSync45(jobPath, "utf-8"));
67937
68183
  const jobTime = new Date(job.startedAt ?? job.completedAt ?? 0).getTime();
67938
68184
  if (jobTime > 0 && jobTime < cutoff && job.status !== "running") {
67939
68185
  const { unlinkSync: unlinkSync13 } = __require("node:fs");
@@ -67953,8 +68199,8 @@ function startApiServer(options = {}) {
67953
68199
  if (useTls) {
67954
68200
  try {
67955
68201
  tlsOpts = {
67956
- cert: readFileSync44(resolve31(tlsCert)),
67957
- key: readFileSync44(resolve31(tlsKey))
68202
+ cert: readFileSync45(resolve31(tlsCert)),
68203
+ key: readFileSync45(resolve31(tlsKey))
67958
68204
  };
67959
68205
  } catch (e) {
67960
68206
  log2(`
@@ -68104,6 +68350,7 @@ var init_serve = __esm({
68104
68350
  init_logger();
68105
68351
  init_openapi();
68106
68352
  init_auth_oidc();
68353
+ init_chat_session();
68107
68354
  init_usage_tracker();
68108
68355
  init_oa_directory();
68109
68356
  init_render();
@@ -68127,11 +68374,11 @@ var init_serve = __esm({
68127
68374
 
68128
68375
  // packages/cli/dist/tui/interactive.js
68129
68376
  import { cwd } from "node:process";
68130
- import { resolve as resolve32, join as join73, dirname as dirname22, extname as extname11 } from "node:path";
68377
+ import { resolve as resolve32, join as join74, dirname as dirname22, extname as extname11 } from "node:path";
68131
68378
  import { createRequire as createRequire4 } from "node:module";
68132
68379
  import { fileURLToPath as fileURLToPath14 } from "node:url";
68133
- import { readFileSync as readFileSync45, writeFileSync as writeFileSync28, appendFileSync as appendFileSync5, rmSync as rmSync3, readdirSync as readdirSync22, mkdirSync as mkdirSync30 } from "node:fs";
68134
- import { existsSync as existsSync56 } from "node:fs";
68380
+ import { readFileSync as readFileSync46, writeFileSync as writeFileSync28, appendFileSync as appendFileSync5, rmSync as rmSync3, readdirSync as readdirSync23, mkdirSync as mkdirSync30 } from "node:fs";
68381
+ import { existsSync as existsSync57 } from "node:fs";
68135
68382
  import { execSync as execSync35 } from "node:child_process";
68136
68383
  import { homedir as homedir19 } from "node:os";
68137
68384
  function formatTimeAgo(date) {
@@ -68152,12 +68399,12 @@ function getVersion4() {
68152
68399
  const require2 = createRequire4(import.meta.url);
68153
68400
  const thisDir = dirname22(fileURLToPath14(import.meta.url));
68154
68401
  const candidates = [
68155
- join73(thisDir, "..", "package.json"),
68156
- join73(thisDir, "..", "..", "package.json"),
68157
- join73(thisDir, "..", "..", "..", "package.json")
68402
+ join74(thisDir, "..", "package.json"),
68403
+ join74(thisDir, "..", "..", "package.json"),
68404
+ join74(thisDir, "..", "..", "..", "package.json")
68158
68405
  ];
68159
68406
  for (const pkgPath of candidates) {
68160
- if (existsSync56(pkgPath)) {
68407
+ if (existsSync57(pkgPath)) {
68161
68408
  const pkg = require2(pkgPath);
68162
68409
  if (pkg.name === "open-agents-ai" || pkg.name === "@open-agents/cli" || pkg.name === "@open-agents/monorepo") {
68163
68410
  return pkg.version ?? "0.0.0";
@@ -68396,15 +68643,15 @@ Use task_status("${taskId}") or task_output("${taskId}") to check progress.`
68396
68643
  function gatherMemorySnippets(root) {
68397
68644
  const snippets = [];
68398
68645
  const dirs = [
68399
- join73(root, ".oa", "memory"),
68400
- join73(root, ".open-agents", "memory")
68646
+ join74(root, ".oa", "memory"),
68647
+ join74(root, ".open-agents", "memory")
68401
68648
  ];
68402
68649
  for (const dir of dirs) {
68403
- if (!existsSync56(dir))
68650
+ if (!existsSync57(dir))
68404
68651
  continue;
68405
68652
  try {
68406
- for (const f of readdirSync22(dir).filter((f2) => f2.endsWith(".json"))) {
68407
- const data = JSON.parse(readFileSync45(join73(dir, f), "utf-8"));
68653
+ for (const f of readdirSync23(dir).filter((f2) => f2.endsWith(".json"))) {
68654
+ const data = JSON.parse(readFileSync46(join74(dir, f), "utf-8"));
68408
68655
  for (const val of Object.values(data)) {
68409
68656
  const v = typeof val === "object" && val !== null && "value" in val ? String(val.value) : String(val);
68410
68657
  if (v.length > 10)
@@ -68561,9 +68808,9 @@ ${metabolismMemories}
68561
68808
  } catch {
68562
68809
  }
68563
68810
  try {
68564
- const archeFile = join73(repoRoot, ".oa", "arche", "variants.json");
68565
- if (existsSync56(archeFile)) {
68566
- const variants = JSON.parse(readFileSync45(archeFile, "utf8"));
68811
+ const archeFile = join74(repoRoot, ".oa", "arche", "variants.json");
68812
+ if (existsSync57(archeFile)) {
68813
+ const variants = JSON.parse(readFileSync46(archeFile, "utf8"));
68567
68814
  if (variants.length > 0) {
68568
68815
  let filtered = variants;
68569
68816
  if (taskType) {
@@ -68732,9 +68979,9 @@ RULES:
68732
68979
  const compactionThreshold = modelTier === "small" ? 12e3 : modelTier === "medium" ? 24e3 : 4e4;
68733
68980
  let identityInjection = "";
68734
68981
  try {
68735
- const ikStateFile = join73(repoRoot, ".oa", "identity", "self-state.json");
68736
- if (existsSync56(ikStateFile)) {
68737
- const selfState = JSON.parse(readFileSync45(ikStateFile, "utf8"));
68982
+ const ikStateFile = join74(repoRoot, ".oa", "identity", "self-state.json");
68983
+ if (existsSync57(ikStateFile)) {
68984
+ const selfState = JSON.parse(readFileSync46(ikStateFile, "utf8"));
68738
68985
  const lines = [
68739
68986
  `[Identity State v${selfState.version}]`,
68740
68987
  `Self: ${selfState.narrative_summary}`,
@@ -69378,11 +69625,11 @@ When done, either call task_complete with your answer, or use FINAL_VAR(variable
69378
69625
  });
69379
69626
  }
69380
69627
  try {
69381
- const ikDir = join73(repoRoot, ".oa", "identity");
69382
- const ikFile = join73(ikDir, "self-state.json");
69628
+ const ikDir = join74(repoRoot, ".oa", "identity");
69629
+ const ikFile = join74(ikDir, "self-state.json");
69383
69630
  let ikState;
69384
- if (existsSync56(ikFile)) {
69385
- ikState = JSON.parse(readFileSync45(ikFile, "utf8"));
69631
+ if (existsSync57(ikFile)) {
69632
+ ikState = JSON.parse(readFileSync46(ikFile, "utf8"));
69386
69633
  } else {
69387
69634
  mkdirSync30(ikDir, { recursive: true });
69388
69635
  const machineId = Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
@@ -69425,9 +69672,9 @@ When done, either call task_complete with your answer, or use FINAL_VAR(variable
69425
69672
  } else {
69426
69673
  renderTaskIncomplete(result.turns, result.toolCalls, result.durationMs, tokens);
69427
69674
  try {
69428
- const ikFile = join73(repoRoot, ".oa", "identity", "self-state.json");
69429
- if (existsSync56(ikFile)) {
69430
- const ikState = JSON.parse(readFileSync45(ikFile, "utf8"));
69675
+ const ikFile = join74(repoRoot, ".oa", "identity", "self-state.json");
69676
+ if (existsSync57(ikFile)) {
69677
+ const ikState = JSON.parse(readFileSync46(ikFile, "utf8"));
69431
69678
  ikState.homeostasis.uncertainty = Math.min(1, ikState.homeostasis.uncertainty + 0.1);
69432
69679
  ikState.homeostasis.coherence = Math.max(0, ikState.homeostasis.coherence - 0.05);
69433
69680
  ikState.session_count = (ikState.session_count || 0) + 1;
@@ -69529,10 +69776,10 @@ async function startInteractive(config, repoPath) {
69529
69776
  process.stdin.pause();
69530
69777
  }
69531
69778
  try {
69532
- const oaDir = join73(repoRoot, ".oa");
69533
- const nexusPidFile = join73(oaDir, "nexus", "daemon.pid");
69534
- if (existsSync56(nexusPidFile)) {
69535
- const pid = parseInt(readFileSync45(nexusPidFile, "utf8").trim(), 10);
69779
+ const oaDir = join74(repoRoot, ".oa");
69780
+ const nexusPidFile = join74(oaDir, "nexus", "daemon.pid");
69781
+ if (existsSync57(nexusPidFile)) {
69782
+ const pid = parseInt(readFileSync46(nexusPidFile, "utf8").trim(), 10);
69536
69783
  if (pid > 0) {
69537
69784
  try {
69538
69785
  process.kill(pid, 0);
@@ -69869,7 +70116,7 @@ Review its full output in the [${id}] tab or via full_sub_agent(action='output',
69869
70116
  let p2pGateway = null;
69870
70117
  let peerMesh = null;
69871
70118
  let inferenceRouter = null;
69872
- const secretVault = new SecretVault(join73(repoRoot, ".oa", "vault.enc"));
70119
+ const secretVault = new SecretVault(join74(repoRoot, ".oa", "vault.enc"));
69873
70120
  let adminSessionKey = null;
69874
70121
  const callSubAgents = /* @__PURE__ */ new Map();
69875
70122
  const streamRenderer = new StreamRenderer();
@@ -70092,13 +70339,13 @@ Rationale: ${proposal.rationale}${provenanceNote}`;
70092
70339
  const hits = allCompletions.filter((c3) => c3.toLowerCase().startsWith(lower));
70093
70340
  return [hits, line];
70094
70341
  }
70095
- const HISTORY_DIR = join73(homedir19(), ".open-agents");
70096
- const HISTORY_FILE = join73(HISTORY_DIR, "repl-history");
70342
+ const HISTORY_DIR = join74(homedir19(), ".open-agents");
70343
+ const HISTORY_FILE = join74(HISTORY_DIR, "repl-history");
70097
70344
  const MAX_HISTORY_LINES = 500;
70098
70345
  let savedHistory = [];
70099
70346
  try {
70100
- if (existsSync56(HISTORY_FILE)) {
70101
- const raw = readFileSync45(HISTORY_FILE, "utf8").trim();
70347
+ if (existsSync57(HISTORY_FILE)) {
70348
+ const raw = readFileSync46(HISTORY_FILE, "utf8").trim();
70102
70349
  if (raw)
70103
70350
  savedHistory = raw.split("\n").reverse();
70104
70351
  }
@@ -70204,7 +70451,7 @@ Rationale: ${proposal.rationale}${provenanceNote}`;
70204
70451
  mkdirSync30(HISTORY_DIR, { recursive: true });
70205
70452
  appendFileSync5(HISTORY_FILE, line + "\n", "utf8");
70206
70453
  if (Math.random() < 0.02) {
70207
- const all = readFileSync45(HISTORY_FILE, "utf8").trim().split("\n");
70454
+ const all = readFileSync46(HISTORY_FILE, "utf8").trim().split("\n");
70208
70455
  if (all.length > MAX_HISTORY_LINES) {
70209
70456
  writeFileSync28(HISTORY_FILE, all.slice(-MAX_HISTORY_LINES).join("\n") + "\n", "utf8");
70210
70457
  }
@@ -70390,7 +70637,7 @@ Rationale: ${proposal.rationale}${provenanceNote}`;
70390
70637
  } catch {
70391
70638
  }
70392
70639
  try {
70393
- const oaDir = join73(repoRoot, ".oa");
70640
+ const oaDir = join74(repoRoot, ".oa");
70394
70641
  const reconnected = await ExposeGateway.checkAndReconnect(oaDir, {
70395
70642
  onInfo: (msg) => writeContent(() => renderInfo(msg)),
70396
70643
  onError: (msg) => writeContent(() => renderWarning(msg))
@@ -70422,7 +70669,7 @@ Rationale: ${proposal.rationale}${provenanceNote}`;
70422
70669
  } catch {
70423
70670
  }
70424
70671
  try {
70425
- const oaDir = join73(repoRoot, ".oa");
70672
+ const oaDir = join74(repoRoot, ".oa");
70426
70673
  const reconnectedP2P = await ExposeP2PGateway.checkAndReconnect(oaDir, new NexusTool(repoRoot), {
70427
70674
  onInfo: (msg) => writeContent(() => renderInfo(msg)),
70428
70675
  onError: (msg) => writeContent(() => renderWarning(msg))
@@ -70463,11 +70710,11 @@ Rationale: ${proposal.rationale}${provenanceNote}`;
70463
70710
  }
70464
70711
  try {
70465
70712
  const { homedir: _hd, hostname: _hn, userInfo: _ui } = await import("node:os");
70466
- const globalNamePath = join73(_hd(), ".open-agents", "agent-name");
70713
+ const globalNamePath = join74(_hd(), ".open-agents", "agent-name");
70467
70714
  let agName = "";
70468
70715
  try {
70469
- if (existsSync56(globalNamePath))
70470
- agName = readFileSync45(globalNamePath, "utf8").trim();
70716
+ if (existsSync57(globalNamePath))
70717
+ agName = readFileSync46(globalNamePath, "utf8").trim();
70471
70718
  } catch {
70472
70719
  }
70473
70720
  if (!agName) {
@@ -71443,7 +71690,7 @@ Respond concisely and safely. Remember: you are talking to the general public.`;
71443
71690
  kind,
71444
71691
  targetUrl,
71445
71692
  authKey,
71446
- stateDir: join73(repoRoot, ".oa"),
71693
+ stateDir: join74(repoRoot, ".oa"),
71447
71694
  passthrough: passthrough ?? false,
71448
71695
  loadbalance: loadbalance ?? false,
71449
71696
  endpointAuth: passthrough ? currentConfig.apiKey : void 0,
@@ -71489,7 +71736,7 @@ Respond concisely and safely. Remember: you are talking to the general public.`;
71489
71736
  await tunnelGateway.stop();
71490
71737
  tunnelGateway = null;
71491
71738
  }
71492
- const newTunnel = new ExposeGateway({ kind, targetUrl, authKey, fullAccess, stateDir: join73(repoRoot, ".oa") });
71739
+ const newTunnel = new ExposeGateway({ kind, targetUrl, authKey, fullAccess, stateDir: join74(repoRoot, ".oa") });
71493
71740
  newTunnel.on("stats", (stats) => {
71494
71741
  statusBar.setExposeStatus({
71495
71742
  status: stats.status,
@@ -71578,9 +71825,9 @@ Respond concisely and safely. Remember: you are talking to the general public.`;
71578
71825
  if (!result.success)
71579
71826
  throw new Error(result.error || "Connect failed");
71580
71827
  try {
71581
- const nexusPidFile = join73(repoRoot, ".oa", "nexus", "daemon.pid");
71582
- if (existsSync56(nexusPidFile)) {
71583
- const pid = parseInt(readFileSync45(nexusPidFile, "utf8").trim(), 10);
71828
+ const nexusPidFile = join74(repoRoot, ".oa", "nexus", "daemon.pid");
71829
+ if (existsSync57(nexusPidFile)) {
71830
+ const pid = parseInt(readFileSync46(nexusPidFile, "utf8").trim(), 10);
71584
71831
  if (pid > 0) {
71585
71832
  registry.register({
71586
71833
  name: "Nexus",
@@ -71776,10 +72023,10 @@ Respond concisely and safely. Remember: you are talking to the general public.`;
71776
72023
  writeContent(() => renderInfo(`Killed ${bgKilled} background task(s).`));
71777
72024
  }
71778
72025
  try {
71779
- const nexusDir = join73(repoRoot, OA_DIR, "nexus");
71780
- const pidFile = join73(nexusDir, "daemon.pid");
71781
- if (existsSync56(pidFile)) {
71782
- const pid = parseInt(readFileSync45(pidFile, "utf8").trim(), 10);
72026
+ const nexusDir = join74(repoRoot, OA_DIR, "nexus");
72027
+ const pidFile = join74(nexusDir, "daemon.pid");
72028
+ if (existsSync57(pidFile)) {
72029
+ const pid = parseInt(readFileSync46(pidFile, "utf8").trim(), 10);
71783
72030
  if (pid > 0) {
71784
72031
  try {
71785
72032
  if (process.platform === "win32") {
@@ -71801,13 +72048,13 @@ Respond concisely and safely. Remember: you are talking to the general public.`;
71801
72048
  } catch {
71802
72049
  }
71803
72050
  try {
71804
- const voiceDir2 = join73(homedir19(), ".open-agents", "voice");
72051
+ const voiceDir2 = join74(homedir19(), ".open-agents", "voice");
71805
72052
  const voicePidFiles = ["luxtts-daemon.pid", "piper-daemon.pid"];
71806
72053
  for (const pf of voicePidFiles) {
71807
- const pidPath = join73(voiceDir2, pf);
71808
- if (existsSync56(pidPath)) {
72054
+ const pidPath = join74(voiceDir2, pf);
72055
+ if (existsSync57(pidPath)) {
71809
72056
  try {
71810
- const pid = parseInt(readFileSync45(pidPath, "utf8").trim(), 10);
72057
+ const pid = parseInt(readFileSync46(pidPath, "utf8").trim(), 10);
71811
72058
  if (pid > 0) {
71812
72059
  if (process.platform === "win32") {
71813
72060
  try {
@@ -71831,8 +72078,8 @@ Respond concisely and safely. Remember: you are talking to the general public.`;
71831
72078
  execSync35(process.platform === "win32" ? "timeout /t 1 /nobreak >nul" : "sleep 0.5", { timeout: 3e3, stdio: "ignore" });
71832
72079
  } catch {
71833
72080
  }
71834
- const oaPath = join73(repoRoot, OA_DIR);
71835
- if (existsSync56(oaPath)) {
72081
+ const oaPath = join74(repoRoot, OA_DIR);
72082
+ if (existsSync57(oaPath)) {
71836
72083
  let deleted = false;
71837
72084
  for (let attempt = 0; attempt < 3; attempt++) {
71838
72085
  try {
@@ -71915,19 +72162,19 @@ Respond concisely and safely. Remember: you are talking to the general public.`;
71915
72162
  try {
71916
72163
  const { isPersonaPlexRunning: isPersonaPlexRunning2 } = await Promise.resolve().then(() => (init_personaplex(), personaplex_exports));
71917
72164
  if (isPersonaPlexRunning2()) {
71918
- const ppPidFile = join73(homedir19(), ".open-agents", "voice", "personaplex", "daemon.pid");
71919
- const ppPortFile = join73(homedir19(), ".open-agents", "voice", "personaplex", "daemon.port");
71920
- if (existsSync56(ppPidFile)) {
71921
- const ppPid = parseInt(readFileSync45(ppPidFile, "utf8").trim(), 10);
71922
- const ppPort = existsSync56(ppPortFile) ? parseInt(readFileSync45(ppPortFile, "utf8").trim(), 10) : void 0;
72165
+ const ppPidFile = join74(homedir19(), ".open-agents", "voice", "personaplex", "daemon.pid");
72166
+ const ppPortFile = join74(homedir19(), ".open-agents", "voice", "personaplex", "daemon.port");
72167
+ if (existsSync57(ppPidFile)) {
72168
+ const ppPid = parseInt(readFileSync46(ppPidFile, "utf8").trim(), 10);
72169
+ const ppPort = existsSync57(ppPortFile) ? parseInt(readFileSync46(ppPortFile, "utf8").trim(), 10) : void 0;
71923
72170
  if (ppPid > 0 && !registry.daemons.has("PersonaPlex")) {
71924
72171
  registry.register({ name: "PersonaPlex", pid: ppPid, port: ppPort, startedAt: Date.now(), status: "running" });
71925
72172
  }
71926
72173
  }
71927
72174
  }
71928
- const nexusPidFile = join73(repoRoot, ".oa", "nexus", "daemon.pid");
71929
- if (existsSync56(nexusPidFile)) {
71930
- const nPid = parseInt(readFileSync45(nexusPidFile, "utf8").trim(), 10);
72175
+ const nexusPidFile = join74(repoRoot, ".oa", "nexus", "daemon.pid");
72176
+ if (existsSync57(nexusPidFile)) {
72177
+ const nPid = parseInt(readFileSync46(nexusPidFile, "utf8").trim(), 10);
71931
72178
  if (nPid > 0 && !registry.daemons.has("Nexus")) {
71932
72179
  try {
71933
72180
  process.kill(nPid, 0);
@@ -72269,8 +72516,8 @@ Execute this skill now. Follow the behavioral guidance above.`;
72269
72516
  }
72270
72517
  }
72271
72518
  const cleanPath = input.replace(/^['"]|['"]$/g, "").trim();
72272
- const isImage = isImagePath(cleanPath) && existsSync56(resolve32(repoRoot, cleanPath));
72273
- const isMedia = !isImage && isTranscribablePath(cleanPath) && existsSync56(resolve32(repoRoot, cleanPath));
72519
+ const isImage = isImagePath(cleanPath) && existsSync57(resolve32(repoRoot, cleanPath));
72520
+ const isMedia = !isImage && isTranscribablePath(cleanPath) && existsSync57(resolve32(repoRoot, cleanPath));
72274
72521
  if (activeTask) {
72275
72522
  if (activeTask.runner.isPaused) {
72276
72523
  activeTask.runner.resume();
@@ -72279,7 +72526,7 @@ Execute this skill now. Follow the behavioral guidance above.`;
72279
72526
  if (isImage) {
72280
72527
  try {
72281
72528
  const imgPath = resolve32(repoRoot, cleanPath);
72282
- const imgBuffer = readFileSync45(imgPath);
72529
+ const imgBuffer = readFileSync46(imgPath);
72283
72530
  const base64 = imgBuffer.toString("base64");
72284
72531
  const ext = extname11(cleanPath).toLowerCase();
72285
72532
  const mime = ext === ".png" ? "image/png" : ext === ".gif" ? "image/gif" : ext === ".webp" ? "image/webp" : "image/jpeg";
@@ -72494,7 +72741,7 @@ Summarize or analyze this transcription as appropriate.`;
72494
72741
 
72495
72742
  NEW TASK: ${fullInput}`;
72496
72743
  restoredSessionContext = null;
72497
- } else if (existsSync56(join73(repoRoot, ".oa", "context", "session-diary.md"))) {
72744
+ } else if (existsSync57(join74(repoRoot, ".oa", "context", "session-diary.md"))) {
72498
72745
  taskInput = `[Previous sessions exist \u2014 file_read(".oa/context/session-diary.md") to recall]
72499
72746
 
72500
72747
  ${fullInput}`;
@@ -72811,11 +73058,11 @@ async function runWithTUI(task, config, repoPath) {
72811
73058
  const handle = startTask(task, config, repoRoot);
72812
73059
  await handle.promise;
72813
73060
  try {
72814
- const ikDir = join73(repoRoot, ".oa", "identity");
72815
- const ikFile = join73(ikDir, "self-state.json");
73061
+ const ikDir = join74(repoRoot, ".oa", "identity");
73062
+ const ikFile = join74(ikDir, "self-state.json");
72816
73063
  let ikState;
72817
- if (existsSync56(ikFile)) {
72818
- ikState = JSON.parse(readFileSync45(ikFile, "utf8"));
73064
+ if (existsSync57(ikFile)) {
73065
+ ikState = JSON.parse(readFileSync46(ikFile, "utf8"));
72819
73066
  } else {
72820
73067
  mkdirSync30(ikDir, { recursive: true });
72821
73068
  ikState = {
@@ -72848,12 +73095,12 @@ async function runWithTUI(task, config, repoPath) {
72848
73095
  ec.archiveVariantSync(`Task: ${task.slice(0, 200)}`, "success \u2014 completed", ["general"]);
72849
73096
  } catch {
72850
73097
  try {
72851
- const archeDir = join73(repoRoot, ".oa", "arche");
72852
- const archeFile = join73(archeDir, "variants.json");
73098
+ const archeDir = join74(repoRoot, ".oa", "arche");
73099
+ const archeFile = join74(archeDir, "variants.json");
72853
73100
  let variants = [];
72854
73101
  try {
72855
- if (existsSync56(archeFile))
72856
- variants = JSON.parse(readFileSync45(archeFile, "utf8"));
73102
+ if (existsSync57(archeFile))
73103
+ variants = JSON.parse(readFileSync46(archeFile, "utf8"));
72857
73104
  } catch {
72858
73105
  }
72859
73106
  variants.push({
@@ -72874,9 +73121,9 @@ async function runWithTUI(task, config, repoPath) {
72874
73121
  }
72875
73122
  }
72876
73123
  try {
72877
- const metaFile = join73(repoRoot, ".oa", "memory", "metabolism", "store.json");
72878
- if (existsSync56(metaFile)) {
72879
- const store2 = JSON.parse(readFileSync45(metaFile, "utf8"));
73124
+ const metaFile = join74(repoRoot, ".oa", "memory", "metabolism", "store.json");
73125
+ if (existsSync57(metaFile)) {
73126
+ const store2 = JSON.parse(readFileSync46(metaFile, "utf8"));
72880
73127
  const surfaced = store2.filter((m) => m.type !== "quarantine" && m.scores?.confidence > 0.15).sort((a, b) => b.scores.utility * b.scores.confidence - a.scores.utility * a.scores.confidence).slice(0, 5);
72881
73128
  let updated = false;
72882
73129
  for (const item of surfaced) {
@@ -72940,9 +73187,9 @@ Rules:
72940
73187
  try {
72941
73188
  const { initDb: initDb2 } = __require("@open-agents/memory");
72942
73189
  const { ProceduralMemoryStore: ProceduralMemoryStore2 } = __require("@open-agents/memory");
72943
- const dbDir = join73(repoRoot, ".oa", "memory");
73190
+ const dbDir = join74(repoRoot, ".oa", "memory");
72944
73191
  mkdirSync30(dbDir, { recursive: true });
72945
- const db = initDb2(join73(dbDir, "structured.db"));
73192
+ const db = initDb2(join74(dbDir, "structured.db"));
72946
73193
  const memStore = new ProceduralMemoryStore2(db);
72947
73194
  memStore.createWithEmbedding({
72948
73195
  content: content.slice(0, 600),
@@ -72957,12 +73204,12 @@ Rules:
72957
73204
  db.close();
72958
73205
  } catch {
72959
73206
  }
72960
- const metaDir = join73(repoRoot, ".oa", "memory", "metabolism");
72961
- const storeFile = join73(metaDir, "store.json");
73207
+ const metaDir = join74(repoRoot, ".oa", "memory", "metabolism");
73208
+ const storeFile = join74(metaDir, "store.json");
72962
73209
  let store2 = [];
72963
73210
  try {
72964
- if (existsSync56(storeFile))
72965
- store2 = JSON.parse(readFileSync45(storeFile, "utf8"));
73211
+ if (existsSync57(storeFile))
73212
+ store2 = JSON.parse(readFileSync46(storeFile, "utf8"));
72966
73213
  } catch {
72967
73214
  }
72968
73215
  store2.push({
@@ -72985,19 +73232,19 @@ Rules:
72985
73232
  } catch {
72986
73233
  }
72987
73234
  try {
72988
- const cohereSettingsFile = join73(repoRoot, ".oa", "settings.json");
73235
+ const cohereSettingsFile = join74(repoRoot, ".oa", "settings.json");
72989
73236
  let cohereActive = false;
72990
73237
  try {
72991
- if (existsSync56(cohereSettingsFile)) {
72992
- const settings = JSON.parse(readFileSync45(cohereSettingsFile, "utf8"));
73238
+ if (existsSync57(cohereSettingsFile)) {
73239
+ const settings = JSON.parse(readFileSync46(cohereSettingsFile, "utf8"));
72993
73240
  cohereActive = settings.cohere === true;
72994
73241
  }
72995
73242
  } catch {
72996
73243
  }
72997
73244
  if (cohereActive) {
72998
- const metaFile = join73(repoRoot, ".oa", "memory", "metabolism", "store.json");
72999
- if (existsSync56(metaFile)) {
73000
- const store2 = JSON.parse(readFileSync45(metaFile, "utf8"));
73245
+ const metaFile = join74(repoRoot, ".oa", "memory", "metabolism", "store.json");
73246
+ if (existsSync57(metaFile)) {
73247
+ const store2 = JSON.parse(readFileSync46(metaFile, "utf8"));
73001
73248
  const latest = store2.filter((m) => m.sourceTrace === "trajectory-extraction" || m.sourceTrace === "llm-trajectory-extraction").slice(-1)[0];
73002
73249
  if (latest && latest.scores?.confidence >= 0.6) {
73003
73250
  try {
@@ -73022,18 +73269,18 @@ Rules:
73022
73269
  }
73023
73270
  } catch (err) {
73024
73271
  try {
73025
- const ikFile = join73(repoRoot, ".oa", "identity", "self-state.json");
73026
- if (existsSync56(ikFile)) {
73027
- const ikState = JSON.parse(readFileSync45(ikFile, "utf8"));
73272
+ const ikFile = join74(repoRoot, ".oa", "identity", "self-state.json");
73273
+ if (existsSync57(ikFile)) {
73274
+ const ikState = JSON.parse(readFileSync46(ikFile, "utf8"));
73028
73275
  ikState.homeostasis.uncertainty = Math.min(1, ikState.homeostasis.uncertainty + 0.1);
73029
73276
  ikState.homeostasis.coherence = Math.max(0, ikState.homeostasis.coherence - 0.05);
73030
73277
  ikState.session_count = (ikState.session_count || 0) + 1;
73031
73278
  ikState.updated_at = (/* @__PURE__ */ new Date()).toISOString();
73032
73279
  writeFileSync28(ikFile, JSON.stringify(ikState, null, 2));
73033
73280
  }
73034
- const metaFile = join73(repoRoot, ".oa", "memory", "metabolism", "store.json");
73035
- if (existsSync56(metaFile)) {
73036
- const store2 = JSON.parse(readFileSync45(metaFile, "utf8"));
73281
+ const metaFile = join74(repoRoot, ".oa", "memory", "metabolism", "store.json");
73282
+ if (existsSync57(metaFile)) {
73283
+ const store2 = JSON.parse(readFileSync46(metaFile, "utf8"));
73037
73284
  const surfaced = store2.filter((m) => m.type !== "quarantine" && m.scores?.confidence > 0.15).sort((a, b) => b.scores.utility * b.scores.confidence - a.scores.utility * a.scores.confidence).slice(0, 5);
73038
73285
  for (const item of surfaced) {
73039
73286
  item.accessCount = (item.accessCount || 0) + 1;
@@ -73044,12 +73291,12 @@ Rules:
73044
73291
  writeFileSync28(metaFile, JSON.stringify(store2, null, 2));
73045
73292
  }
73046
73293
  try {
73047
- const archeDir = join73(repoRoot, ".oa", "arche");
73048
- const archeFile = join73(archeDir, "variants.json");
73294
+ const archeDir = join74(repoRoot, ".oa", "arche");
73295
+ const archeFile = join74(archeDir, "variants.json");
73049
73296
  let variants = [];
73050
73297
  try {
73051
- if (existsSync56(archeFile))
73052
- variants = JSON.parse(readFileSync45(archeFile, "utf8"));
73298
+ if (existsSync57(archeFile))
73299
+ variants = JSON.parse(readFileSync46(archeFile, "utf8"));
73053
73300
  } catch {
73054
73301
  }
73055
73302
  variants.push({
@@ -73135,12 +73382,12 @@ __export(run_exports, {
73135
73382
  });
73136
73383
  import { resolve as resolve33 } from "node:path";
73137
73384
  import { spawn as spawn22 } from "node:child_process";
73138
- import { mkdirSync as mkdirSync31, writeFileSync as writeFileSync29, readFileSync as readFileSync46, readdirSync as readdirSync23, existsSync as existsSync57 } from "node:fs";
73385
+ import { mkdirSync as mkdirSync31, writeFileSync as writeFileSync29, readFileSync as readFileSync47, readdirSync as readdirSync24, existsSync as existsSync58 } from "node:fs";
73139
73386
  import { randomBytes as randomBytes17 } from "node:crypto";
73140
- import { join as join74 } from "node:path";
73387
+ import { join as join75 } from "node:path";
73141
73388
  function jobsDir2(repoPath) {
73142
73389
  const root = resolve33(repoPath ?? process.cwd());
73143
- const dir = join74(root, ".oa", "jobs");
73390
+ const dir = join75(root, ".oa", "jobs");
73144
73391
  mkdirSync31(dir, { recursive: true });
73145
73392
  return dir;
73146
73393
  }
@@ -73226,7 +73473,7 @@ async function runBackground(task, config, opts) {
73226
73473
  });
73227
73474
  child.unref();
73228
73475
  job.pid = child.pid ?? 0;
73229
- writeFileSync29(join74(dir, `${id}.json`), JSON.stringify(job, null, 2));
73476
+ writeFileSync29(join75(dir, `${id}.json`), JSON.stringify(job, null, 2));
73230
73477
  let output = "";
73231
73478
  child.stdout?.on("data", (chunk) => {
73232
73479
  output += chunk.toString();
@@ -73242,7 +73489,7 @@ async function runBackground(task, config, opts) {
73242
73489
  job.summary = result.summary;
73243
73490
  job.durationMs = result.durationMs;
73244
73491
  job.error = result.error;
73245
- writeFileSync29(join74(dir, `${id}.json`), JSON.stringify(job, null, 2));
73492
+ writeFileSync29(join75(dir, `${id}.json`), JSON.stringify(job, null, 2));
73246
73493
  } catch {
73247
73494
  }
73248
73495
  });
@@ -73258,13 +73505,13 @@ async function runBackground(task, config, opts) {
73258
73505
  }
73259
73506
  function statusCommand(jobId, repoPath) {
73260
73507
  const dir = jobsDir2(repoPath);
73261
- const file = join74(dir, `${jobId}.json`);
73262
- if (!existsSync57(file)) {
73508
+ const file = join75(dir, `${jobId}.json`);
73509
+ if (!existsSync58(file)) {
73263
73510
  console.error(`Job not found: ${jobId}`);
73264
73511
  console.log(`Available jobs: oa jobs`);
73265
73512
  process.exit(1);
73266
73513
  }
73267
- const job = JSON.parse(readFileSync46(file, "utf-8"));
73514
+ const job = JSON.parse(readFileSync47(file, "utf-8"));
73268
73515
  const runtime = job.completedAt ? `${((new Date(job.completedAt).getTime() - new Date(job.startedAt).getTime()) / 1e3).toFixed(0)}s` : `${((Date.now() - new Date(job.startedAt).getTime()) / 1e3).toFixed(0)}s`;
73269
73516
  const icon = job.status === "completed" ? "\u2713" : job.status === "failed" ? "\u2717" : "\u25CF";
73270
73517
  console.log(`${icon} ${job.id} [${job.status}] ${runtime}`);
@@ -73279,7 +73526,7 @@ function statusCommand(jobId, repoPath) {
73279
73526
  }
73280
73527
  function jobsCommand(repoPath) {
73281
73528
  const dir = jobsDir2(repoPath);
73282
- const files = readdirSync23(dir).filter((f) => f.endsWith(".json")).sort();
73529
+ const files = readdirSync24(dir).filter((f) => f.endsWith(".json")).sort();
73283
73530
  if (files.length === 0) {
73284
73531
  console.log("No jobs found.");
73285
73532
  return;
@@ -73287,7 +73534,7 @@ function jobsCommand(repoPath) {
73287
73534
  console.log("Jobs:");
73288
73535
  for (const file of files) {
73289
73536
  try {
73290
- const job = JSON.parse(readFileSync46(join74(dir, file), "utf-8"));
73537
+ const job = JSON.parse(readFileSync47(join75(dir, file), "utf-8"));
73291
73538
  const icon = job.status === "completed" ? "\u2713" : job.status === "failed" ? "\u2717" : "\u25CF";
73292
73539
  const runtime = job.completedAt ? `${((new Date(job.completedAt).getTime() - new Date(job.startedAt).getTime()) / 1e3).toFixed(0)}s` : `${((Date.now() - new Date(job.startedAt).getTime()) / 1e3).toFixed(0)}s`;
73293
73540
  console.log(` ${icon} ${job.id} [${job.status}] ${runtime} \u2014 ${job.task.slice(0, 60)}`);
@@ -73307,7 +73554,7 @@ import { glob } from "glob";
73307
73554
  import ignore from "ignore";
73308
73555
  import { readFile as readFile23, stat as stat4 } from "node:fs/promises";
73309
73556
  import { createHash as createHash6 } from "node:crypto";
73310
- import { join as join75, relative as relative4, extname as extname12, basename as basename17 } from "node:path";
73557
+ import { join as join76, relative as relative4, extname as extname12, basename as basename17 } from "node:path";
73311
73558
  var DEFAULT_EXCLUDE, LANGUAGE_MAP, CodebaseIndexer;
73312
73559
  var init_codebase_indexer = __esm({
73313
73560
  "packages/indexer/dist/codebase-indexer.js"() {
@@ -73351,7 +73598,7 @@ var init_codebase_indexer = __esm({
73351
73598
  const ig = ignore.default();
73352
73599
  if (this.config.respectGitignore) {
73353
73600
  try {
73354
- const gitignoreContent = await readFile23(join75(this.config.rootDir, ".gitignore"), "utf-8");
73601
+ const gitignoreContent = await readFile23(join76(this.config.rootDir, ".gitignore"), "utf-8");
73355
73602
  ig.add(gitignoreContent);
73356
73603
  } catch {
73357
73604
  }
@@ -73366,7 +73613,7 @@ var init_codebase_indexer = __esm({
73366
73613
  for (const relativePath of files) {
73367
73614
  if (ig.ignores(relativePath))
73368
73615
  continue;
73369
- const fullPath = join75(this.config.rootDir, relativePath);
73616
+ const fullPath = join76(this.config.rootDir, relativePath);
73370
73617
  try {
73371
73618
  const fileStat = await stat4(fullPath);
73372
73619
  if (fileStat.size > this.config.maxFileSize)
@@ -73412,7 +73659,7 @@ var init_codebase_indexer = __esm({
73412
73659
  if (!child) {
73413
73660
  child = {
73414
73661
  name: part,
73415
- path: join75(current.path, part),
73662
+ path: join76(current.path, part),
73416
73663
  type: "directory",
73417
73664
  children: []
73418
73665
  };
@@ -73495,13 +73742,13 @@ __export(index_repo_exports, {
73495
73742
  indexRepoCommand: () => indexRepoCommand
73496
73743
  });
73497
73744
  import { resolve as resolve34 } from "node:path";
73498
- import { existsSync as existsSync58, statSync as statSync17 } from "node:fs";
73745
+ import { existsSync as existsSync59, statSync as statSync17 } from "node:fs";
73499
73746
  import { cwd as cwd2 } from "node:process";
73500
73747
  async function indexRepoCommand(opts, _config) {
73501
73748
  const repoRoot = resolve34(opts.repoPath ?? cwd2());
73502
73749
  printHeader("Index Repository");
73503
73750
  printInfo(`Indexing: ${repoRoot}`);
73504
- if (!existsSync58(repoRoot)) {
73751
+ if (!existsSync59(repoRoot)) {
73505
73752
  printError(`Path does not exist: ${repoRoot}`);
73506
73753
  process.exit(1);
73507
73754
  }
@@ -73753,7 +74000,7 @@ var config_exports2 = {};
73753
74000
  __export(config_exports2, {
73754
74001
  configCommand: () => configCommand
73755
74002
  });
73756
- import { join as join76, resolve as resolve35 } from "node:path";
74003
+ import { join as join77, resolve as resolve35 } from "node:path";
73757
74004
  import { homedir as homedir20 } from "node:os";
73758
74005
  import { cwd as cwd3 } from "node:process";
73759
74006
  function redactIfSensitive(key, value) {
@@ -73836,7 +74083,7 @@ function handleShow(opts, config) {
73836
74083
  }
73837
74084
  }
73838
74085
  printSection("Config File");
73839
- printInfo(`~/.open-agents/config.json (${join76(homedir20(), ".open-agents", "config.json")})`);
74086
+ printInfo(`~/.open-agents/config.json (${join77(homedir20(), ".open-agents", "config.json")})`);
73840
74087
  printSection("Priority Chain");
73841
74088
  printInfo(" 1. CLI flags (--model, --backend-url, etc.)");
73842
74089
  printInfo(" 2. Project .oa/settings.json (--local)");
@@ -73875,7 +74122,7 @@ function handleSet(opts, _config) {
73875
74122
  const coerced = coerceForSettings(key, value);
73876
74123
  saveProjectSettings(repoRoot, { [key]: coerced });
73877
74124
  printSuccess(`Project override set: ${key} = ${redactIfSensitive(key, value)}`);
73878
- printInfo(`Saved to ${join76(repoRoot, ".oa", "settings.json")}`);
74125
+ printInfo(`Saved to ${join77(repoRoot, ".oa", "settings.json")}`);
73879
74126
  printInfo("This override applies only when running in this workspace.");
73880
74127
  } catch (err) {
73881
74128
  printError(`Failed to save: ${err instanceof Error ? err.message : String(err)}`);
@@ -74019,7 +74266,7 @@ __export(eval_exports, {
74019
74266
  });
74020
74267
  import { tmpdir as tmpdir10 } from "node:os";
74021
74268
  import { mkdirSync as mkdirSync32, writeFileSync as writeFileSync30 } from "node:fs";
74022
- import { join as join77 } from "node:path";
74269
+ import { join as join78 } from "node:path";
74023
74270
  async function evalCommand(opts, config) {
74024
74271
  const suiteName = opts.suite ?? "basic";
74025
74272
  const suite = SUITES[suiteName];
@@ -74144,9 +74391,9 @@ async function evalCommand(opts, config) {
74144
74391
  process.exit(failed > 0 ? 1 : 0);
74145
74392
  }
74146
74393
  function createTempEvalRepo() {
74147
- const dir = join77(tmpdir10(), `open-agents-eval-${Date.now()}`);
74394
+ const dir = join78(tmpdir10(), `open-agents-eval-${Date.now()}`);
74148
74395
  mkdirSync32(dir, { recursive: true });
74149
- writeFileSync30(join77(dir, "package.json"), JSON.stringify({ name: "eval-repo", version: "0.0.0" }, null, 2) + "\n", "utf8");
74396
+ writeFileSync30(join78(dir, "package.json"), JSON.stringify({ name: "eval-repo", version: "0.0.0" }, null, 2) + "\n", "utf8");
74150
74397
  return dir;
74151
74398
  }
74152
74399
  var BASIC_SUITE, FULL_SUITE, SUITES;
@@ -74206,7 +74453,7 @@ init_updater();
74206
74453
  import { parseArgs as nodeParseArgs2 } from "node:util";
74207
74454
  import { createRequire as createRequire5 } from "node:module";
74208
74455
  import { fileURLToPath as fileURLToPath15 } from "node:url";
74209
- import { dirname as dirname23, join as join78 } from "node:path";
74456
+ import { dirname as dirname23, join as join79 } from "node:path";
74210
74457
 
74211
74458
  // packages/cli/dist/cli.js
74212
74459
  import { createInterface } from "node:readline";
@@ -74313,7 +74560,7 @@ init_output();
74313
74560
  function getVersion5() {
74314
74561
  try {
74315
74562
  const require2 = createRequire5(import.meta.url);
74316
- const pkgPath = join78(dirname23(fileURLToPath15(import.meta.url)), "..", "package.json");
74563
+ const pkgPath = join79(dirname23(fileURLToPath15(import.meta.url)), "..", "package.json");
74317
74564
  const pkg = require2(pkgPath);
74318
74565
  return pkg.version;
74319
74566
  } catch {
@@ -74589,11 +74836,11 @@ function crashLog(label, err) {
74589
74836
  `;
74590
74837
  try {
74591
74838
  const { appendFileSync: appendFileSync6, mkdirSync: mkdirSync33 } = __require("node:fs");
74592
- const { join: join79 } = __require("node:path");
74839
+ const { join: join80 } = __require("node:path");
74593
74840
  const { homedir: homedir21 } = __require("node:os");
74594
- const logDir = join79(homedir21(), ".open-agents");
74841
+ const logDir = join80(homedir21(), ".open-agents");
74595
74842
  mkdirSync33(logDir, { recursive: true });
74596
- appendFileSync6(join79(logDir, "crash.log"), logLine);
74843
+ appendFileSync6(join80(logDir, "crash.log"), logLine);
74597
74844
  } catch {
74598
74845
  }
74599
74846
  try {