@defrex/autobuild 1.0.0-beta.1 → 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.
- package/SPEC.md +285 -53
- package/bin/ab-build-runner.ts +10 -8
- package/docs/architecture.md +173 -23
- package/docs/configuration.md +35 -4
- package/docs/hosted-service.md +35 -0
- package/docs/integration-tree.md +81 -4
- package/docs/landing-policy.md +11 -0
- package/docs/migration-1.0.md +9 -0
- package/docs/operator-api.md +18 -0
- package/docs/remote-store-protocol.md +11 -0
- package/docs/restacking.md +42 -7
- package/docs/setup.md +21 -0
- package/docs/ticket-dependencies.md +6 -45
- package/package.json +3 -3
- package/packages/core/src/cli/attention.ts +4 -1
- package/packages/core/src/cli/binary.ts +17 -1
- package/packages/core/src/cli/context.ts +53 -1
- package/packages/core/src/cli/dashboard/actions.ts +4 -0
- package/packages/core/src/cli/dashboard/detail.ts +45 -1
- package/packages/core/src/cli/dashboard/facts.ts +7 -2
- package/packages/core/src/cli/dashboard/integration-detail.ts +142 -0
- package/packages/core/src/cli/dashboard/integration-row.ts +248 -0
- package/packages/core/src/cli/dashboard/landing-display.ts +64 -0
- package/packages/core/src/cli/dashboard/model.ts +140 -16
- package/packages/core/src/cli/dashboard/poll.ts +40 -4
- package/packages/core/src/cli/dashboard/render.ts +106 -5
- package/packages/core/src/cli/dashboard/transcript.ts +2 -1
- package/packages/core/src/cli/dispatch-frontend.ts +6 -0
- package/packages/core/src/cli/dispatch.ts +44 -14
- package/packages/core/src/cli/help.ts +16 -1
- package/packages/core/src/cli/main.ts +37 -0
- package/packages/core/src/cli/publication-settlement.ts +49 -5
- package/packages/core/src/cli/repository-status.ts +97 -2
- package/packages/core/src/cli/status.ts +24 -1
- package/packages/core/src/cli/terminals.ts +94 -93
- package/packages/core/src/cli/wait.ts +11 -2
- package/packages/core/src/cli/watch.ts +12 -0
- package/packages/core/src/config/schema.ts +3 -0
- package/packages/core/src/events/catalog.ts +38 -0
- package/packages/core/src/events/compatibility.ts +183 -0
- package/packages/core/src/events/native-session.ts +13 -0
- package/packages/core/src/events/payloads.ts +148 -2
- package/packages/core/src/events/policy.ts +209 -0
- package/packages/core/src/events/repository.ts +48 -0
- package/packages/core/src/integration/harness.ts +4 -4
- package/packages/core/src/kernel/__snapshots__/{reducer-registry.test.ts.snap → reducer-accumulator-shapes.json} +771 -538
- package/packages/core/src/kernel/change-presence.ts +4 -2
- package/packages/core/src/kernel/dispatch-capacity.ts +119 -0
- package/packages/core/src/kernel/dispatcher-liveness.ts +5 -1
- package/packages/core/src/kernel/engine.ts +25 -5
- package/packages/core/src/kernel/forge-health.ts +19 -0
- package/packages/core/src/kernel/generators/build-log.ts +18 -0
- package/packages/core/src/kernel/generators/node-restack-log.ts +1 -1
- package/packages/core/src/kernel/generators/repository-journals.ts +10 -0
- package/packages/core/src/kernel/guarded-forge.ts +159 -0
- package/packages/core/src/kernel/incremental.ts +4 -2
- package/packages/core/src/kernel/integration-completeness.ts +61 -0
- package/packages/core/src/kernel/integration-landing.ts +5 -4
- package/packages/core/src/kernel/janitor-failure.ts +36 -0
- package/packages/core/src/kernel/landing-publication.ts +35 -15
- package/packages/core/src/kernel/landing-state.ts +7 -0
- package/packages/core/src/kernel/leaf-restack-state.ts +1 -1
- package/packages/core/src/kernel/log-index.ts +12 -1
- package/packages/core/src/kernel/mixed-version.ts +52 -0
- package/packages/core/src/kernel/node-landing.ts +14 -11
- package/packages/core/src/kernel/node-restack-demand.ts +29 -0
- package/packages/core/src/kernel/node-restack-state.ts +46 -16
- package/packages/core/src/kernel/node-restack-transaction.ts +151 -8
- package/packages/core/src/kernel/node-restack.ts +34 -10
- package/packages/core/src/kernel/publication.ts +22 -0
- package/packages/core/src/kernel/read-deferrals.ts +111 -0
- package/packages/core/src/kernel/read-facts.ts +27 -6
- package/packages/core/src/kernel/reconcile-restack.ts +23 -2
- package/packages/core/src/kernel/reducer-registry.ts +15 -2
- package/packages/core/src/kernel/reducer.ts +196 -10
- package/packages/core/src/kernel/repository-attention.ts +38 -1
- package/packages/core/src/kernel/terminal-guard.ts +11 -4
- package/packages/core/src/operator/annotations.ts +6 -0
- package/packages/core/src/operator/index.ts +2 -0
- package/packages/core/src/operator/presentation.ts +5 -0
- package/packages/core/src/operator/query.ts +45 -11
- package/packages/core/src/operator/registry.ts +17 -1
- package/packages/core/src/operator/restack.ts +51 -0
- package/packages/core/src/plugin-sdk/index.ts +10 -0
- package/packages/core/src/plugins/manifest.ts +1 -1
- package/packages/core/src/ports/forge/contract.ts +23 -0
- package/packages/core/src/ports/forge/fake.ts +6 -2
- package/packages/core/src/ports/forge/git-rewrite.ts +92 -64
- package/packages/core/src/ports/forge/github-transport.ts +45 -2
- package/packages/core/src/ports/forge/github.ts +56 -17
- package/packages/core/src/ports/forge/local-git.ts +7 -2
- package/packages/core/src/ports/forge-failure.ts +40 -0
- package/packages/core/src/ports/forge-request-context.ts +35 -0
- package/packages/core/src/ports/forge-telemetry.ts +16 -0
- package/packages/core/src/ports/runner/claude.ts +136 -9
- package/packages/core/src/ports/runner/codex.ts +112 -7
- package/packages/core/src/ports/runner/contract.ts +78 -0
- package/packages/core/src/ports/runner/fake.ts +59 -1
- package/packages/core/src/ports/runner/native-cli-fixture.ts +86 -0
- package/packages/core/src/ports/runner/native-process-fixture.ts +38 -0
- package/packages/core/src/ports/runner/native-session.ts +110 -0
- package/packages/core/src/ports/runner/pi-rpc.ts +7 -1
- package/packages/core/src/ports/runner/pi.ts +162 -2
- package/packages/core/src/ports/types.ts +53 -5
- package/packages/core/src/ports/workspace/git-worktree.ts +45 -51
- package/packages/core/src/ports/workspace/vercel-sandbox.ts +28 -12
- package/packages/core/src/processes/build-child-exit.ts +50 -2
- package/packages/core/src/processes/build-child.ts +15 -7
- package/packages/core/src/processes/build-runner.ts +909 -213
- package/packages/core/src/processes/dispatcher.ts +652 -334
- package/packages/core/src/processes/execution-no-progress.ts +15 -0
- package/packages/core/src/processes/pause-execution-fixture.ts +37 -0
- package/packages/core/src/processes/phase-failure-budget.ts +2 -1
- package/packages/core/src/processes/publication-loss.ts +7 -3
- package/packages/core/src/processes/repo-view.ts +53 -6
- package/packages/core/src/processes/tick-publication.ts +6 -2
- package/packages/core/src/runtime-identity.ts +37 -0
- package/packages/core/src/store/adapter.ts +4 -2
- package/packages/core/src/store/build-scope.ts +9 -0
- package/packages/core/src/store/contract.ts +203 -16
- package/packages/core/src/store/digest.ts +20 -2
- package/packages/core/src/store/local/schema.ts +6 -0
- package/packages/core/src/store/local/store.ts +57 -4
- package/packages/core/src/store/memory.ts +83 -2
- package/packages/core/src/store/new-build.ts +2 -2
- package/packages/core/src/store/phase-session.ts +13 -0
- package/packages/core/src/store/reduced-reads.ts +43 -4
- package/packages/core/src/store/reducer-value-shapes.json +8238 -5764
- package/packages/core/src/store/reducer-value-validation.ts +103 -3
- package/packages/core/src/store/reducer-values.ts +21 -6
- package/packages/core/src/store/remote/client.ts +145 -20
- package/packages/core/src/store/remote/index.ts +2 -0
- package/packages/core/src/store/remote/protocol.ts +19 -0
- package/packages/core/src/store/remote/version.ts +2 -0
- package/packages/core/src/store/repo-state-events.ts +3 -1
- package/packages/core/src/store/repo-tick.ts +6 -1
- package/packages/core/src/store/session-handle.ts +8 -0
- package/packages/core/src/store/snapshots.ts +21 -5
- package/packages/core/src/store/types.ts +17 -1
- package/packages/core/src/testing/dispatch-read-budget.ts +17 -2
- package/packages/core/src/testing/index.ts +7 -0
- package/packages/core/src/testing/newer-writer.ts +37 -0
- package/packages/core/src/testing/reduced-read-budget.ts +3 -0
- package/skills/guide/SKILL.md +137 -24
- package/skills/guide/references/integration-tree.md +81 -4
- package/skills/guide/references/landing-policy.md +11 -0
- package/skills/guide/references/migration-1.0.md +9 -0
- package/skills/guide/references/operator-api.md +18 -0
- package/skills/guide/references/plugin-authoring.md +47 -4
- package/skills/guide/references/remote-store-protocol.md +11 -0
- package/skills/guide/references/restacking.md +42 -7
- package/skills/guide/references/setup.md +21 -0
- package/skills/guide/references/ticket-dependencies.md +6 -45
- package/skills/implement/SKILL.md +4 -2
- package/skills/operate/SKILL.md +63 -6
- package/skills/reconcile/SKILL.md +3 -1
- package/skills/spec/SKILL.md +49 -39
- package/skills/tickets/SKILL.md +15 -43
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { z } from 'zod'
|
|
2
|
+
/** Additive plugin API: recognizable across separately loaded SDK copies. */
|
|
3
|
+
export type ForgeFailureDetails =
|
|
4
|
+
| { kind: 'rate-limited'; resetAt: string }
|
|
5
|
+
| { kind: 'transient'; retry: 'retryable' }
|
|
6
|
+
|
|
7
|
+
export class ForgeFailure extends Error {
|
|
8
|
+
readonly forgeFailure = 'autobuild.forge-failure.v1' as const
|
|
9
|
+
constructor(
|
|
10
|
+
message: string,
|
|
11
|
+
readonly details: ForgeFailureDetails,
|
|
12
|
+
) {
|
|
13
|
+
super(message)
|
|
14
|
+
this.name = 'ForgeFailure'
|
|
15
|
+
if (!isForgeFailure(this)) throw new TypeError('Invalid forge failure details')
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function isForgeFailure(error: unknown): error is ForgeFailure {
|
|
20
|
+
if (!error || typeof error !== 'object') return false
|
|
21
|
+
const value = error as ForgeFailure
|
|
22
|
+
if (
|
|
23
|
+
value.forgeFailure !== 'autobuild.forge-failure.v1' ||
|
|
24
|
+
typeof value.message !== 'string' ||
|
|
25
|
+
value.message.length === 0
|
|
26
|
+
)
|
|
27
|
+
return false
|
|
28
|
+
const details = value.details
|
|
29
|
+
return (
|
|
30
|
+
!!details &&
|
|
31
|
+
((details.kind === 'rate-limited' && z.iso.datetime().safeParse(details.resetAt).success) ||
|
|
32
|
+
(details.kind === 'transient' && details.retry === 'retryable'))
|
|
33
|
+
)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface ForgeRequestContext {
|
|
37
|
+
build?: string
|
|
38
|
+
}
|
|
39
|
+
/** Called once for each actual provider request, including failed requests. */
|
|
40
|
+
export type ForgeRequestObserver = (context: ForgeRequestContext) => void
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
2
|
+
import type { ForgeRequestContext } from './forge-failure'
|
|
3
|
+
const context = new AsyncLocalStorage<ForgeRequestContext>()
|
|
4
|
+
export const forgeRequestContext = (): ForgeRequestContext => context.getStore() ?? {}
|
|
5
|
+
export function withForgeRequestContext<T>(value: ForgeRequestContext, work: () => T): T {
|
|
6
|
+
return context.run(value, work)
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** Kernel-only per-operation gate, inherited by all wire calls in that operation. */
|
|
10
|
+
const gates = new AsyncLocalStorage<{
|
|
11
|
+
before: () => Promise<void>
|
|
12
|
+
failed: (error: unknown) => Promise<void>
|
|
13
|
+
}>()
|
|
14
|
+
export function withForgeRequestGate<T>(
|
|
15
|
+
gate: NonNullable<ReturnType<typeof gates.getStore>>,
|
|
16
|
+
work: () => T,
|
|
17
|
+
): T {
|
|
18
|
+
return gates.run(gate, work)
|
|
19
|
+
}
|
|
20
|
+
export async function guardedForgeRequest<T>(work: () => Promise<T>): Promise<T> {
|
|
21
|
+
const gate = gates.getStore()
|
|
22
|
+
await gate?.before()
|
|
23
|
+
try {
|
|
24
|
+
return await work()
|
|
25
|
+
} catch (error) {
|
|
26
|
+
await gate?.failed(error)
|
|
27
|
+
throw error
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Observers from another concurrent operation cannot prove this probe succeeded. */
|
|
32
|
+
export const forgeRequestGateActive = (gate: object): boolean => gates.getStore() === gate
|
|
33
|
+
|
|
34
|
+
/** Internal scheduling deferral; adapters must not turn it into a policy refusal. */
|
|
35
|
+
export class ForgeRequestDeferred extends Error {}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { z } from 'zod'
|
|
2
|
+
/** Bounded operational evidence, never lifecycle authority. */
|
|
3
|
+
export const forgeRequestCountsSchema = z.strictObject({
|
|
4
|
+
total: z.number().int().nonnegative(),
|
|
5
|
+
unattributed: z.number().int().nonnegative(),
|
|
6
|
+
builds: z
|
|
7
|
+
.array(z.strictObject({ build: z.string().min(1), requests: z.number().int().positive() }))
|
|
8
|
+
.max(10),
|
|
9
|
+
complete: z.boolean(),
|
|
10
|
+
})
|
|
11
|
+
export type ForgeRequestCounts = z.infer<typeof forgeRequestCountsSchema>
|
|
12
|
+
export function forgeHotspot(counts: ForgeRequestCounts | undefined): string | undefined {
|
|
13
|
+
if (!counts) return undefined
|
|
14
|
+
const attributed = counts.total - counts.unattributed
|
|
15
|
+
return counts.builds.find((row) => row.requests >= 2 && row.requests > attributed / 2)?.build
|
|
16
|
+
}
|
|
@@ -1,3 +1,13 @@
|
|
|
1
|
+
import { hostname } from 'node:os'
|
|
2
|
+
import {
|
|
3
|
+
guardNativeHandle,
|
|
4
|
+
nativeObserver,
|
|
5
|
+
nativeStateUnavailable,
|
|
6
|
+
NativeIdentityMismatch,
|
|
7
|
+
NativeObservationError,
|
|
8
|
+
notResumable,
|
|
9
|
+
} from './native-session'
|
|
10
|
+
import type { NativeSessionHandle, AgentResumeResult } from '../types'
|
|
1
11
|
/**
|
|
2
12
|
* ClaudeAgentRunner (SPEC §9): AgentRunner over the locally installed Claude
|
|
3
13
|
* Code CLI. Each turn runs `claude -p` with structured streaming output;
|
|
@@ -159,6 +169,7 @@ interface TurnRecord {
|
|
|
159
169
|
}
|
|
160
170
|
|
|
161
171
|
interface SessionState {
|
|
172
|
+
nativeId?: string
|
|
162
173
|
opts: AgentStartOpts
|
|
163
174
|
model?: string
|
|
164
175
|
turns: TurnRecord[]
|
|
@@ -191,16 +202,19 @@ export class ClaudeAgentRunner implements AgentRunner, OneShotCompletion {
|
|
|
191
202
|
|
|
192
203
|
private readonly runCli: ClaudeCliRunFn
|
|
193
204
|
private readonly runCliStream: ClaudeCliStreamFn | undefined
|
|
205
|
+
private readonly host: () => string
|
|
194
206
|
private readonly createSessionId: () => string
|
|
195
207
|
private readonly sessions = new Map<string, SessionState>()
|
|
196
208
|
|
|
197
209
|
constructor(
|
|
198
210
|
opts: {
|
|
211
|
+
hostname?: () => string
|
|
199
212
|
runCli?: ClaudeCliRunFn
|
|
200
213
|
runCliStream?: ClaudeCliStreamFn
|
|
201
214
|
createSessionId?: () => string
|
|
202
215
|
} = {},
|
|
203
216
|
) {
|
|
217
|
+
this.host = opts.hostname ?? hostname
|
|
204
218
|
this.runCli = opts.runCli ?? runClaudeCli
|
|
205
219
|
// A test injecting only the buffered boundary takes the buffered
|
|
206
220
|
// translation path for streaming turns (degraded latency, same content);
|
|
@@ -244,6 +258,9 @@ export class ClaudeAgentRunner implements AgentRunner, OneShotCompletion {
|
|
|
244
258
|
this.sessions.set(session.id, {
|
|
245
259
|
opts,
|
|
246
260
|
...(opts.model !== undefined ? { model: opts.model } : {}),
|
|
261
|
+
nativeId: turn.events
|
|
262
|
+
.map((e) => e.session_id)
|
|
263
|
+
.find((id): id is string => typeof id === 'string' && id.trim().length > 0),
|
|
247
264
|
turns: [this.turnRecord(1, prompt, turn)],
|
|
248
265
|
})
|
|
249
266
|
return { session, result: this.toResult(turn) }
|
|
@@ -265,12 +282,66 @@ export class ClaudeAgentRunner implements AgentRunner, OneShotCompletion {
|
|
|
265
282
|
? { ...state.opts, env: { ...state.opts.env, ...opts.env } }
|
|
266
283
|
: state.opts),
|
|
267
284
|
stream: opts?.stream,
|
|
285
|
+
onNativeSession: opts?.onNativeSession,
|
|
286
|
+
}
|
|
287
|
+
if (state.nativeId !== undefined) {
|
|
288
|
+
const observe = nativeObserver({ ...turnOpts }, this.name, this.host(), state.nativeId)
|
|
289
|
+
await observe(state.nativeId)
|
|
290
|
+
turnOpts.onNativeSession = async (handle) => observe(handle.nativeId)
|
|
268
291
|
}
|
|
269
|
-
const turn = await this.runTurn(
|
|
292
|
+
const turn = await this.runTurn(
|
|
293
|
+
message,
|
|
294
|
+
turnOpts,
|
|
295
|
+
{ resume: state.nativeId ?? session.id },
|
|
296
|
+
opts?.signal,
|
|
297
|
+
)
|
|
270
298
|
state.turns.push(this.turnRecord(state.turns.length + 1, message, turn))
|
|
271
299
|
return this.toResult(turn)
|
|
272
300
|
}
|
|
273
301
|
|
|
302
|
+
async resume(
|
|
303
|
+
handle: NativeSessionHandle,
|
|
304
|
+
message: string,
|
|
305
|
+
opts: AgentStartOpts,
|
|
306
|
+
): Promise<AgentResumeResult> {
|
|
307
|
+
const invalid = guardNativeHandle(handle, this.name, opts, this.host())
|
|
308
|
+
if (invalid !== undefined) return invalid
|
|
309
|
+
let observed = false
|
|
310
|
+
const callerObserver = opts.onNativeSession
|
|
311
|
+
opts = {
|
|
312
|
+
...opts,
|
|
313
|
+
onNativeSession: async (native) => {
|
|
314
|
+
observed = true
|
|
315
|
+
await callerObserver?.(native)
|
|
316
|
+
},
|
|
317
|
+
}
|
|
318
|
+
let turn: ClaudeTurn
|
|
319
|
+
try {
|
|
320
|
+
turn = await this.runTurn(message, opts, { resume: handle.nativeId })
|
|
321
|
+
} catch (error) {
|
|
322
|
+
if (error instanceof NativeIdentityMismatch)
|
|
323
|
+
return notResumable('missing-state', 'Native resume returned a different identity')
|
|
324
|
+
throw error
|
|
325
|
+
}
|
|
326
|
+
if (turn.failure !== undefined && nativeStateUnavailable(turn.failure))
|
|
327
|
+
return notResumable('missing-state', turn.failure.message)
|
|
328
|
+
if (!observed && turn.failure === undefined)
|
|
329
|
+
return notResumable('missing-state', 'Native resume reported no identity')
|
|
330
|
+
const id = handle.nativeId
|
|
331
|
+
const session: AgentSessionHandle = {
|
|
332
|
+
id,
|
|
333
|
+
runner: this.name,
|
|
334
|
+
...(opts.model !== undefined ? { model: opts.model } : {}),
|
|
335
|
+
}
|
|
336
|
+
this.sessions.set(id, {
|
|
337
|
+
opts,
|
|
338
|
+
model: opts.model,
|
|
339
|
+
nativeId: id,
|
|
340
|
+
turns: [this.turnRecord(1, message, turn)],
|
|
341
|
+
})
|
|
342
|
+
return { kind: 'resumed', session, result: this.toResult(turn) }
|
|
343
|
+
}
|
|
344
|
+
|
|
274
345
|
async end(session: AgentSessionHandle): Promise<Transcript> {
|
|
275
346
|
const state = this.liveState(session, 'end')
|
|
276
347
|
this.sessions.delete(session.id)
|
|
@@ -316,6 +387,28 @@ export class ClaudeAgentRunner implements AgentRunner, OneShotCompletion {
|
|
|
316
387
|
session: { sessionId: string } | { resume: string },
|
|
317
388
|
signal: AbortSignal | undefined = opts.signal,
|
|
318
389
|
): Promise<ClaudeTurn> {
|
|
390
|
+
const observe = nativeObserver(
|
|
391
|
+
opts,
|
|
392
|
+
this.name,
|
|
393
|
+
this.host(),
|
|
394
|
+
'resume' in session ? session.resume : undefined,
|
|
395
|
+
)
|
|
396
|
+
const observeEvent = async (event: JsonRecord) => {
|
|
397
|
+
const id = event.session_id
|
|
398
|
+
if (typeof id === 'string') await observe(id)
|
|
399
|
+
}
|
|
400
|
+
const conflict = (opts.args ?? []).find((arg) =>
|
|
401
|
+
CLAUDE_SESSION_ARGS.some((flag) => arg === flag || arg.startsWith(`${flag}=`)),
|
|
402
|
+
)
|
|
403
|
+
if (conflict !== undefined) {
|
|
404
|
+
const failed = launchFailure(new Error(`Conflicting session-control argument: ${conflict}`))
|
|
405
|
+
failed.failure = {
|
|
406
|
+
message: `Conflicting session-control argument: ${conflict}`,
|
|
407
|
+
permanent: true,
|
|
408
|
+
cause: 'configuration',
|
|
409
|
+
}
|
|
410
|
+
return failed
|
|
411
|
+
}
|
|
319
412
|
const args = this.baseArgs()
|
|
320
413
|
if ('sessionId' in session) args.push('--session-id', session.sessionId)
|
|
321
414
|
else args.push('--resume', session.resume)
|
|
@@ -331,7 +424,15 @@ export class ClaudeAgentRunner implements AgentRunner, OneShotCompletion {
|
|
|
331
424
|
env: sessionEnv(opts.env),
|
|
332
425
|
...(signal !== undefined ? { signal } : {}),
|
|
333
426
|
}
|
|
334
|
-
if (opts.stream === undefined
|
|
427
|
+
if (opts.stream === undefined && opts.onNativeSession === undefined)
|
|
428
|
+
return this.runPrompt(invocation)
|
|
429
|
+
if (opts.stream === undefined) {
|
|
430
|
+
if (this.runCliStream !== undefined)
|
|
431
|
+
return this.runStreamingPrompt(invocation, undefined, observe)
|
|
432
|
+
const turn = await this.runPrompt(invocation)
|
|
433
|
+
for (const event of turn.events) await observeEvent(event)
|
|
434
|
+
return turn
|
|
435
|
+
}
|
|
335
436
|
|
|
336
437
|
// Streaming turn: translate while the CLI runs. Without an injected
|
|
337
438
|
// streaming boundary (offline fakes), the buffered path still translates
|
|
@@ -340,10 +441,11 @@ export class ClaudeAgentRunner implements AgentRunner, OneShotCompletion {
|
|
|
340
441
|
emitter.append([promptPart(prompt), startPart(crypto.randomUUID())])
|
|
341
442
|
let turn: ClaudeTurn
|
|
342
443
|
if (this.runCliStream !== undefined) {
|
|
343
|
-
turn = await this.runStreamingPrompt(invocation, emitter)
|
|
444
|
+
turn = await this.runStreamingPrompt(invocation, emitter, observe)
|
|
344
445
|
} else {
|
|
345
446
|
turn = await this.runPrompt(invocation)
|
|
346
|
-
|
|
447
|
+
for (const event of turn.events) await observeEvent(event)
|
|
448
|
+
translateBufferedClaudeTurn(turn, (parts) => emitter?.append(parts))
|
|
347
449
|
}
|
|
348
450
|
this.emitTurnEnd(turn, emitter, signal)
|
|
349
451
|
return turn
|
|
@@ -394,16 +496,24 @@ export class ClaudeAgentRunner implements AgentRunner, OneShotCompletion {
|
|
|
394
496
|
* feed the ordinary accumulators (so outcome classification is identical). */
|
|
395
497
|
private async runStreamingPrompt(
|
|
396
498
|
invocation: ClaudeCliInvocation,
|
|
397
|
-
emitter: SessionStreamEmitter,
|
|
499
|
+
emitter: SessionStreamEmitter | undefined,
|
|
500
|
+
observe: (id: string) => Promise<void>,
|
|
398
501
|
): Promise<ClaudeTurn> {
|
|
399
502
|
let handle: ClaudeCliStreamHandle
|
|
503
|
+
const controller = new AbortController()
|
|
400
504
|
try {
|
|
401
|
-
handle = this.runCliStream!(
|
|
505
|
+
handle = this.runCliStream!({
|
|
506
|
+
...invocation,
|
|
507
|
+
signal:
|
|
508
|
+
invocation.signal === undefined
|
|
509
|
+
? controller.signal
|
|
510
|
+
: AbortSignal.any([invocation.signal, controller.signal]),
|
|
511
|
+
})
|
|
402
512
|
} catch (error) {
|
|
403
513
|
return launchFailure(error)
|
|
404
514
|
}
|
|
405
515
|
const acc = new ClaudeOutputAccumulator()
|
|
406
|
-
const translator = createClaudeStreamTranslator((parts) => emitter
|
|
516
|
+
const translator = createClaudeStreamTranslator((parts) => emitter?.append(parts))
|
|
407
517
|
try {
|
|
408
518
|
for await (const line of handle.lines) {
|
|
409
519
|
let value: unknown
|
|
@@ -417,10 +527,17 @@ export class ClaudeAgentRunner implements AgentRunner, OneShotCompletion {
|
|
|
417
527
|
acc.push(line)
|
|
418
528
|
continue
|
|
419
529
|
}
|
|
530
|
+
const id = value.session_id
|
|
531
|
+
if (typeof id === 'string') await observe(id)
|
|
420
532
|
acc.pushRecord(value)
|
|
421
533
|
translator.onEvent(value)
|
|
422
534
|
}
|
|
423
|
-
} catch {
|
|
535
|
+
} catch (error) {
|
|
536
|
+
if (error instanceof NativeObservationError) {
|
|
537
|
+
controller.abort(error)
|
|
538
|
+
void handle.result.catch(() => {})
|
|
539
|
+
throw error
|
|
540
|
+
}
|
|
424
541
|
// The result promise below still carries the CLI's exit and stderr.
|
|
425
542
|
}
|
|
426
543
|
const cli = await handle.result
|
|
@@ -429,7 +546,7 @@ export class ClaudeAgentRunner implements AgentRunner, OneShotCompletion {
|
|
|
429
546
|
// nothing streamed, translate the buffered events instead.
|
|
430
547
|
if (!translator.streamedAnything()) {
|
|
431
548
|
const turn = this.finishTurn(cli, parsed)
|
|
432
|
-
translateBufferedClaudeTurn(turn, (parts) => emitter
|
|
549
|
+
translateBufferedClaudeTurn(turn, (parts) => emitter?.append(parts))
|
|
433
550
|
return turn
|
|
434
551
|
}
|
|
435
552
|
return this.finishTurn(cli, parsed)
|
|
@@ -871,3 +988,13 @@ function translateBufferedClaudeTurn(turn: ClaudeTurn, emit: (parts: StreamPart[
|
|
|
871
988
|
function errorText(error: unknown): string {
|
|
872
989
|
return error instanceof Error ? error.message : String(error)
|
|
873
990
|
}
|
|
991
|
+
|
|
992
|
+
const CLAUDE_SESSION_ARGS = [
|
|
993
|
+
'--resume',
|
|
994
|
+
'-r',
|
|
995
|
+
'--continue',
|
|
996
|
+
'-c',
|
|
997
|
+
'--session-id',
|
|
998
|
+
'--fork-session',
|
|
999
|
+
'--no-session-persistence',
|
|
1000
|
+
]
|
|
@@ -1,3 +1,13 @@
|
|
|
1
|
+
import { hostname } from 'node:os'
|
|
2
|
+
import {
|
|
3
|
+
guardNativeHandle,
|
|
4
|
+
nativeObserver,
|
|
5
|
+
nativeStateUnavailable,
|
|
6
|
+
NativeIdentityMismatch,
|
|
7
|
+
NativeObservationError,
|
|
8
|
+
notResumable,
|
|
9
|
+
} from './native-session'
|
|
10
|
+
import type { NativeSessionHandle, AgentResumeResult } from '../types'
|
|
1
11
|
/**
|
|
2
12
|
* CodexAgentRunner (SPEC §9): AgentRunner over the locally installed OpenAI
|
|
3
13
|
* Codex CLI. Phase turns use Codex's JSONL exec protocol and native thread
|
|
@@ -202,16 +212,19 @@ export class CodexAgentRunner implements AgentRunner, OneShotCompletion {
|
|
|
202
212
|
|
|
203
213
|
private readonly runCli: CodexCliRunFn
|
|
204
214
|
private readonly runCliStream: CodexCliStreamFn | undefined
|
|
215
|
+
private readonly host: () => string
|
|
205
216
|
private readonly createSessionId: () => string
|
|
206
217
|
private readonly sessions = new Map<string, SessionState>()
|
|
207
218
|
|
|
208
219
|
constructor(
|
|
209
220
|
opts: {
|
|
221
|
+
hostname?: () => string
|
|
210
222
|
runCli?: CodexCliRunFn
|
|
211
223
|
runCliStream?: CodexCliStreamFn
|
|
212
224
|
createSessionId?: () => string
|
|
213
225
|
} = {},
|
|
214
226
|
) {
|
|
227
|
+
this.host = opts.hostname ?? hostname
|
|
215
228
|
this.runCli = opts.runCli ?? runCodexCli
|
|
216
229
|
// A test injecting only the buffered boundary takes the buffered
|
|
217
230
|
// translation path for streaming turns (degraded latency, same content);
|
|
@@ -305,12 +318,61 @@ export class CodexAgentRunner implements AgentRunner, OneShotCompletion {
|
|
|
305
318
|
? { ...state.opts, env: { ...state.opts.env, ...opts.env } }
|
|
306
319
|
: state.opts),
|
|
307
320
|
stream: opts?.stream,
|
|
321
|
+
onNativeSession: opts?.onNativeSession,
|
|
322
|
+
}
|
|
323
|
+
if (state.nativeThreadId !== undefined) {
|
|
324
|
+
const observe = nativeObserver({ ...turnOpts }, this.name, this.host(), state.nativeThreadId)
|
|
325
|
+
await observe(state.nativeThreadId)
|
|
326
|
+
turnOpts.onNativeSession = async (handle) => observe(handle.nativeId)
|
|
308
327
|
}
|
|
309
328
|
const turn = await this.runTurn(message, turnOpts, state.nativeThreadId, opts?.signal)
|
|
310
329
|
state.turns.push(this.turnRecord(state.turns.length + 1, message, turn))
|
|
311
330
|
return this.toResult(turn)
|
|
312
331
|
}
|
|
313
332
|
|
|
333
|
+
async resume(
|
|
334
|
+
handle: NativeSessionHandle,
|
|
335
|
+
message: string,
|
|
336
|
+
opts: AgentStartOpts,
|
|
337
|
+
): Promise<AgentResumeResult> {
|
|
338
|
+
const invalid = guardNativeHandle(handle, this.name, opts, this.host())
|
|
339
|
+
if (invalid !== undefined) return invalid
|
|
340
|
+
let observed = false
|
|
341
|
+
const callerObserver = opts.onNativeSession
|
|
342
|
+
opts = {
|
|
343
|
+
...opts,
|
|
344
|
+
onNativeSession: async (native) => {
|
|
345
|
+
observed = true
|
|
346
|
+
await callerObserver?.(native)
|
|
347
|
+
},
|
|
348
|
+
}
|
|
349
|
+
let turn: CodexTurn
|
|
350
|
+
try {
|
|
351
|
+
turn = await this.runTurn(message, opts, handle.nativeId)
|
|
352
|
+
} catch (error) {
|
|
353
|
+
if (error instanceof NativeIdentityMismatch)
|
|
354
|
+
return notResumable('missing-state', 'Native resume returned a different identity')
|
|
355
|
+
throw error
|
|
356
|
+
}
|
|
357
|
+
if (turn.failure !== undefined && nativeStateUnavailable(turn.failure))
|
|
358
|
+
return notResumable('missing-state', turn.failure.message)
|
|
359
|
+
if (!observed && turn.failure === undefined)
|
|
360
|
+
return notResumable('missing-state', 'Native resume reported no identity')
|
|
361
|
+
const id = handle.nativeId
|
|
362
|
+
const session: AgentSessionHandle = {
|
|
363
|
+
id,
|
|
364
|
+
runner: this.name,
|
|
365
|
+
...(opts.model !== undefined ? { model: opts.model } : {}),
|
|
366
|
+
}
|
|
367
|
+
this.sessions.set(id, {
|
|
368
|
+
opts,
|
|
369
|
+
model: opts.model,
|
|
370
|
+
nativeThreadId: id,
|
|
371
|
+
turns: [this.turnRecord(1, message, turn)],
|
|
372
|
+
})
|
|
373
|
+
return { kind: 'resumed', session, result: this.toResult(turn) }
|
|
374
|
+
}
|
|
375
|
+
|
|
314
376
|
async end(session: AgentSessionHandle): Promise<Transcript> {
|
|
315
377
|
const state = this.liveState(session, 'end')
|
|
316
378
|
this.sessions.delete(session.id)
|
|
@@ -357,6 +419,23 @@ export class CodexAgentRunner implements AgentRunner, OneShotCompletion {
|
|
|
357
419
|
resume?: string,
|
|
358
420
|
signal: AbortSignal | undefined = opts.signal,
|
|
359
421
|
): Promise<CodexTurn> {
|
|
422
|
+
const observe = nativeObserver(opts, this.name, this.host(), resume)
|
|
423
|
+
const observeEvent = async (event: JsonRecord) => {
|
|
424
|
+
const id = event.type === 'thread.started' ? (event.thread_id ?? event.threadId) : undefined
|
|
425
|
+
if (typeof id === 'string') await observe(id)
|
|
426
|
+
}
|
|
427
|
+
const conflict = (opts.args ?? []).find((arg) =>
|
|
428
|
+
CODEX_SESSION_ARGS.some((flag) => arg === flag || arg.startsWith(`${flag}=`)),
|
|
429
|
+
)
|
|
430
|
+
if (conflict !== undefined) {
|
|
431
|
+
const failed = launchFailure(new Error(`Conflicting session-control argument: ${conflict}`))
|
|
432
|
+
failed.failure = {
|
|
433
|
+
message: `Conflicting session-control argument: ${conflict}`,
|
|
434
|
+
permanent: true,
|
|
435
|
+
cause: 'configuration',
|
|
436
|
+
}
|
|
437
|
+
return failed
|
|
438
|
+
}
|
|
360
439
|
const args = ['exec']
|
|
361
440
|
if (resume !== undefined) args.push('resume')
|
|
362
441
|
args.push(
|
|
@@ -375,7 +454,15 @@ export class CodexAgentRunner implements AgentRunner, OneShotCompletion {
|
|
|
375
454
|
env: sessionEnv(opts.env),
|
|
376
455
|
...(signal !== undefined ? { signal } : {}),
|
|
377
456
|
}
|
|
378
|
-
if (opts.stream === undefined
|
|
457
|
+
if (opts.stream === undefined && opts.onNativeSession === undefined)
|
|
458
|
+
return this.runPrompt(invocation)
|
|
459
|
+
if (opts.stream === undefined) {
|
|
460
|
+
if (this.runCliStream !== undefined)
|
|
461
|
+
return this.runStreamingPrompt(invocation, undefined, observe)
|
|
462
|
+
const turn = await this.runPrompt(invocation)
|
|
463
|
+
for (const event of turn.events) await observeEvent(event)
|
|
464
|
+
return turn
|
|
465
|
+
}
|
|
379
466
|
|
|
380
467
|
// Streaming turn: translate while the CLI runs. Without an injected
|
|
381
468
|
// streaming boundary (offline fakes), the buffered path still translates
|
|
@@ -384,10 +471,11 @@ export class CodexAgentRunner implements AgentRunner, OneShotCompletion {
|
|
|
384
471
|
emitter.append([promptPart(prompt), startPart(crypto.randomUUID())])
|
|
385
472
|
let turn: CodexTurn
|
|
386
473
|
if (this.runCliStream !== undefined) {
|
|
387
|
-
turn = await this.runStreamingPrompt(invocation, emitter)
|
|
474
|
+
turn = await this.runStreamingPrompt(invocation, emitter, observe)
|
|
388
475
|
} else {
|
|
389
476
|
turn = await this.runPrompt(invocation)
|
|
390
|
-
|
|
477
|
+
for (const event of turn.events) await observeEvent(event)
|
|
478
|
+
translateBufferedCodexTurn(turn, (parts) => emitter?.append(parts))
|
|
391
479
|
}
|
|
392
480
|
this.emitTurnEnd(turn, emitter, signal)
|
|
393
481
|
return turn
|
|
@@ -417,16 +505,24 @@ export class CodexAgentRunner implements AgentRunner, OneShotCompletion {
|
|
|
417
505
|
* same records feed the ordinary accumulators. */
|
|
418
506
|
private async runStreamingPrompt(
|
|
419
507
|
invocation: CodexCliInvocation,
|
|
420
|
-
emitter: SessionStreamEmitter,
|
|
508
|
+
emitter: SessionStreamEmitter | undefined,
|
|
509
|
+
observe: (id: string) => Promise<void>,
|
|
421
510
|
): Promise<CodexTurn> {
|
|
422
511
|
let handle: CodexCliStreamHandle
|
|
512
|
+
const controller = new AbortController()
|
|
423
513
|
try {
|
|
424
|
-
handle = this.runCliStream!(
|
|
514
|
+
handle = this.runCliStream!({
|
|
515
|
+
...invocation,
|
|
516
|
+
signal:
|
|
517
|
+
invocation.signal === undefined
|
|
518
|
+
? controller.signal
|
|
519
|
+
: AbortSignal.any([invocation.signal, controller.signal]),
|
|
520
|
+
})
|
|
425
521
|
} catch (error) {
|
|
426
522
|
return launchFailure(error)
|
|
427
523
|
}
|
|
428
524
|
const acc = new CodexOutputAccumulator()
|
|
429
|
-
const translator = createCodexStreamTranslator((parts) => emitter
|
|
525
|
+
const translator = createCodexStreamTranslator((parts) => emitter?.append(parts))
|
|
430
526
|
try {
|
|
431
527
|
for await (const line of handle.lines) {
|
|
432
528
|
let value: unknown
|
|
@@ -440,10 +536,17 @@ export class CodexAgentRunner implements AgentRunner, OneShotCompletion {
|
|
|
440
536
|
acc.push(line)
|
|
441
537
|
continue
|
|
442
538
|
}
|
|
539
|
+
const id = value.type === 'thread.started' ? (value.thread_id ?? value.threadId) : undefined
|
|
540
|
+
if (typeof id === 'string') await observe(id)
|
|
443
541
|
acc.pushRecord(value)
|
|
444
542
|
translator.onEvent(value)
|
|
445
543
|
}
|
|
446
|
-
} catch {
|
|
544
|
+
} catch (error) {
|
|
545
|
+
if (error instanceof NativeObservationError) {
|
|
546
|
+
controller.abort(error)
|
|
547
|
+
void handle.result.catch(() => {})
|
|
548
|
+
throw error
|
|
549
|
+
}
|
|
447
550
|
// The result promise below still carries the CLI's exit and stderr.
|
|
448
551
|
}
|
|
449
552
|
const cli = await handle.result
|
|
@@ -875,3 +978,5 @@ function translateBufferedCodexTurn(turn: CodexTurn, emit: (parts: StreamPart[])
|
|
|
875
978
|
}
|
|
876
979
|
emit([finishStepPart()])
|
|
877
980
|
}
|
|
981
|
+
|
|
982
|
+
const CODEX_SESSION_ARGS = ['--ephemeral', '--last', '--all', '--fork']
|
|
@@ -490,3 +490,81 @@ export function describeAgentRunnerContract(
|
|
|
490
490
|
})
|
|
491
491
|
})
|
|
492
492
|
}
|
|
493
|
+
|
|
494
|
+
export interface NativeResumeContractFixture {
|
|
495
|
+
createRunner(): AgentRunner
|
|
496
|
+
opts: import('../types').AgentStartOpts
|
|
497
|
+
/** Delete the fixture's native state, independently of adapter memory. */
|
|
498
|
+
forget(): Promise<void>
|
|
499
|
+
cleanup(): Promise<void>
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/** A fixture supplies native persistence shared by otherwise independent runners.
|
|
503
|
+
* Plugins without resume may still run the existing live-session contract. */
|
|
504
|
+
export function describeNativeResumeContract(
|
|
505
|
+
name: string,
|
|
506
|
+
factory: () => Promise<NativeResumeContractFixture>,
|
|
507
|
+
): void {
|
|
508
|
+
describe(`Native resume contract: ${name}`, () => {
|
|
509
|
+
test('serialized identity continues in a fresh runner, guards location, and retains endable results', async () => {
|
|
510
|
+
const { resumeAgent } = await import('./native-session')
|
|
511
|
+
const f = await factory()
|
|
512
|
+
try {
|
|
513
|
+
let handle: import('../types').NativeSessionHandle | undefined
|
|
514
|
+
const a = f.createRunner()
|
|
515
|
+
const started = await a.start({
|
|
516
|
+
...f.opts,
|
|
517
|
+
onNativeSession: async (value) => {
|
|
518
|
+
handle = value
|
|
519
|
+
},
|
|
520
|
+
})
|
|
521
|
+
expect(started.result.kind).toBe('completed')
|
|
522
|
+
expect(handle).toBeDefined()
|
|
523
|
+
await a.continue(started.session, 'remember contract-secret')
|
|
524
|
+
await a.end(started.session)
|
|
525
|
+
const durable = JSON.parse(JSON.stringify(handle)) as import('../types').NativeSessionHandle
|
|
526
|
+
const b = f.createRunner()
|
|
527
|
+
expect(
|
|
528
|
+
(await resumeAgent(b, { ...durable, host: 'another-host.invalid' }, 'recall', f.opts))
|
|
529
|
+
.kind,
|
|
530
|
+
).toBe('not-resumable')
|
|
531
|
+
expect(
|
|
532
|
+
(
|
|
533
|
+
await resumeAgent(b, durable, 'recall', {
|
|
534
|
+
...f.opts,
|
|
535
|
+
workspacePath: `${f.opts.workspacePath}/other`,
|
|
536
|
+
})
|
|
537
|
+
).kind,
|
|
538
|
+
).toBe('not-resumable')
|
|
539
|
+
expect(
|
|
540
|
+
(await resumeAgent(b, { ...durable, runner: 'another-adapter' }, 'recall', f.opts)).kind,
|
|
541
|
+
).toBe('not-resumable')
|
|
542
|
+
const resumed = await resumeAgent(b, durable, 'recall', {
|
|
543
|
+
...f.opts,
|
|
544
|
+
env: { NATIVE_CONTRACT_FRESH: 'fresh' },
|
|
545
|
+
})
|
|
546
|
+
expect(resumed.kind).toBe('resumed')
|
|
547
|
+
if (resumed.kind !== 'resumed') throw new Error(resumed.message)
|
|
548
|
+
expect(resumed.result.kind).toBe('completed')
|
|
549
|
+
expect(resumed.result.text).toContain('contract-secret')
|
|
550
|
+
expect(resumed.result.text).toContain('fresh')
|
|
551
|
+
const transcript = await b.end(resumed.session)
|
|
552
|
+
expect(transcript.content).toContain('recall')
|
|
553
|
+
expect(transcript.metadata.usage.turns).toBe(1)
|
|
554
|
+
const failedRunner = f.createRunner()
|
|
555
|
+
const failed = await resumeAgent(failedRunner, durable, 'provider-failure', f.opts)
|
|
556
|
+
expect(failed.kind).toBe('resumed')
|
|
557
|
+
if (failed.kind === 'resumed') {
|
|
558
|
+
expect(failed.result.kind).toBe('failed')
|
|
559
|
+
await failedRunner.end(failed.session)
|
|
560
|
+
}
|
|
561
|
+
await f.forget()
|
|
562
|
+
expect((await resumeAgent(f.createRunner(), durable, 'recall', f.opts)).kind).toBe(
|
|
563
|
+
'not-resumable',
|
|
564
|
+
)
|
|
565
|
+
} finally {
|
|
566
|
+
await f.cleanup()
|
|
567
|
+
}
|
|
568
|
+
})
|
|
569
|
+
})
|
|
570
|
+
}
|