minicode-ai 0.11.0 → 0.13.0

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 (221) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/LICENSE +21 -21
  3. package/README.md +4 -4
  4. package/cli/args.ts +46 -0
  5. package/cli/commands/acp.ts +163 -10
  6. package/cli/commands/config.ts +33 -18
  7. package/cli/commands/daemon.ts +515 -0
  8. package/cli/commands/exec.ts +145 -53
  9. package/cli/commands/openwork.ts +986 -0
  10. package/cli/commands/sessions.ts +4 -1
  11. package/cli/commands/stats.ts +34 -4
  12. package/cli/commands.ts +217 -2
  13. package/cli/index.ts +146 -14
  14. package/cli/recovery-warning.ts +115 -0
  15. package/cli/router.ts +32 -1
  16. package/cli/setup.ts +2332 -171
  17. package/cli/tui.ts +113 -7
  18. package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +489 -0
  19. package/docs/OUTPUT_EVENT_MODEL.md +289 -0
  20. package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +391 -0
  21. package/docs/OUTPUT_PROTOCOL_SPEC.md +285 -0
  22. package/docs/OUTPUT_RENDERING_SPEC.md +248 -0
  23. package/docs/OUTPUT_UX_RULES.md +449 -0
  24. package/docs/PLAN_UIUX_V6.md +2 -2
  25. package/docs/README.md +4 -3
  26. package/docs/TERMINAL_CONTRACT.md +278 -66
  27. package/docs/architecture.md +89 -7
  28. package/docs/changelog.md +1 -1
  29. package/docs/choosing-mode.md +2 -2
  30. package/docs/cli.md +9 -5
  31. package/docs/concepts.md +1 -1
  32. package/docs/contributing.md +9 -2
  33. package/docs/environment.md +6 -2
  34. package/docs/exec.md +46 -5
  35. package/docs/memory-sessions.md +2 -0
  36. package/docs/policy-sandbox.md +1 -1
  37. package/docs/pricing-budget.md +1 -1
  38. package/docs/quickstart.md +2 -2
  39. package/docs/repl.md +6 -2
  40. package/docs/security-model.md +1 -1
  41. package/docs/security.md +1 -1
  42. package/docs/skills.md +2 -2
  43. package/docs/terminal.md +9 -5
  44. package/docs/tools.md +1 -1
  45. package/package.json +35 -5
  46. package/src/app/session.ts +261 -15
  47. package/src/app/tool-layer.ts +94 -7
  48. package/src/daemon/approvals.ts +361 -0
  49. package/src/daemon/capability.ts +145 -0
  50. package/src/daemon/children.ts +142 -0
  51. package/src/daemon/client.ts +267 -0
  52. package/src/daemon/control.ts +350 -0
  53. package/src/daemon/discovery.ts +234 -0
  54. package/src/daemon/feed.ts +155 -0
  55. package/src/daemon/framing.ts +94 -0
  56. package/src/daemon/host.ts +316 -0
  57. package/src/daemon/protocol.ts +217 -0
  58. package/src/daemon/resource.ts +170 -0
  59. package/src/daemon/sanitize.ts +57 -0
  60. package/src/daemon/server.ts +627 -0
  61. package/src/daemon/store.ts +317 -0
  62. package/src/daemon/subscription.ts +270 -0
  63. package/src/daemon/telemetry.ts +81 -0
  64. package/src/hooks/run.ts +12 -1
  65. package/src/lib/atomic-write.ts +29 -3
  66. package/src/lib/db-path.ts +26 -0
  67. package/src/lib/keystore.ts +544 -42
  68. package/src/lib/net.ts +43 -1
  69. package/src/lib/safe-open.ts +116 -1
  70. package/src/lib/session-id.ts +15 -0
  71. package/src/lsp/client.ts +123 -5
  72. package/src/mcp/client.ts +139 -17
  73. package/src/mcp/server.ts +177 -50
  74. package/src/mcp/transport.ts +16 -19
  75. package/src/memory/vector.ts +770 -55
  76. package/src/policy/allowlist.ts +14 -2
  77. package/src/policy/bash-guard.ts +105 -10
  78. package/src/policy/compaction.ts +82 -5
  79. package/src/policy/consequence-engine.ts +220 -0
  80. package/src/policy/context.ts +132 -0
  81. package/src/policy/executor.ts +187 -121
  82. package/src/policy/no-progress.ts +559 -0
  83. package/src/policy/permission.ts +4 -8
  84. package/src/policy/pricing.ts +17 -3
  85. package/src/policy/scrub.ts +69 -2
  86. package/src/policy/tool-contract.ts +515 -0
  87. package/src/policy/usage.ts +310 -24
  88. package/src/policy/verifier.ts +6 -3
  89. package/src/policy/work-mode.ts +182 -0
  90. package/src/presentation/adapter.ts +533 -26
  91. package/src/presentation/events.ts +151 -0
  92. package/src/presentation/model.ts +180 -27
  93. package/src/presentation/projection.ts +858 -0
  94. package/src/presentation/reducer.ts +645 -310
  95. package/src/presentation/store.ts +12 -7
  96. package/src/providers/anthropic.ts +18 -10
  97. package/src/providers/responses.ts +17 -7
  98. package/src/runtime/capability.ts +409 -0
  99. package/src/runtime/child-execution.ts +274 -0
  100. package/src/runtime/composition.ts +958 -0
  101. package/src/runtime/dispatch.ts +591 -0
  102. package/src/runtime/execution-backend.ts +632 -0
  103. package/src/runtime/execution-events.ts +272 -0
  104. package/src/runtime/execution-id.ts +230 -0
  105. package/src/runtime/execution-journal.ts +926 -0
  106. package/src/runtime/execution-kernel.ts +456 -0
  107. package/src/runtime/execution-registry.ts +379 -0
  108. package/src/runtime/process-supervision.ts +276 -0
  109. package/src/runtime/production-execution.ts +551 -0
  110. package/src/runtime/production-runtime.ts +217 -0
  111. package/src/runtime/recovery-safety.ts +70 -0
  112. package/src/runtime/recovery.ts +477 -0
  113. package/src/runtime/runtime-capabilities.ts +179 -0
  114. package/src/runtime/runtime-diagnostics.ts +141 -0
  115. package/src/runtime/runtime-host.ts +365 -0
  116. package/src/runtime/runtime-status-facts.ts +222 -0
  117. package/src/runtime/runtime-status-provider.ts +74 -0
  118. package/src/runtime/runtime-status.ts +459 -0
  119. package/src/runtime/runtime-task-admission.ts +101 -0
  120. package/src/runtime/supervisor.ts +444 -0
  121. package/src/session/authority.ts +168 -0
  122. package/src/session/checkpoint.ts +88 -1
  123. package/src/session/context-adapter.ts +251 -0
  124. package/src/session/context-assembly.ts +242 -0
  125. package/src/session/context-identity.ts +389 -0
  126. package/src/session/context-projection.ts +248 -0
  127. package/src/session/context-selector.ts +500 -0
  128. package/src/session/cross-session-adoption.ts +249 -0
  129. package/src/session/full-history-fold.ts +171 -0
  130. package/src/session/identity.ts +192 -0
  131. package/src/session/journal.ts +805 -102
  132. package/src/session/open-work-intent.ts +732 -0
  133. package/src/session/open-work.ts +767 -0
  134. package/src/session/pending-tools.ts +94 -0
  135. package/src/session/persistence.ts +3569 -127
  136. package/src/session/runtime-header.ts +208 -0
  137. package/src/session/shadow-git.ts +13 -5
  138. package/src/session/verification.ts +1623 -0
  139. package/src/task/assignment.ts +136 -0
  140. package/src/task/autonomous-adapter.ts +168 -0
  141. package/src/task/autonomous-context.ts +630 -0
  142. package/src/task/autonomous-policy.ts +490 -0
  143. package/src/task/continuity.ts +179 -0
  144. package/src/task/execution-cancellation.ts +165 -0
  145. package/src/task/graph-validate.ts +379 -0
  146. package/src/task/graph.ts +305 -0
  147. package/src/task/identity.ts +230 -0
  148. package/src/task/model.ts +417 -0
  149. package/src/task/production-scheduler.ts +293 -0
  150. package/src/task/readiness.ts +229 -0
  151. package/src/task/scheduler-observability.ts +387 -0
  152. package/src/task/scheduler.ts +1197 -0
  153. package/src/task/scheduling-policy.ts +165 -0
  154. package/src/task/session-authority.ts +148 -0
  155. package/src/task/session-ownership.ts +211 -0
  156. package/src/task/store.ts +2887 -0
  157. package/src/task/sync.ts +343 -0
  158. package/src/task/trigger.ts +260 -0
  159. package/src/tools/bash.ts +377 -211
  160. package/src/tools/code_run.ts +1 -1
  161. package/src/tools/delete_file.ts +1 -1
  162. package/src/tools/edit.ts +33 -6
  163. package/src/tools/evidence.ts +30 -0
  164. package/src/tools/git.ts +4 -4
  165. package/src/tools/glob.ts +12 -3
  166. package/src/tools/grep.ts +1 -1
  167. package/src/tools/lsp.ts +4 -4
  168. package/src/tools/mcp_call.ts +11 -4
  169. package/src/tools/memory.ts +153 -18
  170. package/src/tools/move_file.ts +1 -1
  171. package/src/tools/patch.ts +1 -1
  172. package/src/tools/read_file.ts +1 -1
  173. package/src/tools/read_image.ts +1 -1
  174. package/src/tools/submit_result.ts +1 -1
  175. package/src/tools/task.ts +437 -41
  176. package/src/tools/todo.ts +662 -35
  177. package/src/tools/web_fetch.ts +4 -2
  178. package/src/tools/web_search.ts +9 -3
  179. package/src/tools/write_file.ts +1 -1
  180. package/src/ui/assistant/simple.ts +123 -50
  181. package/src/ui/assistant/turn-status.ts +17 -3
  182. package/src/ui/contract.ts +184 -0
  183. package/src/ui/footer.ts +54 -18
  184. package/src/ui/i18n/en.ts +62 -6
  185. package/src/ui/i18n/id.ts +62 -6
  186. package/src/ui/input/prompt-engine.ts +120 -25
  187. package/src/ui/render/errors.ts +39 -1
  188. package/src/ui/render/markdown-table.ts +455 -0
  189. package/src/ui/render/markdown.ts +22 -1
  190. package/src/ui/render/table-grid.ts +184 -0
  191. package/src/ui/render/table.ts +15 -76
  192. package/src/ui/runtime/screen.ts +7 -2
  193. package/src/ui/runtime/statusline.ts +25 -6
  194. package/src/ui/tui/app.ts +598 -133
  195. package/src/ui/tui/transcript.ts +531 -89
  196. package/vendor/minicore/VENDOR.md +1 -1
  197. package/vendor/minicore/src/core/budget.ts +25 -25
  198. package/vendor/minicore/src/core/compact.ts +75 -75
  199. package/vendor/minicore/src/core/errors.ts +59 -59
  200. package/vendor/minicore/src/core/events.ts +73 -73
  201. package/vendor/minicore/src/core/executor.ts +139 -139
  202. package/vendor/minicore/src/core/history.ts +31 -31
  203. package/vendor/minicore/src/core/index.ts +41 -41
  204. package/vendor/minicore/src/core/loop.ts +355 -355
  205. package/vendor/minicore/src/core/permission.ts +22 -22
  206. package/vendor/minicore/src/core/provider.ts +39 -39
  207. package/vendor/minicore/src/core/recovery.ts +35 -35
  208. package/vendor/minicore/src/core/session.ts +327 -327
  209. package/vendor/minicore/src/core/snapshot.ts +146 -146
  210. package/vendor/minicore/src/core/tokens.ts +107 -107
  211. package/vendor/minicore/src/core/tool.ts +115 -115
  212. package/vendor/minicore/src/core/types.ts +50 -50
  213. package/vendor/minicore/src/providers/openai-compat.ts +417 -417
  214. package/AGENTS.md +0 -45
  215. package/PLAN.md +0 -491
  216. package/docs/ARCHITECTURE.html +0 -1248
  217. package/docs/CONTROL-PLANE-MAP.md +0 -139
  218. package/docs/HARNESS.md +0 -150
  219. package/docs/SUMMARY.md +0 -52
  220. package/docs/UI_RENDER_PIPELINE.md +0 -165
  221. package/docs/USAGE.md +0 -11
@@ -0,0 +1,630 @@
1
+ // PHASE 6R — AUTONOMOUS EXECUTION CONTEXT.
2
+ //
3
+ // 6N F5/§7 established the problem: the production kernel's turn is a WHOLE
4
+ // CONVERSATION MERGE behind a single running slot, with a session-global abort.
5
+ // An autonomous turn cannot reuse the user's session: it would merge into the
6
+ // user's conversation, contend for one busy slot, share one abort channel, and
7
+ // emit into the interactive presentation stream at a moment the user did not ask
8
+ // for.
9
+ //
10
+ // 6O ADR-1 selected Model B: a PRIVATE CHILD SESSION per dispatched work item.
11
+ // This module is that boundary, and nothing else.
12
+ //
13
+ // THE CENTRAL SEPARATION — read this twice, it is the whole design:
14
+ //
15
+ // TASK namespace = the PARENT session. The task being executed IS a row
16
+ // in the parent's namespace, and the lineage/ownership
17
+ // facts (6P) and incarnation guard (6Q) are all expressed
18
+ // in terms of that namespace. Moving it would relocate the
19
+ // task and break every invariant 6P/6Q established.
20
+ // CONVERSATION namespace = a CHILD session id. History, busy slot, abort
21
+ // controller, event bus and counters all belong to it, so
22
+ // the autonomous turn shares NONE of them with the user.
23
+ //
24
+ // A context that conflated the two would either pollute the user's conversation
25
+ // or lose track of which task it is executing. They are deliberately different
26
+ // namespaces and the type system names them differently.
27
+ //
28
+ // [DESIGN DECISION] This module holds NO global/singleton state. A context is
29
+ // constructed with everything it needs (DI), so isolation cannot depend on
30
+ // module-level configuration that another call could mutate.
31
+
32
+ import type { ProductionExecutionRunner } from "../runtime/production-execution.ts"
33
+ import type { OperationalStateSnapshot } from "../session/runtime-header.ts"
34
+ import { buildRuntimeStateHeader } from "../session/runtime-header.ts"
35
+ import type { TaskStore } from "./store.ts"
36
+
37
+ // ── identity ─────────────────────────────────────────────────────────────────
38
+
39
+ /**
40
+ * [PHASE 6R] The deterministic conversation-session id of one autonomous
41
+ * execution.
42
+ *
43
+ * It is derived from (parent, task, generation) so it is reproducible from
44
+ * durable facts alone — no registry, no allocation, nothing to leak.
45
+ *
46
+ * [DESIGN DECISION] The shape is deliberately one an INTERACTIVE session id can
47
+ * never have. Production session ids are 8 hex characters
48
+ * (`cli/commands/acp.ts:334` -> `randomUUID().slice(0, 8)`); this contains a
49
+ * `~` and a `#` and is far longer, so an autonomous context can never be
50
+ * confused with — or collide with — a user's session. `isAutonomousSessionId`
51
+ * is the recogniser, and `assertNotAutonomousSessionId` is used on every
52
+ * interactive entry point that must refuse an autonomous id.
53
+ */
54
+ export function autonomousSessionId(
55
+ parentSessionId: string,
56
+ taskId: string,
57
+ execGeneration: number,
58
+ ): string {
59
+ return `auto~${parentSessionId}~${taskId}~${execGeneration}`
60
+ }
61
+
62
+ /** True for an id produced by `autonomousSessionId`. */
63
+ export function isAutonomousSessionId(sessionId: string): boolean {
64
+ return sessionId.startsWith("auto~") && sessionId.split("~").length === 4
65
+ }
66
+
67
+ /** Parse an autonomous id back into its parts, or null if it is not one. */
68
+ export function parseAutonomousSessionId(
69
+ sessionId: string,
70
+ ): { parentSessionId: string; taskId: string; execGeneration: number } | null {
71
+ if (!isAutonomousSessionId(sessionId)) return null
72
+ const parts = sessionId.split("~")
73
+ const [, parentSessionId, taskId, gen] = parts
74
+ const n = Number(gen)
75
+ if (parentSessionId === undefined || taskId === undefined) return null
76
+ if (!Number.isSafeInteger(n) || n < 1) return null
77
+ return { parentSessionId, taskId, execGeneration: n }
78
+ }
79
+
80
+ // ── tool scope ───────────────────────────────────────────────────────────────
81
+
82
+ import {
83
+ AUTONOMOUS_TOOL_NAMES,
84
+ type AutonomousDenialReason,
85
+ type AutonomousPermissionHandler,
86
+ AutonomousPolicyLedger,
87
+ assertAutonomousToolScope,
88
+ createAutonomousPermissionHandler,
89
+ } from "./autonomous-policy.ts"
90
+
91
+ export { AUTONOMOUS_TOOL_NAMES, assertAutonomousToolScope }
92
+
93
+ // ── the injected session primitive ───────────────────────────────────────────
94
+
95
+ /**
96
+ * [PHASE 6R] The structural subset of a child session this module uses.
97
+ *
98
+ * Deliberately the SAME shape as `SubAgentSession` in `src/tools/task.ts`, so the
99
+ * existing sub-agent session factory can satisfy it unchanged. [DESIGN DECISION]
100
+ * Reusing that seam is what keeps 6R from becoming a second session system.
101
+ */
102
+ export interface AutonomousSession {
103
+ run(
104
+ input: string,
105
+ opts: { signal: AbortSignal; model?: string },
106
+ ): Promise<{ finalText?: string; usage: { steps: number } }>
107
+ abort(): void
108
+ /** Present on the kernel Session (`vendor/minicore/.../session.ts:278`). */
109
+ cleanup?(): void
110
+ }
111
+
112
+ export interface AutonomousSessionSpec {
113
+ readonly provider: unknown
114
+ readonly tools: readonly { name: string }[]
115
+ readonly cwd: string
116
+ readonly permissionMode: "readonly"
117
+ readonly maxSteps: number
118
+ readonly timeoutMs: number
119
+ readonly systemExtra: string
120
+ /** The CHILD session id. Metadata only — never the parent. */
121
+ readonly sessionId: string
122
+ readonly parentSessionId: string
123
+ readonly model?: string
124
+ /**
125
+ * [PHASE 6S] The INVOCATION-TIME gate.
126
+ *
127
+ * [DESIGN DECISION] The creation-time tool-set check is necessary but not
128
+ * sufficient: `withMcpTools()` appends MCP tools to a registry at runtime, so
129
+ * a set that was correct when the context was built can be stale by the time a
130
+ * call is made. The kernel guarantees it consults `SessionConfig.permissions`
131
+ * before every tool execution, so this is the narrowest authoritative
132
+ * boundary, and the handler denies out-of-scope calls immediately and
133
+ * synchronously - it can never block waiting for a human who is not there.
134
+ */
135
+ readonly permissionHandler: AutonomousPermissionHandler
136
+ }
137
+
138
+ // ── outcomes ─────────────────────────────────────────────────────────────────
139
+
140
+ /**
141
+ * [PHASE 6R][DESIGN DECISION] The autonomous turn contract.
142
+ *
143
+ * 6N §7 required that normal/error/cancellation be DISTINCT rather than collapsed
144
+ * into one generic exception, so a caller can tell "the model failed" from "the
145
+ * user pressed stop" from "the session I belonged to is gone". `cancelled` and
146
+ * `session-superseded` in particular must not be mistaken for a work failure:
147
+ * neither is evidence that the task was not done.
148
+ */
149
+ export type AutonomousOutcome =
150
+ | "returned"
151
+ | "error"
152
+ | "cancelled"
153
+ | "session-superseded"
154
+ | "task-superseded"
155
+ | "permission-denied"
156
+
157
+ export interface AutonomousTurnResult {
158
+ readonly outcome: AutonomousOutcome
159
+ readonly ok: boolean
160
+ readonly detail?: string
161
+ readonly finalText?: string
162
+ readonly steps: number
163
+ /** The child session this ran in, for attribution and diagnosis. */
164
+ readonly childSessionId: string
165
+ }
166
+
167
+ export type AutonomousContextState =
168
+ | "created"
169
+ | "initializing"
170
+ | "ready"
171
+ | "executing"
172
+ | "settled"
173
+ | "disposed"
174
+
175
+ // ── the context ──────────────────────────────────────────────────────────────
176
+
177
+ export interface AutonomousContextConfig {
178
+ /** The session that OWNS the task. Task namespace == this session. */
179
+ readonly parentSessionId: string
180
+ readonly taskId: string
181
+ readonly taskTitle: string
182
+ readonly instruction: string
183
+ /** The generation the Scheduler claimed; part of the child identity. */
184
+ readonly execGeneration: number
185
+ /** [6Q] The parent incarnation the claim was made under. */
186
+ readonly sessionIncarnation: number
187
+ /**
188
+ * The workspace the task belongs to. [DESIGN DECISION] REQUIRED, never
189
+ * defaulted to `process.cwd()`: 6R §11 requires the autonomous execution to
190
+ * run deterministically in the task's workspace, and a silent fallback is how
191
+ * an executor ends up reading or writing the wrong project.
192
+ */
193
+ readonly cwd: string
194
+ readonly model?: string
195
+ readonly maxSteps?: number
196
+ readonly timeoutMs?: number
197
+ readonly provider?: unknown
198
+ /**
199
+ * Child-session factory (DI). In production this is `createMinicodeSession`;
200
+ * in tests it is a fake. [DESIGN DECISION] No default: a context must never
201
+ * construct a real provider chain implicitly.
202
+ */
203
+ readonly sessionFactory: (spec: AutonomousSessionSpec) => Promise<AutonomousSession>
204
+ readonly tools: readonly { name: string }[]
205
+ readonly onEvent?: (event: AutonomousContextEvent) => void
206
+ /**
207
+ * [Fase 4 / LOOP-13, LOOP-INV-16] Snapshot state operasional deterministik
208
+ * yang dirender ke header `[RUNTIME_STATE_HEADER ...]` di konteks otonom.
209
+ * Opsional: absen = perilaku lama persis (tanpa header).
210
+ */
211
+ readonly operationalState?: () => OperationalStateSnapshot | null
212
+ /**
213
+ * [P1 M15] Admission runtime (DI) untuk turn otonom.
214
+ *
215
+ * [DESIGN DECISION] Opsional dan default TIDAK ada: tanpa ini, `execute()`
216
+ * persis seperti sebelum M15. Xiang dispatcher tidak boleh mengarang eksekusi —
217
+ * ia hanya meneruskan intent ke M13 yang sudah memutuskan.
218
+ *
219
+ * Tidak ada jalur ganda: kalau runner ada, turn ini SELALU lewat runner; kalau
220
+ * tidak, SELALU legacy. Tidak pernah keduanya untuk satu intent.
221
+ */
222
+ readonly executionRunner?: ProductionExecutionRunner
223
+ }
224
+
225
+ export type AutonomousContextEvent =
226
+ | { readonly kind: "context:created"; readonly childSessionId: string }
227
+ | { readonly kind: "context:ready"; readonly childSessionId: string }
228
+ | { readonly kind: "turn:started"; readonly childSessionId: string }
229
+ | {
230
+ readonly kind: "turn:settled"
231
+ readonly childSessionId: string
232
+ readonly outcome: AutonomousOutcome
233
+ }
234
+ | { readonly kind: "context:disposed"; readonly childSessionId: string }
235
+
236
+ export class AutonomousContextError extends Error {
237
+ readonly reason: string
238
+ constructor(reason: string, message: string) {
239
+ super(message)
240
+ this.name = "AutonomousContextError"
241
+ this.reason = reason
242
+ }
243
+ }
244
+
245
+ /**
246
+ * [PHASE 6R] One autonomous execution: a private child conversation session
247
+ * bound to exactly one claimed task of one parent session.
248
+ *
249
+ * LIFECYCLE: create -> initialize -> execute -> settled -> dispose. Every
250
+ * terminal path lands in `dispose`, and `dispose` is idempotent, so no execution
251
+ * can leave a listener, an AbortController, or a provider resource behind.
252
+ */
253
+ export class AutonomousExecutionContext {
254
+ readonly childSessionId: string
255
+ readonly parentSessionId: string
256
+ readonly taskId: string
257
+ readonly execGeneration: number
258
+ readonly sessionIncarnation: number
259
+ readonly cwd: string
260
+
261
+ private readonly config: AutonomousContextConfig
262
+ private state: AutonomousContextState = "created"
263
+ private session: AutonomousSession | null = null
264
+ /**
265
+ * [DESIGN DECISION] Its OWN AbortController. The parent's abort is never wired
266
+ * in and this one is never exposed, so cancelling a user turn cannot cancel an
267
+ * autonomous execution and vice versa. Cancellation of THIS context only.
268
+ */
269
+ private readonly abort: AbortController = new AbortController()
270
+ private cancelRequested = false
271
+ /**
272
+ * [PHASE 6S] Per-execution denial record. Not module-global, so two concurrent
273
+ * contexts cannot read each other's denials. Its only purpose is to let
274
+ * `execute()` distinguish "the model asked for something forbidden" from a
275
+ * generic failure - the turn result alone cannot say.
276
+ */
277
+ private readonly ledger: AutonomousPolicyLedger = new AutonomousPolicyLedger()
278
+
279
+ constructor(config: AutonomousContextConfig) {
280
+ // [DESIGN DECISION] Identity is derived, never supplied, so two contexts for
281
+ // the same work are literally the same identity and cannot silently diverge.
282
+ this.childSessionId = autonomousSessionId(
283
+ config.parentSessionId,
284
+ config.taskId,
285
+ config.execGeneration,
286
+ )
287
+ this.parentSessionId = config.parentSessionId
288
+ this.taskId = config.taskId
289
+ this.execGeneration = config.execGeneration
290
+ this.sessionIncarnation = config.sessionIncarnation
291
+ this.cwd = config.cwd
292
+ this.config = config
293
+ }
294
+
295
+ getState(): AutonomousContextState {
296
+ return this.state
297
+ }
298
+
299
+ getSession(): AutonomousSession | null {
300
+ return this.session
301
+ }
302
+
303
+ /**
304
+ * [PHASE 6S] Every capability the policy refused during this execution.
305
+ *
306
+ * Exposed so the caller can attribute a failure, and so a test can assert the
307
+ * gate fired without inferring it from a turn's prose.
308
+ */
309
+ getDenials(): readonly { tool: string; reason: AutonomousDenialReason }[] {
310
+ return this.ledger.denials_
311
+ }
312
+
313
+ private emit(event: AutonomousContextEvent): void {
314
+ try {
315
+ this.config.onEvent?.(event)
316
+ } catch {
317
+ // An observer may never fail an execution - same rule as Scheduler.emit.
318
+ }
319
+ }
320
+
321
+ /**
322
+ * Build the child session.
323
+ *
324
+ * [DESIGN DECISION] The tool scope is checked HERE, at construction, so a
325
+ * misconfigured factory cannot hand an unattended executor a writable tool set
326
+ * even for one turn.
327
+ */
328
+ async initialize(): Promise<void> {
329
+ if (this.state !== "created") {
330
+ throw new AutonomousContextError("lifecycle", `cannot initialize from ${this.state}`)
331
+ }
332
+ this.state = "initializing"
333
+ assertAutonomousToolScope(this.config.tools.map((t) => t.name))
334
+ this.emit({ kind: "context:created", childSessionId: this.childSessionId })
335
+
336
+ this.session = await this.config.sessionFactory({
337
+ provider: this.config.provider,
338
+ tools: this.config.tools,
339
+ cwd: this.cwd,
340
+ // [DESIGN DECISION] `readonly` is fixed, not inherited. An autonomous
341
+ // executor never receives the user's live permission mode: a human
342
+ // widening or narrowing interactive permissions mid-session must not
343
+ // silently change what an unattended executor may do.
344
+ permissionMode: "readonly",
345
+ maxSteps: this.config.maxSteps ?? 8,
346
+ timeoutMs: this.config.timeoutMs ?? 120_000,
347
+ systemExtra: this.systemExtra(),
348
+ sessionId: this.childSessionId,
349
+ parentSessionId: this.parentSessionId,
350
+ // [PHASE 6S] the invocation-time gate, built from THIS context's ledger
351
+ permissionHandler: createAutonomousPermissionHandler(this.ledger),
352
+ ...(this.config.model ? { model: this.config.model } : {}),
353
+ })
354
+ this.state = "ready"
355
+ this.emit({ kind: "context:ready", childSessionId: this.childSessionId })
356
+ }
357
+
358
+ /**
359
+ * [PHASE 6R] The minimum sufficient context for the turn.
360
+ *
361
+ * [DESIGN DECISION] It contains the TASK and the workspace - never the user's
362
+ * conversation. The user's history is not loaded, not summarised and not
363
+ * referenced: a background worker has no use for it, and copying it is exactly
364
+ * how an autonomous run ends up conditioned on an unrelated request. The
365
+ * child's own `ContextStore` starts empty, so "child session" genuinely means
366
+ * an empty conversation rather than a shared one.
367
+ */
368
+ private systemExtra(): string {
369
+ const base = [
370
+ "You are an AUTONOMOUS execution context, not an interactive assistant.",
371
+ "No user is watching this turn. There is no one to answer a question, so " +
372
+ "never call ask_user; state what you need in your final message instead.",
373
+ "You have read-only tools. Do not attempt to modify files, run commands, " +
374
+ "or change any task: you cannot, and trying is a failed run.",
375
+ `Workspace: ${this.cwd}`,
376
+ `Task: ${this.config.taskTitle}`,
377
+ `Task instruction: ${this.config.instruction}`,
378
+ ].join("\n")
379
+ // [Fase 4 / LOOP-13, LOOP-INV-16] Header operasional deterministik ikut
380
+ // dikirim ke model otonom bila snapshot tersedia. Absen = perilaku lama.
381
+ let header = ""
382
+ try {
383
+ const state = this.config.operationalState?.()
384
+ if (state) header = `${buildRuntimeStateHeader(state)}\n\n`
385
+ } catch {
386
+ // Observability tak boleh menggagalkan eksekusi otonom.
387
+ }
388
+ return `${header}${base}`
389
+ }
390
+
391
+ /**
392
+ * Run the autonomous turn.
393
+ *
394
+ * [DESIGN DECISION] Every outcome is a RETURN VALUE, including cancellation
395
+ * and supersession. An unattended executor has no one to throw to, so a throw
396
+ * here would either kill the process or be swallowed into a false "the model
397
+ * failed".
398
+ */
399
+ async execute(): Promise<AutonomousTurnResult> {
400
+ if (this.state === "disposed") {
401
+ throw new AutonomousContextError("lifecycle", "context is disposed")
402
+ }
403
+ if (this.session === null) await this.initialize()
404
+ const session = this.session!
405
+ this.state = "executing"
406
+ this.emit({ kind: "turn:started", childSessionId: this.childSessionId })
407
+
408
+ const settle = (r: AutonomousTurnResult): AutonomousTurnResult => {
409
+ this.state = "settled"
410
+ this.emit({ kind: "turn:settled", childSessionId: this.childSessionId, outcome: r.outcome })
411
+ return r
412
+ }
413
+
414
+ // A cancellation requested before the turn began is honoured, not raced.
415
+ if (this.cancelRequested || this.abort.signal.aborted) {
416
+ return settle({
417
+ outcome: "cancelled",
418
+ ok: false,
419
+ detail: "cancelled before the turn started",
420
+ steps: 0,
421
+ childSessionId: this.childSessionId,
422
+ })
423
+ }
424
+
425
+ this.emit({ kind: "turn:started", childSessionId: this.childSessionId })
426
+ try {
427
+ // [P1 M15] Turn otonom melewati admission runtime bila ada runner (mode
428
+ // `owned`). Kegagalan admission = TIDAK ada eksekusi (fail-closed) dan
429
+ // dilaporkan sebagai hasil turn yang gagal — bukan "jalankan legacy saja",
430
+ // yang akan membuat dua jalur untuk satu intent.
431
+ const runner = this.config.executionRunner
432
+ const runTurn = () =>
433
+ session.run(this.config.instruction, {
434
+ signal: this.abort.signal,
435
+ ...(this.config.model ? { model: this.config.model } : {}),
436
+ })
437
+ const outcome = runner
438
+ ? await runner.run(
439
+ {
440
+ kind: "background",
441
+ schedulerSource: "autonomous",
442
+ // Authority adalah milik lease Scheduler, bukan milik konteks: ia
443
+ // sudah dibuktikan di claim (store.claimTask + session lease).
444
+ authorityHeld: true,
445
+ provenance: { requestedBy: "scheduler", reason: `task=${this.config.taskId}` },
446
+ taskId: this.config.taskId,
447
+ generation: this.config.execGeneration,
448
+ },
449
+ runTurn,
450
+ { signal: this.abort.signal },
451
+ )
452
+ : null
453
+ const res = outcome
454
+ ? (outcome.result as Awaited<ReturnType<typeof runTurn>>)
455
+ : await runTurn()
456
+ // A run that resolves after our own cancellation is a CANCELLED turn, not a
457
+ // successful one: the abort may have been observed late.
458
+ if (this.cancelRequested || this.abort.signal.aborted) {
459
+ return settle({
460
+ outcome: "cancelled",
461
+ ok: false,
462
+ detail: "cancelled during the turn",
463
+ steps: res.usage?.steps ?? 0,
464
+ childSessionId: this.childSessionId,
465
+ })
466
+ }
467
+ // [PHASE 6S] A refusal DISQUALIFIES the turn, even though it resolved.
468
+ //
469
+ // [DESIGN DECISION] The model can catch a denial, apologise in prose and
470
+ // return a confident summary - `run()` resolves normally and its exit code
471
+ // says nothing about what happened. Reporting `returned` in that case would
472
+ // be the worst available answer: it tells the Scheduler the autonomous
473
+ // execution SUCCEEDED, and 6P would then let it commit that claim while the
474
+ // work was never permitted, let alone done. A capability refusal is
475
+ // therefore a terminal outcome in its own right, checked before success.
476
+ if (this.ledger.denied) {
477
+ return settle({
478
+ outcome: "permission-denied",
479
+ ok: false,
480
+ detail: `autonomous policy refused: ${this.ledger.summary()}`,
481
+ steps: res.usage?.steps ?? 0,
482
+ childSessionId: this.childSessionId,
483
+ })
484
+ }
485
+ return settle({
486
+ outcome: "returned",
487
+ ok: true,
488
+ ...(res.finalText === undefined ? {} : { finalText: res.finalText }),
489
+ steps: res.usage?.steps ?? 0,
490
+ childSessionId: this.childSessionId,
491
+ })
492
+ } catch (e) {
493
+ const detail = e instanceof Error ? e.message : String(e)
494
+ if (this.cancelRequested || this.abort.signal.aborted) {
495
+ return settle({
496
+ outcome: "cancelled",
497
+ ok: false,
498
+ detail,
499
+ steps: 0,
500
+ childSessionId: this.childSessionId,
501
+ })
502
+ }
503
+ // [PHASE 6S] A refusal is deterministic; the `busy` classification below is a
504
+ // guess read out of an error message. A deterministic fact outranks a
505
+ // heuristic, so the policy verdict is consulted first.
506
+ if (this.ledger.denied) {
507
+ return settle({
508
+ outcome: "permission-denied",
509
+ ok: false,
510
+ detail: `autonomous policy refused: ${this.ledger.summary()}`,
511
+ steps: 0,
512
+ childSessionId: this.childSessionId,
513
+ })
514
+ }
515
+ // The kernel reports contention as a `busy` AgentError. In an autonomous
516
+ // context that means THIS child was already running, which is a lifecycle
517
+ // fault rather than a work failure, and must stay distinguishable.
518
+ if (/already running|\bbusy\b/i.test(detail)) {
519
+ return settle({
520
+ outcome: "error",
521
+ ok: false,
522
+ detail,
523
+ steps: 0,
524
+ childSessionId: this.childSessionId,
525
+ })
526
+ }
527
+ return settle({
528
+ outcome: "error",
529
+ ok: false,
530
+ detail,
531
+ steps: 0,
532
+ childSessionId: this.childSessionId,
533
+ })
534
+ }
535
+ }
536
+
537
+ /**
538
+ * Cancel THIS execution only.
539
+ *
540
+ * [DESIGN DECISION] Aborts the context's own controller AND the child session's
541
+ * own abort, so both the in-flight turn and any later `run()` on the child see
542
+ * the cancellation. It cannot reach the parent: nothing here holds a reference
543
+ * to the parent's session or abort.
544
+ */
545
+ cancel(_reason = "cancelled"): void {
546
+ if (this.state === "disposed") return
547
+ this.cancelRequested = true
548
+ if (!this.abort.signal.aborted) this.abort.abort(new Error("autonomous execution cancelled"))
549
+ try {
550
+ this.session?.abort()
551
+ } catch {
552
+ // Aborting a session that already ended is not an error worth propagating.
553
+ }
554
+ }
555
+
556
+ get isCancelled(): boolean {
557
+ return this.cancelRequested || this.abort.signal.aborted
558
+ }
559
+
560
+ /**
561
+ * Release everything this context owns.
562
+ *
563
+ * Idempotent, and safe to call from any state including mid-turn: the abort is
564
+ * fired first so an in-flight turn stops, then the child's provider resources
565
+ * are released through the kernel's own `cleanup()`.
566
+ */
567
+ dispose(): void {
568
+ if (this.state === "disposed") return
569
+ if (!this.abort.signal.aborted) {
570
+ this.abort.abort(new Error("autonomous context disposed"))
571
+ }
572
+ const session = this.session
573
+ this.session = null
574
+ // [6R] The child's OWN abort as well as ours. `run()` joins them, so aborting
575
+ // ours is enough to stop the in-flight turn - but only the child's abort marks
576
+ // the KERNEL session as aborted, which is what makes a disposed child
577
+ // unusable for any later `run()`. Disposal that leaves the child runnable
578
+ // would make "disposed" a claim rather than a fact.
579
+ try {
580
+ session?.abort()
581
+ } catch {
582
+ // Aborting a session that already ended is not an error worth propagating.
583
+ }
584
+ try {
585
+ session?.cleanup?.()
586
+ } catch {
587
+ // Cleanup must never throw out of dispose: a disposal path that can fail is
588
+ // a disposal path that leaks.
589
+ }
590
+ this.state = "disposed"
591
+ this.emit({ kind: "context:disposed", childSessionId: this.childSessionId })
592
+ }
593
+ }
594
+
595
+ // ── identity verification ────────────────────────────────────────────────────
596
+
597
+ /**
598
+ * [PHASE 6R] Fail closed when a context does not belong to the session it claims.
599
+ *
600
+ * Used on every path where a context is handed a session id, so a mismatched or
601
+ * replayed context cannot execute against the wrong namespace. [DESIGN DECISION]
602
+ * A durable check rather than an assertion: this is the boundary where a wrong
603
+ * answer would let an executor read or write another session's tasks.
604
+ */
605
+ export function assertContextBelongsTo(
606
+ context: AutonomousExecutionContext,
607
+ sessionId: string,
608
+ expectedIncarnation: number,
609
+ ): void {
610
+ if (context.parentSessionId !== sessionId) {
611
+ throw new AutonomousContextError(
612
+ "identity",
613
+ `context belongs to session ${context.parentSessionId}, not ${sessionId}`,
614
+ )
615
+ }
616
+ if (context.sessionIncarnation !== expectedIncarnation) {
617
+ throw new AutonomousContextError(
618
+ "identity",
619
+ `context was created under incarnation ${context.sessionIncarnation}, current is ${expectedIncarnation}`,
620
+ )
621
+ }
622
+ if (!isAutonomousSessionId(context.childSessionId)) {
623
+ throw new AutonomousContextError(
624
+ "identity",
625
+ `child session id is not an autonomous id: ${context.childSessionId}`,
626
+ )
627
+ }
628
+ }
629
+
630
+ export type { TaskStore }