@agentic-sdlc-kit/cli 0.0.0-stage → 0.8.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.
- package/LICENSE +21 -0
- package/README.md +32 -2
- package/dist/application/agent/execution-store.d.ts +55 -0
- package/dist/application/agent/execution-store.d.ts.map +1 -0
- package/dist/application/agent/execution-store.js +90 -0
- package/dist/application/agent/execution-store.js.map +1 -0
- package/dist/application/agent/gateway.d.ts +74 -0
- package/dist/application/agent/gateway.d.ts.map +1 -0
- package/dist/application/agent/gateway.js +580 -0
- package/dist/application/agent/gateway.js.map +1 -0
- package/dist/application/agent/index.d.ts +6 -0
- package/dist/application/agent/index.d.ts.map +1 -0
- package/dist/application/agent/index.js +18 -0
- package/dist/application/agent/index.js.map +1 -0
- package/dist/application/agent/orchestrator.d.ts +76 -0
- package/dist/application/agent/orchestrator.d.ts.map +1 -0
- package/dist/application/agent/orchestrator.js +422 -0
- package/dist/application/agent/orchestrator.js.map +1 -0
- package/dist/application/agent/providers/claude-code/claude-argv.d.ts +15 -0
- package/dist/application/agent/providers/claude-code/claude-argv.d.ts.map +1 -0
- package/dist/application/agent/providers/claude-code/claude-argv.js +98 -0
- package/dist/application/agent/providers/claude-code/claude-argv.js.map +1 -0
- package/dist/application/agent/providers/claude-code/index.d.ts +7 -0
- package/dist/application/agent/providers/claude-code/index.d.ts.map +1 -0
- package/dist/application/agent/providers/claude-code/index.js +13 -0
- package/dist/application/agent/providers/claude-code/index.js.map +1 -0
- package/dist/application/agent/providers/claude-code/mod-parity.d.ts +15 -0
- package/dist/application/agent/providers/claude-code/mod-parity.d.ts.map +1 -0
- package/dist/application/agent/providers/claude-code/mod-parity.js +41 -0
- package/dist/application/agent/providers/claude-code/mod-parity.js.map +1 -0
- package/dist/application/agent/providers/claude-code/permission-config.d.ts +59 -0
- package/dist/application/agent/providers/claude-code/permission-config.d.ts.map +1 -0
- package/dist/application/agent/providers/claude-code/permission-config.js +189 -0
- package/dist/application/agent/providers/claude-code/permission-config.js.map +1 -0
- package/dist/application/agent/providers/claude-code/provider.d.ts +38 -0
- package/dist/application/agent/providers/claude-code/provider.d.ts.map +1 -0
- package/dist/application/agent/providers/claude-code/provider.js +577 -0
- package/dist/application/agent/providers/claude-code/provider.js.map +1 -0
- package/dist/application/agent/providers/claude-code/resume-store.d.ts +25 -0
- package/dist/application/agent/providers/claude-code/resume-store.d.ts.map +1 -0
- package/dist/application/agent/providers/claude-code/resume-store.js +120 -0
- package/dist/application/agent/providers/claude-code/resume-store.js.map +1 -0
- package/dist/application/agent/providers/claude-code/stream-parser.d.ts +50 -0
- package/dist/application/agent/providers/claude-code/stream-parser.d.ts.map +1 -0
- package/dist/application/agent/providers/claude-code/stream-parser.js +129 -0
- package/dist/application/agent/providers/claude-code/stream-parser.js.map +1 -0
- package/dist/application/agent/test-fixture.d.ts +15 -0
- package/dist/application/agent/test-fixture.d.ts.map +1 -0
- package/dist/application/agent/test-fixture.js +93 -0
- package/dist/application/agent/test-fixture.js.map +1 -0
- package/dist/application/agent/workspace.d.ts +24 -0
- package/dist/application/agent/workspace.d.ts.map +1 -0
- package/dist/application/agent/workspace.js +139 -0
- package/dist/application/agent/workspace.js.map +1 -0
- package/dist/application/dispatcher.d.ts +13 -0
- package/dist/application/dispatcher.d.ts.map +1 -0
- package/dist/application/dispatcher.js +104 -0
- package/dist/application/dispatcher.js.map +1 -0
- package/dist/application/index.d.ts +5 -0
- package/dist/application/index.d.ts.map +1 -0
- package/dist/application/index.js +6 -0
- package/dist/application/index.js.map +1 -0
- package/dist/application/registry.d.ts +8 -0
- package/dist/application/registry.d.ts.map +1 -0
- package/dist/application/registry.js +17 -0
- package/dist/application/registry.js.map +1 -0
- package/dist/application/version.d.ts +2 -0
- package/dist/application/version.d.ts.map +1 -0
- package/dist/application/version.js +7 -0
- package/dist/application/version.js.map +1 -0
- package/dist/commands/doctor.d.ts +3 -0
- package/dist/commands/doctor.d.ts.map +1 -0
- package/dist/commands/doctor.js +68 -0
- package/dist/commands/doctor.js.map +1 -0
- package/dist/commands/elicit.d.ts +3 -0
- package/dist/commands/elicit.d.ts.map +1 -0
- package/dist/commands/elicit.js +163 -0
- package/dist/commands/elicit.js.map +1 -0
- package/dist/commands/evolve.d.ts +3 -0
- package/dist/commands/evolve.d.ts.map +1 -0
- package/dist/commands/evolve.js +165 -0
- package/dist/commands/evolve.js.map +1 -0
- package/dist/commands/feature.d.ts +13 -0
- package/dist/commands/feature.d.ts.map +1 -0
- package/dist/commands/feature.js +326 -0
- package/dist/commands/feature.js.map +1 -0
- package/dist/commands/fix.d.ts +3 -0
- package/dist/commands/fix.d.ts.map +1 -0
- package/dist/commands/fix.js +61 -0
- package/dist/commands/fix.js.map +1 -0
- package/dist/commands/help.d.ts +4 -0
- package/dist/commands/help.d.ts.map +1 -0
- package/dist/commands/help.js +32 -0
- package/dist/commands/help.js.map +1 -0
- package/dist/commands/index.d.ts +21 -0
- package/dist/commands/index.d.ts.map +1 -0
- package/dist/commands/index.js +22 -0
- package/dist/commands/index.js.map +1 -0
- package/dist/commands/init.d.ts +3 -0
- package/dist/commands/init.d.ts.map +1 -0
- package/dist/commands/init.js +90 -0
- package/dist/commands/init.js.map +1 -0
- package/dist/commands/inspect.d.ts +3 -0
- package/dist/commands/inspect.d.ts.map +1 -0
- package/dist/commands/inspect.js +64 -0
- package/dist/commands/inspect.js.map +1 -0
- package/dist/commands/install.d.ts +3 -0
- package/dist/commands/install.d.ts.map +1 -0
- package/dist/commands/install.js +329 -0
- package/dist/commands/install.js.map +1 -0
- package/dist/commands/journal.d.ts +3 -0
- package/dist/commands/journal.d.ts.map +1 -0
- package/dist/commands/journal.js +107 -0
- package/dist/commands/journal.js.map +1 -0
- package/dist/commands/memory.d.ts +3 -0
- package/dist/commands/memory.d.ts.map +1 -0
- package/dist/commands/memory.js +85 -0
- package/dist/commands/memory.js.map +1 -0
- package/dist/commands/new.d.ts +3 -0
- package/dist/commands/new.d.ts.map +1 -0
- package/dist/commands/new.js +68 -0
- package/dist/commands/new.js.map +1 -0
- package/dist/commands/next.d.ts +3 -0
- package/dist/commands/next.d.ts.map +1 -0
- package/dist/commands/next.js +107 -0
- package/dist/commands/next.js.map +1 -0
- package/dist/commands/optimize.d.ts +3 -0
- package/dist/commands/optimize.d.ts.map +1 -0
- package/dist/commands/optimize.js +28 -0
- package/dist/commands/optimize.js.map +1 -0
- package/dist/commands/plugin-linker.d.ts +34 -0
- package/dist/commands/plugin-linker.d.ts.map +1 -0
- package/dist/commands/plugin-linker.js +177 -0
- package/dist/commands/plugin-linker.js.map +1 -0
- package/dist/commands/refactor.d.ts +3 -0
- package/dist/commands/refactor.d.ts.map +1 -0
- package/dist/commands/refactor.js +32 -0
- package/dist/commands/refactor.js.map +1 -0
- package/dist/commands/types.d.ts +19 -0
- package/dist/commands/types.d.ts.map +1 -0
- package/dist/commands/types.js +7 -0
- package/dist/commands/types.js.map +1 -0
- package/dist/commands/validate-plan.d.ts +3 -0
- package/dist/commands/validate-plan.d.ts.map +1 -0
- package/dist/commands/validate-plan.js +62 -0
- package/dist/commands/validate-plan.js.map +1 -0
- package/dist/commands/validate-spec.d.ts +3 -0
- package/dist/commands/validate-spec.d.ts.map +1 -0
- package/dist/commands/validate-spec.js +62 -0
- package/dist/commands/validate-spec.js.map +1 -0
- package/dist/commands/verify.d.ts +3 -0
- package/dist/commands/verify.d.ts.map +1 -0
- package/dist/commands/verify.js +103 -0
- package/dist/commands/verify.js.map +1 -0
- package/dist/commands/version.d.ts +3 -0
- package/dist/commands/version.d.ts.map +1 -0
- package/dist/commands/version.js +12 -0
- package/dist/commands/version.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +27 -0
- package/dist/index.js.map +1 -0
- package/dist/output/formatter.d.ts +2 -0
- package/dist/output/formatter.d.ts.map +1 -0
- package/dist/output/formatter.js +10 -0
- package/dist/output/formatter.js.map +1 -0
- package/dist/output/index.d.ts +2 -0
- package/dist/output/index.d.ts.map +1 -0
- package/dist/output/index.js +3 -0
- package/dist/output/index.js.map +1 -0
- package/package.json +37 -3
- package/src/application/agent/execution-store.ts +162 -0
- package/src/application/agent/gateway.test.ts +529 -0
- package/src/application/agent/gateway.ts +744 -0
- package/src/application/agent/index.ts +18 -0
- package/src/application/agent/orchestrator.test.ts +341 -0
- package/src/application/agent/orchestrator.ts +628 -0
- package/src/application/agent/providers/claude-code/claude-argv.ts +119 -0
- package/src/application/agent/providers/claude-code/claude-code-smoke.test.ts +139 -0
- package/src/application/agent/providers/claude-code/fixtures/fake-claude.mjs +125 -0
- package/src/application/agent/providers/claude-code/index.ts +28 -0
- package/src/application/agent/providers/claude-code/mod-parity.ts +50 -0
- package/src/application/agent/providers/claude-code/permission-config.test.ts +221 -0
- package/src/application/agent/providers/claude-code/permission-config.ts +242 -0
- package/src/application/agent/providers/claude-code/provider.test.ts +378 -0
- package/src/application/agent/providers/claude-code/provider.ts +717 -0
- package/src/application/agent/providers/claude-code/resume-store.test.ts +161 -0
- package/src/application/agent/providers/claude-code/resume-store.ts +157 -0
- package/src/application/agent/providers/claude-code/stream-parser.ts +166 -0
- package/src/application/agent/test-fixture.ts +131 -0
- package/src/application/agent/workspace.test.ts +104 -0
- package/src/application/agent/workspace.ts +156 -0
- package/src/application/dispatcher.test.ts +89 -0
- package/src/application/dispatcher.ts +98 -0
- package/src/application/index.ts +5 -0
- package/src/application/registry.ts +24 -0
- package/src/application/version.ts +7 -0
- package/src/commands/clse.test.ts +181 -0
- package/src/commands/doctor.test.ts +29 -0
- package/src/commands/doctor.ts +78 -0
- package/src/commands/elicit.test.ts +111 -0
- package/src/commands/elicit.ts +188 -0
- package/src/commands/evolve.ts +209 -0
- package/src/commands/feature.test.ts +323 -0
- package/src/commands/feature.ts +405 -0
- package/src/commands/fix.test.ts +36 -0
- package/src/commands/fix.ts +69 -0
- package/src/commands/help.test.ts +33 -0
- package/src/commands/help.ts +35 -0
- package/src/commands/index.ts +21 -0
- package/src/commands/init.test.ts +65 -0
- package/src/commands/init.ts +103 -0
- package/src/commands/inspect.test.ts +57 -0
- package/src/commands/inspect.ts +73 -0
- package/src/commands/install.test.ts +61 -0
- package/src/commands/install.ts +375 -0
- package/src/commands/journal.ts +118 -0
- package/src/commands/memory.ts +96 -0
- package/src/commands/new.test.ts +44 -0
- package/src/commands/new.ts +77 -0
- package/src/commands/next.test.ts +241 -0
- package/src/commands/next.ts +124 -0
- package/src/commands/optimize.ts +30 -0
- package/src/commands/plugin-linker.test.ts +139 -0
- package/src/commands/plugin-linker.ts +196 -0
- package/src/commands/refactor.ts +34 -0
- package/src/commands/stack-commands.test.ts +67 -0
- package/src/commands/tier-c-conformance.test.ts +194 -0
- package/src/commands/types.ts +26 -0
- package/src/commands/validate-plan.test.ts +107 -0
- package/src/commands/validate-plan.ts +67 -0
- package/src/commands/validate-spec.test.ts +59 -0
- package/src/commands/validate-spec.ts +68 -0
- package/src/commands/verify.test.ts +117 -0
- package/src/commands/verify.ts +112 -0
- package/src/commands/version.test.ts +11 -0
- package/src/commands/version.ts +14 -0
- package/src/index.ts +30 -0
- package/src/output/formatter.ts +10 -0
- package/src/output/index.ts +2 -0
|
@@ -0,0 +1,717 @@
|
|
|
1
|
+
// packages/cli/src/application/agent/providers/claude-code/provider.ts
|
|
2
|
+
//
|
|
3
|
+
// ClaudeCodeProvider — the secure Claude Code provider for Mode 1
|
|
4
|
+
// (kit-orchestrated) execution. ADR-0019 PR4 (security-critical).
|
|
5
|
+
//
|
|
6
|
+
// What this provider guarantees (and where each guarantee is tested):
|
|
7
|
+
// - HEADLESS: `claude -p --output-format stream-json` with an ARGV ARRAY,
|
|
8
|
+
// shell:false, cwd = the run's isolated workspace (worktree) — never
|
|
9
|
+
// the developer's tree. (provider.test.ts: argv assertions)
|
|
10
|
+
// - POLICY-DERIVED PERMISSIONS: the session's permission configuration is
|
|
11
|
+
// GENERATED from the canonical snapshot (permission-config.ts); no
|
|
12
|
+
// hand-maintained second policy (ADR-0020 §2). `bypassPermissions` and
|
|
13
|
+
// `--dangerously-skip-permissions` are never emitted (asserted at
|
|
14
|
+
// build time in claude-argv.ts and pinned by tests).
|
|
15
|
+
// - MODS PARITY: the kit's runtime Mods are linked into the workspace
|
|
16
|
+
// before the agent starts; the outcome is reported honestly
|
|
17
|
+
// (mod-parity.ts).
|
|
18
|
+
// - HONEST BUDGETS: duration + tool calls are gateway-enforced (the
|
|
19
|
+
// provider wires abort -> kill and streams tool.requested events LIVE
|
|
20
|
+
// so the gateway's counters actually fire mid-run); tokens and cost
|
|
21
|
+
// are reported best-effort from Claude's own usage telemetry — declared
|
|
22
|
+
// best-effort, never provider-enforced (revision C).
|
|
23
|
+
// - HONEST STATUSES: cancellation/crash/turn-limit are VALUES on the
|
|
24
|
+
// result (cancelled/interrupted/failed), never `completed`
|
|
25
|
+
// (provider.test.ts: cancel, crash, max-turns, error, no-result).
|
|
26
|
+
// - CROSS-PROCESS RESUME: the session id + resume token persist ONLY in
|
|
27
|
+
// the AES-256-GCM store (resume-store.ts); the token never appears in
|
|
28
|
+
// events, logs, or plaintext on disk. (resume-store.test.ts,
|
|
29
|
+
// provider.test.ts: resume round-trip with a fresh provider instance)
|
|
30
|
+
// - NO FABRICATED EVIDENCE: proposedArtifacts is always empty — the
|
|
31
|
+
// agent's claims are not evidence; Kit derives truth from git
|
|
32
|
+
// (ADR-0018).
|
|
33
|
+
//
|
|
34
|
+
// Approval policy: when the canonical policy does not allow autonomous
|
|
35
|
+
// execution for a capability that requires approval, the provider blocks
|
|
36
|
+
// with `needs_approval` BEFORE spawning anything — CI runs are autonomous
|
|
37
|
+
// but never silent.
|
|
38
|
+
|
|
39
|
+
import { spawn, type ChildProcess } from 'node:child_process';
|
|
40
|
+
import {
|
|
41
|
+
AGENT_EVENT_SCHEMA_VERSION,
|
|
42
|
+
AGENT_EXECUTION_SCHEMA_VERSION,
|
|
43
|
+
type AgentEventSink,
|
|
44
|
+
type AgentExecutionError,
|
|
45
|
+
type AgentExecutionEvent,
|
|
46
|
+
type AgentExecutionHandle,
|
|
47
|
+
type AgentExecutionRequest,
|
|
48
|
+
type AgentExecutionResult,
|
|
49
|
+
type AgentHealth,
|
|
50
|
+
type AgentProvider,
|
|
51
|
+
type AgentProviderCapabilities,
|
|
52
|
+
} from '@agentic-sdlc-kit/contracts';
|
|
53
|
+
import { buildClaudeArgv, buildClaudeResumeArgv, CLAUDE_VERSION_ARGS } from './claude-argv.js';
|
|
54
|
+
import { CLAUDE_CODE_SUPPORTED_CAPABILITIES } from './permission-config.js';
|
|
55
|
+
import { ensureRuntimeModsActive } from './mod-parity.js';
|
|
56
|
+
import {
|
|
57
|
+
generateResumeToken,
|
|
58
|
+
loadSessionRecord,
|
|
59
|
+
saveSessionRecord,
|
|
60
|
+
verifyResumeToken,
|
|
61
|
+
} from './resume-store.js';
|
|
62
|
+
import { capabilityOfToolUse, ClaudeStreamParser, type ClaudeFinalResult } from './stream-parser.js';
|
|
63
|
+
import { loadExecution } from '../../execution-store.js';
|
|
64
|
+
|
|
65
|
+
export interface ClaudeCodeProviderOptions {
|
|
66
|
+
/** Where the gateway persists execution records (also roots the encrypted resume store). */
|
|
67
|
+
readonly projectRoot: string;
|
|
68
|
+
/** The claude executable. Default 'claude'. */
|
|
69
|
+
readonly cliPath?: string;
|
|
70
|
+
/**
|
|
71
|
+
* Args inserted before the derived claude args (e.g. a fixture script path
|
|
72
|
+
* when cliPath is a runtime binary). Test seam only; default none.
|
|
73
|
+
*/
|
|
74
|
+
readonly cliArgvPrefix?: readonly string[];
|
|
75
|
+
/** Probe timeout for healthCheck (default 3s). */
|
|
76
|
+
readonly healthTimeoutMs?: number;
|
|
77
|
+
/** Bounded output: kill the process past this many stdout+stderr bytes (default 16 MiB). */
|
|
78
|
+
readonly maxOutputBytes?: number;
|
|
79
|
+
/** Grace between SIGTERM and SIGKILL on cancel (default 5s). */
|
|
80
|
+
readonly killGraceMs?: number;
|
|
81
|
+
/** Extra env merged over process.env for the child (test seam). */
|
|
82
|
+
readonly env?: Readonly<Record<string, string>>;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const DEFAULT_CLI = 'claude';
|
|
86
|
+
const DEFAULT_HEALTH_TIMEOUT_MS = 3_000;
|
|
87
|
+
const DEFAULT_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
|
|
88
|
+
const DEFAULT_KILL_GRACE_MS = 5_000;
|
|
89
|
+
const DEFAULT_RESUME_DURATION_MS = 600_000;
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Honest enforcement levels (revision C): the gateway owns the process and
|
|
93
|
+
* the event counters, so duration and tool calls are gateway-enforced.
|
|
94
|
+
* Claude reports token usage and cost in its final result, but the provider
|
|
95
|
+
* cannot HARD-enforce them — declared best-effort and reported, never
|
|
96
|
+
* claimed enforced.
|
|
97
|
+
*/
|
|
98
|
+
const CLAUDE_CODE_BUDGET_ENFORCEMENT: AgentProviderCapabilities['budgetEnforcement'] = {
|
|
99
|
+
maxDurationMs: 'gateway-enforced',
|
|
100
|
+
maxToolCalls: 'gateway-enforced',
|
|
101
|
+
maxInputTokens: 'best-effort',
|
|
102
|
+
maxOutputTokens: 'best-effort',
|
|
103
|
+
maxTotalTokens: 'best-effort',
|
|
104
|
+
maxEstimatedCost: 'best-effort',
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
/** Live, replayable event stream for one execution (same contract as the mock). */
|
|
108
|
+
class ExecutionEventStream {
|
|
109
|
+
private sequence = 0;
|
|
110
|
+
private readonly buffer: AgentExecutionEvent[] = [];
|
|
111
|
+
private readonly listeners = new Set<AgentEventSink>();
|
|
112
|
+
|
|
113
|
+
constructor(
|
|
114
|
+
private readonly executionId: string,
|
|
115
|
+
private readonly policyHash: string,
|
|
116
|
+
) {}
|
|
117
|
+
|
|
118
|
+
emit(
|
|
119
|
+
payload: Record<string, unknown>,
|
|
120
|
+
): void {
|
|
121
|
+
this.sequence += 1;
|
|
122
|
+
const event = {
|
|
123
|
+
schemaVersion: AGENT_EVENT_SCHEMA_VERSION,
|
|
124
|
+
eventId: `evt-${this.executionId}-${this.sequence}`,
|
|
125
|
+
executionId: this.executionId,
|
|
126
|
+
sequence: this.sequence,
|
|
127
|
+
policyHash: this.policyHash,
|
|
128
|
+
occurredAt: new Date().toISOString(),
|
|
129
|
+
...payload,
|
|
130
|
+
} as AgentExecutionEvent;
|
|
131
|
+
this.buffer.push(event);
|
|
132
|
+
for (const sink of this.listeners) sink(event);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
subscribe(sink: AgentEventSink): () => void {
|
|
136
|
+
for (const buffered of this.buffer) sink(buffered);
|
|
137
|
+
this.listeners.add(sink);
|
|
138
|
+
return () => {
|
|
139
|
+
this.listeners.delete(sink);
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
interface RunningExecution {
|
|
145
|
+
readonly child: ChildProcess;
|
|
146
|
+
kill: () => void;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
interface SpawnContext {
|
|
150
|
+
readonly executionId: string;
|
|
151
|
+
readonly workflowRunId: AgentExecutionResult['workflowRunId'];
|
|
152
|
+
readonly taskId: AgentExecutionResult['taskId'];
|
|
153
|
+
readonly policyHash: string;
|
|
154
|
+
readonly args: readonly string[];
|
|
155
|
+
readonly cwd: string;
|
|
156
|
+
readonly stream: ExecutionEventStream;
|
|
157
|
+
readonly modsNote: string | undefined;
|
|
158
|
+
readonly signal: AbortSignal;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export class ClaudeCodeProvider implements AgentProvider {
|
|
162
|
+
readonly id = 'claude-code' as const;
|
|
163
|
+
|
|
164
|
+
private readonly opts: {
|
|
165
|
+
projectRoot: string;
|
|
166
|
+
cliPath: string;
|
|
167
|
+
cliArgvPrefix: readonly string[];
|
|
168
|
+
healthTimeoutMs: number;
|
|
169
|
+
maxOutputBytes: number;
|
|
170
|
+
killGraceMs: number;
|
|
171
|
+
env: Readonly<Record<string, string>>;
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
private readonly inFlight = new Map<string, RunningExecution>();
|
|
175
|
+
|
|
176
|
+
constructor(opts: ClaudeCodeProviderOptions) {
|
|
177
|
+
this.opts = {
|
|
178
|
+
projectRoot: opts.projectRoot,
|
|
179
|
+
cliPath: opts.cliPath ?? DEFAULT_CLI,
|
|
180
|
+
cliArgvPrefix: opts.cliArgvPrefix ?? [],
|
|
181
|
+
healthTimeoutMs: opts.healthTimeoutMs ?? DEFAULT_HEALTH_TIMEOUT_MS,
|
|
182
|
+
maxOutputBytes: opts.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,
|
|
183
|
+
killGraceMs: opts.killGraceMs ?? DEFAULT_KILL_GRACE_MS,
|
|
184
|
+
env: opts.env ?? {},
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
async capabilities(): Promise<AgentProviderCapabilities> {
|
|
189
|
+
return {
|
|
190
|
+
capabilities: [...CLAUDE_CODE_SUPPORTED_CAPABILITIES],
|
|
191
|
+
budgetEnforcement: { ...CLAUDE_CODE_BUDGET_ENFORCEMENT },
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async healthCheck(): Promise<AgentHealth> {
|
|
196
|
+
return this.probeVersion();
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async start(request: AgentExecutionRequest, signal: AbortSignal): Promise<AgentExecutionHandle> {
|
|
200
|
+
const stream = new ExecutionEventStream(request.executionId, request.policyHash);
|
|
201
|
+
|
|
202
|
+
// 1. Already-aborted: a cancelled VALUE, never a spawn (mirrors the mock).
|
|
203
|
+
if (signal.aborted) {
|
|
204
|
+
return settledHandle(request.executionId, stream, () =>
|
|
205
|
+
directResult(request, 'cancelled', 'claude-code execution cancelled: aborted before start', [
|
|
206
|
+
{ code: 'CANCELLED', message: 'execution aborted before start', retryable: false },
|
|
207
|
+
]),
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// 2. Approval policy: block BEFORE spawning anything when the policy
|
|
212
|
+
// requires human approval the run may not take autonomously.
|
|
213
|
+
// Autonomous-but-never-silent (ADR-0020 §4).
|
|
214
|
+
const approvalBlocked =
|
|
215
|
+
!request.approvalPolicy.allowAutonomousExecution &&
|
|
216
|
+
request.approvalPolicy.requireApprovalFor.some((c) =>
|
|
217
|
+
request.permissions.capabilities.includes(c),
|
|
218
|
+
);
|
|
219
|
+
if (approvalBlocked) {
|
|
220
|
+
const message =
|
|
221
|
+
`the policy snapshot requires human approval for ` +
|
|
222
|
+
`${request.approvalPolicy.requireApprovalFor.join(', ')} and autonomous execution ` +
|
|
223
|
+
`is disabled — the provider did not start the agent`;
|
|
224
|
+
stream.emit({ type: 'execution.started' });
|
|
225
|
+
stream.emit({ type: 'execution.completed', status: 'needs_approval' });
|
|
226
|
+
return settledHandle(request.executionId, stream, () =>
|
|
227
|
+
directResult(request, 'needs_approval', message, [
|
|
228
|
+
{ code: 'APPROVAL_REQUIRED', message, retryable: false },
|
|
229
|
+
]),
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// 3. Runtime Mods parity: link the kit's Mods into the workspace before
|
|
234
|
+
// the agent can run (honest note either way).
|
|
235
|
+
const mods = await ensureRuntimeModsActive(request.workspace.rootPath);
|
|
236
|
+
|
|
237
|
+
// 4. Headless invocation, derived entirely from the canonical policy.
|
|
238
|
+
const { args } = buildClaudeArgv(request);
|
|
239
|
+
|
|
240
|
+
return this.spawnAndSettle({
|
|
241
|
+
executionId: request.executionId,
|
|
242
|
+
workflowRunId: request.workflowRunId,
|
|
243
|
+
taskId: request.taskId,
|
|
244
|
+
policyHash: request.policyHash,
|
|
245
|
+
args,
|
|
246
|
+
cwd: request.workspace.rootPath,
|
|
247
|
+
stream,
|
|
248
|
+
modsNote: mods.note,
|
|
249
|
+
signal,
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
async resume(executionId: string, resumeToken: string): Promise<AgentExecutionHandle> {
|
|
254
|
+
// The gateway owns the original request (revision A); the provider
|
|
255
|
+
// re-reads its own persisted execution record for the ids/policy it
|
|
256
|
+
// must echo, and the ENCRYPTED session record for the provider session.
|
|
257
|
+
const execution = await loadExecution(this.opts.projectRoot, executionId);
|
|
258
|
+
if (!execution) {
|
|
259
|
+
const stream = new ExecutionEventStream(executionId, 'no-policy');
|
|
260
|
+
return settledHandle(executionId, stream, () =>
|
|
261
|
+
resumeRefusal(executionId, `no persisted execution '${executionId}' — cannot resume`),
|
|
262
|
+
);
|
|
263
|
+
}
|
|
264
|
+
const record = await loadSessionRecord(this.opts.projectRoot, executionId);
|
|
265
|
+
if (!record) {
|
|
266
|
+
const stream = new ExecutionEventStream(executionId, execution.policyHash);
|
|
267
|
+
return settledHandle(executionId, stream, () =>
|
|
268
|
+
resumeRefusal(
|
|
269
|
+
executionId,
|
|
270
|
+
`no encrypted session record for '${executionId}' — the execution cannot be resumed cross-process`,
|
|
271
|
+
),
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
if (!verifyResumeToken(record, resumeToken)) {
|
|
275
|
+
const stream = new ExecutionEventStream(executionId, execution.policyHash);
|
|
276
|
+
return settledHandle(executionId, stream, () =>
|
|
277
|
+
resumeRefusal(executionId, 'invalid resume token — refusing to resume'),
|
|
278
|
+
);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const { args } = buildClaudeResumeArgv(executionId, record.sessionId);
|
|
282
|
+
const stream = new ExecutionEventStream(executionId, execution.policyHash);
|
|
283
|
+
const budgetMs = execution.request.budget.maxDurationMs;
|
|
284
|
+
return this.spawnAndSettle({
|
|
285
|
+
executionId,
|
|
286
|
+
workflowRunId: execution.workflowRunId,
|
|
287
|
+
taskId: execution.taskId,
|
|
288
|
+
policyHash: execution.policyHash,
|
|
289
|
+
args,
|
|
290
|
+
cwd: execution.request.workspace.rootPath,
|
|
291
|
+
stream,
|
|
292
|
+
modsNote: undefined,
|
|
293
|
+
signal: AbortSignal.timeout(budgetMs > 0 ? budgetMs : DEFAULT_RESUME_DURATION_MS),
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
async cancel(executionId: string): Promise<void> {
|
|
298
|
+
// Unknown id: the execution is already stopped — a no-op by contract.
|
|
299
|
+
this.inFlight.get(executionId)?.kill();
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// ---- internals ---------------------------------------------------------
|
|
303
|
+
|
|
304
|
+
private childEnv(): NodeJS.ProcessEnv {
|
|
305
|
+
// The child is the user's own claude runtime and needs its own auth
|
|
306
|
+
// config, so the environment is passed through; the provider injects
|
|
307
|
+
// NOTHING beyond the (non-secret) test seam values. ADR-0020 §6.4:
|
|
308
|
+
// environment secrets never enter the agent CONTEXT — the prompt is
|
|
309
|
+
// exactly the request's instructions.
|
|
310
|
+
return { ...process.env, ...this.opts.env };
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
private probeVersion(): Promise<AgentHealth> {
|
|
314
|
+
return new Promise<AgentHealth>((resolve) => {
|
|
315
|
+
let done = false;
|
|
316
|
+
const child = spawn(this.opts.cliPath, [...this.opts.cliArgvPrefix, ...CLAUDE_VERSION_ARGS], {
|
|
317
|
+
stdio: ['ignore', 'ignore', 'ignore'],
|
|
318
|
+
shell: false,
|
|
319
|
+
env: this.childEnv(),
|
|
320
|
+
});
|
|
321
|
+
const finish = (health: AgentHealth): void => {
|
|
322
|
+
if (done) return;
|
|
323
|
+
done = true;
|
|
324
|
+
clearTimeout(timer);
|
|
325
|
+
try {
|
|
326
|
+
child.removeAllListeners();
|
|
327
|
+
child.kill('SIGKILL');
|
|
328
|
+
} catch {
|
|
329
|
+
/* already gone */
|
|
330
|
+
}
|
|
331
|
+
resolve(health);
|
|
332
|
+
};
|
|
333
|
+
const timer = setTimeout(
|
|
334
|
+
() =>
|
|
335
|
+
finish({
|
|
336
|
+
available: false,
|
|
337
|
+
message: `claude CLI at '${this.opts.cliPath}' did not answer --version within ${this.opts.healthTimeoutMs}ms`,
|
|
338
|
+
}),
|
|
339
|
+
this.opts.healthTimeoutMs,
|
|
340
|
+
);
|
|
341
|
+
child.on('error', (err) =>
|
|
342
|
+
finish({
|
|
343
|
+
available: false,
|
|
344
|
+
message:
|
|
345
|
+
`claude CLI not found at '${this.opts.cliPath}' ` +
|
|
346
|
+
`(${(err as NodeJS.ErrnoException).code ?? 'error'}) — install Claude Code, or inject a ` +
|
|
347
|
+
`provider via createFeatureCommand({ agentProviders })`,
|
|
348
|
+
}),
|
|
349
|
+
);
|
|
350
|
+
child.on('exit', (code, sig) => {
|
|
351
|
+
if (code === 0) finish({ available: true, message: `claude CLI available at '${this.opts.cliPath}'` });
|
|
352
|
+
else
|
|
353
|
+
finish({
|
|
354
|
+
available: false,
|
|
355
|
+
message: `claude CLI at '${this.opts.cliPath}' exited ${code ?? `signal ${sig}`} on --version`,
|
|
356
|
+
});
|
|
357
|
+
});
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
private spawnAndSettle(ctx: SpawnContext): Promise<AgentExecutionHandle> {
|
|
362
|
+
return new Promise<AgentExecutionHandle>((resolveHandle) => {
|
|
363
|
+
let resolveResult!: (r: AgentExecutionResult) => void;
|
|
364
|
+
const resultPromise = new Promise<AgentExecutionResult>((res) => {
|
|
365
|
+
resolveResult = res;
|
|
366
|
+
});
|
|
367
|
+
|
|
368
|
+
let outputBytes = 0;
|
|
369
|
+
let finalResult: ClaudeFinalResult | undefined;
|
|
370
|
+
let weCancelled = false;
|
|
371
|
+
let boundExceeded = false;
|
|
372
|
+
let settled = false;
|
|
373
|
+
let exitInfo: { code: number | null; signal: NodeJS.Signals | null } | undefined;
|
|
374
|
+
let stderrTail = '';
|
|
375
|
+
const startedAt = Date.now();
|
|
376
|
+
|
|
377
|
+
const child = spawn(this.opts.cliPath, [...this.opts.cliArgvPrefix, ...ctx.args], {
|
|
378
|
+
cwd: ctx.cwd,
|
|
379
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
380
|
+
shell: false,
|
|
381
|
+
env: this.childEnv(),
|
|
382
|
+
});
|
|
383
|
+
|
|
384
|
+
const kill = (): void => {
|
|
385
|
+
if (weCancelled || boundExceeded) return;
|
|
386
|
+
weCancelled = true;
|
|
387
|
+
try {
|
|
388
|
+
child.kill('SIGTERM');
|
|
389
|
+
} catch {
|
|
390
|
+
/* already gone */
|
|
391
|
+
}
|
|
392
|
+
const grace = setTimeout(() => {
|
|
393
|
+
try {
|
|
394
|
+
child.kill('SIGKILL');
|
|
395
|
+
} catch {
|
|
396
|
+
/* already gone */
|
|
397
|
+
}
|
|
398
|
+
}, this.opts.killGraceMs);
|
|
399
|
+
grace.unref?.();
|
|
400
|
+
};
|
|
401
|
+
this.inFlight.set(ctx.executionId, { child, kill });
|
|
402
|
+
|
|
403
|
+
const onAbort = (): void => kill();
|
|
404
|
+
if (ctx.signal.aborted) kill();
|
|
405
|
+
else ctx.signal.addEventListener('abort', onAbort, { once: true });
|
|
406
|
+
|
|
407
|
+
const parser = new ClaudeStreamParser((obs) => {
|
|
408
|
+
switch (obs.kind) {
|
|
409
|
+
case 'init':
|
|
410
|
+
ctx.stream.emit({ type: 'execution.started' });
|
|
411
|
+
break;
|
|
412
|
+
case 'text-delta':
|
|
413
|
+
ctx.stream.emit({ type: 'message.delta', content: obs.content });
|
|
414
|
+
break;
|
|
415
|
+
case 'tool-use': {
|
|
416
|
+
const capability = capabilityOfToolUse(obs);
|
|
417
|
+
// An event never authorizes anything; if the tool is outside the
|
|
418
|
+
// derived table we skip the event rather than assert a capability
|
|
419
|
+
// we cannot honestly name (the gateway counts what it can see).
|
|
420
|
+
if (capability) {
|
|
421
|
+
ctx.stream.emit({
|
|
422
|
+
type: 'tool.requested',
|
|
423
|
+
toolCallId: obs.toolCallId,
|
|
424
|
+
capability,
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
break;
|
|
428
|
+
}
|
|
429
|
+
case 'tool-result':
|
|
430
|
+
ctx.stream.emit({
|
|
431
|
+
type: 'tool.result',
|
|
432
|
+
toolCallId: obs.toolCallId,
|
|
433
|
+
status: obs.status,
|
|
434
|
+
});
|
|
435
|
+
break;
|
|
436
|
+
case 'result':
|
|
437
|
+
finalResult = obs.result;
|
|
438
|
+
break;
|
|
439
|
+
}
|
|
440
|
+
});
|
|
441
|
+
|
|
442
|
+
const onStdout = (chunk: Buffer): void => {
|
|
443
|
+
outputBytes += chunk.length;
|
|
444
|
+
if (outputBytes > this.opts.maxOutputBytes) {
|
|
445
|
+
boundExceeded = true;
|
|
446
|
+
weCancelled = true; // we initiate this kill too
|
|
447
|
+
try {
|
|
448
|
+
child.kill('SIGTERM');
|
|
449
|
+
} catch {
|
|
450
|
+
/* already gone */
|
|
451
|
+
}
|
|
452
|
+
return;
|
|
453
|
+
}
|
|
454
|
+
for (const line of chunk.toString('utf8').split('\n')) parser.consume(line.trim());
|
|
455
|
+
};
|
|
456
|
+
const onStderr = (chunk: Buffer): void => {
|
|
457
|
+
outputBytes += chunk.length;
|
|
458
|
+
if (stderrTail.length < 8_192) stderrTail = (stderrTail + chunk.toString('utf8')).slice(-8_192);
|
|
459
|
+
};
|
|
460
|
+
child.stdout?.on('data', onStdout);
|
|
461
|
+
child.stderr?.on('data', onStderr);
|
|
462
|
+
|
|
463
|
+
const finalize = async (): Promise<void> => {
|
|
464
|
+
if (settled) return;
|
|
465
|
+
settled = true;
|
|
466
|
+
ctx.signal.removeEventListener('abort', onAbort);
|
|
467
|
+
this.inFlight.delete(ctx.executionId);
|
|
468
|
+
|
|
469
|
+
const result = this.buildResult({
|
|
470
|
+
ctx,
|
|
471
|
+
finalResult,
|
|
472
|
+
weCancelled,
|
|
473
|
+
boundExceeded,
|
|
474
|
+
durationMs: Date.now() - startedAt,
|
|
475
|
+
stderrTail,
|
|
476
|
+
exitInfo,
|
|
477
|
+
});
|
|
478
|
+
// The encrypted session record must exist before the result is
|
|
479
|
+
// observable, or a cross-process resume test could race it.
|
|
480
|
+
if (result.session?.sessionId) await this.persistSession(result);
|
|
481
|
+
ctx.stream.emit({ type: 'execution.completed', status: result.status });
|
|
482
|
+
resolveResult(result);
|
|
483
|
+
};
|
|
484
|
+
|
|
485
|
+
child.on('close', (code, signal) => {
|
|
486
|
+
exitInfo = { code, signal };
|
|
487
|
+
void finalize();
|
|
488
|
+
});
|
|
489
|
+
child.on('error', () => {
|
|
490
|
+
exitInfo = { code: null, signal: null };
|
|
491
|
+
void finalize();
|
|
492
|
+
});
|
|
493
|
+
|
|
494
|
+
resolveHandle({
|
|
495
|
+
executionId: ctx.executionId,
|
|
496
|
+
result: () => resultPromise,
|
|
497
|
+
events: (sink: AgentEventSink) => ctx.stream.subscribe(sink),
|
|
498
|
+
});
|
|
499
|
+
});
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
private buildResult(input: {
|
|
503
|
+
ctx: SpawnContext;
|
|
504
|
+
finalResult: ClaudeFinalResult | undefined;
|
|
505
|
+
weCancelled: boolean;
|
|
506
|
+
boundExceeded: boolean;
|
|
507
|
+
durationMs: number;
|
|
508
|
+
stderrTail: string;
|
|
509
|
+
exitInfo: { code: number | null; signal: NodeJS.Signals | null } | undefined;
|
|
510
|
+
}): AgentExecutionResult {
|
|
511
|
+
const { ctx, finalResult, weCancelled, boundExceeded, durationMs, stderrTail, exitInfo } = input;
|
|
512
|
+
const base = {
|
|
513
|
+
schemaVersion: AGENT_EXECUTION_SCHEMA_VERSION,
|
|
514
|
+
executionId: ctx.executionId,
|
|
515
|
+
workflowRunId: ctx.workflowRunId,
|
|
516
|
+
taskId: ctx.taskId,
|
|
517
|
+
providerId: this.id,
|
|
518
|
+
proposedArtifacts: [],
|
|
519
|
+
requestedApprovals: [],
|
|
520
|
+
errors: [] as AgentExecutionError[],
|
|
521
|
+
};
|
|
522
|
+
|
|
523
|
+
// Cancellation (SIGINT, gateway cancel, budget breach): a VALUE.
|
|
524
|
+
if (weCancelled && !boundExceeded) {
|
|
525
|
+
return {
|
|
526
|
+
...base,
|
|
527
|
+
status: 'cancelled',
|
|
528
|
+
summary: withMods('claude-code execution cancelled before completion', ctx.modsNote),
|
|
529
|
+
usage: { durationMs },
|
|
530
|
+
errors: [
|
|
531
|
+
{
|
|
532
|
+
code: 'CANCELLED',
|
|
533
|
+
message: 'execution aborted (SIGINT, gateway cancel, or budget breach)',
|
|
534
|
+
retryable: false,
|
|
535
|
+
},
|
|
536
|
+
],
|
|
537
|
+
};
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
// Bounded output: a budget-class failure, never silent continuation.
|
|
541
|
+
if (boundExceeded) {
|
|
542
|
+
return {
|
|
543
|
+
...base,
|
|
544
|
+
status: 'failed',
|
|
545
|
+
summary: withMods(
|
|
546
|
+
`claude-code output exceeded the bounded limit of ${this.opts.maxOutputBytes} bytes and the process was killed`,
|
|
547
|
+
ctx.modsNote,
|
|
548
|
+
),
|
|
549
|
+
usage: { durationMs },
|
|
550
|
+
errors: [{ code: 'BUDGET_EXCEEDED', message: 'output byte bound exceeded', retryable: false }],
|
|
551
|
+
};
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
if (finalResult) {
|
|
555
|
+
const usage = {
|
|
556
|
+
durationMs: finalResult.durationMs ?? durationMs,
|
|
557
|
+
...(finalResult.inputTokens !== undefined ? { inputTokens: finalResult.inputTokens } : {}),
|
|
558
|
+
...(finalResult.outputTokens !== undefined ? { outputTokens: finalResult.outputTokens } : {}),
|
|
559
|
+
...(finalResult.totalCostUsd !== undefined
|
|
560
|
+
? { estimatedCost: finalResult.totalCostUsd, currency: 'USD' }
|
|
561
|
+
: {}),
|
|
562
|
+
};
|
|
563
|
+
// The session + resume credential: token generated here, persisted
|
|
564
|
+
// ENCRYPTED below; the gateway holds it in memory only.
|
|
565
|
+
const session =
|
|
566
|
+
finalResult.sessionId !== undefined
|
|
567
|
+
? { sessionId: finalResult.sessionId, resumeToken: generateResumeToken() }
|
|
568
|
+
: undefined;
|
|
569
|
+
|
|
570
|
+
if (finalResult.subtype === 'success' && !finalResult.isError) {
|
|
571
|
+
const result: AgentExecutionResult = {
|
|
572
|
+
...base,
|
|
573
|
+
status: 'completed',
|
|
574
|
+
summary: withMods(finalResult.text || 'claude-code completed without a final message', ctx.modsNote),
|
|
575
|
+
...(session ? { session } : {}),
|
|
576
|
+
usage,
|
|
577
|
+
};
|
|
578
|
+
return result;
|
|
579
|
+
}
|
|
580
|
+
if (finalResult.subtype === 'error_max_turns') {
|
|
581
|
+
const result: AgentExecutionResult = {
|
|
582
|
+
...base,
|
|
583
|
+
status: 'failed',
|
|
584
|
+
summary: withMods(
|
|
585
|
+
finalResult.text || 'claude-code hit the derived --max-turns bound before completing',
|
|
586
|
+
ctx.modsNote,
|
|
587
|
+
),
|
|
588
|
+
...(session ? { session } : {}),
|
|
589
|
+
usage,
|
|
590
|
+
errors: [
|
|
591
|
+
{
|
|
592
|
+
code: 'BUDGET_EXCEEDED',
|
|
593
|
+
message: 'turn bound (--max-turns) reached before completion',
|
|
594
|
+
retryable: false,
|
|
595
|
+
},
|
|
596
|
+
],
|
|
597
|
+
};
|
|
598
|
+
return result;
|
|
599
|
+
}
|
|
600
|
+
// error_during_execution — or an error shape we do not recognize:
|
|
601
|
+
// fail closed as a failure, never completed.
|
|
602
|
+
const blob = `${finalResult.text} ${stderrTail}`;
|
|
603
|
+
const denied = /permission|not allowed|denied|unauthorized/i.test(blob);
|
|
604
|
+
const result: AgentExecutionResult = {
|
|
605
|
+
...base,
|
|
606
|
+
status: 'failed',
|
|
607
|
+
summary: withMods(finalResult.text || stderrTail || 'claude-code execution failed', ctx.modsNote),
|
|
608
|
+
...(session ? { session } : {}),
|
|
609
|
+
usage,
|
|
610
|
+
errors: [
|
|
611
|
+
{
|
|
612
|
+
code: denied ? 'CAPABILITY_DENIED' : 'PROVIDER_INTERNAL',
|
|
613
|
+
message: (finalResult.text || stderrTail || 'claude-code reported an execution error').slice(0, 500),
|
|
614
|
+
retryable: false,
|
|
615
|
+
},
|
|
616
|
+
],
|
|
617
|
+
};
|
|
618
|
+
return result;
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
// No final result object: the CLI crashed, was killed by a signal, or
|
|
622
|
+
// violated the stream contract. Honest statuses, never `completed`.
|
|
623
|
+
const killedBySignal = exitInfo?.signal !== null && exitInfo?.signal !== undefined;
|
|
624
|
+
const message = stderrTail
|
|
625
|
+
? `claude-code process ended without a result object: ${stderrTail.slice(-300)}`
|
|
626
|
+
: 'claude-code process ended without a result object';
|
|
627
|
+
return {
|
|
628
|
+
...base,
|
|
629
|
+
status: killedBySignal || exitInfo?.code === 0 || exitInfo === undefined ? 'interrupted' : 'failed',
|
|
630
|
+
summary: withMods(message, ctx.modsNote),
|
|
631
|
+
usage: { durationMs },
|
|
632
|
+
errors: [
|
|
633
|
+
{
|
|
634
|
+
code: exitInfo?.code !== undefined && exitInfo.code !== null && exitInfo.code !== 0 ? 'PROVIDER_INTERNAL' : 'UNKNOWN',
|
|
635
|
+
message:
|
|
636
|
+
`stream ended without a result object ` +
|
|
637
|
+
`(exit ${exitInfo?.code ?? 'n/a'}${exitInfo?.signal ? `, signal ${exitInfo.signal}` : ''})`,
|
|
638
|
+
retryable: false,
|
|
639
|
+
},
|
|
640
|
+
],
|
|
641
|
+
};
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
/** Persist the session record for cross-process resume (encrypted at rest). */
|
|
645
|
+
private async persistSession(result: AgentExecutionResult): Promise<void> {
|
|
646
|
+
if (!result.session?.sessionId) return;
|
|
647
|
+
try {
|
|
648
|
+
await saveSessionRecord(this.opts.projectRoot, {
|
|
649
|
+
executionId: result.executionId,
|
|
650
|
+
providerId: this.id,
|
|
651
|
+
sessionId: result.session.sessionId,
|
|
652
|
+
resumeToken: result.session.resumeToken ?? '',
|
|
653
|
+
createdAt: new Date().toISOString(),
|
|
654
|
+
});
|
|
655
|
+
} catch {
|
|
656
|
+
// Honest degradation: without the encrypted record the session is
|
|
657
|
+
// simply not resumable cross-process; the in-memory token still
|
|
658
|
+
// serves the gateway's own resume API within this process.
|
|
659
|
+
result.session = undefined;
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
function withMods(summary: string, modsNote: string | undefined): string {
|
|
665
|
+
return modsNote ? `${summary} [${modsNote}]` : summary;
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
/** A result for paths that never spawned a process. */
|
|
669
|
+
function directResult(
|
|
670
|
+
request: AgentExecutionRequest,
|
|
671
|
+
status: AgentExecutionResult['status'],
|
|
672
|
+
summary: string,
|
|
673
|
+
errors: AgentExecutionError[],
|
|
674
|
+
): AgentExecutionResult {
|
|
675
|
+
return {
|
|
676
|
+
schemaVersion: AGENT_EXECUTION_SCHEMA_VERSION,
|
|
677
|
+
executionId: request.executionId,
|
|
678
|
+
workflowRunId: request.workflowRunId,
|
|
679
|
+
taskId: request.taskId,
|
|
680
|
+
providerId: 'claude-code',
|
|
681
|
+
status,
|
|
682
|
+
summary,
|
|
683
|
+
proposedArtifacts: [],
|
|
684
|
+
requestedApprovals: [],
|
|
685
|
+
errors,
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
/** Resume refusals are failed results (honest values), never throws. */
|
|
690
|
+
function resumeRefusal(executionId: string, message: string): AgentExecutionResult {
|
|
691
|
+
return {
|
|
692
|
+
schemaVersion: AGENT_EXECUTION_SCHEMA_VERSION,
|
|
693
|
+
executionId,
|
|
694
|
+
workflowRunId: 'run-resume' as AgentExecutionResult['workflowRunId'],
|
|
695
|
+
taskId: 'task-resume' as AgentExecutionResult['taskId'],
|
|
696
|
+
providerId: 'claude-code',
|
|
697
|
+
status: 'failed',
|
|
698
|
+
summary: message,
|
|
699
|
+
proposedArtifacts: [],
|
|
700
|
+
requestedApprovals: [],
|
|
701
|
+
errors: [{ code: 'SESSION_EXPIRED', message, retryable: false }],
|
|
702
|
+
};
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
/** A handle whose result() is already decided (no spawn happened). */
|
|
706
|
+
function settledHandle(
|
|
707
|
+
executionId: string,
|
|
708
|
+
stream: ExecutionEventStream,
|
|
709
|
+
produce: () => AgentExecutionResult,
|
|
710
|
+
): Promise<AgentExecutionHandle> {
|
|
711
|
+
const promise = Promise.resolve(produce());
|
|
712
|
+
return Promise.resolve({
|
|
713
|
+
executionId,
|
|
714
|
+
result: () => promise,
|
|
715
|
+
events: (sink: AgentEventSink) => stream.subscribe(sink),
|
|
716
|
+
});
|
|
717
|
+
}
|