operon-agents-core 0.1.0-alpha.16 → 0.1.0-alpha.18

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 (74) hide show
  1. package/dist/agent/compose-hooks.js +6 -1
  2. package/dist/agent/durable-state.d.ts +22 -0
  3. package/dist/agent/durable-state.js +54 -0
  4. package/dist/agent/run-support.js +1 -1
  5. package/dist/agent/runner.js +34 -16
  6. package/dist/agent/session.d.ts +68 -15
  7. package/dist/agent/session.js +190 -50
  8. package/dist/agent/subagent-tools.js +3 -3
  9. package/dist/agent/subagent.js +28 -13
  10. package/dist/capabilities/background/manager.js +1 -1
  11. package/dist/capabilities/capability-data.d.ts +8 -8
  12. package/dist/capabilities/capability-data.js +5 -5
  13. package/dist/capabilities/capability-state.d.ts +3 -15
  14. package/dist/capabilities/capability-state.js +5 -44
  15. package/dist/capabilities/capability.d.ts +47 -5
  16. package/dist/capabilities/goal/goal-store.d.ts +42 -12
  17. package/dist/capabilities/goal/goal-store.js +55 -53
  18. package/dist/capabilities/goal/index.d.ts +1 -1
  19. package/dist/capabilities/goal/index.js +19 -6
  20. package/dist/capabilities/plan/index.js +10 -3
  21. package/dist/capabilities/plan/plan-mode.d.ts +16 -6
  22. package/dist/capabilities/plan/plan-mode.js +28 -22
  23. package/dist/capabilities/plan/tools.js +1 -1
  24. package/dist/capabilities/todo/index.js +9 -5
  25. package/dist/capabilities/todo/todo-store.d.ts +13 -4
  26. package/dist/capabilities/todo/todo-store.js +21 -8
  27. package/dist/events/index.d.ts +2 -2
  28. package/dist/events/index.js +1 -1
  29. package/dist/events/projection.d.ts +49 -1
  30. package/dist/events/projection.js +130 -16
  31. package/dist/events/publisher.js +1 -2
  32. package/dist/index.d.ts +1 -1
  33. package/dist/loop/context.d.ts +21 -1
  34. package/dist/loop/context.js +41 -8
  35. package/dist/loop/run-turn.d.ts +2 -0
  36. package/dist/loop/run-turn.js +2 -1
  37. package/dist/loop/tool-call.d.ts +2 -0
  38. package/dist/loop/tool-call.js +2 -0
  39. package/dist/loop/turn-step.d.ts +2 -0
  40. package/dist/loop/turn-step.js +3 -3
  41. package/dist/loop/types.d.ts +6 -0
  42. package/dist/mcp/credentials.d.ts +35 -0
  43. package/dist/mcp/credentials.js +2 -0
  44. package/dist/mcp/index.d.ts +1 -0
  45. package/dist/mcp/manager.d.ts +7 -1
  46. package/dist/mcp/manager.js +35 -6
  47. package/dist/permission/manager.d.ts +2 -0
  48. package/dist/permission/manager.js +4 -0
  49. package/dist/store/catalog-store.d.ts +4 -1
  50. package/dist/store/catalog-store.js +5 -1
  51. package/dist/store/checkpointing-store.d.ts +41 -0
  52. package/dist/store/checkpointing-store.js +86 -0
  53. package/dist/store/disk-store.d.ts +8 -0
  54. package/dist/store/disk-store.js +127 -5
  55. package/dist/store/index.d.ts +3 -2
  56. package/dist/store/index.js +2 -1
  57. package/dist/store/log-store.d.ts +8 -0
  58. package/dist/store/log-store.js +67 -3
  59. package/dist/store/migrate.d.ts +8 -2
  60. package/dist/store/migrate.js +9 -2
  61. package/dist/store/pg.js +29 -2
  62. package/dist/store/redis.js +23 -0
  63. package/dist/store/repository.d.ts +9 -1
  64. package/dist/store/repository.js +22 -2
  65. package/dist/store/session-catalog.d.ts +4 -0
  66. package/dist/store/session-catalog.js +6 -0
  67. package/dist/store/store.d.ts +88 -22
  68. package/dist/store/store.js +53 -3
  69. package/dist/testing.d.ts +1 -1
  70. package/dist/testing.js +6 -3
  71. package/dist/tool/define.d.ts +14 -8
  72. package/dist/tool/define.js +8 -2
  73. package/dist/tool/types.d.ts +10 -3
  74. package/package.json +2 -2
@@ -89,8 +89,13 @@ function buildAuthorizer(state, context, tools) {
89
89
  if (answer) {
90
90
  // Audit record: this is the single chokepoint both live and durable approvals
91
91
  // flow through (the responder/resume answer is applied here).
92
- context.record({ type: "permission.record_approval", toolCallId: ctx.toolCall.id, toolName: ctx.toolCall.name, decision: answer.decision, feedback: answer.feedback, approvalRule: ctx.plan.approvalRule, scope: answer.scope });
92
+ context.audit({ type: "permission.record_approval", toolCallId: ctx.toolCall.id, toolName: ctx.toolCall.name, decision: answer.decision, feedback: answer.feedback, approvalRule: ctx.plan.approvalRule, scope: answer.scope });
93
+ // That record is this frame's audit trail. A session grant is the SESSION's state, so the
94
+ // session persists it — what a reopen restores from — whichever frame earned it.
95
+ const grants = answer.decision === "approved" && answer.scope === "session" && !state.permission.sessionGrants.includes(ctx.plan.approvalRule);
93
96
  const ok = state.permission.applyApproval(ctx.plan.approvalRule, answer);
97
+ if (grants)
98
+ state.session.persistPermissionState();
94
99
  if (ok)
95
100
  return undefined;
96
101
  return { block: true, reason: answer.feedback ?? `Tool ${ctx.toolCall.name} was ${answer.decision}.` };
@@ -0,0 +1,22 @@
1
+ import type { Logger } from "../logging/index.ts";
2
+ import type { SessionStore, StateKey } from "../store/index.ts";
3
+ /**
4
+ * Writes current-state values to the store's key/value side, one key at a time.
5
+ *
6
+ * A write reads its value (`read()`) when it RUNS, not when it is asked for, so asking again
7
+ * while a write is waiting to start changes nothing — that write will carry the newer value —
8
+ * and writes for one key land in the order they were asked for. Nothing here touches the log.
9
+ */
10
+ export declare class DurableStateWriter {
11
+ private readonly slots;
12
+ private readonly store;
13
+ private readonly logger;
14
+ constructor(store: SessionStore | undefined, logger: Logger);
15
+ /** Store `read()` under `key` (null/undefined removes it). See the class doc for ordering. */
16
+ write(key: StateKey, read: () => unknown): Promise<void>;
17
+ /** Settles once every write asked for `key` so far has finished (succeeded or failed). */
18
+ settled(key: StateKey): Promise<void>;
19
+ /** Settles once every write asked for so far has finished (succeeded or failed). */
20
+ flush(): Promise<void>;
21
+ }
22
+ //# sourceMappingURL=durable-state.d.ts.map
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Writes current-state values to the store's key/value side, one key at a time.
3
+ *
4
+ * A write reads its value (`read()`) when it RUNS, not when it is asked for, so asking again
5
+ * while a write is waiting to start changes nothing — that write will carry the newer value —
6
+ * and writes for one key land in the order they were asked for. Nothing here touches the log.
7
+ */
8
+ export class DurableStateWriter {
9
+ slots = new Map();
10
+ store;
11
+ logger;
12
+ constructor(store, logger) {
13
+ this.store = store;
14
+ this.logger = logger;
15
+ }
16
+ /** Store `read()` under `key` (null/undefined removes it). See the class doc for ordering. */
17
+ write(key, read) {
18
+ const store = this.store;
19
+ if (store === undefined)
20
+ return Promise.resolve();
21
+ let slot = this.slots.get(key);
22
+ if (slot === undefined) {
23
+ slot = { tail: Promise.resolve(), waiting: undefined };
24
+ this.slots.set(key, slot);
25
+ }
26
+ if (slot.waiting !== undefined)
27
+ return slot.waiting;
28
+ const current = slot;
29
+ const write = current.tail.then(async () => {
30
+ // Running now: a change from here on must be carried by a write after this one.
31
+ current.waiting = undefined;
32
+ const value = read();
33
+ if (value === undefined || value === null)
34
+ await store.deleteState(key);
35
+ else
36
+ await store.putState(key, value);
37
+ });
38
+ current.waiting = write;
39
+ current.tail = write.catch(() => undefined);
40
+ write.catch((error) => {
41
+ this.logger.log("warn", `failed to persist state "${key}"`, { error: error instanceof Error ? error.message : String(error) });
42
+ });
43
+ return write;
44
+ }
45
+ /** Settles once every write asked for `key` so far has finished (succeeded or failed). */
46
+ settled(key) {
47
+ return this.slots.get(key)?.tail ?? Promise.resolve();
48
+ }
49
+ /** Settles once every write asked for so far has finished (succeeded or failed). */
50
+ async flush() {
51
+ await Promise.all([...this.slots.values()].map((slot) => slot.tail));
52
+ }
53
+ }
54
+ //# sourceMappingURL=durable-state.js.map
@@ -54,7 +54,7 @@ export function historyChangeEmitter(events, sessionId) {
54
54
  case "context.apply_compaction":
55
55
  void events.emit({
56
56
  type: "history.compacted",
57
- cutoff: record.cutoff,
57
+ cutoff: record.compactedCount,
58
58
  summary: record.summary,
59
59
  summaryTimestamp: record.summaryTimestamp,
60
60
  ...(record.loadedTools !== undefined ? { loadedTools: record.loadedTools } : {}),
@@ -1,7 +1,7 @@
1
1
  import { addUsage, emptyUsage } from "../loop/usage.js";
2
2
  import { runTurn } from "../loop/run-turn.js";
3
3
  import { isAbortError } from "../loop/errors.js";
4
- import { ConversationContext, replayContext } from "../loop/context.js";
4
+ import { ConversationContext, readShardTail } from "../loop/context.js";
5
5
  import { PermissionManager } from "../permission/manager.js";
6
6
  import { assembleCapabilities } from "../capabilities/assembler.js";
7
7
  import { computeContextBreakdown } from "./context-report.js";
@@ -143,7 +143,7 @@ export class Runner {
143
143
  try {
144
144
  await store.putState(INTERRUPTION_STATE_KEY, updated);
145
145
  // History is the log's job — replay it (the active agent's shard) to rebuild context.
146
- context = await replayContext(store, rootFrame.address);
146
+ context = await session.openFrameContext(rootFrame.address);
147
147
  session.setLiveContext(rootFrame.address, context);
148
148
  }
149
149
  catch (error) {
@@ -238,13 +238,15 @@ export class Runner {
238
238
  throw new Error("Cannot continue session: handoff chain exceeds 64 transfers.");
239
239
  }
240
240
  visited.add(head.address);
241
- const records = [];
242
- for await (const record of store.readRecords({ address: head.address }))
243
- records.push(record);
244
- if (expectedAcceptance !== undefined &&
245
- !records.some((record) => record.type === "agent.handoff.accepted" &&
246
- record.handoffId === expectedAcceptance.handoffId &&
247
- record.fromAddress === expectedAcceptance.fromAddress)) {
241
+ // From the shard's newest checkpoint: a committed handoff freezes the shard, so it is
242
+ // always after the last checkpoint, and the tail is all the live context needs.
243
+ const records = await readShardTail(store, head.address);
244
+ const accepted = (from) => from.some((record) => record.type === "agent.handoff.accepted" &&
245
+ record.handoffId === expectedAcceptance.handoffId &&
246
+ record.fromAddress === expectedAcceptance.fromAddress);
247
+ // The acceptance opens the target shard, so a compaction there has since moved the
248
+ // tail past it: only then is the rest of the shard worth reading to find it.
249
+ if (expectedAcceptance !== undefined && !accepted(records) && !accepted(await readWholeShard(store, head.address))) {
248
250
  throw new Error(`Cannot continue session: handoff "${expectedAcceptance.handoffId}" points to uninitialized shard "${head.address}".`);
249
251
  }
250
252
  const committed = records.filter((record) => record.type === "agent.handoff" &&
@@ -254,12 +256,7 @@ export class Runner {
254
256
  // Reuse the leaf records we already read to seed the live cache; otherwise the caller
255
257
  // would immediately replay the same shard a second time before appending the prompt.
256
258
  if (session.liveContext(head.address) === undefined) {
257
- const context = new ConversationContext({
258
- store,
259
- address: head.address,
260
- });
261
- context.loadFromRecords(records);
262
- session.setLiveContext(head.address, context);
259
+ session.setLiveContext(head.address, await session.frameContextFrom(head.address, records));
263
260
  }
264
261
  break;
265
262
  }
@@ -324,7 +321,7 @@ export class Runner {
324
321
  }
325
322
  else {
326
323
  context = state.store
327
- ? await replayContext(state.store, state.address)
324
+ ? await session.openFrameContext(state.address)
328
325
  : new ConversationContext({
329
326
  store: state.store,
330
327
  address: state.address,
@@ -383,6 +380,7 @@ export class Runner {
383
380
  state.usage = addUsage(state.usage, error.usage);
384
381
  const activeContext = session.liveContext(state.address) ?? context;
385
382
  activeContext.record({ type: "usage.record", usage: error.usage, total: state.usage });
383
+ countSessionUsage(state, error.usage);
386
384
  if (state.store === undefined)
387
385
  void emitRunEvent(state, { type: "usage.updated", usage: state.usage });
388
386
  }
@@ -648,6 +646,7 @@ class Engine {
648
646
  // Per-address ledger: main agent and each subagent line keep independent
649
647
  // read-before-write state that survives across turns and run() calls.
650
648
  fileLedger: state.session.fileLedgerFor(state.address),
649
+ hostContext: state.context,
651
650
  system,
652
651
  context,
653
652
  tools: toolset.tools,
@@ -700,6 +699,7 @@ class Engine {
700
699
  state.usage = addUsage(state.usage, r.usage);
701
700
  // Audit record: per-turn cost, journaled in order with the message stream (not history).
702
701
  context.record({ type: "usage.record", model: model.id, usage: r.usage, total: state.usage });
702
+ countSessionUsage(state, r.usage);
703
703
  if (state.store === undefined)
704
704
  emitRunEvent(state, { type: "usage.updated", usage: state.usage });
705
705
  if (r.stopReason === "interrupt") {
@@ -807,10 +807,14 @@ class Engine {
807
807
  const result = await hook({
808
808
  turnId: `${state.sessionId}-t${state.turns}`,
809
809
  stepNumber: state.turns,
810
+ address: state.address,
810
811
  usage,
811
812
  stopReason: "end_turn",
812
813
  signal: state.signal,
813
814
  model,
815
+ // A child frame shares its parent's capabilities (`deriveChild`), so every
816
+ // continuation hook also sees subagent stops — this is how it tells them apart.
817
+ isRootAgent: state.parentFrameId === undefined,
814
818
  });
815
819
  if (result?.continue === true)
816
820
  return true;
@@ -855,4 +859,18 @@ function mergeSignals(a, b) {
855
859
  return a;
856
860
  return AbortSignal.any([a, b]);
857
861
  }
862
+ /**
863
+ * Add a turn's usage to the session's running total (`Session.usage`), for a ROOT frame only.
864
+ * A subagent's turns are audited in its own shard but are not the session's.
865
+ */
866
+ function countSessionUsage(state, usage) {
867
+ if (state.parentFrameId === undefined)
868
+ state.session.addSessionUsage(usage);
869
+ }
870
+ async function readWholeShard(store, address) {
871
+ const records = [];
872
+ for await (const record of store.readRecords({ address }))
873
+ records.push(record);
874
+ return records;
875
+ }
858
876
  //# sourceMappingURL=runner.js.map
@@ -11,6 +11,7 @@ import type { ContextBreakdown } from "./context-report.ts";
11
11
  import { type EventSink } from "../events/index.ts";
12
12
  import { type Logger } from "../logging/index.ts";
13
13
  import { type AgentRecord, type SessionStore } from "../store/index.ts";
14
+ import type { Usage } from "../protocol/index.ts";
14
15
  import { type TracingProcessor } from "../tracing/index.ts";
15
16
  import { ConversationContext } from "../loop/context.ts";
16
17
  import { SteerBus, type SteerContent, type SteerOptions, type SteerOrigin, type SteerReceipt } from "../loop/steer.ts";
@@ -65,12 +66,12 @@ export interface SessionOpenOptions {
65
66
  */
66
67
  readonly store?: SessionStore;
67
68
  /**
68
- * The session's full append log, pre-read by the caller. `open` then skips its own
69
- * `readLog` and every open-time consumer (log-fold capabilities, context pre-build)
70
- * folds THESE records — sharing the read AND the `Message` object graph with whatever
71
- * else the caller seeded from them (e.g. a `SessionProjection`), instead of holding a
72
- * second parsed+blob-rehydrated copy for the session's lifetime.
73
- * Must be the complete log (all addresses, append order) as `readRecords()` returns it.
69
+ * The session's log, pre-read by the caller: every shard from its newest checkpoint on
70
+ * (`readSessionTails`), or the whole log. `open` then reads no log itself — the context
71
+ * pre-build folds `main`'s records from THESE, sharing the read AND the `Message` object graph
72
+ * with whatever else the caller seeded from them (e.g. a `SessionProjection`). Without it,
73
+ * `open` reads only `main` from its newest checkpoint. State is read from the store's
74
+ * key/value side either way.
74
75
  */
75
76
  readonly preloadedLog?: readonly AgentRecord[];
76
77
  /** Reopened from a store (vs created fresh). Only telemetry cares; the stream cannot tell. */
@@ -162,6 +163,16 @@ export interface SessionPort {
162
163
  setConversationHead(head: ConversationHead): void;
163
164
  /** Register a forked frame's inbox; the returned function unregisters it. */
164
165
  registerFrameBus(address: string, bus: SteerBus): () => void;
166
+ /**
167
+ * Rebuild a frame's conversation from its shard to resume it — read from the shard's newest
168
+ * checkpoint, never its head — and restore the frame's own capability state (its todo list)
169
+ * from what is stored for its address. Requires a store.
170
+ */
171
+ openFrameContext(address: string): Promise<ConversationContext>;
172
+ /** Add one root-agent turn's usage to the session's running total and return the new total. */
173
+ addSessionUsage(usage: Usage): Usage;
174
+ /** Persist the session's runtime permission state after a grant was applied in memory. */
175
+ persistPermissionState(): void;
165
176
  }
166
177
  /**
167
178
  * Service access on a session has two tiers, one rule each:
@@ -230,6 +241,18 @@ export declare class Session implements SessionPort {
230
241
  private lastContextBreakdown?;
231
242
  /** Built at the end of `open`, once every capability's policies are in. */
232
243
  private permissionManager?;
244
+ /** The mode set at RUNTIME (`setPermissionMode`, or restored from one) — what is persisted.
245
+ * A mode that only came from the host's options is not session state: reopening with
246
+ * different options must still take effect. */
247
+ private explicitPermissionMode;
248
+ /** The root agent's usage across the session's whole life, stored as `session:usage`. */
249
+ private totalUsage;
250
+ /** Beneath the publisher: stamps checkpoints, and folds each shard's lifecycle for them. */
251
+ private readonly checkpointing;
252
+ /** Writes capability and session current state to the store's key/value side. */
253
+ private readonly durable;
254
+ /** Each stateful capability's `durableState`, by name — registered when it is restored. */
255
+ private readonly durableOwners;
233
256
  private constructor();
234
257
  /**
235
258
  * Open a session. Everything it depends on arrives in `opts`; `open` fills in the defaults for
@@ -246,12 +269,32 @@ export declare class Session implements SessionPort {
246
269
  */
247
270
  private openCapabilities;
248
271
  /**
249
- * Journal a capability's record into the main conversation. Through its live context when
250
- * there is one, so the record keeps its place in the context's write order; straight to the
251
- * store before the first run has built it. A storeless session with no context keeps nothing
252
- * durable — `records()` still sees the write, from memory.
272
+ * A shard's records from its newest checkpoint on. A checkpoint written without the shard's
273
+ * lifecycle (by a context outside any session) can restore history but not the open turn, so
274
+ * in that case the whole shard is read and the lifecycle is folded from its head.
275
+ */
276
+ private readShardForRestore;
277
+ private readWholeShard;
278
+ /**
279
+ * Restore `cap`'s state for `address` from the value stored for it. Any write of that value
280
+ * still in flight lands first, so the read is never older than what this process last wrote.
253
281
  */
254
- private appendToMain;
282
+ private restoreOwner;
283
+ /** `SessionContext.persistState` for capability `owner`. */
284
+ private persistOwnerState;
285
+ /** The session's runtime permission state as persisted: the runtime mode, and its grants. */
286
+ private permissionState;
287
+ addSessionUsage(usage: Usage): Usage;
288
+ /** The root agent's token usage across the session's whole life — every run, every reopen.
289
+ * Subagents' turns are not in it (each is audited in its own shard). */
290
+ get usage(): Usage | undefined;
291
+ openFrameContext(address: string): Promise<ConversationContext>;
292
+ /** @internal `openFrameContext` over records the caller already read (the shard from a
293
+ * checkpoint on, or whole). */
294
+ frameContextFrom(address: string, records: readonly AgentRecord[]): Promise<ConversationContext>;
295
+ /** Write a capability's record to the audit shard (about `main`). Best effort: a failure is
296
+ * logged, and `records()` still sees the write, from memory. */
297
+ private appendAuditRecord;
255
298
  /**
256
299
  * Open `capability` in this live session. With no run in flight that is immediate; otherwise it
257
300
  * waits for the last run to stop, so a run never sees its capability set change under it — the
@@ -278,11 +321,18 @@ export declare class Session implements SessionPort {
278
321
  * Construct the session-lived PermissionManager: capability policy slots are collected from
279
322
  * the opened capabilities' static `policies` (session-tier fault isolation: a capability whose
280
323
  * provision failed contributes nothing; a per-run `start()` failure does NOT retract its
281
- * policies — they are pure evaluators over session-lived state). Then runtime permission
282
- * state is folded back from the log — `permission.set_mode` (last wins) and approve-for-session
283
- * grants (`permission.record_approval` with scope "session").
324
+ * policies — they are pure evaluators over session-lived state). Then the runtime permission
325
+ * state stored for the session (`session:permission`) is applied over the host's options.
284
326
  */
285
327
  private buildPermissionManager;
328
+ private restorePermissionMode;
329
+ /**
330
+ * Persist the session's runtime permission state — after an approve-for-session grant, which
331
+ * is already applied in memory (`PermissionManager.applyApproval`); this is the durable half.
332
+ * Not awaited: a lost grant only means the user is asked again. The frame's
333
+ * `permission.record_approval` stays the audit record of who granted it.
334
+ */
335
+ persistPermissionState(): void;
286
336
  /** The session-lived permission manager (policy chain + mode + approval memory). Built by
287
337
  * `open` once every capability's policies are known; another session's manager is meaningless,
288
338
  * so it is a field rather than a registry entry. */
@@ -326,8 +376,11 @@ export declare class Session implements SessionPort {
326
376
  getContextBreakdown(): ContextBreakdown | undefined;
327
377
  /** Runner-internal: record the breakdown assembled for the turn about to be sent. */
328
378
  recordContextBreakdown(breakdown: ContextBreakdown): void;
329
- /** Every record of an address in append order (for rendering the transcript). */
379
+ /** Every record of an address in append order (for rendering the transcript). Without an
380
+ * address, every conversation shard — the audit shard is read with `getAuditRecords`. */
330
381
  getRecords(address?: string): Promise<AgentRecord[]>;
382
+ /** The audit shard's records in append order; each names the shard it concerns in `about`. */
383
+ getAuditRecords(): Promise<AgentRecord[]>;
331
384
  /** @internal The kept live context for an address, or undefined (cold → caller replays). */
332
385
  liveContext(address: string): ConversationContext | undefined;
333
386
  /** @internal Cache the live context so the next turn on this address reuses it. */