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
@@ -1,7 +1,102 @@
1
1
  /** Tool names whose results carry the durable goal record in `details.goal`. */
2
2
  export const GOAL_TOOL_NAMES = ["UpdateGoal", "SetGoalBudget"];
3
+ function positiveInt(name, value) {
4
+ if (!Number.isInteger(value) || value <= 0)
5
+ throw new Error(`Goal budget ${name} must be a positive integer.`);
6
+ return value;
7
+ }
8
+ function normalizeBudget(input) {
9
+ const budget = {};
10
+ if (input.turns !== undefined)
11
+ budget.turns = positiveInt("turns", input.turns);
12
+ if (input.tokens !== undefined)
13
+ budget.tokens = positiveInt("tokens", input.tokens);
14
+ if (input.wallClockMs !== undefined)
15
+ budget.wallClockMs = positiveInt("wallClockMs", input.wallClockMs);
16
+ if (Object.keys(budget).length === 0)
17
+ throw new Error("At least one goal budget field is required.");
18
+ return budget;
19
+ }
3
20
  export class GoalStore {
4
21
  goal = null;
22
+ /** Set by the capability's provision; absent in a bare store (tests, replay). */
23
+ announce;
24
+ /** Persists the whole state after each change. Absent in a bare store (tests). */
25
+ persist;
26
+ /**
27
+ * Where every goal change becomes durable. Every mutation goes through this store — a tool, a
28
+ * host command (`/goal pause`), the per-turn accounting — so persisting here, rather than in
29
+ * the goal tools' results, is what makes a change from OUTSIDE the loop survive a reopen.
30
+ */
31
+ attachPersistence(persist) {
32
+ this.persist = persist;
33
+ }
34
+ changed() {
35
+ this.persist?.();
36
+ }
37
+ /**
38
+ * Where a goal change becomes a `goal.updated` event. The store owns this because the store is
39
+ * what changes: a facade that emitted on the caller's behalf could only cover the calls that
40
+ * went through it, and left anything mutating the goal directly silently unobserved.
41
+ */
42
+ attachAnnouncer(announce) {
43
+ this.announce = announce;
44
+ }
45
+ async announced(snapshot) {
46
+ await this.announce?.(snapshot);
47
+ return snapshot;
48
+ }
49
+ /**
50
+ * Start a goal, replacing any goal already running. The budget is validated BEFORE anything
51
+ * changes, so a bad budget leaves the previous goal intact rather than half-replacing it.
52
+ */
53
+ async create(input) {
54
+ const objective = input.objective.trim();
55
+ if (objective.length === 0)
56
+ throw new Error("Goal objective cannot be empty.");
57
+ const budget = input.budget !== undefined ? normalizeBudget(input.budget) : undefined;
58
+ if (this.has())
59
+ this.update({ status: "complete" });
60
+ let snapshot = this.update({
61
+ objective,
62
+ completionCriterion: input.completionCriterion?.trim(),
63
+ status: "active",
64
+ });
65
+ if (budget !== undefined)
66
+ snapshot = this.setBudget(budget);
67
+ if (snapshot === null)
68
+ throw new Error("Goal was not created.");
69
+ await this.announce?.(snapshot);
70
+ return snapshot;
71
+ }
72
+ /** Change a running goal's status. Returns null (and announces nothing) when there is none. */
73
+ async transition(status, reason) {
74
+ if (this.snapshot() === null)
75
+ return null;
76
+ return this.announced(this.update({ status, reason }));
77
+ }
78
+ pause(reason) {
79
+ return this.transition("paused", reason);
80
+ }
81
+ resume(reason) {
82
+ return this.transition("active", reason);
83
+ }
84
+ block(reason) {
85
+ return this.transition("blocked", reason);
86
+ }
87
+ /** End the current goal. Returns the snapshot AS IT WAS, or null if there was none. */
88
+ async cancel(reason) {
89
+ const previous = this.snapshot();
90
+ if (previous === null)
91
+ return null;
92
+ this.update({ status: "complete", reason });
93
+ await this.announce?.(null);
94
+ return previous;
95
+ }
96
+ /** Validate, apply and announce — the budget path a caller outside the loop should use. */
97
+ async changeBudget(budget) {
98
+ return this.announced(this.setBudget(normalizeBudget(budget)));
99
+ }
5
100
  isActive() {
6
101
  return this.goal?.status === "active";
7
102
  }
@@ -10,7 +105,10 @@ export class GoalStore {
10
105
  }
11
106
  update(input) {
12
107
  if (input.status === "complete") {
108
+ const had = this.goal !== null;
13
109
  this.goal = null;
110
+ if (had)
111
+ this.changed();
14
112
  return null;
15
113
  }
16
114
  if (this.goal === null) {
@@ -27,6 +125,7 @@ export class GoalStore {
27
125
  startedAtMs: Date.now(),
28
126
  terminalReason: input.reason,
29
127
  };
128
+ this.changed();
30
129
  return this.snapshot();
31
130
  }
32
131
  if (input.objective !== undefined)
@@ -39,6 +138,7 @@ export class GoalStore {
39
138
  this.goal.terminalReason = input.reason;
40
139
  else if (input.status === "active")
41
140
  this.goal.terminalReason = undefined;
141
+ this.changed();
42
142
  return this.snapshot();
43
143
  }
44
144
  setBudget(budget) {
@@ -50,15 +150,30 @@ export class GoalStore {
50
150
  this.goal.budget.tokenBudget = budget.tokens;
51
151
  if (budget.wallClockMs !== undefined)
52
152
  this.goal.budget.wallClockBudgetMs = budget.wallClockMs;
153
+ this.changed();
53
154
  return this.snapshot();
54
155
  }
55
- recordTurn(usage) {
156
+ /**
157
+ * Account one finished turn of the ROOT agent, then auto-block if a budget is reached — one
158
+ * change, journaled once. Returns true when the budget blocked the goal. A subagent's turns
159
+ * are not the goal's: the goal driver never calls this for them.
160
+ */
161
+ accountTurn(usage) {
56
162
  if (this.goal === null)
57
- return;
163
+ return false;
58
164
  this.goal.turnsUsed += 1;
59
165
  this.goal.tokensUsed += usage.totalTokens;
166
+ const blocked = this.applyBudget();
167
+ this.changed();
168
+ return blocked;
60
169
  }
61
170
  enforceBudget() {
171
+ const blocked = this.applyBudget();
172
+ if (blocked)
173
+ this.changed();
174
+ return blocked;
175
+ }
176
+ applyBudget() {
62
177
  if (this.goal === null || this.goal.status !== "active")
63
178
  return false;
64
179
  const { budget } = this.goal;
@@ -111,62 +226,31 @@ export class GoalStore {
111
226
  terminalReason: this.goal.terminalReason,
112
227
  };
113
228
  }
114
- /**
115
- * Rebuild from the log by replaying it in order through the SAME mutations as live:
116
- * each goal-tool result re-applies the durable record; each per-turn `usage` entry accrues a
117
- * turn iff the goal is active then auto-blocks on budget — mirroring `goalDriver`. So counters
118
- * and budget status come out identical to the live run, and correct for the current log.
119
- */
120
- reconstruct(entries) {
121
- this.goal = null;
122
- for (const entry of entries) {
123
- if (entry.type === "context.append_message") {
124
- const msg = entry.message;
125
- if (msg.role !== "toolResult" || !isGoalToolName(msg.toolName))
126
- continue;
127
- const details = msg.details;
128
- if (details === undefined || !("goal" in details))
129
- continue;
130
- this.applyPersisted(details.goal ?? null);
131
- }
132
- else if (entry.type === "usage.record" && this.isActive()) {
133
- // Matches goalDriver: account the finished turn, then auto-block if a budget hit.
134
- this.recordTurn(entry.usage);
135
- this.enforceBudget();
136
- }
137
- }
229
+ /** The whole durable state — see {@link GoalDurable}. */
230
+ durable() {
231
+ if (this.goal === null)
232
+ return null;
233
+ return { ...this.goal, budget: { ...this.goal.budget } };
138
234
  }
139
- applyPersisted(p) {
140
- if (p === null) {
141
- this.goal = null;
142
- return;
143
- }
144
- if (this.goal === null) {
145
- this.goal = {
146
- objective: p.objective,
147
- completionCriterion: p.completionCriterion,
148
- status: p.status,
149
- budget: { ...p.budget },
150
- turnsUsed: 0,
151
- tokensUsed: 0,
152
- startedAtMs: p.startedAtMs,
153
- terminalReason: p.terminalReason,
154
- };
155
- return;
156
- }
157
- // Update of an existing goal: replace the durable fields, keep accrued counters.
158
- this.goal.objective = p.objective;
159
- this.goal.completionCriterion = p.completionCriterion;
160
- this.goal.status = p.status;
161
- this.goal.budget = { ...p.budget };
162
- this.goal.startedAtMs = p.startedAtMs;
163
- this.goal.terminalReason = p.terminalReason;
235
+ /** Restore from the value stored for the goal (undefined: none). Persists nothing. */
236
+ restore(value) {
237
+ this.goal = isGoalDurable(value) ? { ...value, budget: { ...value.budget } } : null;
164
238
  }
165
239
  wallClockMs() {
166
240
  return this.goal === null ? 0 : Math.max(0, Date.now() - this.goal.startedAtMs);
167
241
  }
168
242
  }
169
- function isGoalToolName(name) {
170
- return GOAL_TOOL_NAMES.includes(name);
243
+ function isGoalDurable(value) {
244
+ if (typeof value !== "object" || value === null)
245
+ return false;
246
+ const v = value;
247
+ const budget = v["budget"];
248
+ return (typeof v["objective"] === "string" &&
249
+ (v["status"] === "active" || v["status"] === "blocked" || v["status"] === "paused") &&
250
+ typeof v["turnsUsed"] === "number" &&
251
+ typeof v["tokensUsed"] === "number" &&
252
+ typeof v["startedAtMs"] === "number" &&
253
+ typeof budget === "object" &&
254
+ budget !== null);
171
255
  }
172
256
  //# sourceMappingURL=goal-store.js.map
@@ -1,6 +1,6 @@
1
1
  import type { Capability } from "../capability.ts";
2
2
  import { GoalStore } from "./goal-store.ts";
3
3
  export { GoalStore } from "./goal-store.ts";
4
- export type { GoalSnapshot, GoalStatus, GoalBudget, GoalPersisted, GoalDetails } from "./goal-store.ts";
4
+ export type { GoalSnapshot, GoalStatus, GoalBudget, GoalPersisted, GoalDetails, GoalDurable } from "./goal-store.ts";
5
5
  export declare function goalCapability(store?: GoalStore): Capability;
6
6
  //# sourceMappingURL=index.d.ts.map
@@ -1,30 +1,53 @@
1
- import { readSessionLog } from "../capability-state.js";
1
+ import { DEFAULT_ADDRESS } from "../../store/index.js";
2
2
  import { GoalStore } from "./goal-store.js";
3
3
  import { getGoalTool, setGoalBudgetTool, updateGoalTool } from "./tools.js";
4
4
  import { GoalInjector } from "./injector.js";
5
5
  export { GoalStore } from "./goal-store.js";
6
6
  function goalDriver(store) {
7
7
  return async (ctx) => {
8
+ // The goal is the conversation's, pursued by the root agent. A subagent stopping is its own
9
+ // work finishing: it is neither the goal's turn to count nor one to drive onward — it cannot
10
+ // even mark the goal complete (its goal tools are read-only), so driving it would only spin
11
+ // it to its turn limit.
12
+ if (ctx.isRootAgent === false)
13
+ return undefined;
8
14
  if (!store.isActive())
9
15
  return { continue: false };
10
16
  // Account for the turn that just finished, then auto-block if a hard budget hit.
11
- store.recordTurn(ctx.usage);
12
- if (store.enforceBudget())
17
+ if (store.accountTurn(ctx.usage))
13
18
  return { continue: false };
14
19
  return { continue: store.isActive() };
15
20
  };
16
21
  }
22
+ /** `store` may be pre-built by an embedder (or a test) that wants to hold the instance. */
23
+ const GOAL_WRITE_TOOL_NAMES = new Set(["UpdateGoal", "SetGoalBudget"]);
17
24
  export function goalCapability(store = new GoalStore()) {
18
25
  return {
19
26
  name: "goal",
27
+ contract: "invariant",
20
28
  tools: [updateGoalTool(store), getGoalTool(store), setGoalBudgetTool(store)],
21
- service: store,
29
+ // The goal is the CONVERSATION's, so a subagent may read it — knowing what the session is
30
+ // for helps it do its part — but not rewrite it or change its budget. Those are the root
31
+ // agent's, the one accountable to the human who set the goal.
32
+ toolFilters: [(tools, ctx) => (ctx.isRootAgent ? tools : tools.filter((tool) => !GOAL_WRITE_TOOL_NAMES.has(tool.schema.name)))],
22
33
  injectors: [new GoalInjector(store)],
23
34
  hooks: { shouldContinueAfterStop: goalDriver(store) },
24
- // Rebuild the goal (incl. turn/token counters) by replaying the session log, so resume
25
- // and fork restore it instead of starting from an empty in-memory store.
35
+ service: store,
36
+ // The goal is SESSION state: it lives in `main`, whichever frame is running. A lost write
37
+ // costs at most one turn of drift (a counter, or one extra driven turn after the model
38
+ // completed it), so nothing waits for it.
39
+ durableState: {
40
+ snapshot: (address) => (address === DEFAULT_ADDRESS ? store.durable() : undefined),
41
+ restore: (address, value) => {
42
+ if (address === DEFAULT_ADDRESS)
43
+ store.restore(value);
44
+ },
45
+ },
26
46
  openSession: async (ctx) => {
27
- store.reconstruct(await readSessionLog(ctx));
47
+ store.attachPersistence(() => void ctx.persistState());
48
+ store.attachAnnouncer(async (snapshot) => {
49
+ await ctx.events.emit({ type: "goal.updated", snapshot, address: "main", sessionId: ctx.sessionId });
50
+ });
28
51
  },
29
52
  };
30
53
  }
@@ -1,7 +1,10 @@
1
- export type { AssembledGates, Capability, CapabilityContext, CapabilityDiagnostic, CapabilityGates, CompactionGate, CompactionGateContext, CompactionGateResult, SessionContext, SessionControls, ToolFilter, } from "./capability.ts";
1
+ export type { AssembledGates, Capability, CapabilityDiagnostic, CapabilityGates, CompactionGate, CompactionGateContext, CompactionGateResult, CapabilityContract, CloseReason, CapabilityProviderHooks, ProviderHeaders, ProviderHookContext, RunContext, SessionContext, SessionControls, ToolFilter, } from "./capability.ts";
2
2
  export type { Injector, InjectionContext, InjectionResult, InjectionAppender } from "./injection.ts";
3
3
  export { BoundaryInjector, InjectionManager, systemReminder } from "./injection.ts";
4
- export { readLog } from "./capability-state.ts";
4
+ export { readLog, readSessionLog } from "./capability-state.ts";
5
+ export type { CapabilityRecord, CapabilityState } from "./capability-data.ts";
6
+ export type { SkillsService } from "./skills/service.ts";
7
+ export { taskToSubagentRecord, taskToWorkflowSnapshot } from "./background/projections.ts";
5
8
  export type { ToolProvider } from "./tool-provider.ts";
6
9
  export { staticToolProvider, tagToolSource, toolSource } from "./tool-provider.ts";
7
10
  export { planCapability, PlanMode } from "./plan/index.ts";
@@ -18,8 +21,8 @@ export { compactionCapability, CompactionService, CompactionStrategy, DEFAULT_CO
18
21
  export type { CompactRequestOptions, CompactionOptions, CompactionConfig, PendingCompaction } from "./compaction/index.ts";
19
22
  export { userHooksCapability, HookEngine, HOOK_EVENT_TYPES } from "./user-hooks/index.ts";
20
23
  export type { HookDef, HookEventType } from "./user-hooks/index.ts";
21
- export { backgroundCapability, BackgroundManager, CommandBackgroundTask, AgentBackgroundTask, WorkflowBackgroundTask, QuestionBackgroundTask, backgroundListTool, backgroundOutputTool, backgroundStopTool, TERMINAL_STATUSES, isBackgroundTaskTerminal, StoreBackgroundTaskPersistence, DiskBackgroundTaskPersistence, isPersistedTaskTerminal, isValidPersistedTask, } from "./background/index.ts";
22
- export type { BackgroundManagerOptions, BackgroundManagerRuntime, BackgroundTaskOutputDelta, BackgroundTaskOutputSnapshot, BackgroundTask, BackgroundTaskInfo, BackgroundTaskInfoBase, BackgroundTaskSink, BackgroundTaskSettlement, BackgroundTaskSettlementStatus, BackgroundTaskStatus, CommandBackgroundTaskInfo, AgentBackgroundTaskInfo, AgentBackgroundTaskOptions, WorkflowBackgroundTaskInfo, WorkflowBackgroundTaskOptions, QuestionBackgroundTaskInfo, QuestionBackgroundTaskOptions, BackgroundTaskPersistence, PersistedTask, TaskOutputRef, TaskOutputLocation, } from "./background/index.ts";
23
- export { skillsCapability, SkillRegistry, SkillNotFoundError, SkillCatalogInjector, skillTool, flowSkillProvider, flowSkillToolName, resolveSkillRoots, discoverSkills, parseSkillText, parseSkillFromMachine, parseFrontmatter, expandSkillParameters, skillArgumentNames, SkillParseError, FrontmatterError, UnsupportedSkillTypeError, MAX_SKILL_QUERY_DEPTH, NestedSkillTooDeepError, normalizeSkillName, isInlineSkillType, isFlowSkillType, isUserActivatableSkillType, isSupportedSkillType, summarizeSkill, } from "./skills/index.ts";
24
- export type { SkillsOptions, SkillCatalog, SkillDefinition, SkillMetadata, SkillSource, SkillSummary, SkillRoot, SkillPluginContext, SkippedSkill, FlowSkillExecutor, FlowSkillRequest, SkillRegistryOptions, ResolveSkillRootsOptions, DiscoverSkillsOptions, } from "./skills/index.ts";
24
+ export { backgroundCapability, BackgroundManager, CommandBackgroundTask, AgentBackgroundTask, WorkflowBackgroundTask, QuestionBackgroundTask, CodeBackgroundTask, asTaskRegistrar, backgroundListTool, backgroundOutputTool, backgroundStopTool, TERMINAL_STATUSES, isBackgroundTaskTerminal, StoreBackgroundTaskPersistence, DiskBackgroundTaskPersistence, isPersistedTaskTerminal, isValidPersistedTask, } from "./background/index.ts";
25
+ export type { BackgroundManagerOptions, BackgroundManagerRuntime, BackgroundTaskOutputDelta, BackgroundTaskOutputSnapshot, BackgroundTask, BackgroundTaskInfo, BackgroundTaskInfoBase, BackgroundTaskSink, BackgroundTaskSettlement, BackgroundTaskSettlementStatus, BackgroundTaskStatus, CommandBackgroundTaskInfo, AgentBackgroundTaskInfo, AgentBackgroundTaskOptions, WorkflowBackgroundTaskInfo, WorkflowBackgroundTaskOptions, CodeBackgroundTaskInfo, CodeBackgroundTaskOptions, BackgroundTaskRegistrar, QuestionBackgroundTaskInfo, QuestionBackgroundTaskOptions, BackgroundTaskPersistence, PersistedTask, TaskOutputRef, TaskOutputLocation, } from "./background/index.ts";
26
+ export { skillsCapability, loadSkillRoots, SkillRegistry, SkillNotFoundError, SkillCatalogInjector, skillTool, flowSkillProvider, flowSkillToolName, resolveSkillRoots, discoverSkills, parseSkillText, parseSkillFromEnvironment, parseFrontmatter, expandSkillParameters, skillArgumentNames, SkillParseError, FrontmatterError, UnsupportedSkillTypeError, MAX_SKILL_QUERY_DEPTH, NestedSkillTooDeepError, normalizeSkillName, isInlineSkillType, isFlowSkillType, isUserActivatableSkillType, isSupportedSkillType, summarizeSkill, } from "./skills/index.ts";
27
+ export type { ActivateSkillRequest, SkillActivationResult, SkillActivationTrigger, SkillsOptions, SkillCatalog, SkillDefinition, SkillMetadata, SkillSource, SkillSummary, SkillRoot, SkillPluginContext, SkippedSkill, FlowSkillExecutor, FlowSkillRequest, SkillRegistryOptions, ResolveSkillRootsOptions, DiscoverSkillsOptions, } from "./skills/index.ts";
25
28
  //# sourceMappingURL=index.d.ts.map
@@ -1,5 +1,6 @@
1
1
  export { BoundaryInjector, InjectionManager, systemReminder } from "./injection.js";
2
- export { readLog } from "./capability-state.js";
2
+ export { readLog, readSessionLog } from "./capability-state.js";
3
+ export { taskToSubagentRecord, taskToWorkflowSnapshot } from "./background/projections.js";
3
4
  export { staticToolProvider, tagToolSource, toolSource } from "./tool-provider.js";
4
5
  // Extensions are a HARNESS concept and live in `operon-agents` — core deliberately knows
5
6
  // nothing about them. What an extension runtime is built out of is all here: `Capability`,
@@ -17,6 +18,6 @@ export { taskCapability, TaskStore, TaskListInjector, StoreTaskListPersistence,
17
18
  // capability's export of the same name. Use `taskCapability()` to get the wired tools.
18
19
  export { compactionCapability, CompactionService, CompactionStrategy, DEFAULT_COMPACTION_CONFIG, MicroCompaction, estimateTokens, estimateTokensForMessages } from "./compaction/index.js";
19
20
  export { userHooksCapability, HookEngine, HOOK_EVENT_TYPES } from "./user-hooks/index.js";
20
- export { backgroundCapability, BackgroundManager, CommandBackgroundTask, AgentBackgroundTask, WorkflowBackgroundTask, QuestionBackgroundTask, backgroundListTool, backgroundOutputTool, backgroundStopTool, TERMINAL_STATUSES, isBackgroundTaskTerminal, StoreBackgroundTaskPersistence, DiskBackgroundTaskPersistence, isPersistedTaskTerminal, isValidPersistedTask, } from "./background/index.js";
21
- export { skillsCapability, SkillRegistry, SkillNotFoundError, SkillCatalogInjector, skillTool, flowSkillProvider, flowSkillToolName, resolveSkillRoots, discoverSkills, parseSkillText, parseSkillFromMachine, parseFrontmatter, expandSkillParameters, skillArgumentNames, SkillParseError, FrontmatterError, UnsupportedSkillTypeError, MAX_SKILL_QUERY_DEPTH, NestedSkillTooDeepError, normalizeSkillName, isInlineSkillType, isFlowSkillType, isUserActivatableSkillType, isSupportedSkillType, summarizeSkill, } from "./skills/index.js";
21
+ export { backgroundCapability, BackgroundManager, CommandBackgroundTask, AgentBackgroundTask, WorkflowBackgroundTask, QuestionBackgroundTask, CodeBackgroundTask, asTaskRegistrar, backgroundListTool, backgroundOutputTool, backgroundStopTool, TERMINAL_STATUSES, isBackgroundTaskTerminal, StoreBackgroundTaskPersistence, DiskBackgroundTaskPersistence, isPersistedTaskTerminal, isValidPersistedTask, } from "./background/index.js";
22
+ export { skillsCapability, loadSkillRoots, SkillRegistry, SkillNotFoundError, SkillCatalogInjector, skillTool, flowSkillProvider, flowSkillToolName, resolveSkillRoots, discoverSkills, parseSkillText, parseSkillFromEnvironment, parseFrontmatter, expandSkillParameters, skillArgumentNames, SkillParseError, FrontmatterError, UnsupportedSkillTypeError, MAX_SKILL_QUERY_DEPTH, NestedSkillTooDeepError, normalizeSkillName, isInlineSkillType, isFlowSkillType, isUserActivatableSkillType, isSupportedSkillType, summarizeSkill, } from "./skills/index.js";
22
23
  //# sourceMappingURL=index.js.map
@@ -1,24 +1,41 @@
1
- import { readSessionLog } from "../capability-state.js";
1
+ import { DEFAULT_ADDRESS } from "../../store/index.js";
2
2
  import { PlanMode } from "./plan-mode.js";
3
3
  import { enterPlanModeTool, exitPlanModeTool } from "./tools.js";
4
4
  import { exitPlanModeReviewAskPolicy, planModeGuardDenyPolicy, planModeToolApprovePolicy, } from "./policies.js";
5
5
  import { PlanModeInjector } from "./injector.js";
6
6
  export { PlanMode } from "./plan-mode.js";
7
+ const PLAN_TOOL_NAMES = new Set(["EnterPlanMode", "ExitPlanMode"]);
7
8
  export function planCapability(planMode = new PlanMode()) {
8
9
  return {
9
10
  name: "plan",
10
- service: planMode,
11
+ contract: "invariant",
11
12
  tools: [enterPlanModeTool(planMode), exitPlanModeTool(planMode)],
13
+ // Plan mode is a negotiation with the human: enter it and the agent stops acting, exit it
14
+ // and a plan is put up for approval. A subagent has no one to negotiate with — and the mode
15
+ // it would be toggling is the whole session's, including its parent's. So the tools are the
16
+ // root agent's, while the MODE stays session-owned (docs/state-and-lifetime.md §6).
17
+ toolFilters: [(tools, ctx) => (ctx.isRootAgent ? tools : tools.filter((tool) => !PLAN_TOOL_NAMES.has(tool.schema.name)))],
12
18
  policies: [
13
19
  planModeGuardDenyPolicy(planMode),
14
20
  exitPlanModeReviewAskPolicy(planMode),
15
21
  planModeToolApprovePolicy(planMode),
16
22
  ],
17
23
  injectors: [new PlanModeInjector(planMode)],
24
+ service: planMode,
25
+ // The mode is SESSION state (see above): it lives in `main`.
26
+ durableState: {
27
+ snapshot: (address) => (address === DEFAULT_ADDRESS ? planMode.details() : undefined),
28
+ restore: (address, value) => {
29
+ if (address === DEFAULT_ADDRESS)
30
+ planMode.restore(value);
31
+ },
32
+ },
18
33
  openSession: async (ctx) => {
19
- planMode.attachMachine(ctx.machine);
20
- // Rebuild plan-mode state from the log's latest enter/exit result (resume/fork aware).
21
- planMode.reconstruct(await readSessionLog(ctx));
34
+ planMode.attachEnvironment(ctx.environment);
35
+ planMode.attachPersistence(() => ctx.persistState());
36
+ planMode.attachAnnouncer(async (snapshot) => {
37
+ await ctx.events.emit({ type: "plan.updated", snapshot, address: "main", sessionId: ctx.sessionId });
38
+ });
22
39
  },
23
40
  };
24
41
  }
@@ -1,5 +1,4 @@
1
- import type { Machine } from "../../tool/machine.ts";
2
- import type { AgentRecord } from "../../store/index.ts";
1
+ import type { Environment } from "../../tool/environment.ts";
3
2
  export type PlanData = null | {
4
3
  readonly id: string;
5
4
  readonly content: string;
@@ -7,7 +6,8 @@ export type PlanData = null | {
7
6
  };
8
7
  /** Tool names whose results carry plan-mode state in `details`. */
9
8
  export declare const PLAN_TOOL_NAMES: readonly ["EnterPlanMode", "ExitPlanMode"];
10
- /** Plan-mode state carried in enter/exit tool result `details`, folded back on session open. */
9
+ /** Plan-mode state: carried in enter/exit tool result `details` for the transcript, and the
10
+ * whole durable state the plan capability stores after every change. */
11
11
  export interface PlanDetails {
12
12
  readonly planActive: boolean;
13
13
  readonly planId: string | null;
@@ -17,17 +17,38 @@ export declare class PlanMode {
17
17
  private active;
18
18
  private planId;
19
19
  private filePath;
20
- private machine;
21
- attachMachine(machine: Machine): void;
20
+ private environment;
21
+ /** Persists the whole state after each change. Absent in a bare PlanMode (tests). */
22
+ private persist;
23
+ attachEnvironment(environment: Environment): void;
24
+ /**
25
+ * Where entering or leaving plan mode becomes durable — whether the tool did it or the host
26
+ * did (`setEnabled`, e.g. `/plan on`). Awaited by both: plan mode restricts the agent, so a
27
+ * change must not be reported done while a reopen could still come back in the other mode.
28
+ */
29
+ attachPersistence(persist: () => Promise<void>): void;
22
30
  get isActive(): boolean;
23
31
  get planFilePath(): string | null;
24
32
  enter(createFile?: boolean): Promise<void>;
25
- exit(): void;
33
+ exit(): Promise<void>;
26
34
  /** Current state for journaling into an enter/exit tool result `details`. */
27
35
  details(): PlanDetails;
28
- /** Rebuild from the log: the latest enter/exit result is the current plan-mode state.
29
- * Restores in-memory flags only — never re-creates the plan file (no side effects). */
30
- reconstruct(entries: readonly AgentRecord[]): void;
36
+ /**
37
+ * Restore from the value stored for plan mode (undefined: none). Restores in-memory flags
38
+ * only — never re-creates the plan file (no side effects), and persists nothing.
39
+ */
40
+ restore(value: unknown): void;
41
+ /** Set by the capability's provision; absent in a bare PlanMode (tests, replay). */
42
+ private announce;
43
+ /** Where entering or leaving plan mode becomes a `plan.updated` event. See `GoalStore`. */
44
+ attachAnnouncer(announce: (snapshot: PlanData) => Promise<void>): void;
45
+ /**
46
+ * Enter or leave plan mode, and announce the result. Idempotent: asking for the state it is
47
+ * already in changes nothing, but still answers with the current plan.
48
+ */
49
+ setEnabled(enabled: boolean, options?: {
50
+ readonly createFile?: boolean;
51
+ }): Promise<PlanData>;
31
52
  data(): Promise<PlanData>;
32
53
  private planFilePathFor;
33
54
  private safeHome;
@@ -1,5 +1,5 @@
1
1
  import { dirname, join } from "pathe";
2
- import { readTextFile, writeTextFile } from "../../tool/support/machine-ops.js";
2
+ import { readTextFile, writeTextFile } from "../../tool/support/environment-ops.js";
3
3
  /** Tool names whose results carry plan-mode state in `details`. */
4
4
  export const PLAN_TOOL_NAMES = ["EnterPlanMode", "ExitPlanMode"];
5
5
  let planCounter = 0;
@@ -11,9 +11,19 @@ export class PlanMode {
11
11
  active = false;
12
12
  planId = null;
13
13
  filePath = null;
14
- machine = null;
15
- attachMachine(machine) {
16
- this.machine = machine;
14
+ environment = null;
15
+ /** Persists the whole state after each change. Absent in a bare PlanMode (tests). */
16
+ persist;
17
+ attachEnvironment(environment) {
18
+ this.environment = environment;
19
+ }
20
+ /**
21
+ * Where entering or leaving plan mode becomes durable — whether the tool did it or the host
22
+ * did (`setEnabled`, e.g. `/plan on`). Awaited by both: plan mode restricts the agent, so a
23
+ * change must not be reported done while a reopen could still come back in the other mode.
24
+ */
25
+ attachPersistence(persist) {
26
+ this.persist = persist;
17
27
  }
18
28
  get isActive() {
19
29
  return this.active;
@@ -29,45 +39,57 @@ export class PlanMode {
29
39
  this.active = true;
30
40
  this.planId = id;
31
41
  this.filePath = path;
42
+ await this.persist?.();
32
43
  if (createFile) {
33
44
  await this.ensureDir(path);
34
45
  await this.writeEmpty(path);
35
46
  }
36
47
  }
37
- exit() {
48
+ async exit() {
38
49
  this.active = false;
39
50
  this.planId = null;
40
51
  this.filePath = null;
52
+ await this.persist?.();
41
53
  }
42
54
  /** Current state for journaling into an enter/exit tool result `details`. */
43
55
  details() {
44
56
  return { planActive: this.active, planId: this.planId, planFilePath: this.filePath };
45
57
  }
46
- /** Rebuild from the log: the latest enter/exit result is the current plan-mode state.
47
- * Restores in-memory flags only — never re-creates the plan file (no side effects). */
48
- reconstruct(entries) {
49
- let latest;
50
- for (const entry of entries) {
51
- if (entry.type !== "context.append_message")
52
- continue;
53
- const msg = entry.message;
54
- if (msg.role !== "toolResult" || !isPlanToolName(msg.toolName))
55
- continue;
56
- const d = msg.details;
57
- if (d && typeof d.planActive === "boolean") {
58
- latest = { planActive: d.planActive, planId: d.planId ?? null, planFilePath: d.planFilePath ?? null };
59
- }
60
- }
61
- this.active = latest?.planActive ?? false;
62
- this.planId = latest?.planId ?? null;
63
- this.filePath = latest?.planFilePath ?? null;
58
+ /**
59
+ * Restore from the value stored for plan mode (undefined: none). Restores in-memory flags
60
+ * only — never re-creates the plan file (no side effects), and persists nothing.
61
+ */
62
+ restore(value) {
63
+ const d = isPlanDetails(value) ? value : undefined;
64
+ this.active = d?.planActive ?? false;
65
+ this.planId = d?.planId ?? null;
66
+ this.filePath = d?.planFilePath ?? null;
67
+ }
68
+ /** Set by the capability's provision; absent in a bare PlanMode (tests, replay). */
69
+ announce;
70
+ /** Where entering or leaving plan mode becomes a `plan.updated` event. See `GoalStore`. */
71
+ attachAnnouncer(announce) {
72
+ this.announce = announce;
73
+ }
74
+ /**
75
+ * Enter or leave plan mode, and announce the result. Idempotent: asking for the state it is
76
+ * already in changes nothing, but still answers with the current plan.
77
+ */
78
+ async setEnabled(enabled, options = {}) {
79
+ if (enabled && !this.isActive)
80
+ await this.enter(options.createFile ?? true);
81
+ else if (!enabled && this.isActive)
82
+ await this.exit();
83
+ const snapshot = await this.data();
84
+ await this.announce?.(snapshot);
85
+ return snapshot;
64
86
  }
65
87
  async data() {
66
- if (!this.planId || !this.filePath || !this.machine)
88
+ if (!this.planId || !this.filePath || !this.environment)
67
89
  return null;
68
90
  let content = "";
69
91
  try {
70
- content = await readTextFile(this.machine, this.filePath);
92
+ content = await readTextFile(this.environment, this.filePath);
71
93
  }
72
94
  catch (error) {
73
95
  if (!isMissingFileError(error))
@@ -82,7 +104,7 @@ export class PlanMode {
82
104
  }
83
105
  safeHome() {
84
106
  try {
85
- return this.machine?.gethome() ?? "";
107
+ return this.environment?.gethome() ?? "";
86
108
  }
87
109
  catch {
88
110
  return "";
@@ -90,22 +112,25 @@ export class PlanMode {
90
112
  }
91
113
  safeCwd() {
92
114
  try {
93
- return this.machine?.getcwd() ?? "";
115
+ return this.environment?.getcwd() ?? "";
94
116
  }
95
117
  catch {
96
118
  return "";
97
119
  }
98
120
  }
99
121
  async ensureDir(path) {
100
- await this.machine?.mkdir(dirname(path), { parents: true, existOk: true });
122
+ await this.environment?.mkdir(dirname(path), { parents: true, existOk: true });
101
123
  }
102
124
  async writeEmpty(path) {
103
- if (this.machine)
104
- await writeTextFile(this.machine, path, "");
125
+ if (this.environment)
126
+ await writeTextFile(this.environment, path, "");
105
127
  }
106
128
  }
107
- function isPlanToolName(name) {
108
- return PLAN_TOOL_NAMES.includes(name);
129
+ function isPlanDetails(value) {
130
+ if (typeof value !== "object" || value === null)
131
+ return false;
132
+ const v = value;
133
+ return typeof v["planActive"] === "boolean";
109
134
  }
110
135
  function isMissingFileError(error) {
111
136
  return error !== null && typeof error === "object" && error.code === "ENOENT";
@@ -65,7 +65,7 @@ export function exitPlanModeTool(planMode) {
65
65
  display,
66
66
  run: async () => {
67
67
  const wasActive = planMode.isActive;
68
- planMode.exit();
68
+ await planMode.exit();
69
69
  if (!wasActive) {
70
70
  return { content: [{ type: "text", text: "Plan mode was not active. All tools available." }], details: planMode.details() };
71
71
  }