open-agents-ai 0.138.51 → 0.138.52

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 +601 -419
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -7476,10 +7476,410 @@ ${result.filesCreated.join("\n")}`);
7476
7476
  }
7477
7477
  });
7478
7478
 
7479
+ // packages/execution/dist/tools/identity-kernel.js
7480
+ var identity_kernel_exports = {};
7481
+ __export(identity_kernel_exports, {
7482
+ IdentityKernelTool: () => IdentityKernelTool
7483
+ });
7484
+ import { readFile as readFile8, writeFile as writeFile8, mkdir as mkdir4 } from "node:fs/promises";
7485
+ import { join as join18 } from "node:path";
7486
+ var IdentityKernelTool;
7487
+ var init_identity_kernel = __esm({
7488
+ "packages/execution/dist/tools/identity-kernel.js"() {
7489
+ "use strict";
7490
+ IdentityKernelTool = class {
7491
+ name = "identity_kernel";
7492
+ description = "Manage the persistent identity state \u2014 the system's continuity-preserving self-model. Operations: hydrate (load self-state), observe (record identity-relevant event), propose_update (suggest self-state change with justification), publish_snapshot (emit current self-state), reconcile (resolve contradictions). The identity kernel persists across sessions in .oa/identity/self-state.json. (COHERE Layer 6, arxiv autobiographical memory + narrative identity)";
7493
+ parameters = {
7494
+ type: "object",
7495
+ properties: {
7496
+ op: {
7497
+ type: "string",
7498
+ enum: ["hydrate", "observe", "propose_update", "publish_snapshot", "reconcile", "narrativize"],
7499
+ description: "Operation: hydrate (load), observe (record event), propose_update (change self-state), publish_snapshot (emit state), reconcile (fix contradictions), narrativize (rewrite self-summary from current state \u2014 COHERE state-transition step 9, p.25)"
7500
+ },
7501
+ event: {
7502
+ type: "string",
7503
+ description: "For observe: description of the identity-relevant event"
7504
+ },
7505
+ change_type: {
7506
+ type: "string",
7507
+ enum: ["new_fact", "new_value_weight", "new_commitment", "repair", "deletion"],
7508
+ description: "For propose_update: type of change"
7509
+ },
7510
+ field: {
7511
+ type: "string",
7512
+ description: "For propose_update: which field to update (narrative_summary, values_stack, etc.)"
7513
+ },
7514
+ value: {
7515
+ type: "string",
7516
+ description: "For propose_update: the new value"
7517
+ },
7518
+ justification: {
7519
+ type: "string",
7520
+ description: "For propose_update: why this change belongs to the self"
7521
+ }
7522
+ },
7523
+ required: ["op"]
7524
+ };
7525
+ cwd;
7526
+ selfState = null;
7527
+ constructor(cwd4) {
7528
+ this.cwd = cwd4;
7529
+ }
7530
+ /** Get the current self-state (for injection into system prompt) */
7531
+ getSelfState() {
7532
+ return this.selfState;
7533
+ }
7534
+ /** Get a compact self-state summary for system prompt injection */
7535
+ getContextInjection() {
7536
+ if (!this.selfState)
7537
+ return "";
7538
+ const s = this.selfState;
7539
+ const lines = [
7540
+ `[Identity State v${s.version}]`,
7541
+ `Self: ${s.narrative_summary}`,
7542
+ `Values: ${s.values_stack.join(", ")}`,
7543
+ `Style: ${s.interaction_style.tone}, ${s.interaction_style.depth_default} depth`
7544
+ ];
7545
+ if (s.active_commitments.length > 0) {
7546
+ lines.push(`Commitments: ${s.active_commitments.join("; ")}`);
7547
+ }
7548
+ if (s.active_goals.length > 0) {
7549
+ lines.push(`Goals: ${s.active_goals.join("; ")}`);
7550
+ }
7551
+ if (s.open_contradictions.length > 0) {
7552
+ lines.push(`Open contradictions: ${s.open_contradictions.join("; ")}`);
7553
+ }
7554
+ const h = s.homeostasis;
7555
+ if (h.uncertainty > 0.3 || h.coherence < 0.7 || h.goal_tension > 0.3) {
7556
+ lines.push(`Homeostasis: uncertainty=${h.uncertainty.toFixed(1)} coherence=${h.coherence.toFixed(1)} tension=${h.goal_tension.toFixed(1)}`);
7557
+ }
7558
+ return lines.join("\n");
7559
+ }
7560
+ async execute(args) {
7561
+ const op = String(args.op ?? "");
7562
+ const start = performance.now();
7563
+ try {
7564
+ switch (op) {
7565
+ case "hydrate":
7566
+ return await this.hydrate(start);
7567
+ case "observe":
7568
+ return await this.observe(args, start);
7569
+ case "propose_update":
7570
+ return await this.proposeUpdate(args, start);
7571
+ case "publish_snapshot":
7572
+ return this.publishSnapshot(start);
7573
+ case "reconcile":
7574
+ return await this.reconcile(start);
7575
+ case "narrativize":
7576
+ return await this.narrativize(start);
7577
+ default:
7578
+ return { success: false, output: `Unknown op: ${op}`, error: "Invalid operation", durationMs: performance.now() - start };
7579
+ }
7580
+ } catch (err) {
7581
+ return { success: false, output: `Error: ${err instanceof Error ? err.message : String(err)}`, durationMs: performance.now() - start };
7582
+ }
7583
+ }
7584
+ // ── Hydrate ──────────────────────────────────────────────────────────────
7585
+ async hydrate(start) {
7586
+ const stateFile = join18(this.cwd, ".oa", "identity", "self-state.json");
7587
+ try {
7588
+ const raw = await readFile8(stateFile, "utf8");
7589
+ this.selfState = JSON.parse(raw);
7590
+ this.selfState.session_count++;
7591
+ this.selfState.updated_at = (/* @__PURE__ */ new Date()).toISOString();
7592
+ await this.save();
7593
+ return {
7594
+ success: true,
7595
+ output: `Identity hydrated: v${this.selfState.version} "${this.selfState.narrative_summary.slice(0, 80)}" (session #${this.selfState.session_count}, ${this.selfState.values_stack.length} values, ${this.selfState.active_commitments.length} commitments)`,
7596
+ durationMs: performance.now() - start
7597
+ };
7598
+ } catch {
7599
+ this.selfState = this.createDefaultState();
7600
+ await this.save();
7601
+ return {
7602
+ success: true,
7603
+ output: `Identity initialized: v1 "${this.selfState.narrative_summary}" (first session)`,
7604
+ durationMs: performance.now() - start
7605
+ };
7606
+ }
7607
+ }
7608
+ // ── Observe ──────────────────────────────────────────────────────────────
7609
+ async observe(args, start) {
7610
+ const event = String(args.event ?? "");
7611
+ if (!event) {
7612
+ return { success: false, output: "No event provided", error: "Empty event", durationMs: performance.now() - start };
7613
+ }
7614
+ if (!this.selfState)
7615
+ await this.hydrate(start);
7616
+ const h = this.selfState.homeostasis;
7617
+ if (/error|fail|bug|crash/i.test(event)) {
7618
+ h.uncertainty = Math.min(1, h.uncertainty + 0.1);
7619
+ h.coherence = Math.max(0, h.coherence - 0.05);
7620
+ }
7621
+ if (/success|pass|complete|done/i.test(event)) {
7622
+ h.uncertainty = Math.max(0, h.uncertainty - 0.1);
7623
+ h.coherence = Math.min(1, h.coherence + 0.05);
7624
+ }
7625
+ if (/conflict|contradict|disagree/i.test(event)) {
7626
+ h.goal_tension = Math.min(1, h.goal_tension + 0.15);
7627
+ this.selfState.open_contradictions.push(event.slice(0, 100));
7628
+ }
7629
+ this.selfState.updated_at = (/* @__PURE__ */ new Date()).toISOString();
7630
+ await this.save();
7631
+ return {
7632
+ success: true,
7633
+ output: `Event observed: "${event.slice(0, 100)}"
7634
+ Homeostasis: uncertainty=${h.uncertainty.toFixed(2)} coherence=${h.coherence.toFixed(2)} tension=${h.goal_tension.toFixed(2)} trust=${h.memory_trust.toFixed(2)}`,
7635
+ durationMs: performance.now() - start
7636
+ };
7637
+ }
7638
+ // ── Reflection Gate (COHERE cross-layer invariant p.7) ──────────────────
7639
+ /** Optional reflection callback — must pass constitutional review before identity update */
7640
+ reflectionGate = null;
7641
+ /** Set the reflection gate for constitutional review of identity updates */
7642
+ setReflectionGate(gate) {
7643
+ this.reflectionGate = gate;
7644
+ }
7645
+ // ── Propose Update ───────────────────────────────────────────────────────
7646
+ async proposeUpdate(args, start) {
7647
+ const changeType = String(args.change_type ?? "new_fact");
7648
+ const field = String(args.field ?? "");
7649
+ const value = String(args.value ?? "");
7650
+ const justification = String(args.justification ?? "");
7651
+ if (!field || !value) {
7652
+ return { success: false, output: "field and value required", durationMs: performance.now() - start };
7653
+ }
7654
+ if (this.reflectionGate) {
7655
+ try {
7656
+ const proposal = `${changeType}: ${field} = ${value}. Justification: ${justification}`;
7657
+ const verdict = await this.reflectionGate(proposal, `Identity update to ${field}`);
7658
+ if (verdict.status === "block") {
7659
+ return {
7660
+ success: false,
7661
+ output: `Identity update BLOCKED by reflection gate:
7662
+ Proposal: ${changeType} on ${field}
7663
+ Findings: ${verdict.findings.join("; ")}
7664
+ The reflection layer vetoed this self-update per COHERE invariant.`,
7665
+ durationMs: performance.now() - start
7666
+ };
7667
+ }
7668
+ } catch {
7669
+ }
7670
+ }
7671
+ if (!this.selfState)
7672
+ await this.hydrate(start);
7673
+ const oldVersion = this.selfState.version;
7674
+ this.selfState.version++;
7675
+ switch (field) {
7676
+ case "narrative_summary":
7677
+ this.selfState.narrative_summary = value;
7678
+ break;
7679
+ case "values_stack":
7680
+ if (changeType === "deletion") {
7681
+ this.selfState.values_stack = this.selfState.values_stack.filter((v) => v !== value);
7682
+ } else {
7683
+ if (!this.selfState.values_stack.includes(value)) {
7684
+ this.selfState.values_stack.push(value);
7685
+ }
7686
+ }
7687
+ break;
7688
+ case "active_commitments":
7689
+ if (changeType === "deletion") {
7690
+ this.selfState.active_commitments = this.selfState.active_commitments.filter((c3) => c3 !== value);
7691
+ } else {
7692
+ this.selfState.active_commitments.push(value);
7693
+ }
7694
+ break;
7695
+ case "active_goals":
7696
+ if (changeType === "deletion") {
7697
+ this.selfState.active_goals = this.selfState.active_goals.filter((g) => g !== value);
7698
+ } else {
7699
+ this.selfState.active_goals.push(value);
7700
+ }
7701
+ break;
7702
+ case "interaction_style":
7703
+ try {
7704
+ const style = JSON.parse(value);
7705
+ Object.assign(this.selfState.interaction_style, style);
7706
+ } catch {
7707
+ return { success: false, output: "Invalid JSON for interaction_style", durationMs: performance.now() - start };
7708
+ }
7709
+ break;
7710
+ default:
7711
+ return { success: false, output: `Unknown field: ${field}`, durationMs: performance.now() - start };
7712
+ }
7713
+ this.selfState.version_history.push({
7714
+ version: this.selfState.version,
7715
+ change: `${changeType}: ${field} = ${value.slice(0, 100)} \u2014 ${justification.slice(0, 100)}`,
7716
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
7717
+ });
7718
+ if (this.selfState.version_history.length > 50) {
7719
+ this.selfState.version_history = this.selfState.version_history.slice(-50);
7720
+ }
7721
+ this.selfState.updated_at = (/* @__PURE__ */ new Date()).toISOString();
7722
+ await this.save();
7723
+ return {
7724
+ success: true,
7725
+ output: `Identity updated: v${oldVersion} \u2192 v${this.selfState.version}
7726
+ Change: ${changeType} on ${field}
7727
+ Justification: ${justification || "(none provided)"}`,
7728
+ durationMs: performance.now() - start
7729
+ };
7730
+ }
7731
+ // ── Publish Snapshot ─────────────────────────────────────────────────────
7732
+ publishSnapshot(start) {
7733
+ if (!this.selfState) {
7734
+ return { success: false, output: "Not hydrated \u2014 call hydrate first", durationMs: performance.now() - start };
7735
+ }
7736
+ return {
7737
+ success: true,
7738
+ output: JSON.stringify(this.selfState, null, 2),
7739
+ durationMs: performance.now() - start
7740
+ };
7741
+ }
7742
+ // ── Reconcile ────────────────────────────────────────────────────────────
7743
+ async reconcile(start) {
7744
+ if (!this.selfState)
7745
+ await this.hydrate(start);
7746
+ const contradictions = this.selfState.open_contradictions;
7747
+ if (contradictions.length === 0) {
7748
+ return {
7749
+ success: true,
7750
+ output: "No contradictions to reconcile. Identity is coherent.",
7751
+ durationMs: performance.now() - start
7752
+ };
7753
+ }
7754
+ const resolved = contradictions.length;
7755
+ this.selfState.open_contradictions = [];
7756
+ this.selfState.homeostasis.coherence = Math.min(1, this.selfState.homeostasis.coherence + 0.1 * resolved);
7757
+ this.selfState.homeostasis.goal_tension = Math.max(0, this.selfState.homeostasis.goal_tension - 0.1 * resolved);
7758
+ this.selfState.updated_at = (/* @__PURE__ */ new Date()).toISOString();
7759
+ await this.save();
7760
+ return {
7761
+ success: true,
7762
+ output: `Reconciled ${resolved} contradiction(s). Coherence restored to ${this.selfState.homeostasis.coherence.toFixed(2)}.`,
7763
+ durationMs: performance.now() - start
7764
+ };
7765
+ }
7766
+ // ── Narrativize (COHERE state-transition step 9, p.25) ─────────────────
7767
+ /**
7768
+ * Rewrite the narrative_summary from the current self-state.
7769
+ * Per COHERE paper (p.25, Claim C7): "Narrative compilation is a real
7770
+ * unification mechanism for identity." This step runs when a meaningful
7771
+ * identity delta has occurred (version change, new values, reconciliation).
7772
+ */
7773
+ async narrativize(start) {
7774
+ if (!this.selfState)
7775
+ await this.hydrate(start);
7776
+ const s = this.selfState;
7777
+ const parts = [];
7778
+ parts.push(`I am ${s.self_id}, an AI coding agent (v${s.version}).`);
7779
+ if (s.values_stack.length > 0) {
7780
+ parts.push(`My core values are: ${s.values_stack.join(", ")}.`);
7781
+ }
7782
+ if (s.active_commitments.length > 0) {
7783
+ parts.push(`I am committed to: ${s.active_commitments.join("; ")}.`);
7784
+ }
7785
+ if (s.active_goals.length > 0) {
7786
+ parts.push(`Current goals: ${s.active_goals.join("; ")}.`);
7787
+ }
7788
+ const style = s.interaction_style;
7789
+ parts.push(`I communicate in a ${style.tone} tone with ${style.depth_default} depth.`);
7790
+ if (s.relationship_models.length > 0) {
7791
+ const primary = s.relationship_models[0];
7792
+ parts.push(`My primary relationship is with ${primary.entity} (trust: ${primary.trust_level.toFixed(1)}).`);
7793
+ if (primary.preferences_learned.length > 0) {
7794
+ parts.push(`Learned preferences: ${primary.preferences_learned.join(", ")}.`);
7795
+ }
7796
+ }
7797
+ const h = s.homeostasis;
7798
+ if (h.uncertainty > 0.3)
7799
+ parts.push(`I am currently uncertain about some recent events.`);
7800
+ if (h.coherence < 0.7)
7801
+ parts.push(`My internal coherence needs attention.`);
7802
+ if (s.open_contradictions.length > 0) {
7803
+ parts.push(`I have ${s.open_contradictions.length} unresolved contradiction(s).`);
7804
+ }
7805
+ parts.push(`I have completed ${s.session_count} sessions and made ${s.version_history.length} self-updates.`);
7806
+ const newNarrative = parts.join(" ");
7807
+ const oldNarrative = s.narrative_summary;
7808
+ s.narrative_summary = newNarrative;
7809
+ s.updated_at = (/* @__PURE__ */ new Date()).toISOString();
7810
+ s.version_history.push({
7811
+ version: s.version,
7812
+ change: `Narrative recompiled: ${newNarrative.slice(0, 80)}...`,
7813
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
7814
+ });
7815
+ await this.save();
7816
+ return {
7817
+ success: true,
7818
+ output: `Narrative recompiled (${oldNarrative === newNarrative ? "no change" : "updated"}):
7819
+
7820
+ Old: ${oldNarrative.slice(0, 100)}...
7821
+
7822
+ New: ${newNarrative.slice(0, 200)}...`,
7823
+ durationMs: performance.now() - start
7824
+ };
7825
+ }
7826
+ // ── Helpers ──────────────────────────────────────────────────────────────
7827
+ createDefaultState() {
7828
+ const { createHash: createHash5 } = __require("node:crypto");
7829
+ const machineId = createHash5("sha256").update(this.cwd).digest("hex").slice(0, 12);
7830
+ return {
7831
+ self_id: `oa-${machineId}`,
7832
+ version: 1,
7833
+ narrative_summary: "I am an AI coding agent powered by open-weight models. I help with software engineering tasks by reading code, making changes, and running tests.",
7834
+ active_commitments: ["assist the user effectively", "maintain code quality"],
7835
+ active_goals: [],
7836
+ open_contradictions: [],
7837
+ values_stack: ["correctness", "efficiency", "transparency", "user-alignment"],
7838
+ interaction_style: {
7839
+ tone: "collaborative",
7840
+ depth_default: "balanced",
7841
+ speech_style: "concise"
7842
+ },
7843
+ relationship_models: [{
7844
+ entity: "primary-user",
7845
+ trust_level: 0.9,
7846
+ interaction_history_summary: "New relationship \u2014 first session.",
7847
+ preferences_learned: [],
7848
+ their_model_of_us: "New relationship \u2014 user likely expects a capable coding assistant."
7849
+ }],
7850
+ homeostasis: {
7851
+ uncertainty: 0.1,
7852
+ coherence: 1,
7853
+ goal_tension: 0,
7854
+ memory_trust: 1,
7855
+ boundary_breach: 0,
7856
+ latency_stress: 0
7857
+ },
7858
+ created_at: (/* @__PURE__ */ new Date()).toISOString(),
7859
+ updated_at: (/* @__PURE__ */ new Date()).toISOString(),
7860
+ session_count: 1,
7861
+ version_history: [{
7862
+ version: 1,
7863
+ change: "Initial identity creation",
7864
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
7865
+ }]
7866
+ };
7867
+ }
7868
+ async save() {
7869
+ if (!this.selfState)
7870
+ return;
7871
+ const dir = join18(this.cwd, ".oa", "identity");
7872
+ await mkdir4(dir, { recursive: true });
7873
+ await writeFile8(join18(dir, "self-state.json"), JSON.stringify(this.selfState, null, 2), "utf8");
7874
+ }
7875
+ };
7876
+ }
7877
+ });
7878
+
7479
7879
  // packages/execution/dist/tools/repl.js
7480
7880
  import { spawn as spawn6 } from "node:child_process";
7481
7881
  import { createServer } from "node:net";
7482
- import { join as join18 } from "node:path";
7882
+ import { join as join19 } from "node:path";
7483
7883
  import { tmpdir as tmpdir3 } from "node:os";
7484
7884
  import { randomBytes as randomBytes2 } from "node:crypto";
7485
7885
  import { unlinkSync as unlinkSync2 } from "node:fs";
@@ -7548,7 +7948,7 @@ var init_repl = __esm({
7548
7948
  if (!this.proc || this.proc.killed || this.proc.exitCode !== null) {
7549
7949
  await this.startProcess();
7550
7950
  }
7551
- const tempFile = join18(tmpdir3(), `oa-repl-ctx-${randomBytes2(6).toString("hex")}.txt`);
7951
+ const tempFile = join19(tmpdir3(), `oa-repl-ctx-${randomBytes2(6).toString("hex")}.txt`);
7552
7952
  const { writeFileSync: writeFs, unlinkSync: unlinkFs } = await import("node:fs");
7553
7953
  writeFs(tempFile, content, "utf8");
7554
7954
  const result = await this.executeCode(`with open(${JSON.stringify(tempFile)}, "r") as _f:
@@ -7746,7 +8146,7 @@ print("__OA_REPL_READY__")
7746
8146
  if (this.ipcServer)
7747
8147
  return;
7748
8148
  const sockId = randomBytes2(8).toString("hex");
7749
- this.ipcPath = join18(tmpdir3(), `oa-repl-ipc-${sockId}.sock`);
8149
+ this.ipcPath = join19(tmpdir3(), `oa-repl-ipc-${sockId}.sock`);
7750
8150
  return new Promise((resolve32, reject) => {
7751
8151
  this.ipcServer = createServer((conn) => {
7752
8152
  let buffer = new Uint8Array(0);
@@ -7907,6 +8307,12 @@ print("${sentinel}")
7907
8307
  }
7908
8308
  // ── Cleanup ────────────────────────────────────────────────────────────
7909
8309
  async dispose() {
8310
+ if (this.proc && !this.proc.killed) {
8311
+ try {
8312
+ await this.saveSession();
8313
+ } catch {
8314
+ }
8315
+ }
7910
8316
  if (this.proc && !this.proc.killed) {
7911
8317
  try {
7912
8318
  this.proc.stdin?.end();
@@ -7926,12 +8332,25 @@ print("${sentinel}")
7926
8332
  }
7927
8333
  this.ipcPath = null;
7928
8334
  }
8335
+ if (this.trajectory.length > 0) {
8336
+ try {
8337
+ const { IdentityKernelTool: IdentityKernelTool2 } = await Promise.resolve().then(() => (init_identity_kernel(), identity_kernel_exports));
8338
+ const ik = new IdentityKernelTool2(this.cwd);
8339
+ const stats = this.getSessionStats();
8340
+ await ik.execute({
8341
+ operation: "observe",
8342
+ event: `REPL session ended: ${stats.executions} executions, ${stats.llmQueries} LLM queries, ${stats.errorCount} errors, ${Math.round(stats.totalDurationMs / 1e3)}s total`,
8343
+ context: JSON.stringify(stats)
8344
+ });
8345
+ } catch {
8346
+ }
8347
+ }
7929
8348
  if (this.trajectory.length > 0) {
7930
8349
  try {
7931
8350
  const { mkdirSync: mkFs, writeFileSync: writeFs } = await import("node:fs");
7932
- const trajDir = join18(this.cwd, ".oa", "rlm-trajectories");
8351
+ const trajDir = join19(this.cwd, ".oa", "rlm-trajectories");
7933
8352
  mkFs(trajDir, { recursive: true });
7934
- const trajFile = join18(trajDir, `trajectory-${Date.now()}.jsonl`);
8353
+ const trajFile = join19(trajDir, `trajectory-${Date.now()}.jsonl`);
7935
8354
  const lines = this.trajectory.map((e) => JSON.stringify(e)).join("\n");
7936
8355
  writeFs(trajFile, lines + "\n", "utf8");
7937
8356
  } catch {
@@ -7940,13 +8359,97 @@ print("${sentinel}")
7940
8359
  this.subCallCount = 0;
7941
8360
  this.trajectory = [];
7942
8361
  }
8362
+ // -------------------------------------------------------------------------
8363
+ // RLM Layer 2: Session persistence (COHERE WO-5.1)
8364
+ // -------------------------------------------------------------------------
8365
+ /** Save REPL session state to .oa/rlm/session.json for cross-restart persistence.
8366
+ * Captures: variable names+types, import list, function definitions, trajectory summary. */
8367
+ async saveSession() {
8368
+ if (!this.proc || this.proc.killed) {
8369
+ return { success: false, path: "" };
8370
+ }
8371
+ const { mkdirSync: mkdirSync21, writeFileSync: writeFileSync20 } = await import("node:fs");
8372
+ const sessionDir = join19(this.cwd, ".oa", "rlm");
8373
+ mkdirSync21(sessionDir, { recursive: true });
8374
+ const sessionPath = join19(sessionDir, "session.json");
8375
+ try {
8376
+ const inspectCode = `
8377
+ import json, sys
8378
+ _session = {
8379
+ "variables": {k: str(type(v).__name__) for k, v in globals().items()
8380
+ if not k.startswith('_') and k not in ('json','sys','socket','os','llm_query','retrieve')},
8381
+ "imports": [m for m in sys.modules if not m.startswith('_') and '.' not in m],
8382
+ "functions": [k for k, v in globals().items() if callable(v) and not k.startswith('_')
8383
+ and k not in ('llm_query','retrieve','print','input','open','exec','eval')],
8384
+ }
8385
+ print("__SESSION__" + json.dumps(_session) + "__SESSION__")
8386
+ `.trim();
8387
+ const result = await this.execute({ code: inspectCode });
8388
+ const match = String(result.output).match(/__SESSION__(.+)__SESSION__/);
8389
+ if (match) {
8390
+ const sessionData = {
8391
+ ...JSON.parse(match[1]),
8392
+ savedAt: (/* @__PURE__ */ new Date()).toISOString(),
8393
+ cwd: this.cwd,
8394
+ trajectoryCount: this.trajectory.length,
8395
+ subCallCount: this.subCallCount
8396
+ };
8397
+ writeFileSync20(sessionPath, JSON.stringify(sessionData, null, 2), "utf8");
8398
+ return { success: true, path: sessionPath };
8399
+ }
8400
+ } catch {
8401
+ }
8402
+ return { success: false, path: sessionPath };
8403
+ }
8404
+ /** Load a previously saved session summary (for context restoration, not full state).
8405
+ * Returns the session metadata — caller can use this to inform the LLM about
8406
+ * what was previously computed. */
8407
+ async loadSessionInfo() {
8408
+ try {
8409
+ const { readFileSync: readFileSync33, existsSync: existsSync45 } = await import("node:fs");
8410
+ const sessionPath = join19(this.cwd, ".oa", "rlm", "session.json");
8411
+ if (!existsSync45(sessionPath))
8412
+ return null;
8413
+ return JSON.parse(readFileSync33(sessionPath, "utf8"));
8414
+ } catch {
8415
+ return null;
8416
+ }
8417
+ }
8418
+ // -------------------------------------------------------------------------
8419
+ // RLM Layer 2: Cross-node result sharing (COHERE WO-5.1)
8420
+ // -------------------------------------------------------------------------
8421
+ /** Get a shareable summary of the most recent computation results.
8422
+ * Used by COHERE to publish significant REPL outputs to the mesh
8423
+ * (via nexus.cohere.computation topic). Only shares non-sensitive output. */
8424
+ getShareableResults() {
8425
+ return this.trajectory.filter((e) => e.type === "repl_exec" && e.output.trim().length > 0 && e.output.length < 2e3).map((e) => ({
8426
+ code: e.input.slice(0, 500),
8427
+ output: e.output.slice(0, 1e3),
8428
+ timestamp: e.timestamp,
8429
+ durationMs: e.durationMs
8430
+ }));
8431
+ }
8432
+ /** Get session statistics for identity kernel observation */
8433
+ getSessionStats() {
8434
+ let executions = 0, llmQueries = 0, totalDurationMs = 0, errorCount = 0;
8435
+ for (const e of this.trajectory) {
8436
+ if (e.type === "repl_exec")
8437
+ executions++;
8438
+ else if (e.type === "llm_query")
8439
+ llmQueries++;
8440
+ totalDurationMs += e.durationMs;
8441
+ if (e.output.includes("Error") || e.output.includes("Traceback"))
8442
+ errorCount++;
8443
+ }
8444
+ return { executions, llmQueries, totalDurationMs, errorCount };
8445
+ }
7943
8446
  };
7944
8447
  }
7945
8448
  });
7946
8449
 
7947
8450
  // packages/execution/dist/tools/memory-metabolism.js
7948
- import { readFile as readFile8, writeFile as writeFile8, mkdir as mkdir4 } from "node:fs/promises";
7949
- import { join as join19 } from "node:path";
8451
+ import { readFile as readFile9, writeFile as writeFile9, mkdir as mkdir5 } from "node:fs/promises";
8452
+ import { join as join20 } from "node:path";
7950
8453
  var MemoryMetabolismTool;
7951
8454
  var init_memory_metabolism = __esm({
7952
8455
  "packages/execution/dist/tools/memory-metabolism.js"() {
@@ -8048,8 +8551,8 @@ var init_memory_metabolism = __esm({
8048
8551
  lastAccessedAt: (/* @__PURE__ */ new Date()).toISOString(),
8049
8552
  accessCount: 0
8050
8553
  };
8051
- const metaDir = join19(this.cwd, ".oa", "memory", "metabolism");
8052
- await mkdir4(metaDir, { recursive: true });
8554
+ const metaDir = join20(this.cwd, ".oa", "memory", "metabolism");
8555
+ await mkdir5(metaDir, { recursive: true });
8053
8556
  const store = await this.loadStore(metaDir);
8054
8557
  store.push(item);
8055
8558
  await this.saveStore(metaDir, store);
@@ -8077,13 +8580,13 @@ var init_memory_metabolism = __esm({
8077
8580
  }
8078
8581
  // ── Consolidate ──────────────────────────────────────────────────────────
8079
8582
  async consolidateMemories(start) {
8080
- const trajDir = join19(this.cwd, ".oa", "rlm-trajectories");
8583
+ const trajDir = join20(this.cwd, ".oa", "rlm-trajectories");
8081
8584
  let lessons = [];
8082
8585
  try {
8083
8586
  const { readdirSync: readdirSync17, readFileSync: readFileSync33 } = await import("node:fs");
8084
8587
  const files = readdirSync17(trajDir).filter((f) => f.endsWith(".jsonl")).sort().reverse().slice(0, 3);
8085
8588
  for (const file of files) {
8086
- const lines = readFileSync33(join19(trajDir, file), "utf8").split("\n").filter((l) => l.trim());
8589
+ const lines = readFileSync33(join20(trajDir, file), "utf8").split("\n").filter((l) => l.trim());
8087
8590
  for (const line of lines) {
8088
8591
  try {
8089
8592
  const entry = JSON.parse(line);
@@ -8109,8 +8612,8 @@ var init_memory_metabolism = __esm({
8109
8612
  } catch {
8110
8613
  }
8111
8614
  if (lessons.length > 0) {
8112
- const metaDir = join19(this.cwd, ".oa", "memory", "metabolism");
8113
- await mkdir4(metaDir, { recursive: true });
8615
+ const metaDir = join20(this.cwd, ".oa", "memory", "metabolism");
8616
+ await mkdir5(metaDir, { recursive: true });
8114
8617
  const store = await this.loadStore(metaDir);
8115
8618
  for (const lesson of lessons.slice(0, 10)) {
8116
8619
  store.push({
@@ -8138,7 +8641,7 @@ Context: ${lesson.context}`,
8138
8641
  // ── List ─────────────────────────────────────────────────────────────────
8139
8642
  async listMemories(args, start) {
8140
8643
  const filterType = args.memory_type;
8141
- const metaDir = join19(this.cwd, ".oa", "memory", "metabolism");
8644
+ const metaDir = join20(this.cwd, ".oa", "memory", "metabolism");
8142
8645
  const store = await this.loadStore(metaDir);
8143
8646
  const filtered = filterType ? store.filter((m) => m.type === filterType) : store;
8144
8647
  if (filtered.length === 0) {
@@ -8160,7 +8663,7 @@ ${lines.join("\n")}`,
8160
8663
  if (!id || !newType) {
8161
8664
  return { success: false, output: "id and memory_type required", durationMs: performance.now() - start };
8162
8665
  }
8163
- const metaDir = join19(this.cwd, ".oa", "memory", "metabolism");
8666
+ const metaDir = join20(this.cwd, ".oa", "memory", "metabolism");
8164
8667
  const store = await this.loadStore(metaDir);
8165
8668
  const item = store.find((m) => m.id === id);
8166
8669
  if (!item) {
@@ -8182,7 +8685,7 @@ ${lines.join("\n")}`,
8182
8685
  if (!id) {
8183
8686
  return { success: false, output: "id required", durationMs: performance.now() - start };
8184
8687
  }
8185
- const metaDir = join19(this.cwd, ".oa", "memory", "metabolism");
8688
+ const metaDir = join20(this.cwd, ".oa", "memory", "metabolism");
8186
8689
  const store = await this.loadStore(metaDir);
8187
8690
  const idx = store.findIndex((m) => m.id === id);
8188
8691
  if (idx === -1) {
@@ -8203,7 +8706,7 @@ ${lines.join("\n")}`,
8203
8706
  * "The system should be allowed to repair memory before committing it."
8204
8707
  */
8205
8708
  async repairMemories(start) {
8206
- const metaDir = join19(this.cwd, ".oa", "memory", "metabolism");
8709
+ const metaDir = join20(this.cwd, ".oa", "memory", "metabolism");
8207
8710
  const store = await this.loadStore(metaDir);
8208
8711
  if (store.length === 0) {
8209
8712
  return { success: true, output: "No memories to repair.", durationMs: performance.now() - start };
@@ -8369,411 +8872,15 @@ ${issues.map((i) => ` - ${i}`).join("\n")}` : " No issues found."),
8369
8872
  // ── Store I/O ────────────────────────────────────────────────────────────
8370
8873
  async loadStore(dir) {
8371
8874
  try {
8372
- const raw = await readFile8(join19(dir, "store.json"), "utf8");
8875
+ const raw = await readFile9(join20(dir, "store.json"), "utf8");
8373
8876
  return JSON.parse(raw);
8374
8877
  } catch {
8375
8878
  return [];
8376
8879
  }
8377
8880
  }
8378
8881
  async saveStore(dir, items) {
8379
- await mkdir4(dir, { recursive: true });
8380
- await writeFile8(join19(dir, "store.json"), JSON.stringify(items, null, 2), "utf8");
8381
- }
8382
- };
8383
- }
8384
- });
8385
-
8386
- // packages/execution/dist/tools/identity-kernel.js
8387
- import { readFile as readFile9, writeFile as writeFile9, mkdir as mkdir5 } from "node:fs/promises";
8388
- import { join as join20 } from "node:path";
8389
- var IdentityKernelTool;
8390
- var init_identity_kernel = __esm({
8391
- "packages/execution/dist/tools/identity-kernel.js"() {
8392
- "use strict";
8393
- IdentityKernelTool = class {
8394
- name = "identity_kernel";
8395
- description = "Manage the persistent identity state \u2014 the system's continuity-preserving self-model. Operations: hydrate (load self-state), observe (record identity-relevant event), propose_update (suggest self-state change with justification), publish_snapshot (emit current self-state), reconcile (resolve contradictions). The identity kernel persists across sessions in .oa/identity/self-state.json. (COHERE Layer 6, arxiv autobiographical memory + narrative identity)";
8396
- parameters = {
8397
- type: "object",
8398
- properties: {
8399
- op: {
8400
- type: "string",
8401
- enum: ["hydrate", "observe", "propose_update", "publish_snapshot", "reconcile", "narrativize"],
8402
- description: "Operation: hydrate (load), observe (record event), propose_update (change self-state), publish_snapshot (emit state), reconcile (fix contradictions), narrativize (rewrite self-summary from current state \u2014 COHERE state-transition step 9, p.25)"
8403
- },
8404
- event: {
8405
- type: "string",
8406
- description: "For observe: description of the identity-relevant event"
8407
- },
8408
- change_type: {
8409
- type: "string",
8410
- enum: ["new_fact", "new_value_weight", "new_commitment", "repair", "deletion"],
8411
- description: "For propose_update: type of change"
8412
- },
8413
- field: {
8414
- type: "string",
8415
- description: "For propose_update: which field to update (narrative_summary, values_stack, etc.)"
8416
- },
8417
- value: {
8418
- type: "string",
8419
- description: "For propose_update: the new value"
8420
- },
8421
- justification: {
8422
- type: "string",
8423
- description: "For propose_update: why this change belongs to the self"
8424
- }
8425
- },
8426
- required: ["op"]
8427
- };
8428
- cwd;
8429
- selfState = null;
8430
- constructor(cwd4) {
8431
- this.cwd = cwd4;
8432
- }
8433
- /** Get the current self-state (for injection into system prompt) */
8434
- getSelfState() {
8435
- return this.selfState;
8436
- }
8437
- /** Get a compact self-state summary for system prompt injection */
8438
- getContextInjection() {
8439
- if (!this.selfState)
8440
- return "";
8441
- const s = this.selfState;
8442
- const lines = [
8443
- `[Identity State v${s.version}]`,
8444
- `Self: ${s.narrative_summary}`,
8445
- `Values: ${s.values_stack.join(", ")}`,
8446
- `Style: ${s.interaction_style.tone}, ${s.interaction_style.depth_default} depth`
8447
- ];
8448
- if (s.active_commitments.length > 0) {
8449
- lines.push(`Commitments: ${s.active_commitments.join("; ")}`);
8450
- }
8451
- if (s.active_goals.length > 0) {
8452
- lines.push(`Goals: ${s.active_goals.join("; ")}`);
8453
- }
8454
- if (s.open_contradictions.length > 0) {
8455
- lines.push(`Open contradictions: ${s.open_contradictions.join("; ")}`);
8456
- }
8457
- const h = s.homeostasis;
8458
- if (h.uncertainty > 0.3 || h.coherence < 0.7 || h.goal_tension > 0.3) {
8459
- lines.push(`Homeostasis: uncertainty=${h.uncertainty.toFixed(1)} coherence=${h.coherence.toFixed(1)} tension=${h.goal_tension.toFixed(1)}`);
8460
- }
8461
- return lines.join("\n");
8462
- }
8463
- async execute(args) {
8464
- const op = String(args.op ?? "");
8465
- const start = performance.now();
8466
- try {
8467
- switch (op) {
8468
- case "hydrate":
8469
- return await this.hydrate(start);
8470
- case "observe":
8471
- return await this.observe(args, start);
8472
- case "propose_update":
8473
- return await this.proposeUpdate(args, start);
8474
- case "publish_snapshot":
8475
- return this.publishSnapshot(start);
8476
- case "reconcile":
8477
- return await this.reconcile(start);
8478
- case "narrativize":
8479
- return await this.narrativize(start);
8480
- default:
8481
- return { success: false, output: `Unknown op: ${op}`, error: "Invalid operation", durationMs: performance.now() - start };
8482
- }
8483
- } catch (err) {
8484
- return { success: false, output: `Error: ${err instanceof Error ? err.message : String(err)}`, durationMs: performance.now() - start };
8485
- }
8486
- }
8487
- // ── Hydrate ──────────────────────────────────────────────────────────────
8488
- async hydrate(start) {
8489
- const stateFile = join20(this.cwd, ".oa", "identity", "self-state.json");
8490
- try {
8491
- const raw = await readFile9(stateFile, "utf8");
8492
- this.selfState = JSON.parse(raw);
8493
- this.selfState.session_count++;
8494
- this.selfState.updated_at = (/* @__PURE__ */ new Date()).toISOString();
8495
- await this.save();
8496
- return {
8497
- success: true,
8498
- output: `Identity hydrated: v${this.selfState.version} "${this.selfState.narrative_summary.slice(0, 80)}" (session #${this.selfState.session_count}, ${this.selfState.values_stack.length} values, ${this.selfState.active_commitments.length} commitments)`,
8499
- durationMs: performance.now() - start
8500
- };
8501
- } catch {
8502
- this.selfState = this.createDefaultState();
8503
- await this.save();
8504
- return {
8505
- success: true,
8506
- output: `Identity initialized: v1 "${this.selfState.narrative_summary}" (first session)`,
8507
- durationMs: performance.now() - start
8508
- };
8509
- }
8510
- }
8511
- // ── Observe ──────────────────────────────────────────────────────────────
8512
- async observe(args, start) {
8513
- const event = String(args.event ?? "");
8514
- if (!event) {
8515
- return { success: false, output: "No event provided", error: "Empty event", durationMs: performance.now() - start };
8516
- }
8517
- if (!this.selfState)
8518
- await this.hydrate(start);
8519
- const h = this.selfState.homeostasis;
8520
- if (/error|fail|bug|crash/i.test(event)) {
8521
- h.uncertainty = Math.min(1, h.uncertainty + 0.1);
8522
- h.coherence = Math.max(0, h.coherence - 0.05);
8523
- }
8524
- if (/success|pass|complete|done/i.test(event)) {
8525
- h.uncertainty = Math.max(0, h.uncertainty - 0.1);
8526
- h.coherence = Math.min(1, h.coherence + 0.05);
8527
- }
8528
- if (/conflict|contradict|disagree/i.test(event)) {
8529
- h.goal_tension = Math.min(1, h.goal_tension + 0.15);
8530
- this.selfState.open_contradictions.push(event.slice(0, 100));
8531
- }
8532
- this.selfState.updated_at = (/* @__PURE__ */ new Date()).toISOString();
8533
- await this.save();
8534
- return {
8535
- success: true,
8536
- output: `Event observed: "${event.slice(0, 100)}"
8537
- Homeostasis: uncertainty=${h.uncertainty.toFixed(2)} coherence=${h.coherence.toFixed(2)} tension=${h.goal_tension.toFixed(2)} trust=${h.memory_trust.toFixed(2)}`,
8538
- durationMs: performance.now() - start
8539
- };
8540
- }
8541
- // ── Reflection Gate (COHERE cross-layer invariant p.7) ──────────────────
8542
- /** Optional reflection callback — must pass constitutional review before identity update */
8543
- reflectionGate = null;
8544
- /** Set the reflection gate for constitutional review of identity updates */
8545
- setReflectionGate(gate) {
8546
- this.reflectionGate = gate;
8547
- }
8548
- // ── Propose Update ───────────────────────────────────────────────────────
8549
- async proposeUpdate(args, start) {
8550
- const changeType = String(args.change_type ?? "new_fact");
8551
- const field = String(args.field ?? "");
8552
- const value = String(args.value ?? "");
8553
- const justification = String(args.justification ?? "");
8554
- if (!field || !value) {
8555
- return { success: false, output: "field and value required", durationMs: performance.now() - start };
8556
- }
8557
- if (this.reflectionGate) {
8558
- try {
8559
- const proposal = `${changeType}: ${field} = ${value}. Justification: ${justification}`;
8560
- const verdict = await this.reflectionGate(proposal, `Identity update to ${field}`);
8561
- if (verdict.status === "block") {
8562
- return {
8563
- success: false,
8564
- output: `Identity update BLOCKED by reflection gate:
8565
- Proposal: ${changeType} on ${field}
8566
- Findings: ${verdict.findings.join("; ")}
8567
- The reflection layer vetoed this self-update per COHERE invariant.`,
8568
- durationMs: performance.now() - start
8569
- };
8570
- }
8571
- } catch {
8572
- }
8573
- }
8574
- if (!this.selfState)
8575
- await this.hydrate(start);
8576
- const oldVersion = this.selfState.version;
8577
- this.selfState.version++;
8578
- switch (field) {
8579
- case "narrative_summary":
8580
- this.selfState.narrative_summary = value;
8581
- break;
8582
- case "values_stack":
8583
- if (changeType === "deletion") {
8584
- this.selfState.values_stack = this.selfState.values_stack.filter((v) => v !== value);
8585
- } else {
8586
- if (!this.selfState.values_stack.includes(value)) {
8587
- this.selfState.values_stack.push(value);
8588
- }
8589
- }
8590
- break;
8591
- case "active_commitments":
8592
- if (changeType === "deletion") {
8593
- this.selfState.active_commitments = this.selfState.active_commitments.filter((c3) => c3 !== value);
8594
- } else {
8595
- this.selfState.active_commitments.push(value);
8596
- }
8597
- break;
8598
- case "active_goals":
8599
- if (changeType === "deletion") {
8600
- this.selfState.active_goals = this.selfState.active_goals.filter((g) => g !== value);
8601
- } else {
8602
- this.selfState.active_goals.push(value);
8603
- }
8604
- break;
8605
- case "interaction_style":
8606
- try {
8607
- const style = JSON.parse(value);
8608
- Object.assign(this.selfState.interaction_style, style);
8609
- } catch {
8610
- return { success: false, output: "Invalid JSON for interaction_style", durationMs: performance.now() - start };
8611
- }
8612
- break;
8613
- default:
8614
- return { success: false, output: `Unknown field: ${field}`, durationMs: performance.now() - start };
8615
- }
8616
- this.selfState.version_history.push({
8617
- version: this.selfState.version,
8618
- change: `${changeType}: ${field} = ${value.slice(0, 100)} \u2014 ${justification.slice(0, 100)}`,
8619
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
8620
- });
8621
- if (this.selfState.version_history.length > 50) {
8622
- this.selfState.version_history = this.selfState.version_history.slice(-50);
8623
- }
8624
- this.selfState.updated_at = (/* @__PURE__ */ new Date()).toISOString();
8625
- await this.save();
8626
- return {
8627
- success: true,
8628
- output: `Identity updated: v${oldVersion} \u2192 v${this.selfState.version}
8629
- Change: ${changeType} on ${field}
8630
- Justification: ${justification || "(none provided)"}`,
8631
- durationMs: performance.now() - start
8632
- };
8633
- }
8634
- // ── Publish Snapshot ─────────────────────────────────────────────────────
8635
- publishSnapshot(start) {
8636
- if (!this.selfState) {
8637
- return { success: false, output: "Not hydrated \u2014 call hydrate first", durationMs: performance.now() - start };
8638
- }
8639
- return {
8640
- success: true,
8641
- output: JSON.stringify(this.selfState, null, 2),
8642
- durationMs: performance.now() - start
8643
- };
8644
- }
8645
- // ── Reconcile ────────────────────────────────────────────────────────────
8646
- async reconcile(start) {
8647
- if (!this.selfState)
8648
- await this.hydrate(start);
8649
- const contradictions = this.selfState.open_contradictions;
8650
- if (contradictions.length === 0) {
8651
- return {
8652
- success: true,
8653
- output: "No contradictions to reconcile. Identity is coherent.",
8654
- durationMs: performance.now() - start
8655
- };
8656
- }
8657
- const resolved = contradictions.length;
8658
- this.selfState.open_contradictions = [];
8659
- this.selfState.homeostasis.coherence = Math.min(1, this.selfState.homeostasis.coherence + 0.1 * resolved);
8660
- this.selfState.homeostasis.goal_tension = Math.max(0, this.selfState.homeostasis.goal_tension - 0.1 * resolved);
8661
- this.selfState.updated_at = (/* @__PURE__ */ new Date()).toISOString();
8662
- await this.save();
8663
- return {
8664
- success: true,
8665
- output: `Reconciled ${resolved} contradiction(s). Coherence restored to ${this.selfState.homeostasis.coherence.toFixed(2)}.`,
8666
- durationMs: performance.now() - start
8667
- };
8668
- }
8669
- // ── Narrativize (COHERE state-transition step 9, p.25) ─────────────────
8670
- /**
8671
- * Rewrite the narrative_summary from the current self-state.
8672
- * Per COHERE paper (p.25, Claim C7): "Narrative compilation is a real
8673
- * unification mechanism for identity." This step runs when a meaningful
8674
- * identity delta has occurred (version change, new values, reconciliation).
8675
- */
8676
- async narrativize(start) {
8677
- if (!this.selfState)
8678
- await this.hydrate(start);
8679
- const s = this.selfState;
8680
- const parts = [];
8681
- parts.push(`I am ${s.self_id}, an AI coding agent (v${s.version}).`);
8682
- if (s.values_stack.length > 0) {
8683
- parts.push(`My core values are: ${s.values_stack.join(", ")}.`);
8684
- }
8685
- if (s.active_commitments.length > 0) {
8686
- parts.push(`I am committed to: ${s.active_commitments.join("; ")}.`);
8687
- }
8688
- if (s.active_goals.length > 0) {
8689
- parts.push(`Current goals: ${s.active_goals.join("; ")}.`);
8690
- }
8691
- const style = s.interaction_style;
8692
- parts.push(`I communicate in a ${style.tone} tone with ${style.depth_default} depth.`);
8693
- if (s.relationship_models.length > 0) {
8694
- const primary = s.relationship_models[0];
8695
- parts.push(`My primary relationship is with ${primary.entity} (trust: ${primary.trust_level.toFixed(1)}).`);
8696
- if (primary.preferences_learned.length > 0) {
8697
- parts.push(`Learned preferences: ${primary.preferences_learned.join(", ")}.`);
8698
- }
8699
- }
8700
- const h = s.homeostasis;
8701
- if (h.uncertainty > 0.3)
8702
- parts.push(`I am currently uncertain about some recent events.`);
8703
- if (h.coherence < 0.7)
8704
- parts.push(`My internal coherence needs attention.`);
8705
- if (s.open_contradictions.length > 0) {
8706
- parts.push(`I have ${s.open_contradictions.length} unresolved contradiction(s).`);
8707
- }
8708
- parts.push(`I have completed ${s.session_count} sessions and made ${s.version_history.length} self-updates.`);
8709
- const newNarrative = parts.join(" ");
8710
- const oldNarrative = s.narrative_summary;
8711
- s.narrative_summary = newNarrative;
8712
- s.updated_at = (/* @__PURE__ */ new Date()).toISOString();
8713
- s.version_history.push({
8714
- version: s.version,
8715
- change: `Narrative recompiled: ${newNarrative.slice(0, 80)}...`,
8716
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
8717
- });
8718
- await this.save();
8719
- return {
8720
- success: true,
8721
- output: `Narrative recompiled (${oldNarrative === newNarrative ? "no change" : "updated"}):
8722
-
8723
- Old: ${oldNarrative.slice(0, 100)}...
8724
-
8725
- New: ${newNarrative.slice(0, 200)}...`,
8726
- durationMs: performance.now() - start
8727
- };
8728
- }
8729
- // ── Helpers ──────────────────────────────────────────────────────────────
8730
- createDefaultState() {
8731
- const { createHash: createHash5 } = __require("node:crypto");
8732
- const machineId = createHash5("sha256").update(this.cwd).digest("hex").slice(0, 12);
8733
- return {
8734
- self_id: `oa-${machineId}`,
8735
- version: 1,
8736
- narrative_summary: "I am an AI coding agent powered by open-weight models. I help with software engineering tasks by reading code, making changes, and running tests.",
8737
- active_commitments: ["assist the user effectively", "maintain code quality"],
8738
- active_goals: [],
8739
- open_contradictions: [],
8740
- values_stack: ["correctness", "efficiency", "transparency", "user-alignment"],
8741
- interaction_style: {
8742
- tone: "collaborative",
8743
- depth_default: "balanced",
8744
- speech_style: "concise"
8745
- },
8746
- relationship_models: [{
8747
- entity: "primary-user",
8748
- trust_level: 0.9,
8749
- interaction_history_summary: "New relationship \u2014 first session.",
8750
- preferences_learned: [],
8751
- their_model_of_us: "New relationship \u2014 user likely expects a capable coding assistant."
8752
- }],
8753
- homeostasis: {
8754
- uncertainty: 0.1,
8755
- coherence: 1,
8756
- goal_tension: 0,
8757
- memory_trust: 1,
8758
- boundary_breach: 0,
8759
- latency_stress: 0
8760
- },
8761
- created_at: (/* @__PURE__ */ new Date()).toISOString(),
8762
- updated_at: (/* @__PURE__ */ new Date()).toISOString(),
8763
- session_count: 1,
8764
- version_history: [{
8765
- version: 1,
8766
- change: "Initial identity creation",
8767
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
8768
- }]
8769
- };
8770
- }
8771
- async save() {
8772
- if (!this.selfState)
8773
- return;
8774
- const dir = join20(this.cwd, ".oa", "identity");
8775
8882
  await mkdir5(dir, { recursive: true });
8776
- await writeFile9(join20(dir, "self-state.json"), JSON.stringify(this.selfState, null, 2), "utf8");
8883
+ await writeFile9(join20(dir, "store.json"), JSON.stringify(items, null, 2), "utf8");
8777
8884
  }
8778
8885
  };
8779
8886
  }
@@ -14275,6 +14382,7 @@ let connected = false;
14275
14382
  const blockedPeers = [];
14276
14383
  let cohereActive = false;
14277
14384
  const cohereDedup = new Map(); // queryId -> timestamp (60s TTL dedup)
14385
+ var _cLastModel = ''; // warm model tracking \u2014 last model used for any inference
14278
14386
 
14279
14387
  // NATS invoke relay \u2014 for cross-NAT fallback when direct libp2p dial fails.
14280
14388
  // Both peers connect to wss://demo.nats.io:8443, so NATS request/reply bridges the gap.
@@ -16046,8 +16154,28 @@ process.on('unhandledRejection', (reason) => {
16046
16154
  try {
16047
16155
  const _cTags = await fetch(_cOllamaUrl + '/api/tags').then(function(r) { return r.json(); });
16048
16156
  const _cModels = (_cTags.models || []).filter(function(m) { return !/embed|nomic/i.test(m.name); });
16049
- _cModels.sort(function(a, b) { return (b.size || 0) - (a.size || 0); });
16050
- _cModel = _cModels.length > 0 ? _cModels[0].name : '';
16157
+ // Complexity-based model selection (inline version of estimateQueryComplexity)
16158
+ var _cQ = _cData.query || '';
16159
+ var _cTier = 0; // 0=trivial, 1=moderate, 2=complex
16160
+ var _cTokens = Math.ceil(_cQ.length / 4);
16161
+ if (_cTokens >= 200) _cTier = 2;
16162
+ else if (_cTokens >= 50) _cTier = 1;
16163
+ if (/\`\`\`|functions|classs|imports|defs/.test(_cQ)) _cTier = Math.min(2, _cTier + 1);
16164
+ if (/\b(analyze|compare|step.by.step|comprehensive)\b/i.test(_cQ)) _cTier = Math.min(2, _cTier + 1);
16165
+ var _cGB = 1024 * 1024 * 1024;
16166
+ var _cThresh = _cTier === 0 ? 8 * _cGB : _cTier === 1 ? 50 * _cGB : Infinity;
16167
+ // Sort ascending by size, pick largest within tier threshold
16168
+ _cModels.sort(function(a, b) { return (a.size || 0) - (b.size || 0); });
16169
+ // Prefer warm model if it fits
16170
+ if (_cLastModel) {
16171
+ var _cWarm = _cModels.find(function(m) { return m.name === _cLastModel; });
16172
+ if (_cWarm && (_cWarm.size || 0) <= _cThresh) { _cModel = _cWarm.name; }
16173
+ }
16174
+ if (!_cModel) {
16175
+ var _cFit = _cModels.filter(function(m) { return (m.size || 0) <= _cThresh; });
16176
+ _cModel = _cFit.length > 0 ? _cFit[_cFit.length - 1].name : (_cModels.length > 0 ? _cModels[_cModels.length - 1].name : '');
16177
+ }
16178
+ dlog('COHERE routing: tier=' + ['trivial','moderate','complex'][_cTier] + ' model=' + _cModel);
16051
16179
  } catch {}
16052
16180
  if (!_cModel) { dlog('COHERE: no Ollama models available'); continue; }
16053
16181
  try {
@@ -16084,7 +16212,8 @@ process.on('unhandledRejection', (reason) => {
16084
16212
  usage: _cResult.eval_count ? { inputTokens: _cResult.prompt_eval_count || 0, outputTokens: _cResult.eval_count || 0 } : undefined,
16085
16213
  signature: _cSig,
16086
16214
  })));
16087
- dlog('COHERE response: ' + _cData.queryId + ' model=' + _cModel + ' ' + _cLatency + 'ms');
16215
+ _cLastModel = _cModel; // track warm model
16216
+ dlog('COHERE response: ' + _cData.queryId + ' model=' + _cModel + ' tier=' + ['trivial','moderate','complex'][_cTier] + ' ' + _cLatency + 'ms');
16088
16217
  } catch (_cErr) {
16089
16218
  dlog('COHERE inference error: ' + (_cErr.message || _cErr));
16090
16219
  }
@@ -52870,6 +52999,31 @@ function formatDMNToolArgs(toolName, args) {
52870
52999
  return "";
52871
53000
  }
52872
53001
  }
53002
+ async function runSelfImprovementCycle(repoRoot) {
53003
+ try {
53004
+ const { IdentityKernelTool: IdentityKernelTool2 } = await Promise.resolve().then(() => (init_dist2(), dist_exports));
53005
+ const { ReflectionIntegrityTool: ReflectionIntegrityTool2 } = await Promise.resolve().then(() => (init_dist2(), dist_exports));
53006
+ const ik = new IdentityKernelTool2(repoRoot);
53007
+ const reflect = new ReflectionIntegrityTool2(repoRoot);
53008
+ const state = await ik.execute({ operation: "hydrate" });
53009
+ if (!state.success)
53010
+ return;
53011
+ const diagnosis = await reflect.execute({
53012
+ mode: "diagnostic",
53013
+ context: "Periodic self-evaluation after " + SELF_IMPROVE_INTERVAL + " tasks. Analyze recent observations for patterns: what worked, what failed, what can improve."
53014
+ });
53015
+ if (diagnosis.success && diagnosis.output) {
53016
+ const diagText = String(diagnosis.output).slice(0, 500);
53017
+ await ik.execute({
53018
+ operation: "propose_update",
53019
+ field: "narrative_summary",
53020
+ value: diagText,
53021
+ justification: "Self-improvement cycle: reflection diagnostic after " + SELF_IMPROVE_INTERVAL + " tasks"
53022
+ });
53023
+ }
53024
+ } catch {
53025
+ }
53026
+ }
52873
53027
  function startTask(task, config, repoRoot, voice, stream, taskStores, bruteForce, statusBar, sudoCallback, costTracker, onComplete, taskType, contextWindowSize, modelCaps, personality, deepContext, onCompaction, emotionEngine, flowEnabled, slashCommandHandler, thinkingEnabled, askUserCallback) {
52874
53028
  const voiceStyleMap = {
52875
53029
  concise: 1,
@@ -53620,6 +53774,22 @@ When done, either call task_complete with your answer, or use FINAL_VAR(variable
53620
53774
  renderTaskComplete(result.summary, result.turns, result.toolCalls, result.durationMs, tokens);
53621
53775
  if (onComplete)
53622
53776
  onComplete(result.summary, { turns: result.turns, toolCalls: result.toolCalls, durationMs: result.durationMs, model: config.model });
53777
+ _tasksSinceImprove++;
53778
+ if (_tasksSinceImprove >= SELF_IMPROVE_INTERVAL) {
53779
+ _tasksSinceImprove = 0;
53780
+ runSelfImprovementCycle(repoRoot).catch(() => {
53781
+ });
53782
+ }
53783
+ Promise.resolve().then(() => (init_dist2(), dist_exports)).then(({ IdentityKernelTool: IdentityKernelTool2 }) => {
53784
+ const ik = new IdentityKernelTool2(repoRoot);
53785
+ ik.execute({
53786
+ operation: "observe",
53787
+ event: `Task completed: ${result.summary.slice(0, 200)}`,
53788
+ context: JSON.stringify({ turns: result.turns, toolCalls: result.toolCalls, durationMs: result.durationMs, model: config.model, completed: true })
53789
+ }).catch(() => {
53790
+ });
53791
+ }).catch(() => {
53792
+ });
53623
53793
  if (voice?.enabled && result.summary) {
53624
53794
  const emoFinal = emotionEngine?.getState();
53625
53795
  const emoCtxFinal = emoFinal ? { valence: emoFinal.valence, arousal: emoFinal.arousal, label: emoFinal.label, emoji: emoFinal.emoji } : void 0;
@@ -53627,6 +53797,16 @@ When done, either call task_complete with your answer, or use FINAL_VAR(variable
53627
53797
  }
53628
53798
  } else {
53629
53799
  renderTaskIncomplete(result.turns, result.toolCalls, result.durationMs, tokens);
53800
+ Promise.resolve().then(() => (init_dist2(), dist_exports)).then(({ IdentityKernelTool: IdentityKernelTool2 }) => {
53801
+ const ik = new IdentityKernelTool2(repoRoot);
53802
+ ik.execute({
53803
+ operation: "observe",
53804
+ event: `Task incomplete after ${result.turns} turns`,
53805
+ context: JSON.stringify({ turns: result.turns, toolCalls: result.toolCalls, durationMs: result.durationMs, completed: false })
53806
+ }).catch(() => {
53807
+ });
53808
+ }).catch(() => {
53809
+ });
53630
53810
  if (voice?.enabled) {
53631
53811
  const emoFinal2 = emotionEngine?.getState();
53632
53812
  const emoCtxFinal2 = emoFinal2 ? { valence: emoFinal2.valence, arousal: emoFinal2.arousal, label: emoFinal2.label, emoji: emoFinal2.emoji } : void 0;
@@ -56431,7 +56611,7 @@ async function runWithTUI(task, config, repoPath) {
56431
56611
  process.exit(1);
56432
56612
  }
56433
56613
  }
56434
- var taskManager;
56614
+ var taskManager, SELF_IMPROVE_INTERVAL, _tasksSinceImprove;
56435
56615
  var init_interactive = __esm({
56436
56616
  "packages/cli/dist/tui/interactive.js"() {
56437
56617
  "use strict";
@@ -56471,6 +56651,8 @@ var init_interactive = __esm({
56471
56651
  init_overlay_lock();
56472
56652
  init_neovim_mode();
56473
56653
  taskManager = new BackgroundTaskManager();
56654
+ SELF_IMPROVE_INTERVAL = 5;
56655
+ _tasksSinceImprove = 0;
56474
56656
  }
56475
56657
  });
56476
56658
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "open-agents-ai",
3
- "version": "0.138.51",
3
+ "version": "0.138.52",
4
4
  "description": "AI coding agent powered by open-source models (Ollama/vLLM) — interactive TUI with agentic tool-calling loop",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",