operon-agents-core 0.1.0-alpha.2 → 0.1.0-alpha.21

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 (289) hide show
  1. package/dist/agent/agent.d.ts +8 -7
  2. package/dist/agent/compose-hooks.d.ts +10 -1
  3. package/dist/agent/compose-hooks.js +61 -6
  4. package/dist/agent/concurrency.js +1 -1
  5. package/dist/agent/context-report.d.ts +2 -2
  6. package/dist/agent/durable-state.d.ts +22 -0
  7. package/dist/agent/durable-state.js +54 -0
  8. package/dist/agent/index.d.ts +2 -2
  9. package/dist/agent/index.js +1 -1
  10. package/dist/agent/instruction-context.d.ts +6 -6
  11. package/dist/agent/instruction-context.js +23 -23
  12. package/dist/agent/profile-builtins.js +1 -1
  13. package/dist/agent/run-support.d.ts +1 -1
  14. package/dist/agent/run-support.js +6 -5
  15. package/dist/agent/runner.d.ts +25 -22
  16. package/dist/agent/runner.js +217 -121
  17. package/dist/agent/session.d.ts +262 -156
  18. package/dist/agent/session.js +590 -418
  19. package/dist/agent/subagent-tools.js +3 -3
  20. package/dist/agent/subagent.js +28 -13
  21. package/dist/agent/toolset.d.ts +1 -0
  22. package/dist/agent/toolset.js +13 -7
  23. package/dist/agent/workflow/journal.d.ts +2 -2
  24. package/dist/agent/workflow/journal.js +2 -2
  25. package/dist/agent/workflow/manager.d.ts +1 -1
  26. package/dist/agent/workflow/manager.js +1 -1
  27. package/dist/agent/workflow/prompt.js +2 -2
  28. package/dist/agent/workflow/sandbox.d.ts +1 -1
  29. package/dist/agent/workflow/sandbox.js +1 -1
  30. package/dist/agent/workflow/tool.js +30 -43
  31. package/dist/agent/worktree.d.ts +8 -8
  32. package/dist/agent/worktree.js +15 -15
  33. package/dist/capabilities/assembler.d.ts +29 -5
  34. package/dist/capabilities/assembler.js +85 -9
  35. package/dist/capabilities/background/code-task.d.ts +43 -0
  36. package/dist/capabilities/background/code-task.js +75 -0
  37. package/dist/capabilities/background/command-task.d.ts +9 -2
  38. package/dist/capabilities/background/command-task.js +22 -6
  39. package/dist/capabilities/background/index.d.ts +6 -1
  40. package/dist/capabilities/background/index.js +26 -20
  41. package/dist/capabilities/background/manager.d.ts +57 -1
  42. package/dist/capabilities/background/manager.js +210 -45
  43. package/dist/capabilities/background/persist-disk.d.ts +1 -1
  44. package/dist/capabilities/background/persist-disk.js +1 -1
  45. package/dist/capabilities/background/persist.js +4 -2
  46. package/dist/capabilities/background/projections.d.ts +16 -0
  47. package/dist/capabilities/background/projections.js +86 -0
  48. package/dist/capabilities/background/stall-watchdog.d.ts +41 -0
  49. package/dist/capabilities/background/stall-watchdog.js +85 -0
  50. package/dist/capabilities/background/task.d.ts +8 -7
  51. package/dist/capabilities/background/tools.js +33 -7
  52. package/dist/capabilities/capability-data.d.ts +52 -0
  53. package/dist/capabilities/capability-data.js +88 -0
  54. package/dist/capabilities/capability-state.d.ts +2 -4
  55. package/dist/capabilities/capability-state.js +5 -23
  56. package/dist/capabilities/capability.d.ts +203 -38
  57. package/dist/capabilities/compaction/index.js +10 -4
  58. package/dist/capabilities/compaction/service.d.ts +20 -5
  59. package/dist/capabilities/compaction/service.js +27 -11
  60. package/dist/capabilities/goal/goal-store.d.ts +76 -12
  61. package/dist/capabilities/goal/goal-store.js +137 -53
  62. package/dist/capabilities/goal/index.d.ts +1 -1
  63. package/dist/capabilities/goal/index.js +30 -7
  64. package/dist/capabilities/index.d.ts +9 -6
  65. package/dist/capabilities/index.js +4 -3
  66. package/dist/capabilities/plan/index.js +22 -5
  67. package/dist/capabilities/plan/plan-mode.d.ts +30 -9
  68. package/dist/capabilities/plan/plan-mode.js +57 -32
  69. package/dist/capabilities/plan/tools.js +1 -1
  70. package/dist/capabilities/skills/flow-provider.js +3 -3
  71. package/dist/capabilities/skills/index.d.ts +13 -1
  72. package/dist/capabilities/skills/index.js +30 -21
  73. package/dist/capabilities/skills/parser.d.ts +2 -2
  74. package/dist/capabilities/skills/parser.js +3 -3
  75. package/dist/capabilities/skills/registry.d.ts +5 -6
  76. package/dist/capabilities/skills/registry.js +6 -9
  77. package/dist/capabilities/skills/scanner.d.ts +3 -3
  78. package/dist/capabilities/skills/scanner.js +14 -14
  79. package/dist/capabilities/skills/service.d.ts +2 -1
  80. package/dist/capabilities/skills/service.js +3 -3
  81. package/dist/capabilities/skills/skill-tool.d.ts +2 -0
  82. package/dist/capabilities/skills/skill-tool.js +1 -1
  83. package/dist/capabilities/task/index.js +2 -1
  84. package/dist/capabilities/task/persist-disk.d.ts +1 -1
  85. package/dist/capabilities/task/persist-disk.js +1 -1
  86. package/dist/capabilities/task/persist.js +1 -1
  87. package/dist/capabilities/todo/index.js +11 -6
  88. package/dist/capabilities/todo/injector.js +2 -1
  89. package/dist/capabilities/todo/todo-store.d.ts +28 -7
  90. package/dist/capabilities/todo/todo-store.js +44 -11
  91. package/dist/capabilities/todo/tools.js +8 -3
  92. package/dist/capabilities/tool-provider.d.ts +3 -3
  93. package/dist/capabilities/user-hooks/engine.d.ts +3 -3
  94. package/dist/capabilities/user-hooks/engine.js +7 -7
  95. package/dist/capabilities/user-hooks/index.js +2 -1
  96. package/dist/capabilities/workflow/index.d.ts +5 -3
  97. package/dist/capabilities/workflow/index.js +3 -2
  98. package/dist/commands/index.js +34 -32
  99. package/dist/config/index.d.ts +1 -1
  100. package/dist/config/provider-manager.js +0 -28
  101. package/dist/config/schema.d.ts +53 -4
  102. package/dist/config/schema.js +53 -1
  103. package/dist/events/events.d.ts +43 -11
  104. package/dist/events/events.js +1 -0
  105. package/dist/events/index.d.ts +2 -2
  106. package/dist/events/index.js +1 -1
  107. package/dist/events/projection.d.ts +49 -1
  108. package/dist/events/projection.js +144 -19
  109. package/dist/events/publisher.js +2 -21
  110. package/dist/home.d.ts +1 -1
  111. package/dist/home.js +1 -1
  112. package/dist/index.d.ts +3 -2
  113. package/dist/index.js +2 -1
  114. package/dist/internal.d.ts +5 -2
  115. package/dist/internal.js +5 -2
  116. package/dist/llm/define-model.d.ts +4 -0
  117. package/dist/llm/define-model.js +63 -25
  118. package/dist/llm/index.d.ts +1 -0
  119. package/dist/llm/index.js +1 -0
  120. package/dist/llm/model.d.ts +2 -0
  121. package/dist/llm/provider.d.ts +17 -0
  122. package/dist/llm/provider.js +14 -0
  123. package/dist/llm/retry.js +1 -1
  124. package/dist/loop/context.d.ts +21 -1
  125. package/dist/loop/context.js +47 -9
  126. package/dist/loop/events.d.ts +5 -1
  127. package/dist/loop/index.d.ts +2 -2
  128. package/dist/loop/index.js +1 -1
  129. package/dist/loop/interruption.d.ts +9 -4
  130. package/dist/loop/interruption.js +11 -25
  131. package/dist/loop/run-turn.d.ts +16 -3
  132. package/dist/loop/run-turn.js +13 -4
  133. package/dist/loop/steer.d.ts +78 -12
  134. package/dist/loop/steer.js +101 -38
  135. package/dist/loop/tool-call.d.ts +13 -2
  136. package/dist/loop/tool-call.js +135 -5
  137. package/dist/loop/turn-step.d.ts +13 -2
  138. package/dist/loop/turn-step.js +29 -7
  139. package/dist/loop/types.d.ts +6 -0
  140. package/dist/mcp/auth-tool.d.ts +3 -1
  141. package/dist/mcp/auth-tool.js +2 -2
  142. package/dist/mcp/capability.d.ts +13 -0
  143. package/dist/mcp/capability.js +36 -17
  144. package/dist/mcp/config-loader.d.ts +5 -5
  145. package/dist/mcp/config-loader.js +17 -17
  146. package/dist/mcp/credentials.d.ts +35 -0
  147. package/dist/mcp/credentials.js +2 -0
  148. package/dist/mcp/filter.d.ts +2 -2
  149. package/dist/mcp/index.d.ts +4 -3
  150. package/dist/mcp/index.js +1 -1
  151. package/dist/mcp/manager.d.ts +108 -6
  152. package/dist/mcp/manager.js +262 -18
  153. package/dist/mcp/oauth/callback-server.d.ts +10 -1
  154. package/dist/mcp/oauth/callback-server.js +82 -16
  155. package/dist/mcp/oauth/index.d.ts +2 -2
  156. package/dist/mcp/oauth/provider.d.ts +18 -0
  157. package/dist/mcp/oauth/provider.js +31 -1
  158. package/dist/mcp/oauth/service.d.ts +9 -3
  159. package/dist/mcp/oauth/service.js +29 -4
  160. package/dist/mcp/sdk-transport.js +1 -1
  161. package/dist/mcp/server.js +1 -1
  162. package/dist/permission/auto-approver/prompts-data.d.ts +1 -1
  163. package/dist/permission/auto-approver/prompts-data.js +1 -1
  164. package/dist/permission/manager.d.ts +5 -3
  165. package/dist/permission/manager.js +7 -3
  166. package/dist/permission/policies.d.ts +2 -2
  167. package/dist/permission/policies.js +4 -4
  168. package/dist/plugins/fields.d.ts +14 -0
  169. package/dist/plugins/fields.js +30 -0
  170. package/dist/plugins/hooks.d.ts +2 -2
  171. package/dist/plugins/hooks.js +12 -12
  172. package/dist/plugins/index.js +1 -0
  173. package/dist/plugins/manager.d.ts +8 -3
  174. package/dist/plugins/manager.js +18 -7
  175. package/dist/plugins/manifest.d.ts +2 -2
  176. package/dist/plugins/manifest.js +101 -91
  177. package/dist/plugins/marketplace.js +76 -57
  178. package/dist/plugins/store.d.ts +3 -3
  179. package/dist/plugins/store.js +6 -6
  180. package/dist/protocol/index.d.ts +1 -1
  181. package/dist/store/catalog-store.d.ts +4 -1
  182. package/dist/store/catalog-store.js +5 -1
  183. package/dist/store/checkpointing-store.d.ts +41 -0
  184. package/dist/store/checkpointing-store.js +86 -0
  185. package/dist/store/disk-store.d.ts +8 -0
  186. package/dist/store/disk-store.js +127 -5
  187. package/dist/store/index.d.ts +3 -2
  188. package/dist/store/index.js +2 -1
  189. package/dist/store/log-store.d.ts +9 -1
  190. package/dist/store/log-store.js +68 -4
  191. package/dist/store/migrate.d.ts +8 -2
  192. package/dist/store/migrate.js +9 -2
  193. package/dist/store/origin.d.ts +31 -6
  194. package/dist/store/origin.js +0 -14
  195. package/dist/store/pg.d.ts +1 -0
  196. package/dist/store/pg.js +37 -2
  197. package/dist/store/redis.d.ts +1 -0
  198. package/dist/store/redis.js +30 -0
  199. package/dist/store/repository.d.ts +13 -1
  200. package/dist/store/repository.js +45 -2
  201. package/dist/store/session-catalog.d.ts +4 -0
  202. package/dist/store/session-catalog.js +6 -0
  203. package/dist/store/storage.js +3 -0
  204. package/dist/store/store.d.ts +97 -34
  205. package/dist/store/store.js +64 -10
  206. package/dist/telemetry/appender.d.ts +43 -0
  207. package/dist/telemetry/appender.js +46 -0
  208. package/dist/telemetry/events.d.ts +142 -0
  209. package/dist/telemetry/events.js +141 -0
  210. package/dist/telemetry/index.d.ts +10 -0
  211. package/dist/telemetry/index.js +6 -0
  212. package/dist/telemetry/projection.d.ts +23 -0
  213. package/dist/telemetry/projection.js +185 -0
  214. package/dist/telemetry/redact.d.ts +20 -0
  215. package/dist/telemetry/redact.js +40 -0
  216. package/dist/telemetry/service.d.ts +49 -0
  217. package/dist/telemetry/service.js +137 -0
  218. package/dist/testing.d.ts +58 -0
  219. package/dist/testing.js +123 -0
  220. package/dist/tool/background.d.ts +9 -6
  221. package/dist/tool/background.js +7 -1
  222. package/dist/tool/builtin/ask-user-question.js +6 -5
  223. package/dist/tool/builtin/bash.d.ts +6 -0
  224. package/dist/tool/builtin/bash.js +79 -42
  225. package/dist/tool/builtin/edit.js +82 -109
  226. package/dist/tool/builtin/glob.js +13 -13
  227. package/dist/tool/builtin/grep.js +13 -13
  228. package/dist/tool/builtin/read.js +25 -15
  229. package/dist/tool/builtin/write.js +49 -33
  230. package/dist/tool/define.d.ts +14 -8
  231. package/dist/tool/define.js +8 -2
  232. package/dist/tool/{machine-base.d.ts → environment-base.d.ts} +37 -37
  233. package/dist/tool/{machine-base.js → environment-base.js} +45 -119
  234. package/dist/tool/{machine-local.d.ts → environment-local.d.ts} +9 -8
  235. package/dist/tool/{machine-local.js → environment-local.js} +60 -81
  236. package/dist/tool/{machine-null.d.ts → environment-null.d.ts} +9 -9
  237. package/dist/tool/{machine-null.js → environment-null.js} +9 -9
  238. package/dist/tool/{machine-ssh.d.ts → environment-ssh.d.ts} +33 -18
  239. package/dist/tool/{machine-ssh.js → environment-ssh.js} +118 -149
  240. package/dist/tool/{machine.d.ts → environment.d.ts} +53 -82
  241. package/dist/tool/environment.js +2 -0
  242. package/dist/tool/file-freshness.d.ts +33 -19
  243. package/dist/tool/file-freshness.js +39 -30
  244. package/dist/tool/filesystem-tools.d.ts +1 -1
  245. package/dist/tool/filesystem-tools.js +1 -1
  246. package/dist/tool/git-context.d.ts +2 -2
  247. package/dist/tool/git-context.js +8 -8
  248. package/dist/tool/index.d.ts +12 -12
  249. package/dist/tool/index.js +12 -10
  250. package/dist/tool/policies/path-access.d.ts +4 -4
  251. package/dist/tool/policies/path-access.js +12 -12
  252. package/dist/tool/questions.d.ts +8 -0
  253. package/dist/tool/search/catalog.d.ts +37 -0
  254. package/dist/tool/search/catalog.js +182 -0
  255. package/dist/tool/search/deferral.d.ts +3 -2
  256. package/dist/tool/search/loaded.d.ts +32 -0
  257. package/dist/tool/search/loaded.js +96 -0
  258. package/dist/tool/search/search-tool.d.ts +2 -6
  259. package/dist/tool/search/search-tool.js +16 -15
  260. package/dist/tool/shell-env.js +4 -0
  261. package/dist/tool/support/bash-paths.js +38 -7
  262. package/dist/tool/support/{machine-ops.d.ts → environment-ops.d.ts} +12 -14
  263. package/dist/tool/support/{machine-ops.js → environment-ops.js} +21 -2
  264. package/dist/tool/support/git-worktree.d.ts +3 -3
  265. package/dist/tool/support/git-worktree.js +6 -6
  266. package/dist/tool/support/rg-locator.d.ts +6 -6
  267. package/dist/tool/support/rg-locator.js +6 -6
  268. package/dist/tool/support/ripgrep-run.d.ts +5 -5
  269. package/dist/tool/support/ripgrep-run.js +3 -3
  270. package/dist/tool/support/tool-path.d.ts +3 -3
  271. package/dist/tool/support/tool-path.js +7 -7
  272. package/dist/tool/types.d.ts +54 -10
  273. package/dist/tool/web/fetch-url.js +1 -1
  274. package/dist/tool/web/web-search.js +1 -1
  275. package/dist/tool/workspace-spec.d.ts +3 -3
  276. package/dist/tool/workspace-spec.js +27 -27
  277. package/dist/tracing/bridge.d.ts +9 -1
  278. package/dist/tracing/bridge.js +307 -77
  279. package/dist/tracing/index.d.ts +2 -2
  280. package/dist/tracing/otel.d.ts +28 -1
  281. package/dist/tracing/otel.js +150 -38
  282. package/dist/tracing/processor.d.ts +22 -0
  283. package/dist/tracing/processor.js +2 -0
  284. package/dist/tracing/spans.d.ts +54 -0
  285. package/dist/tracing/spans.js +5 -0
  286. package/package.json +6 -2
  287. package/dist/tool/machine.js +0 -15
  288. package/dist/tool/search/activation.d.ts +0 -13
  289. package/dist/tool/search/activation.js +0 -31
@@ -2,23 +2,24 @@ import type { LoopHooks } from "../loop/types.ts";
2
2
  import type { PermissionPolicy } from "../permission/types.ts";
3
3
  import type { Message } from "../protocol/index.ts";
4
4
  import type { Tool } from "../tool/types.ts";
5
- import type { Machine } from "../tool/machine.ts";
6
- import type { BackgroundSpawner } from "../tool/background.ts";
7
- import type { EventSink } from "../events/index.ts";
8
- import type { AgentRecord, SessionStore } from "../store/index.ts";
9
- import type { SteerBus } from "../loop/steer.ts";
10
- import type { Responder } from "../permission/types.ts";
11
5
  import type { Injector } from "./injection.ts";
12
6
  import type { ToolProvider } from "./tool-provider.ts";
13
- import type { Logger } from "../logging/index.ts";
14
7
  import type { ChatModel } from "../llm/define-model.ts";
15
8
  import type { ThinkingLevel } from "../llm/model.ts";
16
9
  import type { ContextBreakdown } from "../agent/context-report.ts";
17
10
  import type { CompactRequestOptions, PendingCompaction } from "./compaction/index.ts";
11
+ import type { Environment } from "../tool/environment.ts";
12
+ import type { EventSink } from "../events/index.ts";
13
+ import type { AgentRecord, SessionStore } from "../store/index.ts";
14
+ import type { SteerBus } from "../loop/steer.ts";
15
+ import type { Logger } from "../logging/index.ts";
16
+ import type { HeadlessCommand } from "../commands/index.ts";
17
+ import type { CapabilityRecord, CapabilityState } from "./capability-data.ts";
18
18
  /**
19
19
  * The narrow slice of the owning Session a capability may ACT on (as opposed to observe).
20
- * Implemented by `Session`; handed to capabilities that participate in the run rather than
21
- * just watching it — today the extension runtime's `ctx.actions`.
20
+ * Implemented by `Session`; handed to capabilities at `openSession` and to those that
21
+ * participate in the run rather than just watching it — today the extension runtime's
22
+ * `ctx.actions`.
22
23
  *
23
24
  * Deliberately narrow: everything here is already a public Session operation, so nothing new
24
25
  * becomes reachable — a capability simply gets a typed handle instead of the whole Session.
@@ -27,9 +28,9 @@ import type { CompactRequestOptions, PendingCompaction } from "./compaction/inde
27
28
  */
28
29
  export interface SessionControls {
29
30
  /**
30
- * Cancel work. Scope depends on where the controls came from: from a `CapabilityContext`
31
- * (per run) this aborts THAT run and leaves the session usable; from a `SessionContext` it
32
- * aborts the session. Either way the affected run(s) settle as `status: "aborted"`.
31
+ * Cancel work. Scope depends on where the controls came from: from a `RunContext` (per run)
32
+ * this aborts THAT run and leaves the session usable; from `SessionContext.controls` it aborts the
33
+ * session. Either way the affected run(s) settle as `status: "aborted"`.
33
34
  */
34
35
  abort(reason?: string): void;
35
36
  compact(options?: CompactRequestOptions): Promise<PendingCompaction>;
@@ -37,37 +38,83 @@ export interface SessionControls {
37
38
  setModel(model: string | ChatModel): void;
38
39
  setThinking(level: ThinkingLevel): void;
39
40
  }
40
- export interface CapabilityContext {
41
+ /**
42
+ * What a capability is handed when the session opens: the session's own objects, passed by
43
+ * VALUE. There is no registry to look anything up in — a capability receives exactly what
44
+ * `Session.open` decided to give it, and a dependency it did not receive is a dependency it
45
+ * does not have.
46
+ */
47
+ export interface SessionContext {
41
48
  readonly sessionId: string;
42
- readonly machine: Machine;
49
+ readonly environment: Environment;
43
50
  readonly store?: SessionStore;
44
- readonly events?: EventSink;
45
- readonly responder?: Responder;
51
+ readonly events: EventSink;
52
+ /** Aborts when the SESSION is cancelled. */
46
53
  readonly signal: AbortSignal;
47
- readonly background?: BackgroundSpawner;
48
- readonly injection?: import("./injection.ts").InjectionManager;
49
- readonly steer?: SteerBus;
50
- readonly logger?: Logger;
54
+ readonly steer: SteerBus;
51
55
  readonly controls?: SessionControls;
56
+ /** The session's logger, when the host gave it one. */
57
+ readonly logger?: Logger;
58
+ /**
59
+ * Write THIS capability's current state for `address` (default `main`) to the store — the
60
+ * `durableState.snapshot(address)` as of when the write runs. Writes for one address are
61
+ * ordered and coalesced: a call made while one is waiting to start shares it. Resolves once
62
+ * the value is durable; rejects when the write failed (already logged, so a caller that does
63
+ * not need to know may ignore the promise). A no-op for a capability without `durableState`
64
+ * and for a storeless session.
65
+ */
66
+ persistState(address?: string): Promise<void>;
67
+ /**
68
+ * The session's WHOLE log (every shard, append order), read on first call and memoized. A full
69
+ * read — restoring state does not need it (see {@link CapabilityDurableState}); it is for a
70
+ * capability that genuinely wants history from before the newest checkpoint.
71
+ * Use `readSessionLog(ctx)` — it falls back to a direct read when this is absent.
72
+ */
73
+ readonly logRecords?: () => Promise<readonly AgentRecord[]>;
74
+ /**
75
+ * THIS capability's durable key/value state — partitioned by its name, so two capabilities
76
+ * never see each other's keys. Store-backed; in memory for a storeless session.
77
+ */
78
+ readonly state: CapabilityState;
79
+ /** THIS capability's records: those from earlier processes, then this session's, in order. */
80
+ records(): Promise<readonly CapabilityRecord[]>;
81
+ /**
82
+ * Journal a named record for THIS capability into the session's main conversation. Usable at
83
+ * any point in the session — open, a hook, between runs — and read back by `records()`.
84
+ */
85
+ record(name: string, data?: unknown): void;
86
+ }
87
+ /**
88
+ * What a capability's per-run `start` (and its tool providers) receive. Session-lived objects
89
+ * are NOT here: a capability is handed those once, at `openSession`, and keeps them — a run is
90
+ * where they are used, not where they are found. What is here is what only a run has.
91
+ */
92
+ export interface RunContext {
93
+ readonly sessionId: string;
94
+ /** Aborts when this RUN is cancelled (downstream of the session signal). */
95
+ readonly signal: AbortSignal;
96
+ readonly injection: import("./injection.ts").InjectionManager;
52
97
  /** Gates contributed by every capability in this run, for whoever needs to consult them. */
53
- readonly gates?: AssembledGates;
98
+ readonly gates: AssembledGates;
99
+ /** Same operations as the session's controls, except `abort` is scoped to this run. */
100
+ readonly controls: SessionControls;
54
101
  }
55
102
  /** Collected gate implementations, in capability registration order. */
56
103
  export interface AssembledGates {
57
104
  readonly compaction: readonly CompactionGate[];
58
105
  }
59
- export interface SessionContext {
60
- readonly sessionId: string;
61
- readonly machine: Machine;
62
- readonly store?: SessionStore;
63
- readonly events: EventSink;
64
- readonly signal: AbortSignal;
65
- readonly steer: SteerBus;
66
- readonly controls?: SessionControls;
67
- /** The session's records (append order), read once at open and memoized, so log-fold
68
- * capabilities (goal/plan/todo) share one read instead of each calling `readLog`.
69
- * Use `readSessionLog(ctx)` — it falls back to a direct read when this is absent. */
70
- readonly logRecords?: () => Promise<readonly AgentRecord[]>;
106
+ /**
107
+ * Which frame a toolset is being assembled for. A capability's tools are visible to every agent
108
+ * in the session — the main one and each subagent — and some of them should not be: a tool that
109
+ * negotiates with the human (a plan to approve) or rewrites the conversation's own goal belongs
110
+ * to the agent the human is talking to. That is a visibility question, distinct from who OWNS
111
+ * the state behind the tool (docs/state-and-lifetime.md); a capability may need to answer both.
112
+ */
113
+ export interface ToolFilterContext {
114
+ /** The frame's journal address: `main` for the root agent, `main/<agentId>` for a subagent. */
115
+ readonly address: string;
116
+ /** True for the session's root agent — the one whose turns a human is watching. */
117
+ readonly isRootAgent: boolean;
71
118
  }
72
119
  /**
73
120
  * Narrows the assembled toolset just before a turn runs. The mirror image of `toolProviders`:
@@ -75,7 +122,7 @@ export interface SessionContext {
75
122
  * capability tools ∪ handoff/subagent tools), so a filter that drops a handoff tool is
76
123
  * responsible for what that does to the agent graph. A filter that throws is skipped.
77
124
  */
78
- export type ToolFilter = (tools: readonly Tool[]) => readonly Tool[];
125
+ export type ToolFilter = (tools: readonly Tool[], ctx: ToolFilterContext) => readonly Tool[];
79
126
  /**
80
127
  * Gates are the one place where a capability ASKS other capabilities before acting, instead of
81
128
  * the engine asking capabilities. Every other extension point (`hooks`, `toolFilters`,
@@ -111,34 +158,152 @@ export interface CompactionGateResult {
111
158
  };
112
159
  }
113
160
  export type CompactionGate = (ctx: CompactionGateContext) => Promise<CompactionGateResult | undefined>;
161
+ /** Request headers as the provider layer passes them; `null` deletes a header. */
162
+ export type ProviderHeaders = Record<string, string | null>;
163
+ /** Which step a provider hook fires for. */
164
+ export interface ProviderHookContext {
165
+ readonly turnId: string;
166
+ readonly stepNumber: number;
167
+ /** The frame the request belongs to (`main`, or `main/<agentId>` for a subagent). */
168
+ readonly address?: string;
169
+ }
170
+ /**
171
+ * Hooks BELOW the loop, on the HTTP request itself. They fire once per ATTEMPT — a retried
172
+ * request runs them again — so they must be idempotent. Every capability's hooks compose: each
173
+ * sees what the previous one returned, rather than the last one to write `providerOptions`
174
+ * silently replacing the rest.
175
+ */
176
+ export interface CapabilityProviderHooks {
177
+ /** Rewrite the request headers. Return the new set, or nothing to leave them unchanged. */
178
+ headers?(headers: ProviderHeaders, ctx: ProviderHookContext): ProviderHeaders | undefined | void | Promise<ProviderHeaders | undefined | void>;
179
+ /** Rewrite the serialized body, whatever shape this provider uses. Return `{ payload }` to
180
+ * replace it (an object, so that "replace with undefined" and "no change" differ). */
181
+ payload?(payload: unknown, ctx: ProviderHookContext): {
182
+ readonly payload: unknown;
183
+ } | undefined | void | Promise<{
184
+ readonly payload: unknown;
185
+ } | undefined | void>;
186
+ /** Observe the response status and headers — after they arrive, BEFORE the body streams, so
187
+ * a slow observer is latency on every token. A detachable one gets at most 1s. */
188
+ response?(response: {
189
+ readonly status: number;
190
+ readonly headers: Record<string, string>;
191
+ }, ctx: ProviderHookContext): void | Promise<void>;
192
+ }
114
193
  export interface CapabilityGates {
115
194
  compaction?: CompactionGate;
116
195
  }
196
+ /**
197
+ * What the engine promises a capability, and what it demands back. This is the ONE thing that
198
+ * separates an engine part from behaviour written on top of it — not what either can reach.
199
+ *
200
+ * - `invariant` — always present, never timed out, never detached; a failure fails the run.
201
+ * Reserved for the things whose absence is an INCIDENT rather than a missing feature:
202
+ * permission, compaction. Only these may contribute `policies`, and a file may not deliver
203
+ * one (dropping a file in a directory must not be able to rewrite the permission rules).
204
+ * - `detachable` — may be absent, may be hot-swapped, its hooks are timed and its failures are
205
+ * isolated to a log line. Almost everything is this.
206
+ *
207
+ * The test, in one question: if this were skipped once, is that a missing feature or an
208
+ * incident? Missing feature → `detachable`. Incident → `invariant`.
209
+ */
210
+ export type CapabilityContract = "invariant" | "detachable";
211
+ /**
212
+ * How a stateful capability's current state survives a reopen: as its CURRENT VALUE in the
213
+ * store's key/value state, never as a reduction of the log.
214
+ *
215
+ * After every change the capability calls `SessionContext.persistState(address)`; the session
216
+ * then writes `snapshot(address)` under the capability's key for that address. A reopen reads
217
+ * that value back and hands it to `restore` — no log is read, so the state does not depend on
218
+ * when the history was last compacted, nor on whether this capability was open at the time.
219
+ * A detached capability's state stays in the store, and an attach reads it back the same way.
220
+ *
221
+ * The log still carries what the MODEL saw (a tool call and its result), but restoring never
222
+ * reads it, and the two may disagree by one change after a crash between the writes: the state
223
+ * is the authority, and the next change rewrites it. So keep state that must never lag behind
224
+ * what the user was told (a mode that restricts the agent) on an awaited `persistState`.
225
+ *
226
+ * Per address: `main` holds session-owned state; a subagent's address holds that frame's own
227
+ * state, restored when its shard is reopened to resume it.
228
+ */
229
+ export interface CapabilityDurableState {
230
+ /** This capability's state for `address`, as of now; undefined or null when it has none
231
+ * there (the stored value is then removed). Synchronous — read when the write runs. */
232
+ snapshot(address: string): unknown;
233
+ /** Replace this capability's state for `address` with `value`, the value last stored for it
234
+ * (undefined: none stored). Must not persist anything. */
235
+ restore(address: string, value: unknown): void;
236
+ }
237
+ /** Why `closeSession` runs: the session is closing, or the capability alone is being detached. */
238
+ export type CloseReason = "close" | "detach";
239
+ /**
240
+ * A part of the engine, assembled into one session. Two tiers of lifecycle:
241
+ * - SESSION — `openSession` / `closeSession`: the session-lived wiring, driven by `Session.open`
242
+ * and `Session.close`. What it wants to publish goes in `service`.
243
+ * - RUN — `start` / `stop`: per-run wiring, driven by the assembler.
244
+ * Everything else (tools, hooks, injectors, policies, gates) is static contribution.
245
+ */
117
246
  export interface Capability {
118
247
  readonly name: string;
248
+ /** See {@link CapabilityContract}. Decides whether the engine may time this out, isolate its
249
+ * failures, and detach it — and whether it may contribute `policies`. */
250
+ readonly contract: CapabilityContract;
119
251
  readonly tools?: readonly Tool[];
120
252
  readonly toolProviders?: readonly ToolProvider[];
121
253
  readonly toolFilters?: readonly ToolFilter[];
122
254
  /** Arbitration this capability wants a say in. See {@link CapabilityGates}. */
123
255
  readonly gates?: CapabilityGates;
256
+ /** Permission rules. `invariant` only — a rule that can be timed out or detached is a rule
257
+ * that fails OPEN, which is how a dangerous tool runs anyway. */
124
258
  readonly policies?: readonly PermissionPolicy[];
125
259
  readonly hooks?: Partial<LoopHooks>;
260
+ /**
261
+ * Per-call budget for each of this capability's `hooks`, `detachable` only. A hook that throws
262
+ * or overruns is reported as a warning and treated as having returned nothing — the run goes on
263
+ * as if the capability had no opinion this time. Defaults to 30s: hooks block the loop, so they
264
+ * get room for real work (a network call, a subprocess) but not an unbounded stall.
265
+ * `invariant` hooks are never wrapped — their failure IS the run's failure.
266
+ */
267
+ readonly hookTimeoutMs?: number;
268
+ /** See {@link CapabilityProviderHooks}. Isolated like `hooks` when `detachable`. */
269
+ readonly provider?: CapabilityProviderHooks;
270
+ /** Slash commands this capability adds to the session's command set. */
271
+ readonly commands?: readonly HeadlessCommand[];
126
272
  readonly injectors?: readonly Injector[];
273
+ /**
274
+ * What this capability publishes to the session, reachable as `session.service(name)` and
275
+ * through the named accessors (`session.goal`, …). Built by `openSession`, torn down by
276
+ * `closeSession`. One per capability: a capability that wants to publish two things publishes
277
+ * one object with two properties.
278
+ */
127
279
  readonly service?: unknown;
280
+ /**
281
+ * Durable current state the session restores on open WITHOUT reading the whole log. See
282
+ * {@link CapabilityDurableState}.
283
+ */
284
+ readonly durableState?: CapabilityDurableState;
285
+ /**
286
+ * Session-lived setup: attach to the store, connect. Runs once, at `Session.open`, with
287
+ * everything the session decided to hand out — after `durableState.restore`, so the state is
288
+ * already back. A `detachable` capability that throws here is absent for the session (logged,
289
+ * run continues); an `invariant` one fails the open.
290
+ */
291
+ openSession?(ctx: SessionContext): Promise<void> | void;
292
+ /** Session-lived teardown, in reverse registration order. `reason` says whether the whole
293
+ * session is closing or only this capability is leaving it (`Session.detachCapability`). */
294
+ closeSession?(reason: CloseReason): Promise<void> | void;
128
295
  /** Per-run startup. `signal` aborts when the assembler's start timeout expires — the
129
296
  * timeout itself still wins the race (the capability is marked absent), but a
130
297
  * signal-respecting implementation can release whatever it was holding. */
131
- start?(ctx: CapabilityContext, signal?: AbortSignal): Promise<void> | void;
298
+ start?(ctx: RunContext, signal?: AbortSignal): Promise<void> | void;
132
299
  /** Per-run teardown. `signal` aborts when the stop timeout expires; the run does not
133
300
  * wait past the timeout either way, so use the signal to abandon slow flushes
134
301
  * instead of leaking them into the background. */
135
302
  stop?(signal?: AbortSignal): Promise<void> | void;
136
- openSession?(ctx: SessionContext): Promise<void> | void;
137
- closeSession?(): Promise<void> | void;
138
303
  }
139
304
  export interface CapabilityDiagnostic {
140
305
  readonly capability: string;
141
- readonly phase: "register" | "start" | "stop";
306
+ readonly phase: "register" | "start" | "hook" | "stop";
142
307
  readonly level: "warn" | "error";
143
308
  readonly message: string;
144
309
  }
@@ -88,11 +88,19 @@ export function compactionCapability(options) {
88
88
  };
89
89
  return {
90
90
  name: "compaction",
91
+ contract: "invariant",
91
92
  service,
93
+ // The sink and the logger were being picked up in `start`, once per run, from whatever the
94
+ // session held at that moment. They are session-lived, so they are taken once, here.
95
+ openSession: (ctx) => {
96
+ events = ctx.events;
97
+ logger = ctx.logger ?? noopLogger;
98
+ },
92
99
  hooks: {
93
100
  beforeStep: async (ctx) => {
94
101
  maxOutputTokens = ctx.model.maxOutputTokens;
95
- const manual = service.consume();
102
+ // This frame's request only: `beforeStep` runs for every agent in the session.
103
+ const manual = service.consume(ctx.address);
96
104
  if (manual !== null)
97
105
  await compact(ctx, manual);
98
106
  if (micro) {
@@ -134,9 +142,7 @@ export function compactionCapability(options) {
134
142
  },
135
143
  start: (ctx) => {
136
144
  injection = ctx.injection;
137
- gates = ctx.gates?.compaction;
138
- events = ctx.events;
139
- logger = ctx.logger ?? noopLogger;
145
+ gates = ctx.gates.compaction;
140
146
  sessionId = ctx.sessionId;
141
147
  lastAssistantAtMs = Date.now();
142
148
  },
@@ -7,7 +7,19 @@ export interface PendingCompaction {
7
7
  readonly instruction?: string;
8
8
  }
9
9
  export declare class CompactionService {
10
- private pendingRequest;
10
+ /**
11
+ * One pending request PER FRAME (docs/state-and-lifetime.md). `beforeStep` runs for every
12
+ * agent in the session, so a single slot meant whichever frame stepped next consumed the
13
+ * request — a subagent compacting ITS context because the main agent asked, and the main
14
+ * agent's context left untouched with its request gone.
15
+ */
16
+ private readonly pendingByFrame;
17
+ /**
18
+ * Session-wide on purpose: this only invalidates the system-prompt context cache, so a
19
+ * compaction in one frame merely makes another recompute once. Coarse here costs a little
20
+ * work; wrong here would cost correctness, which is the distinction that decides what gets
21
+ * a key and what does not.
22
+ */
11
23
  private completedRevision;
12
24
  private readonly reserveProvider;
13
25
  /** Context tokens the strategy holds back before the window fills — surfaced here (the
@@ -20,9 +32,12 @@ export declare class CompactionService {
20
32
  get revision(): number;
21
33
  /** Capability-internal commit notification; micro-compaction deliberately does not call it. */
22
34
  recordCompleted(): void;
23
- request(options?: CompactRequestOptions): PendingCompaction;
24
- pending(): PendingCompaction | null;
25
- cancel(): PendingCompaction | null;
26
- consume(): PendingCompaction | null;
35
+ /** Ask for a compaction of one frame's context. Defaults to the root agent's, which is what
36
+ * `session.controls().compact()` and the `/compact` command mean. */
37
+ request(options?: CompactRequestOptions, address?: string): PendingCompaction;
38
+ pending(address?: string): PendingCompaction | null;
39
+ cancel(address?: string): PendingCompaction | null;
40
+ /** Taken by the frame that is about to step — never another's request. */
41
+ consume(address?: string): PendingCompaction | null;
27
42
  }
28
43
  //# sourceMappingURL=service.d.ts.map
@@ -1,10 +1,23 @@
1
+ import { DEFAULT_ADDRESS } from "../../store/index.js";
1
2
  let requestCounter = 0;
2
3
  function nextRequestId() {
3
4
  requestCounter += 1;
4
5
  return `compact-${Date.now().toString(36)}-${requestCounter.toString(36)}`;
5
6
  }
6
7
  export class CompactionService {
7
- pendingRequest = null;
8
+ /**
9
+ * One pending request PER FRAME (docs/state-and-lifetime.md). `beforeStep` runs for every
10
+ * agent in the session, so a single slot meant whichever frame stepped next consumed the
11
+ * request — a subagent compacting ITS context because the main agent asked, and the main
12
+ * agent's context left untouched with its request gone.
13
+ */
14
+ pendingByFrame = new Map();
15
+ /**
16
+ * Session-wide on purpose: this only invalidates the system-prompt context cache, so a
17
+ * compaction in one frame merely makes another recompute once. Coarse here costs a little
18
+ * work; wrong here would cost correctness, which is the distinction that decides what gets
19
+ * a key and what does not.
20
+ */
8
21
  completedRevision = 0;
9
22
  reserveProvider;
10
23
  /** Context tokens the strategy holds back before the window fills — surfaced here (the
@@ -25,27 +38,30 @@ export class CompactionService {
25
38
  recordCompleted() {
26
39
  this.completedRevision += 1;
27
40
  }
28
- request(options = {}) {
41
+ /** Ask for a compaction of one frame's context. Defaults to the root agent's, which is what
42
+ * `session.controls().compact()` and the `/compact` command mean. */
43
+ request(options = {}, address = DEFAULT_ADDRESS) {
29
44
  const instruction = options.instruction?.trim();
30
45
  const request = {
31
46
  id: nextRequestId(),
32
47
  requestedAt: Date.now(),
33
48
  ...(instruction !== undefined && instruction.length > 0 ? { instruction } : {}),
34
49
  };
35
- this.pendingRequest = request;
50
+ this.pendingByFrame.set(address, request);
36
51
  return request;
37
52
  }
38
- pending() {
39
- return this.pendingRequest;
53
+ pending(address = DEFAULT_ADDRESS) {
54
+ return this.pendingByFrame.get(address) ?? null;
40
55
  }
41
- cancel() {
42
- const pending = this.pendingRequest;
43
- this.pendingRequest = null;
56
+ cancel(address = DEFAULT_ADDRESS) {
57
+ const pending = this.pending(address);
58
+ this.pendingByFrame.delete(address);
44
59
  return pending;
45
60
  }
46
- consume() {
47
- const pending = this.pendingRequest;
48
- this.pendingRequest = null;
61
+ /** Taken by the frame that is about to step — never another's request. */
62
+ consume(address = DEFAULT_ADDRESS) {
63
+ const pending = this.pending(address);
64
+ this.pendingByFrame.delete(address);
49
65
  return pending;
50
66
  }
51
67
  }
@@ -1,10 +1,9 @@
1
1
  import type { Usage } from "../../protocol/index.ts";
2
- import type { AgentRecord } from "../../store/index.ts";
3
2
  export type GoalStatus = "active" | "blocked" | "paused" | "complete";
4
3
  /** Tool names whose results carry the durable goal record in `details.goal`. */
5
4
  export declare const GOAL_TOOL_NAMES: readonly ["UpdateGoal", "SetGoalBudget"];
6
- /** Durable goal identity carried in goal-tool result `details` (counters are NOT stored — they
7
- * are re-derived from the log's per-turn `usage` entries, exactly as live accrued them). */
5
+ /** Goal identity carried in goal-tool result `details`, for whoever renders the transcript.
6
+ * Restore does not read it — it reads {@link GoalDurable}, which also carries the counters. */
8
7
  export interface GoalPersisted {
9
8
  readonly objective: string;
10
9
  readonly completionCriterion?: string;
@@ -35,14 +34,76 @@ export interface GoalSnapshot {
35
34
  readonly remainingWallClockMs: number | null;
36
35
  };
37
36
  }
37
+ interface GoalRecord {
38
+ objective: string;
39
+ completionCriterion?: string;
40
+ status: GoalStatus;
41
+ budget: {
42
+ turnBudget: number | null;
43
+ tokenBudget: number | null;
44
+ wallClockBudgetMs: number | null;
45
+ };
46
+ turnsUsed: number;
47
+ tokensUsed: number;
48
+ startedAtMs: number;
49
+ terminalReason?: string;
50
+ }
51
+ /** The goal's WHOLE durable state, counters included — what is stored after every change.
52
+ * `null`: no goal. */
53
+ export type GoalDurable = Readonly<Omit<GoalRecord, "budget">> & {
54
+ readonly budget: GoalBudget;
55
+ };
38
56
  export interface UpdateGoalInput {
39
57
  readonly objective?: string;
40
58
  readonly completionCriterion?: string;
41
59
  readonly status?: GoalStatus;
42
60
  readonly reason?: string;
43
61
  }
62
+ /** Everything the session-level goal operations take as input. */
63
+ export interface CreateGoalInput {
64
+ readonly objective: string;
65
+ readonly completionCriterion?: string;
66
+ readonly budget?: GoalBudgetInput;
67
+ }
68
+ export interface GoalBudgetInput {
69
+ readonly turns?: number;
70
+ readonly tokens?: number;
71
+ readonly wallClockMs?: number;
72
+ }
44
73
  export declare class GoalStore {
45
74
  private goal;
75
+ /** Set by the capability's provision; absent in a bare store (tests, replay). */
76
+ private announce;
77
+ /** Persists the whole state after each change. Absent in a bare store (tests). */
78
+ private persist;
79
+ /**
80
+ * Where every goal change becomes durable. Every mutation goes through this store — a tool, a
81
+ * host command (`/goal pause`), the per-turn accounting — so persisting here, rather than in
82
+ * the goal tools' results, is what makes a change from OUTSIDE the loop survive a reopen.
83
+ */
84
+ attachPersistence(persist: () => void): void;
85
+ private changed;
86
+ /**
87
+ * Where a goal change becomes a `goal.updated` event. The store owns this because the store is
88
+ * what changes: a facade that emitted on the caller's behalf could only cover the calls that
89
+ * went through it, and left anything mutating the goal directly silently unobserved.
90
+ */
91
+ attachAnnouncer(announce: (snapshot: GoalSnapshot | null) => Promise<void>): void;
92
+ private announced;
93
+ /**
94
+ * Start a goal, replacing any goal already running. The budget is validated BEFORE anything
95
+ * changes, so a bad budget leaves the previous goal intact rather than half-replacing it.
96
+ */
97
+ create(input: CreateGoalInput): Promise<GoalSnapshot>;
98
+ /** Change a running goal's status. Returns null (and announces nothing) when there is none. */
99
+ private transition;
100
+ pause(reason?: string): Promise<GoalSnapshot | null>;
101
+ resume(reason?: string): Promise<GoalSnapshot | null>;
102
+ block(reason?: string): Promise<GoalSnapshot | null>;
103
+ /** End the current goal. Returns the snapshot AS IT WAS, or null if there was none. */
104
+ cancel(reason?: string): Promise<GoalSnapshot | null>;
105
+ /** Validate, apply and announce — the budget path a caller outside the loop should use. */
106
+ changeBudget(budget: GoalBudgetInput): Promise<GoalSnapshot | null>;
46
107
  isActive(): boolean;
47
108
  has(): boolean;
48
109
  update(input: UpdateGoalInput): GoalSnapshot | null;
@@ -51,19 +112,22 @@ export declare class GoalStore {
51
112
  tokens?: number;
52
113
  wallClockMs?: number;
53
114
  }): GoalSnapshot | null;
54
- recordTurn(usage: Usage): void;
115
+ /**
116
+ * Account one finished turn of the ROOT agent, then auto-block if a budget is reached — one
117
+ * change, journaled once. Returns true when the budget blocked the goal. A subagent's turns
118
+ * are not the goal's: the goal driver never calls this for them.
119
+ */
120
+ accountTurn(usage: Usage): boolean;
55
121
  enforceBudget(): boolean;
122
+ private applyBudget;
56
123
  snapshot(): GoalSnapshot | null;
57
124
  /** Durable record for journaling into a goal-tool result `details` (null when no goal). */
58
125
  persisted(): GoalPersisted | null;
59
- /**
60
- * Rebuild from the log by replaying it in order through the SAME mutations as live:
61
- * each goal-tool result re-applies the durable record; each per-turn `usage` entry accrues a
62
- * turn iff the goal is active then auto-blocks on budget — mirroring `goalDriver`. So counters
63
- * and budget status come out identical to the live run, and correct for the current log.
64
- */
65
- reconstruct(entries: readonly AgentRecord[]): void;
66
- private applyPersisted;
126
+ /** The whole durable state — see {@link GoalDurable}. */
127
+ durable(): GoalDurable | null;
128
+ /** Restore from the value stored for the goal (undefined: none). Persists nothing. */
129
+ restore(value: unknown): void;
67
130
  private wallClockMs;
68
131
  }
132
+ export {};
69
133
  //# sourceMappingURL=goal-store.d.ts.map