@defrex/autobuild 1.0.0 → 1.1.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 (186) hide show
  1. package/README.md +6 -6
  2. package/SPEC.md +360 -229
  3. package/docs/answering-blocked-builds.md +2 -2
  4. package/docs/architecture.md +155 -45
  5. package/docs/assets/headline-wide.png +0 -0
  6. package/docs/builds.md +4 -4
  7. package/docs/cli.md +4 -4
  8. package/docs/configuration-overview.md +4 -4
  9. package/docs/configuration.md +245 -210
  10. package/docs/dispatcher-hosting.md +2 -2
  11. package/docs/dispatcher.md +1 -1
  12. package/docs/forges.md +5 -5
  13. package/docs/getting-started.md +2 -2
  14. package/docs/glossary.md +6 -6
  15. package/docs/hosted-dispatcher.md +6 -3
  16. package/docs/hosted-service.md +16 -5
  17. package/docs/integration-overview.md +15 -15
  18. package/docs/integration-tree.md +45 -38
  19. package/docs/integration.md +6 -6
  20. package/docs/mcp.md +16 -15
  21. package/docs/{landing-policy.md → merge-policy.md} +42 -24
  22. package/docs/migration-1.0.md +17 -13
  23. package/docs/operating.md +41 -18
  24. package/docs/operator-api.md +91 -15
  25. package/docs/operator-surfaces.md +8 -4
  26. package/docs/overview.md +3 -3
  27. package/docs/remote-store-protocol.md +76 -11
  28. package/docs/remote-ticket-protocol.md +1 -1
  29. package/docs/restacking.md +54 -15
  30. package/docs/setup.md +41 -6
  31. package/docs/skills.md +1 -1
  32. package/docs/spec-standard.md +6 -6
  33. package/docs/ticket-dependencies.md +7 -7
  34. package/docs/tickets.md +8 -2
  35. package/docs/troubleshooting.md +2 -2
  36. package/docs/upgrading.md +8 -3
  37. package/docs/verification.md +60 -14
  38. package/package.json +7 -5
  39. package/packages/core/src/cli/binary-direct.ts +13 -1
  40. package/packages/core/src/cli/binary-lifecycle.ts +65 -2
  41. package/packages/core/src/cli/build-control.ts +83 -28
  42. package/packages/core/src/cli/context.ts +81 -38
  43. package/packages/core/src/cli/dashboard/facts.ts +2 -1
  44. package/packages/core/src/cli/dashboard/integration-detail.ts +8 -8
  45. package/packages/core/src/cli/dashboard/integration-row.ts +40 -13
  46. package/packages/core/src/cli/dashboard/landing-display.ts +25 -0
  47. package/packages/core/src/cli/dashboard/model.ts +56 -33
  48. package/packages/core/src/cli/dashboard/poll.ts +9 -3
  49. package/packages/core/src/cli/dashboard/render.ts +59 -37
  50. package/packages/core/src/cli/dashboard/target-distance.ts +14 -0
  51. package/packages/core/src/cli/dashboard/tree.ts +3 -2
  52. package/packages/core/src/cli/dispatch-args.ts +1 -1
  53. package/packages/core/src/cli/dispatch-frontend.ts +6 -3
  54. package/packages/core/src/cli/dispatch.ts +35 -9
  55. package/packages/core/src/cli/env.ts +4 -0
  56. package/packages/core/src/cli/help.ts +30 -23
  57. package/packages/core/src/cli/main.ts +24 -8
  58. package/packages/core/src/cli/node-verification-provenance.ts +1 -97
  59. package/packages/core/src/cli/publication-settlement.ts +43 -20
  60. package/packages/core/src/cli/repository-status.ts +20 -9
  61. package/packages/core/src/cli/status.ts +42 -5
  62. package/packages/core/src/cli/store-opening.ts +6 -1
  63. package/packages/core/src/cli/terminal.ts +22 -1
  64. package/packages/core/src/cli/terminals.ts +14 -10
  65. package/packages/core/src/cli/upgrade-landing.ts +70 -30
  66. package/packages/core/src/cli/upgrade.ts +3 -1
  67. package/packages/core/src/cli/wait.ts +15 -7
  68. package/packages/core/src/cli/watch-lifetime.ts +111 -0
  69. package/packages/core/src/cli/watch.ts +634 -511
  70. package/packages/core/src/config/effective-artifact.fixture.ts +27 -0
  71. package/packages/core/src/config/effective-artifact.ts +13 -0
  72. package/packages/core/src/config/landing.ts +1 -1
  73. package/packages/core/src/config/load.ts +21 -1
  74. package/packages/core/src/config/pipeline-source.ts +28 -0
  75. package/packages/core/src/config/reference-metadata.ts +2 -0
  76. package/packages/core/src/config/reference.ts +22 -7
  77. package/packages/core/src/config/schema.ts +86 -162
  78. package/packages/core/src/context-directory.ts +26 -0
  79. package/packages/core/src/distribution-packaging.ts +26 -5
  80. package/packages/core/src/events/catalog.ts +10 -2
  81. package/packages/core/src/events/globs.ts +1 -1
  82. package/packages/core/src/events/payloads.ts +70 -1
  83. package/packages/core/src/events/policy.ts +7 -0
  84. package/packages/core/src/events/repository.ts +2 -4
  85. package/packages/core/src/events/sessions.ts +6 -6
  86. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +571 -0
  87. package/packages/core/src/kernel/auto-merge.ts +2 -2
  88. package/packages/core/src/kernel/engine.ts +255 -26
  89. package/packages/core/src/kernel/generators/leaf-restack-log.ts +10 -0
  90. package/packages/core/src/kernel/integration-landing.ts +3 -3
  91. package/packages/core/src/kernel/integration-state.ts +27 -4
  92. package/packages/core/src/kernel/leaf-restack-state.ts +28 -3
  93. package/packages/core/src/kernel/log-index.ts +13 -1
  94. package/packages/core/src/kernel/node-landing.ts +8 -8
  95. package/packages/core/src/kernel/node-parent.ts +2 -2
  96. package/packages/core/src/kernel/node-restack-transaction.ts +1 -1
  97. package/packages/core/src/kernel/node-verification-context.ts +216 -0
  98. package/packages/core/src/kernel/phases.ts +1 -1
  99. package/packages/core/src/kernel/plan-verify-selection.ts +16 -0
  100. package/packages/core/src/kernel/publication-retry.ts +168 -0
  101. package/packages/core/src/kernel/reconcile-restack.ts +29 -1
  102. package/packages/core/src/kernel/reducer.ts +82 -5
  103. package/packages/core/src/kernel/target-distance.ts +45 -0
  104. package/packages/core/src/kernel/terminal-guard.ts +10 -1
  105. package/packages/core/src/kernel/verify-stage-state.ts +123 -0
  106. package/packages/core/src/kernel/verify-stages.ts +39 -0
  107. package/packages/core/src/ontology.ts +1 -0
  108. package/packages/core/src/operator/annotations.ts +6 -0
  109. package/packages/core/src/operator/control.ts +1 -1
  110. package/packages/core/src/operator/index.ts +1 -7
  111. package/packages/core/src/operator/landings.ts +5 -1
  112. package/packages/core/src/operator/presentation.ts +6 -1
  113. package/packages/core/src/operator/query.ts +14 -18
  114. package/packages/core/src/operator/registry.ts +17 -6
  115. package/packages/core/src/operator/sandbox-host.ts +64 -40
  116. package/packages/core/src/operator/sandbox.ts +3 -0
  117. package/packages/core/src/operator/ticket-source-backend.ts +3 -12
  118. package/packages/core/src/ports/forge/contract.ts +2 -2
  119. package/packages/core/src/ports/forge/git-rewrite.ts +25 -2
  120. package/packages/core/src/ports/forge/github-readiness.ts +2 -2
  121. package/packages/core/src/ports/forge/github.ts +26 -7
  122. package/packages/core/src/ports/forge/local-git.ts +4 -4
  123. package/packages/core/src/ports/forge/readiness.ts +1 -1
  124. package/packages/core/src/ports/forge-failure.ts +24 -0
  125. package/packages/core/src/ports/workspace/build-execution.ts +3 -1
  126. package/packages/core/src/ports/workspace/phase-scratch.ts +4 -3
  127. package/packages/core/src/ports/workspace/vercel-sandbox.ts +59 -39
  128. package/packages/core/src/processes/build-child.ts +6 -8
  129. package/packages/core/src/processes/build-execution-state.ts +8 -5
  130. package/packages/core/src/processes/build-runner.ts +522 -98
  131. package/packages/core/src/processes/dispatcher.ts +186 -101
  132. package/packages/core/src/processes/execution-no-progress.ts +8 -1
  133. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  134. package/packages/core/src/processes/publication-loss.ts +8 -2
  135. package/packages/core/src/processes/publication-state.ts +42 -4
  136. package/packages/core/src/processes/repo-view.ts +14 -0
  137. package/packages/core/src/processes/verify-cycle-config.ts +96 -0
  138. package/packages/core/src/{integration → scenarios}/harness.ts +330 -317
  139. package/packages/core/src/store/adapter.ts +1 -0
  140. package/packages/core/src/store/build-scope.ts +9 -0
  141. package/packages/core/src/store/contract.ts +113 -1
  142. package/packages/core/src/store/local/schema.ts +13 -0
  143. package/packages/core/src/store/local/store.ts +42 -0
  144. package/packages/core/src/store/memory.ts +47 -0
  145. package/packages/core/src/store/operator-presence.ts +21 -0
  146. package/packages/core/src/store/phase-session.ts +10 -0
  147. package/packages/core/src/store/reducer-value-shapes.json +5081 -4160
  148. package/packages/core/src/store/remote/client.ts +47 -1
  149. package/packages/core/src/store/remote/compatibility.ts +2 -0
  150. package/packages/core/src/store/remote/protocol.ts +4 -0
  151. package/packages/core/src/store/remote/version.ts +3 -1
  152. package/packages/core/src/store/retention.ts +2 -3
  153. package/packages/core/src/store/session-handle.ts +9 -0
  154. package/packages/core/src/store/streams/session-writer.ts +1 -1
  155. package/packages/core/src/store/types.ts +12 -2
  156. package/packages/core/src/testing/index.ts +11 -1
  157. package/packages/core/src/testing/temp-directories.ts +58 -0
  158. package/skills/code-review/SKILL.md +23 -9
  159. package/skills/finalize/SKILL.md +15 -7
  160. package/skills/guide/SKILL.md +253 -118
  161. package/skills/guide/references/integration-tree.md +45 -38
  162. package/skills/guide/references/{landing-policy.md → merge-policy.md} +42 -24
  163. package/skills/guide/references/migration-1.0.md +17 -13
  164. package/skills/guide/references/operator-api.md +91 -15
  165. package/skills/guide/references/remote-store-protocol.md +76 -11
  166. package/skills/guide/references/remote-ticket-protocol.md +1 -1
  167. package/skills/guide/references/restacking.md +54 -15
  168. package/skills/guide/references/setup.md +41 -6
  169. package/skills/guide/references/spec-standard.md +6 -6
  170. package/skills/guide/references/ticket-dependencies.md +7 -7
  171. package/skills/implement/SKILL.md +43 -17
  172. package/skills/operate/SKILL.md +117 -116
  173. package/skills/plan/SKILL.md +39 -13
  174. package/skills/plan-review/SKILL.md +15 -10
  175. package/skills/reconcile/SKILL.md +22 -3
  176. package/skills/spec/SKILL.md +19 -19
  177. package/skills/tickets/SKILL.md +9 -7
  178. package/templates/autobuild.toml +1 -1
  179. package/templates/hosted-service/package.json +2 -2
  180. package/packages/core/src/orchestrator/approvals.ts +0 -115
  181. package/packages/core/src/orchestrator/conversation.ts +0 -167
  182. package/packages/core/src/orchestrator/model.ts +0 -86
  183. package/packages/core/src/orchestrator/prompt.ts +0 -63
  184. package/packages/core/src/orchestrator/tools.ts +0 -117
  185. package/packages/core/src/orchestrator/turn-runner.ts +0 -457
  186. package/packages/core/src/processes/orchestrator-tick.ts +0 -360
@@ -1,117 +0,0 @@
1
- /**
2
- * Registry entries as AI SDK tools (AUT-342): the turn runner binds the
3
- * in-process operator registry, so the agent's tools ARE the operator
4
- * surface — never a reimplementation.
5
- *
6
- * Two rules shape the binding:
7
- *
8
- * 1. **Attribution.** Every call carries the session operator as the human
9
- * actor with `via: {kind: 'session', id}` — the operator's session did
10
- * it, exactly as an MCP client's calls carry `via: {kind: 'mcp', …}`.
11
- *
12
- * 2. **The model never supplies `repo`.** Every registry entry requires a
13
- * `repo` field and `call()` validates it before the handler runs, but
14
- * nothing in the turn's durable state teaches the model a repository
15
- * identity it could type: message-triggered turns carry no repo fact, the
16
- * canonical skill must stay generic, and the registry has no
17
- * repositories.list tool. The model-facing schema therefore strips `repo`
18
- * (the mirror of the registry's own `extendUnion`), and `execute` injects
19
- * the session's repository into the validated input before
20
- * `registry.call` re-validates it — the session's repository is the only
21
- * value a tool can ever target. The registry's `allowedRepo` guard stays
22
- * bound as defense in depth.
23
- *
24
- * A thrown `RegistryError` is caught and returned as the operator-API
25
- * failure body (`kind`/`error`/`code`) so the model can react to a refusal
26
- * instead of the step dying; the registry's JSON-value invariant makes every
27
- * output wire-safe.
28
- */
29
- import { tool, type ToolSet } from 'ai'
30
- import { z } from 'zod'
31
- import { RegistryError, type OperatorToolRegistry } from '../operator/registry'
32
- import type { Via } from '../events/envelope'
33
- import type { ApprovalDecision } from './approvals'
34
-
35
- /** The model-facing stand-in for a stripped `repo` on schemas Zod 4 refuses
36
- * to `.omit()` — an object carrying refinements (`.refine` locks the shape).
37
- * `safeExtend` preserves the refinements while replacing the field with an
38
- * optional `never`: absent is fine, any supplied value fails validation, so
39
- * the model still cannot point a tool anywhere but the session's
40
- * repository. (Checked against the installed zod; `.omit` and `.extend`
41
- * both throw on refined objects.) */
42
- const unsatisfiableRepo = z.optional(z.never())
43
-
44
- /** Strip `repo` from a tool's model-facing schema: plain `ZodObject` entries
45
- * omit the field; union entries (the `extendUnion` shape) strip each option
46
- * and rebuild the union — Zod 4 unions expose no `withOptions`, so the
47
- * original union must never be handed through unchanged (its members still
48
- * require `repo`, which the model cannot know). Refined objects neutralize
49
- * the field instead of omitting it. Returns undefined only for a schema the
50
- * entry table never uses. */
51
- function stripRepoField(schema: z.ZodType): z.ZodType | undefined {
52
- const options = (schema as unknown as { options?: readonly z.ZodType[] }).options
53
- if (Array.isArray(options) && options.length > 0) {
54
- const stripped = options.map((option) => stripRepoField(option) ?? option)
55
- return z.union(stripped)
56
- }
57
- const object = schema as unknown as {
58
- omit?: (mask: Record<string, boolean>) => unknown
59
- safeExtend?: (patch: Record<string, z.ZodType>) => unknown
60
- }
61
- if (typeof object.omit === 'function') {
62
- try {
63
- return object.omit({ repo: true }) as z.ZodType
64
- } catch {
65
- // A refined object: neutralize `repo` instead of omitting it.
66
- if (typeof object.safeExtend === 'function') {
67
- return object.safeExtend({ repo: unsatisfiableRepo }) as z.ZodType
68
- }
69
- }
70
- }
71
- return undefined
72
- }
73
-
74
- export interface RegistryToolsInput {
75
- registry: OperatorToolRegistry
76
- /** The session's repository — the only value any tool can target. */
77
- repo: string
78
- /** The session operator: the human actor every attributed write names. */
79
- operator: string
80
- /** The session-scoped delegate marker. */
81
- via: Via
82
- /** Optional per-tool approval configuration (from `approvals.ts`), keyed
83
- * by registry tool name; absent keys never suspend. (Kept for signature
84
- * symmetry; the agent takes the configuration directly.) */
85
- toolApproval?: Record<string, ApprovalDecision>
86
- }
87
-
88
- /** Build the AI SDK tool set from the registry's closed table. */
89
- export function registryTools(input: RegistryToolsInput): ToolSet {
90
- const tools: ToolSet = {}
91
- for (const entry of input.registry.entries) {
92
- const modelSchema = stripRepoField(entry.inputSchema)
93
- if (modelSchema === undefined) continue
94
- tools[entry.name] = tool({
95
- description: `${entry.description}${entry.outputDescription ? `\n\nReturns: ${entry.outputDescription}` : ''}`,
96
- inputSchema: modelSchema,
97
- execute: async (modelInput: unknown) => {
98
- // Re-inject the session's repository: the registry re-validates the
99
- // whole input (with `repo`) before the handler runs.
100
- const fullInput =
101
- typeof modelInput === 'object' && modelInput !== null
102
- ? { ...(modelInput as Record<string, unknown>), repo: input.repo }
103
- : { repo: input.repo }
104
- try {
105
- return await input.registry.call(entry.name, fullInput, {
106
- identity: input.operator,
107
- via: input.via,
108
- })
109
- } catch (error) {
110
- if (error instanceof RegistryError) return error.body
111
- throw error
112
- }
113
- },
114
- })
115
- }
116
- return tools
117
- }
@@ -1,457 +0,0 @@
1
- /**
2
- * The orchestrator turn runner (AUT-342): a stateless agent loop over the
3
- * operator tool registry. Every invocation reconstructs its whole
4
- * conversation from durable state (`conversation.ts`), streams its output as
5
- * protocol parts onto the turn's session-scoped stream, checkpoints at step
6
- * boundaries via the stream sink's awaitable flush, and records its outcome
7
- * as session facts. A turn that outlives one function invocation suspends on
8
- * budget and resumes in a fresh invocation without losing a step; a tool in
9
- * the approval list suspends the turn until the operator answers.
10
- *
11
- * Nothing here encodes this repository's specifics.
12
- */
13
- import {
14
- ToolLoopAgent,
15
- convertToModelMessages,
16
- isStepCount,
17
- toUIMessageChunk,
18
- type LanguageModel,
19
- } from 'ai'
20
- import { createSessionStreamSink } from '../store/streams/session-writer'
21
- import type { StreamPart } from '../store/streams/types'
22
- import type { Config } from '../config/schema'
23
- import { ORCHESTRATOR_ROUTE_LIMIT_SECONDS } from '../config/schema'
24
- import type { OperatorToolRegistry } from '../operator/registry'
25
- import { agentActor, type Via } from '../events/envelope'
26
- import type { SessionEventEnvelope, SessionEventWrite, SessionEventType } from '../events/sessions'
27
- import type { SessionTurnTrigger } from '../store/session-reducer'
28
- import { reduceSession } from '../store/session-reducer'
29
- import { validateExpectedSeq, type BuildStore, type Clock } from '../store/types'
30
- import type { IdSource } from '../ids'
31
- import { reconstructConversation } from './conversation'
32
- import { buildTurnSystemPrompt } from './prompt'
33
- import { registryTools } from './tools'
34
- import { approvalConfiguration, parseApprovalEntries } from './approvals'
35
- import { classifyModelError, resolveGatewayModel, type TurnFailureKind } from './model'
36
- export type { TurnFailureKind }
37
-
38
- /** Hard cap on tool-loop steps per invocation — a runaway loop stops here
39
- * even when the budget condition somehow never fires. */
40
- export const ORCHESTRATOR_MAX_STEPS = 32
41
-
42
- /** Seconds of margin the budget condition reserves for the final durable
43
- * flush and outcome writes: the stop condition fires slightly before the
44
- * invocation deadline so the suspension lands durably. */
45
- export const ORCHESTRATOR_FLUSH_MARGIN_SECONDS = 5
46
-
47
- /** The wake input a wake trigger delivers: the attention event record and —
48
- * for a build wake — the build's reduced state, frozen at wake time. A
49
- * journal wake omits `buildState`. Embedded in the `turn.started` payload so
50
- * reconstruction is byte-identical across invocations even though live build
51
- * state keeps moving. */
52
- export interface WakeTurnInput {
53
- event: { seq: number; ts: string; type: string; payload: unknown }
54
- buildState?: unknown
55
- }
56
-
57
- export interface TurnOutcome {
58
- kind: 'completed' | 'suspended' | 'failed'
59
- cause?: 'budget' | 'approval'
60
- failureKind?: TurnFailureKind
61
- usage?: { inputTokens: number; outputTokens: number; steps: number }
62
- error?: string
63
- }
64
-
65
- export interface StartTurnOptions {
66
- /** Remaining invocation budget in seconds (the tick's), clamping the
67
- * configured `invocationBudgetSeconds` for this run. The tick recomputes
68
- * it per session so every turn draws down the same deadline. */
69
- remainingBudgetSeconds?: number
70
- }
71
-
72
- export interface StartTurnResult {
73
- /** False when the session was not idle (or the CAS lost the race) — no
74
- * turn was started and no loop is running. */
75
- started: boolean
76
- turn?: string
77
- stream?: string
78
- /** The running loop's outcome. The caller decides to await it (the tick)
79
- * or background it (the operator route via `after()`); the promise starts
80
- * executing immediately either way. */
81
- outcome?: Promise<TurnOutcome>
82
- }
83
-
84
- export interface ResumeTurnOptions {
85
- /** When the turn was suspended for approval and the operator has answered:
86
- * the decision and the answered tool call id. The runner recovers the
87
- * request's wire `approvalId` from the open stream and appends the
88
- * protocol's `tool-approval-response` part so the SDK's resume path
89
- * executes (approve) or synthesizes the denied output (deny). */
90
- approval?: { decision: 'approve' | 'deny'; toolCallId: string }
91
- /** Remaining invocation budget in seconds (the tick's), clamping the
92
- * configured `invocationBudgetSeconds` for this run. */
93
- remainingBudgetSeconds?: number
94
- }
95
-
96
- export interface ResumeTurnResult {
97
- resumed: boolean
98
- outcome?: Promise<TurnOutcome>
99
- }
100
-
101
- export interface OrchestratorTurnRunner {
102
- startTurn(
103
- sessionId: string,
104
- trigger: SessionTurnTrigger,
105
- wake?: WakeTurnInput,
106
- opts?: StartTurnOptions,
107
- ): Promise<StartTurnResult>
108
- resumeTurn(sessionId: string, opts?: ResumeTurnOptions): Promise<ResumeTurnResult>
109
- }
110
-
111
- export interface OrchestratorRunnerOptions {
112
- store: BuildStore
113
- registry: OperatorToolRegistry
114
- /** The repository this runner serves; the session's repository must match. */
115
- repo: string
116
- config: Config
117
- clock: Clock
118
- ids: IdSource
119
- /** Injected language model; defaults to the configured gateway model. */
120
- model?: LanguageModel
121
- /** Remaining invocation budget in seconds (the tick's), clamping the
122
- * configured `invocationBudgetSeconds` for turns this runner starts. */
123
- remainingBudgetSeconds?: number
124
- /** The agent's in-turn retry bound. Default 2 (the plan's bound); tests
125
- * pass 0 to keep model-failure cases fast. */
126
- maxRetries?: number
127
- }
128
-
129
- /** The agent actor every turn fact carries. */
130
- function turnActor(turn: string) {
131
- return agentActor('orchestrator', turn)
132
- }
133
-
134
- /** The session's reduced state and its event log's last sequence — the CAS
135
- * expectation for the runner's own appends. */
136
- async function reduceSessionState(
137
- store: BuildStore,
138
- sessionId: string,
139
- ): Promise<{ state: ReturnType<typeof reduceSession>; lastSeq: number }> {
140
- const events = await store.getSessionEvents(sessionId)
141
- const state = reduceSession(events)
142
- const lastSeq = events.length > 0 ? (events[events.length - 1]?.seq ?? 0) : 0
143
- return { state, lastSeq }
144
- }
145
-
146
- export function createOrchestratorTurnRunner(
147
- options: OrchestratorRunnerOptions,
148
- ): OrchestratorTurnRunner {
149
- const { store, registry, repo, config, clock, ids } = options
150
- const approvals = parseApprovalEntries(config.orchestrator.approvals)
151
- const approvalConfig = approvalConfiguration(approvals)
152
- const budgetSeconds = Math.min(
153
- config.orchestrator.invocationBudgetSeconds,
154
- ORCHESTRATOR_ROUTE_LIMIT_SECONDS,
155
- )
156
-
157
- function modelFor(): LanguageModel {
158
- return options.model ?? resolveGatewayModel(config.orchestrator.model ?? '')
159
- }
160
-
161
- /** The invocation deadline: min(configured budget, caller-supplied
162
- * remaining budget) in wall-clock milliseconds from now. */
163
- function deadlineMs(remainingBudgetSeconds?: number): number {
164
- const effective =
165
- remainingBudgetSeconds === undefined
166
- ? budgetSeconds
167
- : Math.max(0, Math.min(budgetSeconds, remainingBudgetSeconds))
168
- return clock().getTime() + effective * 1000
169
- }
170
-
171
- /** Append one agent session fact; the store validates and sequences it. */
172
- function append<T extends SessionEventType>(
173
- sessionId: string,
174
- turn: string,
175
- type: T,
176
- payload: SessionEventWrite<T>['payload'],
177
- ): Promise<SessionEventEnvelope<T>> {
178
- return store.appendSessionEvent(sessionId, {
179
- actor: turnActor(turn),
180
- type,
181
- payload,
182
- }) as Promise<SessionEventEnvelope<T>>
183
- }
184
-
185
- // ── The agent loop ────────────────────────────────────────────────────────
186
-
187
- async function runLoop(
188
- sessionId: string,
189
- operator: string,
190
- turn: string,
191
- streamId: string,
192
- deadline: number,
193
- ): Promise<TurnOutcome> {
194
- const sink = createSessionStreamSink({
195
- store,
196
- scope: { kind: 'session', session: sessionId },
197
- })
198
- await sink.resume(streamId)
199
-
200
- // Durable reconstruction — identical model input across invocations.
201
- const events = await store.getSessionEvents(sessionId)
202
- const conversation = await reconstructConversation(store, sessionId, events)
203
- const state = reduceSession(events)
204
- const system = await buildTurnSystemPrompt({
205
- store,
206
- repo,
207
- wakeGlobs: state.wakeGlobs,
208
- config: config.orchestrator,
209
- })
210
-
211
- // Tool-call inputs, remembered as their `tool-input-available` parts pass
212
- // so an approval request can name what the model asked to run.
213
- const toolInputs = new Map<string, { toolName: string; input: unknown }>()
214
- let approvalRequest: { toolCallId: string; toolName: string; input: unknown } | undefined
215
- let budgetFired = false
216
-
217
- const via: Via = { kind: 'session', id: sessionId }
218
- const tools = registryTools({ registry, repo, operator, via })
219
- const agent = new ToolLoopAgent({
220
- model: modelFor(),
221
- instructions: system,
222
- tools,
223
- toolApproval: approvalConfig,
224
- maxRetries: options.maxRetries ?? 2,
225
- stopWhen: [
226
- (_loopState) => {
227
- if (clock().getTime() >= deadline - ORCHESTRATOR_FLUSH_MARGIN_SECONDS * 1000) {
228
- budgetFired = true
229
- return true
230
- }
231
- return false
232
- },
233
- isStepCount(ORCHESTRATOR_MAX_STEPS),
234
- ],
235
- onStepEnd: async () => {
236
- // The checkpoint: everything streamed so far is durable before the
237
- // next step starts.
238
- await sink.flush()
239
- },
240
- })
241
-
242
- const abortController = new AbortController()
243
- const abortTimer = setTimeout(
244
- () => abortController.abort(new Error('orchestrator invocation deadline exceeded')),
245
- Math.max(0, deadline - clock().getTime()),
246
- )
247
- abortTimer.unref?.()
248
-
249
- // The SDK surfaces model failures as `error` parts on the full stream
250
- // (never a thrown error), carrying the ORIGINAL error object — the UI
251
- // chunk reduces it to a generic errorText, so the loop consumes the raw
252
- // stream and maps each part through `toUIMessageChunk` itself: typed
253
- // classification sees the real error class, the sink still stores
254
- // protocol chunks.
255
- try {
256
- const result = await agent.stream({
257
- messages: await convertToModelMessages(conversation.messages),
258
- abortSignal: abortController.signal,
259
- })
260
- for await (const part of result.stream) {
261
- if (part.type === 'error') {
262
- throw part.error
263
- }
264
- const chunk = toUIMessageChunk(part as never, { tools: tools as never })
265
- if (chunk === undefined) continue
266
- sink.append([chunk as unknown as StreamPart])
267
- if (chunk.type === 'tool-input-available') {
268
- toolInputs.set(chunk.toolCallId, {
269
- toolName: chunk.toolName as string,
270
- input: chunk.input,
271
- })
272
- } else if (chunk.type === 'tool-approval-request') {
273
- const known = toolInputs.get(chunk.toolCallId)
274
- approvalRequest = {
275
- toolCallId: chunk.toolCallId,
276
- toolName: known?.toolName ?? 'unknown',
277
- input: known?.input ?? {},
278
- }
279
- }
280
- }
281
- clearTimeout(abortTimer)
282
-
283
- // An approval request suspends the turn for the operator; a budget stop
284
- // suspends it for the next invocation; otherwise the turn completed.
285
- if (approvalRequest !== undefined) {
286
- await append(sessionId, turn, 'approval.requested', {
287
- turn,
288
- toolCallId: approvalRequest.toolCallId,
289
- toolName: approvalRequest.toolName,
290
- input: approvalRequest.input as Record<string, unknown>,
291
- })
292
- await append(sessionId, turn, 'turn.suspended', { turn, cause: 'approval' })
293
- return { kind: 'suspended', cause: 'approval' }
294
- }
295
- if (budgetFired || abortController.signal.aborted) {
296
- await append(sessionId, turn, 'turn.suspended', { turn, cause: 'budget' })
297
- return { kind: 'suspended', cause: 'budget' }
298
- }
299
-
300
- const totalUsage = await result.totalUsage
301
- const steps = await result.steps
302
- const usage = {
303
- inputTokens: totalUsage.inputTokens ?? 0,
304
- outputTokens: totalUsage.outputTokens ?? 0,
305
- steps: steps.length,
306
- }
307
- await append(sessionId, turn, 'turn.completed', { turn, usage })
308
- await sink.close('completed')
309
- return { kind: 'completed', usage }
310
- } catch (error) {
311
- clearTimeout(abortTimer)
312
- if (abortController.signal.aborted) {
313
- // A runaway step interrupted at the deadline: the durable state so
314
- // far is the checkpoint; the next invocation resumes it.
315
- await append(sessionId, turn, 'turn.suspended', { turn, cause: 'budget' })
316
- return { kind: 'suspended', cause: 'budget' }
317
- }
318
- const kind = classifyModelError(error)
319
- const message = error instanceof Error ? error.message : String(error)
320
- await append(sessionId, turn, 'turn.failed', { turn, kind, error: message })
321
- await sink.close('aborted')
322
- return { kind: 'failed', failureKind: kind, error: message }
323
- }
324
- }
325
-
326
- return {
327
- async startTurn(sessionId, trigger, wake, opts = {}) {
328
- const { state, lastSeq } = await reduceSessionState(store, sessionId)
329
- if (state.status !== 'idle') return { started: false }
330
- // Sessions with empty wake settings are never woken.
331
- if (trigger.kind === 'wake' && state.wakeGlobs.length === 0) return { started: false }
332
-
333
- const turn = ids('ot')
334
- // The stream is created before the CAS because the fact must name its
335
- // id; on a miss the just-created stream is closed aborted so a losing
336
- // double-click cannot leak an open stream no turn ever references (the
337
- // reaper only watches turns, so an orphan would otherwise live forever).
338
- const stream = await store.createStream(
339
- { kind: 'session', session: sessionId },
340
- `turn:${turn}`,
341
- )
342
- const payload: Record<string, unknown> = { turn, stream: stream.id, trigger }
343
- if (wake !== undefined) payload.wake = wake
344
-
345
- validateExpectedSeq(lastSeq)
346
- const appended = await store
347
- .appendSessionEventIfCurrent(sessionId, lastSeq, {
348
- actor: turnActor(turn),
349
- type: 'turn.started',
350
- payload,
351
- } as unknown as SessionEventWrite<'turn.started'>)
352
- .catch(() => null)
353
- if (appended === null) {
354
- await store.closeStream(stream.id, 'aborted').catch(() => undefined)
355
- return { started: false }
356
- }
357
-
358
- const record = await store.getSession(sessionId)
359
- const outcome = runLoop(
360
- sessionId,
361
- record?.operator ?? '',
362
- turn,
363
- stream.id,
364
- deadlineMs(opts.remainingBudgetSeconds ?? options.remainingBudgetSeconds),
365
- )
366
- return { started: true, turn, stream: stream.id, outcome }
367
- },
368
-
369
- async resumeTurn(sessionId, opts = {}) {
370
- const { state, lastSeq } = await reduceSessionState(store, sessionId)
371
- if (state.status !== 'suspended') return { resumed: false }
372
- if (state.pendingApproval !== undefined) return { resumed: false }
373
- const open = state.openTurn
374
- if (open === undefined) return { resumed: false }
375
-
376
- if (opts.approval !== undefined) {
377
- const recovered = await recoverApprovalResponse(store, open.stream, opts.approval)
378
- if (recovered === null) {
379
- // A missing request part (e.g. dropped by assembly) fails the
380
- // resume with a typed failure rather than proceeding without it.
381
- await append(sessionId, open.turn, 'turn.failed', {
382
- turn: open.turn,
383
- kind: 'internal',
384
- error: `approval answer for tool call ${JSON.stringify(opts.approval.toolCallId)} matches no persisted approval request`,
385
- })
386
- // The failed resume is terminal, so the turn's stream closes here
387
- // like every other terminal path — the reaper only watches running
388
- // turns and would otherwise never close it. Closing an
389
- // already-closed stream is a contract-pinned no-op, so the
390
- // non-open-stream leg of recoverApprovalResponse's null is covered
391
- // too.
392
- await store.closeStream(open.stream, 'aborted').catch(() => undefined)
393
- return { resumed: false }
394
- }
395
- }
396
-
397
- validateExpectedSeq(lastSeq)
398
- const appended = await store
399
- .appendSessionEventIfCurrent(sessionId, lastSeq, {
400
- actor: turnActor(open.turn),
401
- type: 'turn.resumed',
402
- payload: { turn: open.turn },
403
- } as unknown as SessionEventWrite<'turn.resumed'>)
404
- .catch(() => null)
405
- if (appended === null) return { resumed: false }
406
-
407
- const record = await store.getSession(sessionId)
408
- const outcome = runLoop(
409
- sessionId,
410
- record?.operator ?? '',
411
- open.turn,
412
- open.stream,
413
- deadlineMs(opts.remainingBudgetSeconds),
414
- )
415
- return { resumed: true, outcome }
416
- },
417
- }
418
- }
419
-
420
- /** Scan the open turn's stream for the `tool-approval-request` part whose
421
- * top-level `toolCallId` matches the answered call, and append the protocol's
422
- * `tool-approval-response` part. The persisted parts are UI message stream
423
- * chunks — the SDK flattens the internal approval request into a chunk with
424
- * the call id at the top level, and no `toolCall` property exists on the
425
- * stored chunk — and neither `approval.requested` nor the answer event
426
- * carries the wire `approvalId`, so the stream is its durable home. A deny
427
- * response makes the SDK synthesize the denied tool output. Returns null
428
- * (appending nothing) when no request part matches. */
429
- async function recoverApprovalResponse(
430
- store: BuildStore,
431
- streamId: string,
432
- answer: { decision: 'approve' | 'deny'; toolCallId: string },
433
- ): Promise<{ approvalId: string } | null> {
434
- const read = await store.readStream(streamId)
435
- if (read.status !== 'open') return null
436
- let approvalId: string | undefined
437
- for (const chunk of read.chunks) {
438
- for (const part of chunk.parts) {
439
- if (
440
- part.type === 'tool-approval-request' &&
441
- part.toolCallId === answer.toolCallId &&
442
- typeof part.approvalId === 'string'
443
- ) {
444
- approvalId = part.approvalId
445
- }
446
- }
447
- }
448
- if (approvalId === undefined) return null
449
- await store.appendStreamParts(streamId, [
450
- {
451
- type: 'tool-approval-response',
452
- approvalId,
453
- approved: answer.decision === 'approve',
454
- },
455
- ])
456
- return { approvalId }
457
- }