@defrex/autobuild 1.0.0-beta.0 → 1.0.0-beta.2

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 (162) hide show
  1. package/README.md +9 -4
  2. package/SPEC.md +295 -62
  3. package/bin/ab-build-runner.ts +10 -8
  4. package/docs/architecture.md +179 -25
  5. package/docs/configuration.md +41 -6
  6. package/docs/hosted-service.md +35 -0
  7. package/docs/integration-tree.md +81 -4
  8. package/docs/landing-policy.md +11 -0
  9. package/docs/migration-1.0.md +9 -0
  10. package/docs/operator-api.md +18 -0
  11. package/docs/remote-store-protocol.md +11 -0
  12. package/docs/restacking.md +42 -7
  13. package/docs/setup.md +25 -0
  14. package/docs/ticket-dependencies.md +6 -45
  15. package/package.json +3 -3
  16. package/packages/core/src/cli/attention.ts +4 -1
  17. package/packages/core/src/cli/binary.ts +17 -1
  18. package/packages/core/src/cli/context.ts +53 -1
  19. package/packages/core/src/cli/dashboard/actions.ts +4 -0
  20. package/packages/core/src/cli/dashboard/detail.ts +45 -1
  21. package/packages/core/src/cli/dashboard/facts.ts +7 -2
  22. package/packages/core/src/cli/dashboard/integration-detail.ts +142 -0
  23. package/packages/core/src/cli/dashboard/integration-row.ts +248 -0
  24. package/packages/core/src/cli/dashboard/landing-display.ts +64 -0
  25. package/packages/core/src/cli/dashboard/model.ts +140 -16
  26. package/packages/core/src/cli/dashboard/poll.ts +40 -4
  27. package/packages/core/src/cli/dashboard/refresh.ts +20 -13
  28. package/packages/core/src/cli/dashboard/render.ts +106 -5
  29. package/packages/core/src/cli/dashboard/transcript.ts +2 -1
  30. package/packages/core/src/cli/dispatch-frontend.ts +22 -12
  31. package/packages/core/src/cli/dispatch.ts +59 -25
  32. package/packages/core/src/cli/help.ts +19 -2
  33. package/packages/core/src/cli/main.ts +37 -0
  34. package/packages/core/src/cli/publication-settlement.ts +49 -5
  35. package/packages/core/src/cli/repository-status.ts +97 -2
  36. package/packages/core/src/cli/status.ts +24 -1
  37. package/packages/core/src/cli/terminals.ts +94 -93
  38. package/packages/core/src/cli/wait.ts +11 -2
  39. package/packages/core/src/cli/watch.ts +12 -0
  40. package/packages/core/src/config/schema.ts +3 -0
  41. package/packages/core/src/events/catalog.ts +38 -0
  42. package/packages/core/src/events/compatibility.ts +183 -0
  43. package/packages/core/src/events/native-session.ts +13 -0
  44. package/packages/core/src/events/payloads.ts +148 -2
  45. package/packages/core/src/events/policy.ts +209 -0
  46. package/packages/core/src/events/repository.ts +48 -0
  47. package/packages/core/src/integration/harness.ts +4 -4
  48. package/packages/core/src/kernel/__snapshots__/{reducer-registry.test.ts.snap → reducer-accumulator-shapes.json} +771 -538
  49. package/packages/core/src/kernel/change-presence.ts +4 -2
  50. package/packages/core/src/kernel/dispatch-capacity.ts +119 -0
  51. package/packages/core/src/kernel/dispatcher-liveness.ts +5 -1
  52. package/packages/core/src/kernel/engine.ts +25 -5
  53. package/packages/core/src/kernel/forge-health.ts +19 -0
  54. package/packages/core/src/kernel/generators/build-log.ts +18 -0
  55. package/packages/core/src/kernel/generators/node-restack-log.ts +1 -1
  56. package/packages/core/src/kernel/generators/repository-journals.ts +10 -0
  57. package/packages/core/src/kernel/guarded-forge.ts +159 -0
  58. package/packages/core/src/kernel/incremental.ts +4 -2
  59. package/packages/core/src/kernel/integration-completeness.ts +61 -0
  60. package/packages/core/src/kernel/integration-landing.ts +5 -4
  61. package/packages/core/src/kernel/janitor-failure.ts +36 -0
  62. package/packages/core/src/kernel/landing-publication.ts +35 -15
  63. package/packages/core/src/kernel/landing-state.ts +7 -0
  64. package/packages/core/src/kernel/leaf-restack-state.ts +1 -1
  65. package/packages/core/src/kernel/log-index.ts +12 -1
  66. package/packages/core/src/kernel/mixed-version.ts +52 -0
  67. package/packages/core/src/kernel/node-landing.ts +14 -11
  68. package/packages/core/src/kernel/node-restack-demand.ts +29 -0
  69. package/packages/core/src/kernel/node-restack-state.ts +46 -16
  70. package/packages/core/src/kernel/node-restack-transaction.ts +151 -8
  71. package/packages/core/src/kernel/node-restack.ts +34 -10
  72. package/packages/core/src/kernel/publication.ts +22 -0
  73. package/packages/core/src/kernel/read-deferrals.ts +111 -0
  74. package/packages/core/src/kernel/read-facts.ts +27 -6
  75. package/packages/core/src/kernel/reconcile-restack.ts +23 -2
  76. package/packages/core/src/kernel/reducer-registry.ts +15 -2
  77. package/packages/core/src/kernel/reducer.ts +196 -10
  78. package/packages/core/src/kernel/repository-attention.ts +38 -1
  79. package/packages/core/src/kernel/terminal-guard.ts +11 -4
  80. package/packages/core/src/operator/annotations.ts +6 -0
  81. package/packages/core/src/operator/index.ts +2 -0
  82. package/packages/core/src/operator/presentation.ts +5 -0
  83. package/packages/core/src/operator/query.ts +45 -11
  84. package/packages/core/src/operator/registry.ts +17 -1
  85. package/packages/core/src/operator/restack.ts +51 -0
  86. package/packages/core/src/plugin-sdk/index.ts +10 -0
  87. package/packages/core/src/plugins/load.ts +3 -4
  88. package/packages/core/src/plugins/manifest.ts +1 -1
  89. package/packages/core/src/ports/forge/contract.ts +23 -0
  90. package/packages/core/src/ports/forge/fake.ts +6 -2
  91. package/packages/core/src/ports/forge/git-rewrite.ts +92 -64
  92. package/packages/core/src/ports/forge/github-transport.ts +45 -2
  93. package/packages/core/src/ports/forge/github.ts +56 -17
  94. package/packages/core/src/ports/forge/local-git.ts +7 -2
  95. package/packages/core/src/ports/forge-failure.ts +40 -0
  96. package/packages/core/src/ports/forge-request-context.ts +35 -0
  97. package/packages/core/src/ports/forge-telemetry.ts +16 -0
  98. package/packages/core/src/ports/runner/claude.ts +136 -9
  99. package/packages/core/src/ports/runner/codex.ts +112 -7
  100. package/packages/core/src/ports/runner/contract.ts +78 -0
  101. package/packages/core/src/ports/runner/fake.ts +59 -1
  102. package/packages/core/src/ports/runner/native-cli-fixture.ts +86 -0
  103. package/packages/core/src/ports/runner/native-process-fixture.ts +38 -0
  104. package/packages/core/src/ports/runner/native-session.ts +110 -0
  105. package/packages/core/src/ports/runner/pi-rpc.ts +7 -1
  106. package/packages/core/src/ports/runner/pi.ts +162 -2
  107. package/packages/core/src/ports/types.ts +53 -5
  108. package/packages/core/src/ports/workspace/git-worktree.ts +45 -51
  109. package/packages/core/src/ports/workspace/vercel-sandbox.ts +28 -12
  110. package/packages/core/src/processes/build-child-exit.ts +50 -2
  111. package/packages/core/src/processes/build-child.ts +15 -7
  112. package/packages/core/src/processes/build-runner.ts +909 -213
  113. package/packages/core/src/processes/dispatcher.ts +652 -334
  114. package/packages/core/src/processes/execution-no-progress.ts +15 -0
  115. package/packages/core/src/processes/pause-execution-fixture.ts +37 -0
  116. package/packages/core/src/processes/phase-failure-budget.ts +2 -1
  117. package/packages/core/src/processes/publication-loss.ts +7 -3
  118. package/packages/core/src/processes/repo-view.ts +53 -6
  119. package/packages/core/src/processes/tick-publication.ts +6 -2
  120. package/packages/core/src/runtime-identity.ts +37 -0
  121. package/packages/core/src/store/adapter.ts +4 -2
  122. package/packages/core/src/store/build-scope.ts +9 -0
  123. package/packages/core/src/store/contract.ts +203 -16
  124. package/packages/core/src/store/digest.ts +20 -2
  125. package/packages/core/src/store/local/schema.ts +6 -0
  126. package/packages/core/src/store/local/store.ts +57 -4
  127. package/packages/core/src/store/memory.ts +83 -2
  128. package/packages/core/src/store/new-build.ts +2 -2
  129. package/packages/core/src/store/phase-session.ts +13 -0
  130. package/packages/core/src/store/reduced-reads.ts +43 -4
  131. package/packages/core/src/store/reducer-value-shapes.json +8238 -5764
  132. package/packages/core/src/store/reducer-value-validation.ts +103 -3
  133. package/packages/core/src/store/reducer-values.ts +21 -6
  134. package/packages/core/src/store/remote/client.ts +146 -20
  135. package/packages/core/src/store/remote/compatibility.ts +6 -0
  136. package/packages/core/src/store/remote/index.ts +2 -0
  137. package/packages/core/src/store/remote/protocol.ts +19 -0
  138. package/packages/core/src/store/remote/version.ts +2 -0
  139. package/packages/core/src/store/repo-state-events.ts +3 -1
  140. package/packages/core/src/store/repo-tick.ts +6 -1
  141. package/packages/core/src/store/session-handle.ts +8 -0
  142. package/packages/core/src/store/snapshots.ts +21 -5
  143. package/packages/core/src/store/types.ts +19 -1
  144. package/packages/core/src/testing/dispatch-read-budget.ts +17 -2
  145. package/packages/core/src/testing/index.ts +7 -0
  146. package/packages/core/src/testing/newer-writer.ts +37 -0
  147. package/packages/core/src/testing/reduced-read-budget.ts +3 -0
  148. package/skills/guide/SKILL.md +144 -27
  149. package/skills/guide/references/integration-tree.md +81 -4
  150. package/skills/guide/references/landing-policy.md +11 -0
  151. package/skills/guide/references/migration-1.0.md +9 -0
  152. package/skills/guide/references/operator-api.md +18 -0
  153. package/skills/guide/references/plugin-authoring.md +55 -7
  154. package/skills/guide/references/remote-store-protocol.md +11 -0
  155. package/skills/guide/references/restacking.md +42 -7
  156. package/skills/guide/references/setup.md +25 -0
  157. package/skills/guide/references/ticket-dependencies.md +6 -45
  158. package/skills/implement/SKILL.md +4 -2
  159. package/skills/operate/SKILL.md +63 -6
  160. package/skills/reconcile/SKILL.md +3 -1
  161. package/skills/spec/SKILL.md +49 -39
  162. package/skills/tickets/SKILL.md +15 -43
@@ -1,3 +1,6 @@
1
+ import { hostname } from 'node:os'
2
+ import { guardNativeHandle, nativeHandle, notResumable } from './native-session'
3
+ import type { NativeSessionHandle, AgentResumeResult } from '../types'
1
4
  /**
2
5
  * ScriptedAgentRunner (SPEC §9): the deterministic AgentRunner used by every
3
6
  * kernel/process/integration test. A single script function plays the agent;
@@ -86,10 +89,19 @@ export class ScriptedAgentRunner implements AgentRunner {
86
89
  /** Journals keyed by session id (`s_1`, `s_2`, …), in creation order. */
87
90
  readonly sessions = new Map<string, SessionJournal>()
88
91
 
92
+ private readonly nativeIds = new Map<string, string>()
93
+ private readonly nativeState?: Map<string, string[]>
94
+ private readonly host: () => string
89
95
  private readonly script: Script
90
96
  private nextSession = 0
91
97
 
92
- constructor(opts: { script: Script }) {
98
+ constructor(opts: {
99
+ script: Script
100
+ nativeState?: Map<string, string[]>
101
+ hostname?: () => string
102
+ }) {
103
+ this.nativeState = opts.nativeState
104
+ this.host = opts.hostname ?? hostname
93
105
  this.script = opts.script
94
106
  }
95
107
 
@@ -111,6 +123,14 @@ export class ScriptedAgentRunner implements AgentRunner {
111
123
  }
112
124
  this.sessions.set(session.id, journal)
113
125
 
126
+ if (this.nativeState !== undefined) {
127
+ const nativeId = crypto.randomUUID()
128
+ this.nativeIds.set(session.id, nativeId)
129
+ this.nativeState.set(nativeId, [])
130
+ await opts.onNativeSession?.(
131
+ nativeHandle(this.name, this.nativeIds.get(session.id)!, opts.workspacePath, this.host()),
132
+ )
133
+ }
114
134
  const result = await this.runScript(
115
135
  {
116
136
  // Scripts observe the same effective launch environment as production
@@ -133,6 +153,15 @@ export class ScriptedAgentRunner implements AgentRunner {
133
153
  opts?: AgentContinueOpts,
134
154
  ): Promise<AgentTurnResult> {
135
155
  const journal = this.liveJournal(session, 'continue')
156
+ if (this.nativeState !== undefined)
157
+ await opts?.onNativeSession?.(
158
+ nativeHandle(
159
+ this.name,
160
+ this.nativeIds.get(session.id)!,
161
+ journal.opts.workspacePath,
162
+ this.host(),
163
+ ),
164
+ )
136
165
  const history = [...journal.messages]
137
166
  const turn = journal.turns.length + 1
138
167
  // Mirror the real adapters (§10, D8): the continued turn runs under the
@@ -146,6 +175,7 @@ export class ScriptedAgentRunner implements AgentRunner {
146
175
  ...journal.opts,
147
176
  env: sessionEnv(scoped),
148
177
  stream: opts?.stream,
178
+ onNativeSession: opts?.onNativeSession,
149
179
  ...(opts?.signal !== undefined ? { signal: opts.signal } : {}),
150
180
  }
151
181
 
@@ -160,10 +190,38 @@ export class ScriptedAgentRunner implements AgentRunner {
160
190
  opts?.signal,
161
191
  )
162
192
  journal.messages.push(message)
193
+ this.nativeState?.set(this.nativeIds.get(session.id)!, [...journal.messages])
163
194
  journal.turns.push({ turn, message, result })
164
195
  return result
165
196
  }
166
197
 
198
+ async resume(
199
+ handle: NativeSessionHandle,
200
+ message: string,
201
+ opts: AgentStartOpts,
202
+ ): Promise<AgentResumeResult> {
203
+ const invalid = guardNativeHandle(handle, this.name, opts, this.host())
204
+ if (invalid !== undefined) return invalid
205
+ const history = this.nativeState?.get(handle.nativeId)
206
+ if (history === undefined)
207
+ return notResumable('missing-state', 'Fake native state is unavailable')
208
+ const session: AgentSessionHandle = {
209
+ id: handle.nativeId,
210
+ runner: this.name,
211
+ model: opts.model,
212
+ }
213
+ this.nativeIds.set(session.id, handle.nativeId)
214
+ this.sessions.set(session.id, {
215
+ session,
216
+ opts,
217
+ turns: [],
218
+ messages: [...history],
219
+ ended: false,
220
+ })
221
+ const result = await this.continue(session, message, opts)
222
+ return { kind: 'resumed', session, result }
223
+ }
224
+
167
225
  async end(session: AgentSessionHandle): Promise<Transcript> {
168
226
  const journal = this.liveJournal(session, 'end')
169
227
  journal.ended = true
@@ -0,0 +1,86 @@
1
+ #!/usr/bin/env bun
2
+ /** Disk-backed native CLI stand-in. Its private state is outside the workspace. */
3
+ import { readFile, writeFile, access } from 'node:fs/promises'
4
+ import { join } from 'node:path'
5
+ import { createInterface } from 'node:readline'
6
+
7
+ const provider = process.env.AB_NATIVE_FIXTURE_PROVIDER!
8
+ const args = process.argv.slice(2)
9
+ const flag = (name: string) => (args.includes(name) ? args[args.indexOf(name) + 1] : undefined)
10
+ if (args.includes('--version')) {
11
+ console.log('1.3.0')
12
+ process.exit(0)
13
+ }
14
+ const path = flag('--session') ?? join(process.env.AB_NATIVE_FIXTURE_STATE!, 'session.jsonl')
15
+ const resuming = args.includes('resume') || args.includes('--resume') || args.includes('--session')
16
+ if (resuming) {
17
+ try {
18
+ await access(path)
19
+ } catch {
20
+ console.error('Session not found')
21
+ process.exit(1)
22
+ }
23
+ }
24
+ const state: { id: string; memory?: string } = resuming
25
+ ? JSON.parse((await readFile(path, 'utf8')).split('\n')[0]!)
26
+ : { id: flag('--session-id') ?? crypto.randomUUID() }
27
+ const save = () => writeFile(path, `${JSON.stringify({ type: 'session', ...state })}\n`)
28
+ await save()
29
+ const emit = (event: unknown) => console.log(JSON.stringify(event))
30
+ const identify = () =>
31
+ emit(
32
+ provider === 'claude'
33
+ ? { type: 'system', subtype: 'init', session_id: state.id }
34
+ : { type: 'thread.started', thread_id: state.id },
35
+ )
36
+ async function prompt(message: string, env: Record<string, string | undefined>): Promise<string> {
37
+ if (!resuming) state.memory = message.split(' ').at(-1)
38
+ await save()
39
+ if (env.AB_NATIVE_FIXTURE_RELEASE !== undefined) {
40
+ while (!(await Bun.file(env.AB_NATIVE_FIXTURE_RELEASE).exists())) await Bun.sleep(5)
41
+ }
42
+ return `${state.memory} ${env.NATIVE_CONTRACT_FRESH ?? ''}`
43
+ }
44
+ if (provider === 'pi') {
45
+ let env = process.env
46
+ let tokens = 0
47
+ for await (const line of createInterface({ input: process.stdin })) {
48
+ const command = JSON.parse(line) as { id: string; type: string; message?: string }
49
+ const response = (data?: unknown) =>
50
+ emit({ id: command.id, command: command.type, type: 'response', success: true, data })
51
+ if (command.type === 'get_state') response({ sessionId: state.id, sessionFile: path })
52
+ else if (command.type === 'get_session_stats')
53
+ response({ tokens: { input: tokens, output: tokens } })
54
+ else if (command.type === 'prompt' && command.message?.startsWith('/autobuild-configure ')) {
55
+ env = JSON.parse(
56
+ Buffer.from(command.message.split(' ')[1]!, 'base64url').toString(),
57
+ ).environment
58
+ response()
59
+ } else if (command.type === 'prompt') {
60
+ response()
61
+ const text = await prompt(command.message!, env)
62
+ tokens++
63
+ emit({ type: 'message_update', assistantMessageEvent: { type: 'text_delta', delta: text } })
64
+ emit({
65
+ type: 'message_end',
66
+ message: { role: 'assistant', content: [{ type: 'text', text }] },
67
+ })
68
+ emit({ type: 'agent_settled' })
69
+ } else response()
70
+ }
71
+ } else {
72
+ identify()
73
+ const text = await prompt(args.at(-1)!, process.env)
74
+ if (provider === 'claude')
75
+ emit({
76
+ type: 'result',
77
+ subtype: 'success',
78
+ session_id: state.id,
79
+ result: text,
80
+ usage: { input_tokens: 1, output_tokens: 1 },
81
+ })
82
+ else {
83
+ emit({ type: 'item.completed', item: { type: 'agent_message', text } })
84
+ emit({ type: 'turn.completed', usage: { input_tokens: 1, output_tokens: 1 } })
85
+ }
86
+ }
@@ -0,0 +1,38 @@
1
+ /** Child adapter process shared by deterministic and opt-in live resume proofs. */
2
+ import { ClaudeAgentRunner } from './claude'
3
+ import { CodexAgentRunner } from './codex'
4
+ import { PiAgentRunner } from './pi'
5
+ import { resumeAgent } from './native-session'
6
+ import type { AgentStartOpts, NativeSessionHandle } from '../types'
7
+
8
+ if (import.meta.main) {
9
+ const input = JSON.parse(await Bun.stdin.text()) as {
10
+ provider: string
11
+ opts: AgentStartOpts
12
+ handle?: NativeSessionHandle
13
+ message?: string
14
+ }
15
+ const runner =
16
+ input.provider === 'claude'
17
+ ? new ClaudeAgentRunner()
18
+ : input.provider === 'codex'
19
+ ? new CodexAgentRunner()
20
+ : new PiAgentRunner()
21
+ let observed: NativeSessionHandle | undefined
22
+ input.opts.onNativeSession = async (handle) => {
23
+ observed = handle
24
+ }
25
+ if (input.handle === undefined) {
26
+ const started = await runner.start(input.opts)
27
+ await runner.end(started.session)
28
+ if (started.result.kind !== 'completed') throw new Error(started.result.failure.message)
29
+ if (observed === undefined) throw new Error('No native identity reported')
30
+ // Only the serialized handle crosses back from process A.
31
+ process.stdout.write(JSON.stringify(observed))
32
+ } else {
33
+ const resumed = await resumeAgent(runner, input.handle, input.message!, input.opts)
34
+ if (resumed.kind !== 'resumed') throw new Error(resumed.message)
35
+ const transcript = await runner.end(resumed.session)
36
+ process.stdout.write(JSON.stringify({ result: resumed.result, handle: observed, transcript }))
37
+ }
38
+ }
@@ -0,0 +1,110 @@
1
+ import { hostname } from 'node:os'
2
+ import { nativeSessionHandleSchema } from '../../events/native-session'
3
+ export { nativeSessionHandleSchema } from '../../events/native-session'
4
+ import type {
5
+ AgentResumeResult,
6
+ AgentRunner,
7
+ AgentStartOpts,
8
+ AgentTurnFailure,
9
+ NativeSessionHandle,
10
+ } from '../types'
11
+
12
+ export function nativeHandle(
13
+ runner: string,
14
+ nativeId: string,
15
+ workspacePath: string,
16
+ host = hostname(),
17
+ statePath?: string,
18
+ ): NativeSessionHandle {
19
+ return nativeSessionHandleSchema.parse({
20
+ version: 1,
21
+ runner,
22
+ nativeId,
23
+ host,
24
+ workspacePath,
25
+ ...(statePath !== undefined ? { statePath } : {}),
26
+ })
27
+ }
28
+
29
+ export function notResumable(
30
+ reason: Extract<AgentResumeResult, { kind: 'not-resumable' }>['reason'],
31
+ message: string,
32
+ ): AgentResumeResult {
33
+ return { kind: 'not-resumable', reason, message }
34
+ }
35
+
36
+ export function guardNativeHandle(
37
+ handle: NativeSessionHandle,
38
+ runner: string,
39
+ opts: AgentStartOpts,
40
+ host = hostname(),
41
+ ): AgentResumeResult | undefined {
42
+ if (!nativeSessionHandleSchema.safeParse(handle).success)
43
+ return notResumable('missing-state', 'Invalid native session handle')
44
+ if (handle.runner !== runner)
45
+ return notResumable('wrong-runner', 'Native session belongs to another adapter')
46
+ if (handle.host !== host)
47
+ return notResumable('wrong-host', 'Native state belongs to another host')
48
+ if (handle.workspacePath !== opts.workspacePath)
49
+ return notResumable('wrong-workspace', 'Native state belongs to another workspace')
50
+ return undefined
51
+ }
52
+
53
+ /** Compatibility boundary for adapters which have not implemented native resume. */
54
+ export async function resumeAgent(
55
+ runner: AgentRunner,
56
+ handle: NativeSessionHandle,
57
+ message: string,
58
+ opts: AgentStartOpts,
59
+ ): Promise<AgentResumeResult> {
60
+ return runner.resume === undefined
61
+ ? notResumable('unsupported', `${runner.name} does not support native resume`)
62
+ : runner.resume(handle, message, opts)
63
+ }
64
+
65
+ export class NativeObservationError extends Error {
66
+ constructor(readonly failure: unknown) {
67
+ super('Native session observation failed', { cause: failure })
68
+ }
69
+ }
70
+
71
+ export class NativeIdentityMismatch extends NativeObservationError {
72
+ constructor() {
73
+ super(new Error('Conflicting native session identity'))
74
+ }
75
+ }
76
+
77
+ /** Recognized native lookup diagnostics only; provider failures keep their taxonomy. */
78
+ export function nativeStateUnavailable(failure: AgentTurnFailure): boolean {
79
+ if (
80
+ failure.cause === 'credentials' ||
81
+ failure.cause === 'exhaustion' ||
82
+ failure.cause === 'configuration'
83
+ )
84
+ return false
85
+ return /\bno (?:saved )?(?:conversation|session|rollout) found\b|\b(?:session|thread|conversation)[^\n]* (?:not found|does not exist)\b|\b(?:cannot|could not) find (?:a |the )?(?:session|thread|conversation)\b|\b(?:session|thread|conversation) state (?:is )?(?:missing|unavailable)\b|\bunknown (?:session|thread)(?: id)?\b/i.test(
86
+ failure.message,
87
+ )
88
+ }
89
+
90
+ /** Once per turn, with conflicting identities rejected before prompt consumption. */
91
+ export function nativeObserver(
92
+ opts: AgentStartOpts,
93
+ runner: string,
94
+ host: string,
95
+ expected?: string,
96
+ ): (id: string) => Promise<void> {
97
+ let observed: string | undefined
98
+ return async (id) => {
99
+ if (id.trim() === '') return
100
+ if ((expected !== undefined && expected !== id) || (observed !== undefined && observed !== id))
101
+ throw new NativeIdentityMismatch()
102
+ if (observed === id) return
103
+ observed = id
104
+ try {
105
+ await opts.onNativeSession?.(nativeHandle(runner, id, opts.workspacePath, host))
106
+ } catch (error) {
107
+ throw new NativeObservationError(error)
108
+ }
109
+ }
110
+ }
@@ -99,6 +99,7 @@ interface TurnCapture {
99
99
  }
100
100
 
101
101
  export class PiRpcClient implements PiSession {
102
+ readonly sessionFile?: string
102
103
  readonly sessionId: string
103
104
  private nextId = 0
104
105
  private closed = false
@@ -139,6 +140,8 @@ export class PiRpcClient implements PiSession {
139
140
  if (id === undefined || id.length === 0)
140
141
  throw new Error('pi runtime: RPC get_state returned no sessionId')
141
142
  Object.defineProperty(client, 'sessionId', { value: id })
143
+ if (typeof data?.sessionFile === 'string')
144
+ Object.defineProperty(client, 'sessionFile', { value: data.sessionFile })
142
145
  return client
143
146
  } catch (error) {
144
147
  await client.dispose()
@@ -333,6 +336,8 @@ export class PiRpcClient implements PiSession {
333
336
  }
334
337
 
335
338
  export interface PiRpcSessionOptions {
339
+ persistent?: boolean
340
+ sessionFile?: string
336
341
  cwd: string
337
342
  model?: PiModelRef
338
343
  tools: readonly string[]
@@ -348,12 +353,13 @@ export async function createPiRpcSession(opts: PiRpcSessionOptions): Promise<PiS
348
353
  const args = [
349
354
  PI_RPC_MODE_ARG,
350
355
  'rpc',
351
- '--no-session',
356
+ ...(!opts.persistent ? ['--no-session'] : []),
352
357
  '--no-approve',
353
358
  '--no-context-files',
354
359
  '--no-prompt-templates',
355
360
  '--no-themes',
356
361
  ]
362
+ if (opts.sessionFile !== undefined) args.push('--session', opts.sessionFile)
357
363
  if (opts.model !== undefined) args.push(PI_MODEL_ARG, `${opts.model.provider}/${opts.model.id}`)
358
364
  // `--tools` filters both builtin and package tools out of Pi's registry.
359
365
  // Keep the complete registry for build sessions and let the bridge activate
@@ -1,3 +1,12 @@
1
+ import { hostname } from 'node:os'
2
+ import { readFile } from 'node:fs/promises'
3
+ import {
4
+ guardNativeHandle,
5
+ nativeHandle,
6
+ NativeObservationError,
7
+ notResumable,
8
+ } from './native-session'
9
+ import type { NativeSessionHandle, AgentResumeResult } from '../types'
1
10
  /** AgentRunner adapter for the operator's locally installed Pi CLI. */
2
11
  import semver from 'semver'
3
12
  import type { StreamPart } from '../../store/streams/types'
@@ -240,12 +249,15 @@ export interface PiTurn {
240
249
  }
241
250
 
242
251
  export interface PiSession {
252
+ readonly sessionFile?: string
243
253
  readonly sessionId: string
244
254
  prompt(text: string, env: Record<string, string>, signal?: AbortSignal): Promise<PiTurn>
245
255
  dispose(): Promise<void> | void
246
256
  }
247
257
 
248
258
  export type PiCreateSessionFn = (opts: {
259
+ persistent?: boolean
260
+ sessionFile?: string
249
261
  cwd: string
250
262
  model?: PiModelRef
251
263
  tools: readonly string[]
@@ -386,11 +398,19 @@ function createPiTurnTranslator(emit: (parts: StreamPart[]) => void): PiTurnTran
386
398
 
387
399
  export class PiAgentRunner implements AgentRunner, OneShotCompletion {
388
400
  readonly name = 'pi'
401
+ private readonly host: () => string
389
402
  private readonly createSessionFn: PiCreateSessionFn
390
403
  private readonly createSessionId: () => string
391
404
  private readonly sessions = new Map<string, SessionState>()
392
405
 
393
- constructor(opts: { createSessionFn?: PiCreateSessionFn; createSessionId?: () => string } = {}) {
406
+ constructor(
407
+ opts: {
408
+ hostname?: () => string
409
+ createSessionFn?: PiCreateSessionFn
410
+ createSessionId?: () => string
411
+ } = {},
412
+ ) {
413
+ this.host = opts.hostname ?? hostname
394
414
  this.createSessionFn = opts.createSessionFn ?? createLocalPiSession
395
415
  this.createSessionId = opts.createSessionId ?? (() => crypto.randomUUID())
396
416
  }
@@ -422,7 +442,9 @@ export class PiAgentRunner implements AgentRunner, OneShotCompletion {
422
442
  let turn: PiTurn
423
443
  const turnEvents: PiTurnEventHook = {}
424
444
  try {
445
+ rejectSessionArgs(opts.args)
425
446
  native = await this.createSessionFn({
447
+ persistent: true,
426
448
  cwd: opts.workspacePath,
427
449
  ...(model !== undefined ? { model } : {}),
428
450
  tools: PI_TOOLS,
@@ -433,6 +455,21 @@ export class PiAgentRunner implements AgentRunner, OneShotCompletion {
433
455
  // continued turns even when turn 1 streams nothing.
434
456
  onEvent: (event) => turnEvents.translator?.onEvent(event),
435
457
  })
458
+ if (opts.onNativeSession !== undefined) {
459
+ try {
460
+ await opts.onNativeSession(
461
+ nativeHandle(
462
+ this.name,
463
+ native.sessionId,
464
+ opts.workspacePath,
465
+ this.host(),
466
+ native.sessionFile,
467
+ ),
468
+ )
469
+ } catch (error) {
470
+ throw new NativeObservationError(error)
471
+ }
472
+ }
436
473
  turn = await this.runPrompt(
437
474
  native,
438
475
  prompt,
@@ -442,6 +479,10 @@ export class PiAgentRunner implements AgentRunner, OneShotCompletion {
442
479
  turnEvents,
443
480
  )
444
481
  } catch (error) {
482
+ if (error instanceof NativeObservationError) {
483
+ await native?.dispose()
484
+ throw error
485
+ }
445
486
  turn = {
446
487
  text: '',
447
488
  usage: { inputTokens: 0, outputTokens: 0 },
@@ -473,6 +514,15 @@ export class PiAgentRunner implements AgentRunner, OneShotCompletion {
473
514
  if (state.session === undefined) {
474
515
  throw new Error(`pi: cannot continue session "${handle.id}" because local Pi failed to start`)
475
516
  }
517
+ await opts?.onNativeSession?.(
518
+ nativeHandle(
519
+ this.name,
520
+ state.session.sessionId,
521
+ state.opts.workspacePath,
522
+ this.host(),
523
+ state.session.sessionFile,
524
+ ),
525
+ )
476
526
  const scoped = opts?.env !== undefined ? { ...state.opts.env, ...opts.env } : state.opts.env
477
527
  const turn = await this.runPrompt(
478
528
  state.session,
@@ -486,6 +536,93 @@ export class PiAgentRunner implements AgentRunner, OneShotCompletion {
486
536
  return this.toResult(turn)
487
537
  }
488
538
 
539
+ async resume(
540
+ handle: NativeSessionHandle,
541
+ message: string,
542
+ opts: AgentStartOpts,
543
+ ): Promise<AgentResumeResult> {
544
+ const invalid = guardNativeHandle(handle, this.name, opts, this.host())
545
+ if (invalid !== undefined) return invalid
546
+ if (handle.statePath === undefined)
547
+ return notResumable('missing-state', 'Pi handle has no persistent session file')
548
+ try {
549
+ const text = await readFile(handle.statePath, 'utf8')
550
+ const header = JSON.parse(text.split('\n')[0]!) as { type?: string; id?: string }
551
+ if (header.type !== 'session' || header.id !== handle.nativeId)
552
+ return notResumable('missing-state', 'Pi session file identity mismatch')
553
+ } catch {
554
+ return notResumable('missing-state', 'Pi session file is missing or unreadable')
555
+ }
556
+ try {
557
+ rejectSessionArgs(opts.args)
558
+ } catch (error) {
559
+ const session: AgentSessionHandle = { id: this.createSessionId(), runner: this.name }
560
+ const turn: PiTurn = {
561
+ text: '',
562
+ usage: { inputTokens: 0, outputTokens: 0 },
563
+ failure: localPiFailure(error),
564
+ }
565
+ this.sessions.set(session.id, { opts, turns: [this.turnRecord(1, message, turn)] })
566
+ return { kind: 'resumed', session, result: this.toResult(turn) }
567
+ }
568
+ const model = opts.model !== undefined ? parsePiModel(opts.model) : undefined
569
+ const turnEvents: PiTurnEventHook = {}
570
+ let native: PiSession
571
+ try {
572
+ native = await this.createSessionFn({
573
+ persistent: true,
574
+ sessionFile: handle.statePath,
575
+ cwd: opts.workspacePath,
576
+ model,
577
+ tools: PI_TOOLS,
578
+ args: opts.args ?? [],
579
+ skill: opts.skill,
580
+ env: sessionEnv(opts.env),
581
+ onEvent: (event) => turnEvents.translator?.onEvent(event),
582
+ })
583
+ } catch (error) {
584
+ const session: AgentSessionHandle = { id: this.createSessionId(), runner: this.name }
585
+ const turn: PiTurn = {
586
+ text: '',
587
+ usage: { inputTokens: 0, outputTokens: 0 },
588
+ failure: localPiFailure(error),
589
+ }
590
+ this.sessions.set(session.id, { opts, turns: [this.turnRecord(1, message, turn)] })
591
+ return { kind: 'resumed', session, result: this.toResult(turn) }
592
+ }
593
+ if (native.sessionId !== handle.nativeId || native.sessionFile !== handle.statePath) {
594
+ await native.dispose()
595
+ return notResumable('missing-state', 'Pi resumed a different native session')
596
+ }
597
+ try {
598
+ await opts.onNativeSession?.(handle)
599
+ } catch (error) {
600
+ await native.dispose()
601
+ throw new NativeObservationError(error)
602
+ }
603
+ const turn = await this.runPrompt(
604
+ native,
605
+ message,
606
+ this.turnEnv(opts.env),
607
+ opts.signal,
608
+ opts.stream,
609
+ turnEvents,
610
+ )
611
+ const session: AgentSessionHandle = {
612
+ id: native.sessionId,
613
+ runner: this.name,
614
+ model: opts.model,
615
+ }
616
+ this.sessions.set(session.id, {
617
+ opts,
618
+ model: opts.model,
619
+ session: native,
620
+ turnEvents,
621
+ turns: [this.turnRecord(1, message, turn)],
622
+ })
623
+ return { kind: 'resumed', session, result: this.toResult(turn) }
624
+ }
625
+
489
626
  async end(handle: AgentSessionHandle): Promise<Transcript> {
490
627
  const state = this.liveState(handle, 'end')
491
628
  this.sessions.delete(handle.id)
@@ -592,7 +729,11 @@ export class PiAgentRunner implements AgentRunner, OneShotCompletion {
592
729
  function localPiFailure(error: unknown): AgentTurnFailure {
593
730
  const message = errorText(error)
594
731
  if (/executable "pi" was not found/.test(message)) return missingExecutableFailure(message)
595
- if (/requires Pi .* or newer|could not parse detected Pi version/.test(message)) {
732
+ if (
733
+ /conflicting session-control|requires Pi .* or newer|could not parse detected Pi version/.test(
734
+ message,
735
+ )
736
+ ) {
596
737
  return configurationFailure(message)
597
738
  }
598
739
  if (/not ready|authentication|logged in|credentials/i.test(message))
@@ -617,3 +758,22 @@ function isRecord(value: unknown): value is Record<string, unknown> {
617
758
  function errorText(error: unknown): string {
618
759
  return error instanceof Error ? error.message : String(error)
619
760
  }
761
+
762
+ function rejectSessionArgs(args: readonly string[] = []): void {
763
+ const flags = [
764
+ '--no-session',
765
+ '--session',
766
+ '--session-id',
767
+ '--session-dir',
768
+ '--continue',
769
+ '-c',
770
+ '--resume',
771
+ '-r',
772
+ '--fork',
773
+ ]
774
+ const conflict = args.find((arg) =>
775
+ flags.some((flag) => arg === flag || arg.startsWith(`${flag}=`)),
776
+ )
777
+ if (conflict !== undefined)
778
+ throw new Error(`pi runtime: conflicting session-control argument: ${conflict}`)
779
+ }