@mikode13/harness 11.0.1 → 11.2.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/README.md +186 -16
- package/dist/agent/domain/agent.d.ts +41 -3
- package/dist/agent/domain/agent.js.map +1 -1
- package/dist/agent/domain/approval.d.ts +20 -0
- package/dist/agent/domain/approval.js.map +1 -1
- package/dist/agent/domain/inbox.d.ts +42 -0
- package/dist/agent/domain/inbox.js +81 -0
- package/dist/agent/domain/inbox.js.map +1 -0
- package/dist/agent/domain/oneRunAtATime.d.ts +17 -0
- package/dist/agent/domain/oneRunAtATime.js +32 -0
- package/dist/agent/domain/oneRunAtATime.js.map +1 -0
- package/dist/agent/domain/runContext.d.ts +9 -0
- package/dist/agent/domain/runContext.js +5 -0
- package/dist/agent/domain/runContext.js.map +1 -1
- package/dist/agent/domain/session.d.ts +15 -0
- package/dist/agent/domain/session.js +80 -0
- package/dist/agent/domain/session.js.map +1 -0
- package/dist/engines/claude/infrastructure/model/claudeAgent.d.ts +6 -2
- package/dist/engines/claude/infrastructure/model/claudeAgent.js +20 -5
- package/dist/engines/claude/infrastructure/model/claudeAgent.js.map +1 -1
- package/dist/engines/codex/infrastructure/model/codexAgent.d.ts +5 -1
- package/dist/engines/codex/infrastructure/model/codexAgent.js +13 -2
- package/dist/engines/codex/infrastructure/model/codexAgent.js.map +1 -1
- package/dist/engines/domain/model/backgroundAgents.d.ts +5 -2
- package/dist/engines/domain/model/backgroundAgents.js +11 -3
- package/dist/engines/domain/model/backgroundAgents.js.map +1 -1
- package/dist/engines/domain/model/compactor.d.ts +40 -0
- package/dist/engines/domain/model/compactor.js +5 -0
- package/dist/engines/domain/model/compactor.js.map +1 -0
- package/dist/engines/domain/model/llmAgent.d.ts +53 -2
- package/dist/engines/domain/model/llmAgent.js +419 -24
- package/dist/engines/domain/model/llmAgent.js.map +1 -1
- package/dist/engines/domain/model/recentCompaction.d.ts +39 -0
- package/dist/engines/domain/model/recentCompaction.js +119 -0
- package/dist/engines/domain/model/recentCompaction.js.map +1 -0
- package/dist/engines/domain/model/stepContext.js +3 -0
- package/dist/engines/domain/model/stepContext.js.map +1 -1
- package/dist/engines/domain/model/triagedCompaction.d.ts +27 -0
- package/dist/engines/domain/model/triagedCompaction.js +60 -0
- package/dist/engines/domain/model/triagedCompaction.js.map +1 -0
- package/dist/factory/infrastructure/agentLLMFactory.d.ts +56 -15
- package/dist/factory/infrastructure/agentLLMFactory.js +144 -25
- package/dist/factory/infrastructure/agentLLMFactory.js.map +1 -1
- package/dist/index.d.ts +6 -2
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/llm/domain/contextTriage.d.ts +26 -0
- package/dist/llm/domain/contextTriage.js +3 -0
- package/dist/llm/domain/contextTriage.js.map +1 -0
- package/dist/llm/domain/llm.d.ts +18 -1
- package/dist/llm/domain/llm.js.map +1 -1
- package/dist/llm/domain/message.d.ts +18 -1
- package/dist/llm/domain/message.js +20 -0
- package/dist/llm/domain/message.js.map +1 -1
- package/dist/llm/infrastructure/claudeLLMClient.d.ts +4 -5
- package/dist/llm/infrastructure/claudeLLMClient.js +39 -13
- package/dist/llm/infrastructure/claudeLLMClient.js.map +1 -1
- package/dist/llm/infrastructure/jevContextTriage.d.ts +18 -0
- package/dist/llm/infrastructure/jevContextTriage.js +92 -0
- package/dist/llm/infrastructure/jevContextTriage.js.map +1 -0
- package/dist/llm/infrastructure/openAILLMClient.d.ts +4 -5
- package/dist/llm/infrastructure/openAILLMClient.js +20 -9
- package/dist/llm/infrastructure/openAILLMClient.js.map +1 -1
- package/dist/orchestration/domain/model/orchestratorAgent.d.ts +9 -1
- package/dist/orchestration/domain/model/orchestratorAgent.js +20 -3
- package/dist/orchestration/domain/model/orchestratorAgent.js.map +1 -1
- package/dist/recovery/domain/history.d.ts +10 -3
- package/dist/recovery/domain/history.js +1 -0
- package/dist/recovery/domain/history.js.map +1 -1
- package/dist/recovery/domain/recoveryStore.d.ts +14 -2
- package/dist/recovery/domain/recoveryStore.js.map +1 -1
- package/dist/recovery/infrastructure/fileRecoveryStore.d.ts +21 -2
- package/dist/recovery/infrastructure/fileRecoveryStore.js +58 -6
- package/dist/recovery/infrastructure/fileRecoveryStore.js.map +1 -1
- package/dist/recovery/infrastructure/folderClaims.d.ts +27 -0
- package/dist/recovery/infrastructure/folderClaims.js +124 -0
- package/dist/recovery/infrastructure/folderClaims.js.map +1 -0
- package/dist/shared/domain/session.d.ts +12 -0
- package/dist/shared/domain/session.js +2 -0
- package/dist/shared/domain/session.js.map +1 -0
- package/dist/tools/domain/preparedCall.d.ts +5 -2
- package/dist/tools/domain/preparedCall.js +7 -1
- package/dist/tools/domain/preparedCall.js.map +1 -1
- package/dist/tools/domain/readRegistry.d.ts +11 -0
- package/dist/tools/domain/readRegistry.js.map +1 -1
- package/dist/tools/infrastructure/agentAsTool.d.ts +6 -0
- package/dist/tools/infrastructure/agentAsTool.js +9 -0
- package/dist/tools/infrastructure/agentAsTool.js.map +1 -1
- package/dist/tools/infrastructure/commandTool.js +6 -1
- package/dist/tools/infrastructure/commandTool.js.map +1 -1
- package/dist/tools/infrastructure/exploreTool.js +2 -0
- package/dist/tools/infrastructure/exploreTool.js.map +1 -1
- package/dist/tools/infrastructure/fileTools.d.ts +2 -0
- package/dist/tools/infrastructure/fileTools.js +10 -1
- package/dist/tools/infrastructure/fileTools.js.map +1 -1
- package/dist/tools/infrastructure/removeWorktreeTool.d.ts +23 -0
- package/dist/tools/infrastructure/removeWorktreeTool.js +178 -0
- package/dist/tools/infrastructure/removeWorktreeTool.js.map +1 -0
- package/dist/tools/infrastructure/subagents.d.ts +3 -1
- package/dist/tools/infrastructure/subagents.js +2 -1
- package/dist/tools/infrastructure/subagents.js.map +1 -1
- package/dist/tools/infrastructure/trackedEdits.js +1 -0
- package/dist/tools/infrastructure/trackedEdits.js.map +1 -1
- package/dist/tools/infrastructure/workspaceWrites.d.ts +17 -1
- package/dist/tools/infrastructure/workspaceWrites.js +48 -17
- package/dist/tools/infrastructure/workspaceWrites.js.map +1 -1
- package/dist/tools/infrastructure/worktrees.d.ts +49 -0
- package/dist/tools/infrastructure/worktrees.js +154 -0
- package/dist/tools/infrastructure/worktrees.js.map +1 -0
- package/dist/tools/infrastructure/writeCeiling.d.ts +16 -0
- package/dist/tools/infrastructure/writeCeiling.js +49 -0
- package/dist/tools/infrastructure/writeCeiling.js.map +1 -0
- package/dist/tools/infrastructure/writeSession.d.ts +5 -1
- package/dist/tools/infrastructure/writeSession.js +7 -3
- package/dist/tools/infrastructure/writeSession.js.map +1 -1
- package/dist/workflow/domain/workflow.d.ts +3 -0
- package/dist/workflow/domain/workflow.js.map +1 -1
- package/dist/workflow/domain/workflowRunner.js +8 -2
- package/dist/workflow/domain/workflowRunner.js.map +1 -1
- package/package.json +2 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"jevContextTriage.js","sourceRoot":"","sources":["../../../src/llm/infrastructure/jevContextTriage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,cAAc,EAA6B,MAAM,kBAAkB,CAAC;AAEpF,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EAAE,uBAAuB,EAAE,eAAe,EAAE,MAAM,oCAAoC,CAAC;AAE9F,yFAAyF;AACzF,MAAM,QAAQ,GAAG,YAAY,CAAC;AAE9B,2FAA2F;AAC3F,sEAAsE;AACtE,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAChC,MAAM,cAAc,GAAG,KAAK,CAAC;AAC7B,MAAM,eAAe,GAAG,KAAK,CAAC;AAE9B,kGAAkG;AAClG,MAAM,WAAW,GAAG,CAAC,CAAC;AAEtB,MAAM,YAAY,GACjB,mJAAmJ,CAAC;AACrJ,MAAM,QAAQ,GAAG;IAChB,+CAA+C;IAC/C,yDAAyD;IACzD,iFAAiF;IACjF,2EAA2E;CAClE,CAAC;AAEX;;;GAGG;AACH,MAAM,OAAO,gBAAgB;I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,IAAI,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,MAAM,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACjF,OAAO,OAAO,CAAC;AAChB,CAAC;AAED,SAAS,OAAO,CAAC,IAAY,EAAE,GAAW;IACzC,OAAO,IAAI,CAAC,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,GAAG,CAAC;AAC7D,CAAC","sourcesContent":["import { score, TypeSafeClient, type TypeSafeClientConfig } from '@typesafe-ai/sdk';\nimport type { ContextTriage, TriagedResult } from '#src/llm/domain/contextTriage';\nimport { UnrecoverableError } from '#src/shared/domain/errors';\nimport { classifyProviderFailure, describeFailure } from '#src/shared/domain/providerFailure';\n\n/** Pinned, so a new Jev release does not change what the compactor keeps unannounced. */\nconst jevModel = 'jev-1.14.0';\n\n// Each question is judged with the state alone, which Jev bounds at 32k tokens without its\n// slower, less accurate long context: a result is cut well within it.\nconst outputCharacters = 60_000;\nconst textCharacters = 8_000;\nconst inputCharacters = 4_000;\n\n// The public endpoint limits the rate: a context of hundreds of results is triaged a few at once.\nconst concurrency = 8;\n\nconst instructions =\n\t'An agent works on the task. Its context is being compacted. How much does it need this tool result word for word to go on from its latest answer?';\nconst criteria = [\n\t'Not needed again: the work has moved past it.',\n\t'Its gist is enough: a short summary keeps what matters.',\n\t'Some exact details matter: names, numbers, paths or lines the agent will reuse.',\n\t'Needed word for word: the agent is still working on exactly this content.',\n] as const;\n\n/**\n * Jev's triage of the context, one request per tool result. The client is created on the first\n * triage, so a missing `TYPESAFE_API_KEY` fails that triage, never the agent's construction.\n */\nexport class JevContextTriage implements ContextTriage {\n\tprivate client: TypeSafeClient | undefined;\n\tprivate readonly config: Pick<TypeSafeClientConfig, 'apiKey' | 'fetch' | 'retry' | 'compression'>;\n\n\t/** @param config for the tests: the SDK's `apiKey`, `fetch`, `retry` and `compression`. */\n\tconstructor(\n\t\tconfig: Pick<TypeSafeClientConfig, 'apiKey' | 'fetch' | 'retry' | 'compression'> = {},\n\t) {\n\t\tthis.config = config;\n\t}\n\n\tasync score(\n\t\t{\n\t\t\ttask,\n\t\t\tlatestAnswer,\n\t\t\tresults,\n\t\t}: { task: string; latestAnswer: string; results: TriagedResult[] },\n\t\tsignal: AbortSignal,\n\t): Promise<number[]> {\n\t\tconst client = this.connect();\n\t\t// The first failure stops the requests still to go: the whole triage has failed.\n\t\tconst failed = new AbortController();\n\t\tconst requestSignal = AbortSignal.any([signal, failed.signal]);\n\t\tconst request = async (result: TriagedResult) => {\n\t\t\ttry {\n\t\t\t\treturn await client.systemOne(\n\t\t\t\t\t{\n\t\t\t\t\t\tmodel: jevModel,\n\t\t\t\t\t\tstate: {\n\t\t\t\t\t\t\ttask: shorten(task, textCharacters),\n\t\t\t\t\t\t\tlatestAnswer: shorten(latestAnswer, textCharacters),\n\t\t\t\t\t\t\ttoolCall: {\n\t\t\t\t\t\t\t\ttool: result.tool,\n\t\t\t\t\t\t\t\tinput: shorten(JSON.stringify(result.input), inputCharacters),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tresult: shorten(result.output, outputCharacters),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tquestions: { needed: score(instructions, criteria) },\n\t\t\t\t\t},\n\t\t\t\t\t{ signal: requestSignal },\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tfailed.abort();\n\t\t\t\t// The SDK's abort error is not named 'AbortError', so it would pass for a provider failure.\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t\tthrow classifyProviderFailure(error, 'Jev could not triage the context');\n\t\t\t}\n\t\t};\n\t\treturn inPool(results, concurrency, async result => {\n\t\t\tconst response = await request(result);\n\t\t\treturn response.answers.needed.score;\n\t\t});\n\t}\n\n\tprivate connect(): TypeSafeClient {\n\t\ttry {\n\t\t\t// Its logger writes to the console, which belongs to the consumer.\n\t\t\tthis.client ??= new TypeSafeClient({ ...this.config, logLevel: 'off' });\n\t\t} catch (error) {\n\t\t\tthrow new UnrecoverableError('Jev is not configured', { cause: describeFailure(error) });\n\t\t}\n\t\treturn this.client;\n\t}\n}\n\n/** `map` over `items`, at most `limit` at once, the results in their order. */\nasync function inPool<T, R>(items: T[], limit: number, map: (item: T) => Promise<R>): Promise<R[]> {\n\tconst results: R[] = [];\n\tlet next = 0;\n\tconst worker = async () => {\n\t\tfor (let index = next++; index < items.length; index = next++) {\n\t\t\tconst item = items[index];\n\t\t\tif (item !== undefined) results[index] = await map(item);\n\t\t}\n\t};\n\tawait Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));\n\treturn results;\n}\n\nfunction shorten(text: string, max: number): string {\n\treturn text.length <= max ? text : `${text.slice(0, max)}…`;\n}\n"]}
|
|
@@ -15,21 +15,20 @@ export declare class OpenAILLMClient implements LLMClient {
|
|
|
15
15
|
private readonly client;
|
|
16
16
|
private readonly model;
|
|
17
17
|
private readonly reasoningEffort;
|
|
18
|
-
private readonly compactAt;
|
|
19
18
|
readonly systemPrompt: string;
|
|
20
19
|
readonly providerDataSource = "openai";
|
|
21
20
|
private readonly logger;
|
|
22
|
-
constructor({ model, reasoningEffort,
|
|
21
|
+
constructor({ model, reasoningEffort, systemPrompt, logger, }: {
|
|
23
22
|
model: string;
|
|
24
23
|
reasoningEffort?: string;
|
|
25
|
-
/** The input tokens at which OpenAI compacts the context on its side. Without it, never. */
|
|
26
|
-
compactAt?: number | undefined;
|
|
27
24
|
systemPrompt: string;
|
|
28
25
|
logger: ILogger;
|
|
29
26
|
});
|
|
30
27
|
supportsNative(tool: NativeTool): boolean;
|
|
31
|
-
|
|
28
|
+
checkCompactAt(compactAt: number): void;
|
|
29
|
+
send({ context, tools, compactAt, }: {
|
|
32
30
|
context: Message[];
|
|
33
31
|
tools: ToolDefinition[];
|
|
32
|
+
compactAt?: number | 'now' | undefined;
|
|
34
33
|
}, signal: AbortSignal): Promise<LLMResponse>;
|
|
35
34
|
}
|
|
@@ -94,6 +94,9 @@ function toOpenAIItems(part, role, applyPatch) {
|
|
|
94
94
|
return part.source === openAISource ? [part.data] : [];
|
|
95
95
|
case 'reasoning':
|
|
96
96
|
return [];
|
|
97
|
+
case 'contextSummary':
|
|
98
|
+
// Never sent: the agent sends the context derived from it.
|
|
99
|
+
return [];
|
|
97
100
|
}
|
|
98
101
|
}
|
|
99
102
|
function toOpenAIInput(message, applyPatch) {
|
|
@@ -190,6 +193,9 @@ function unmapped(item, logger) {
|
|
|
190
193
|
}, classifyHostFailure, 'OpenAI client logger failed while mapping a response');
|
|
191
194
|
return [];
|
|
192
195
|
}
|
|
196
|
+
// The threshold that compacts a context now: far below what any of its models holds, so a
|
|
197
|
+
// context that no longer fits has long passed it.
|
|
198
|
+
const compactNowAt = 50_000;
|
|
193
199
|
function toStopReason(response) {
|
|
194
200
|
if (response.status === 'incomplete') {
|
|
195
201
|
return response.incomplete_details?.reason === 'content_filter' ? 'refused' : 'truncated';
|
|
@@ -235,6 +241,10 @@ function toLLMResponse(response, logger, applyPatch) {
|
|
|
235
241
|
},
|
|
236
242
|
usage,
|
|
237
243
|
stopReason: toStopReason(response),
|
|
244
|
+
// OpenAI reports the call that compacted with its whole input, the context before it.
|
|
245
|
+
...(response.usage && response.output.some(item => item.type === 'compaction')
|
|
246
|
+
? { compactedContextTokens: response.usage.input_tokens }
|
|
247
|
+
: {}),
|
|
238
248
|
};
|
|
239
249
|
}
|
|
240
250
|
catch (error) {
|
|
@@ -268,22 +278,18 @@ export class OpenAILLMClient {
|
|
|
268
278
|
client;
|
|
269
279
|
model;
|
|
270
280
|
reasoningEffort;
|
|
271
|
-
compactAt;
|
|
272
281
|
systemPrompt;
|
|
273
282
|
providerDataSource = openAISource;
|
|
274
283
|
logger;
|
|
275
284
|
// `model` and `reasoningEffort` are untyped on purpose: this adapter is the one that knows
|
|
276
285
|
// what OpenAI supports.
|
|
277
|
-
constructor({ model, reasoningEffort = 'high',
|
|
286
|
+
constructor({ model, reasoningEffort = 'high', systemPrompt, logger, }) {
|
|
278
287
|
if (!isOneOf(openAIModels, model)) {
|
|
279
288
|
throw new InvalidAgentConfigError(`"${model}" is not an OpenAI model; expected one of: ${openAIModels.join(', ')}`);
|
|
280
289
|
}
|
|
281
290
|
if (!isOneOf(openAIReasoningEfforts, reasoningEffort)) {
|
|
282
291
|
throw new InvalidAgentConfigError(`"${reasoningEffort}" is not an OpenAI reasoning effort; expected one of: ${openAIReasoningEfforts.join(', ')}`);
|
|
283
292
|
}
|
|
284
|
-
if (compactAt !== undefined && !(Number.isInteger(compactAt) && compactAt > 0)) {
|
|
285
|
-
throw new InvalidAgentConfigError(`compactAt must be a positive whole number of tokens, not ${String(compactAt)}`);
|
|
286
|
-
}
|
|
287
293
|
try {
|
|
288
294
|
// The SDK's default retries stay on: they back off and honour `Retry-After`, which
|
|
289
295
|
// `RetryingAgent` does not. See "The provider SDKs keep their transport retries" in decisions.md.
|
|
@@ -297,14 +303,19 @@ export class OpenAILLMClient {
|
|
|
297
303
|
}
|
|
298
304
|
this.model = model;
|
|
299
305
|
this.reasoningEffort = reasoningEffort;
|
|
300
|
-
this.compactAt = compactAt;
|
|
301
306
|
this.systemPrompt = systemPrompt;
|
|
302
307
|
this.logger = logger;
|
|
303
308
|
}
|
|
304
309
|
supportsNative(tool) {
|
|
305
310
|
return tool === 'applyPatch';
|
|
306
311
|
}
|
|
307
|
-
|
|
312
|
+
checkCompactAt(compactAt) {
|
|
313
|
+
if (!(Number.isInteger(compactAt) && compactAt > 0)) {
|
|
314
|
+
throw new InvalidAgentConfigError(`compactAt must be a positive whole number of tokens, not ${String(compactAt)}`);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
async send({ context, tools, compactAt, }, signal) {
|
|
318
|
+
const threshold = compactAt === 'now' ? compactNowAt : compactAt;
|
|
308
319
|
let response;
|
|
309
320
|
const applyPatch = applyPatchName(tools);
|
|
310
321
|
try {
|
|
@@ -316,8 +327,8 @@ export class OpenAILLMClient {
|
|
|
316
327
|
// Left out when empty, so a request without tools stays as it always was.
|
|
317
328
|
...(tools.length > 0 && { tools: tools.map(toOpenAITool) }),
|
|
318
329
|
// OpenAI compacts inside the call that passes it, and answers with the compaction first.
|
|
319
|
-
...(
|
|
320
|
-
context_management: [{ type: 'compaction', compact_threshold:
|
|
330
|
+
...(threshold !== undefined && {
|
|
331
|
+
context_management: [{ type: 'compaction', compact_threshold: threshold }],
|
|
321
332
|
}),
|
|
322
333
|
store: false,
|
|
323
334
|
reasoning: { effort: this.reasoningEffort, summary: 'concise' },
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openAILLMClient.js","sourceRoot":"","sources":["../../../src/llm/infrastructure/openAILLMClient.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,EAAE,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAa1C,OAAO,EACN,uBAAuB,EACvB,gBAAgB,EAChB,kBAAkB,EAClB,eAAe,GACf,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACN,mBAAmB,EACnB,oBAAoB,EACpB,uBAAuB,EACvB,eAAe,EACf,WAAW,GACX,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,4BAA4B,CAAC;AAGrD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD,OAAO,EAAkC,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACnF,OAAO,EAAmB,QAAQ,EAAuB,MAAM,mBAAmB,CAAC;AAEnF,+EAA+E;AAC/E,MAAM,CAAC,MAAM,YAAY,GAAG;IAC3B,aAAa;IACb,aAAa;IACb,cAAc;IACd,eAAe;CACN,CAAC;AAGX,0FAA0F;AAC1F,MAAM,CAAC,MAAM,sBAAsB,GAAG;IACrC,KAAK;IACL,QAAQ;IACR,MAAM;IACN,OAAO;IACP,KAAK;CACsD,CAAC;AAG7D,kFAAkF;AAClF,MAAM,qBAAq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W,CACjB,GAAG,EAAE,CAAC,aAAa,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,EAAE,UAAU,CAAC,EACtD,oBAAoB,EACpB,gCAAgC,CAChC,CAAC;IACH,CAAC;CACD","sourcesContent":["import OpenAI, { APIError } from 'openai';\nimport type { ReasoningEffort } from 'openai/resources/shared';\nimport type {\n\tApplyPatchTool,\n\tFunctionTool,\n\tResponse,\n\tResponseApplyPatchToolCall,\n\tResponseCompactionItemParam,\n\tResponseInputItem,\n\tResponseOutputItem,\n\tResponseReasoningItem,\n\tResponseUsage,\n} from 'openai/resources/responses/responses';\nimport {\n\tInvalidAgentConfigError,\n\tRecoverableError,\n\tUnrecoverableError,\n\twithSpentTokens,\n} from '#src/shared/domain/errors';\nimport {\n\tclassifyHostFailure,\n\tclassifyLocalFailure,\n\tclassifyProviderFailure,\n\tdescribeFailure,\n\ttreatErrors,\n} from '#src/shared/domain/providerFailure';\nimport { isOneOf } from '#src/shared/domain/isOneOf';\nimport type { ILogger } from '#src/shared/domain/logger';\nimport type { Tokens } from '#src/shared/domain/tokens';\nimport { MaxContextError } from '../domain/errors.ts';\nimport type { LLMClient, LLMResponse, StopReason } from '../domain/llm.ts';\nimport { type Message, type MessagePart, sentContext } from '../domain/message.ts';\nimport { type NativeTool, nativeOf, type ToolDefinition } from '../domain/tool.ts';\n\n// The SDK types `model` as a plain string, so this list is maintained by hand.\nexport const openAIModels = [\n\t'gpt-6-astra',\n\t'gpt-5.6-sol',\n\t'gpt-5.6-luna',\n\t'gpt-5.6-terra',\n] as const;\nexport type OpenAIModel = (typeof openAIModels)[number];\n\n// The efforts both the Responses API and Codex's model catalog list for the models above.\nexport const openAIReasoningEfforts = [\n\t'low',\n\t'medium',\n\t'high',\n\t'xhigh',\n\t'max',\n] as const satisfies readonly NonNullable<ReasoningEffort>[];\nexport type OpenAIReasoningEffort = (typeof openAIReasoningEfforts)[number];\n\n// The request itself is wrong or not allowed, so sending it again cannot succeed.\nconst unrecoverableStatuses = [400, 401, 403, 404, 422];\n\n// Out of credit or over a spend limit. These arrive as a 429 like a rate limit, but the account\n// stays blocked however often the request is sent.\nconst exhaustedQuotaCodes = [\n\t'insufficient_quota',\n\t'credit_balance_exhausted',\n\t'project_spend_limit_exceeded',\n];\n\n// The codes OpenAI gives a failed response that a new attempt can succeed past.\nconst transientResponseErrorCodes = ['server_error', 'rate_limit_exceeded'];\n\n// This client's label on the reasoning items it keeps for replay; see `ProviderDataPart`.\nconst openAISource = 'openai';\n\n// Marks a failed call's output, which would otherwise read the same as a successful one.\nconst failedToolPrefix = 'The tool call failed: ';\n\n/**\n * OpenAI takes a flat list of items, so every part becomes its own, in order. Reasoning crosses\n * back only as the encrypted item this client kept, which OpenAI requires beside the tool calls\n * that followed it; a reasoning part is its summary, kept for narration. A call to the tool\n * offered as `apply_patch`, named `applyPatch` here, and its result go back as that tool's own\n * items.\n */\nfunction toOpenAIItems(\n\tpart: MessagePart,\n\trole: 'user' | 'assistant',\n\tapplyPatch: string | undefined,\n): ResponseInputItem[] {\n\tswitch (part.type) {\n\t\tcase 'text':\n\t\t\treturn part.text ? [{ role, content: part.text }] : [];\n\t\tcase 'toolCall':\n\t\t\tif (part.name === applyPatch) {\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: 'apply_patch_call',\n\t\t\t\t\t\tcall_id: part.id,\n\t\t\t\t\t\t// Kept as OpenAI sent it: the conversation holds the operation unchanged.\n\t\t\t\t\t\toperation: part.input as ResponseApplyPatchToolCall['operation'],\n\t\t\t\t\t\tstatus: 'completed',\n\t\t\t\t\t},\n\t\t\t\t];\n\t\t\t}\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'function_call',\n\t\t\t\t\tcall_id: part.id,\n\t\t\t\t\tname: part.name,\n\t\t\t\t\t// A string is arguments that did not parse, sent back as the model wrote them.\n\t\t\t\t\targuments: typeof part.input === 'string' ? part.input : JSON.stringify(part.input),\n\t\t\t\t},\n\t\t\t];\n\t\tcase 'toolResult':\n\t\t\tif (part.name === applyPatch) {\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: 'apply_patch_call_output',\n\t\t\t\t\t\tcall_id: part.callId,\n\t\t\t\t\t\tstatus: part.isError ? 'failed' : 'completed',\n\t\t\t\t\t\toutput: part.output,\n\t\t\t\t\t},\n\t\t\t\t];\n\t\t\t}\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'function_call_output',\n\t\t\t\t\tcall_id: part.callId,\n\t\t\t\t\t// OpenAI has no error flag, so the text says it; the conversation keeps the output as it was.\n\t\t\t\t\toutput: part.isError ? `${failedToolPrefix}${part.output}` : part.output,\n\t\t\t\t},\n\t\t\t];\n\t\tcase 'providerData':\n\t\t\t// Another provider's item would be rejected; losing it only costs that provider's reasoning.\n\t\t\treturn part.source === openAISource ? [part.data as ResponseReasoningItem] : [];\n\t\tcase 'compaction':\n\t\t\t// Another provider's summary means nothing here; this client sends the turns it replaced.\n\t\t\treturn part.source === openAISource ? [part.data as ResponseCompactionItemParam] : [];\n\t\tcase 'reasoning':\n\t\t\treturn [];\n\t}\n}\n\nfunction toOpenAIInput(message: Message, applyPatch: string | undefined): ResponseInputItem[] {\n\t// A tool message holds only results, which carry no role.\n\tconst role = message.role === 'assistant' ? 'assistant' : 'user';\n\treturn message.content.flatMap(part => toOpenAIItems(part, role, applyPatch));\n}\n\n/**\n * Strict: the API constrains the model to the schema, so its arguments always parse and match.\n * A schema outside what strict mode supports fails the request with a 400. The native\n * `apply_patch` has OpenAI's own schema.\n */\nfunction toOpenAITool(definition: ToolDefinition): FunctionTool | ApplyPatchTool {\n\tconst native = nativeOf(definition);\n\tif (native === 'applyPatch') return { type: 'apply_patch' };\n\tif (native !== undefined) {\n\t\tthrow new InvalidAgentConfigError(`OpenAI has no native tool \"${native}\"`);\n\t}\n\tconst { name, description, inputSchema } = definition;\n\treturn { type: 'function', name, description, parameters: inputSchema, strict: true };\n}\n\n/** The name the tool offered as `apply_patch` has in the conversation, if one is offered. */\nfunction applyPatchName(tools: ToolDefinition[]): string | undefined {\n\treturn tools.find(tool => nativeOf(tool) === 'applyPatch')?.name;\n}\n\n/**\n * Strict mode makes arguments that do not parse rare: a response cut short mid-call ends as\n * `truncated` before any tool runs. Should one arrive, the tool gets the raw string and its\n * rejection lets the model correct itself, instead of the run failing.\n */\nfunction parseArguments(serialized: string): unknown {\n\ttry {\n\t\treturn JSON.parse(serialized);\n\t} catch {\n\t\treturn serialized;\n\t}\n}\n\nfunction describeItem(\n\titem: ResponseOutputItem,\n\tlogger: ILogger,\n\tapplyPatch: string | undefined,\n): MessagePart[] {\n\tswitch (item.type) {\n\t\tcase 'message':\n\t\t\t// A refusal is not an answer: it only sets the stop reason.\n\t\t\treturn item.content.flatMap(content =>\n\t\t\t\tcontent.type === 'output_text' ? [{ type: 'text' as const, text: content.text }] : [],\n\t\t\t);\n\t\tcase 'reasoning': {\n\t\t\t// The summary is the readable part; the encrypted item is what OpenAI reads back.\n\t\t\tconst text = item.summary.map(summary => summary.text).join('\\n');\n\t\t\tconst parts: MessagePart[] = text ? [{ type: 'reasoning', text }] : [];\n\t\t\t// Without its encrypted content the item cannot be replayed: OpenAI stores nothing.\n\t\t\tif (item.encrypted_content) {\n\t\t\t\tconst encrypted: ResponseReasoningItem = {\n\t\t\t\t\ttype: 'reasoning',\n\t\t\t\t\tid: item.id,\n\t\t\t\t\tsummary: item.summary,\n\t\t\t\t\tencrypted_content: item.encrypted_content,\n\t\t\t\t};\n\t\t\t\tparts.push({ type: 'providerData', source: openAISource, data: encrypted });\n\t\t\t}\n\t\t\treturn parts;\n\t\t}\n\t\tcase 'compaction': {\n\t\t\t// Encrypted: OpenAI's summary of the context before it, which it alone reads back.\n\t\t\tconst compaction: ResponseCompactionItemParam = {\n\t\t\t\ttype: 'compaction',\n\t\t\t\tid: item.id,\n\t\t\t\tencrypted_content: item.encrypted_content,\n\t\t\t};\n\t\t\treturn [{ type: 'compaction', source: openAISource, data: compaction }];\n\t\t}\n\t\tcase 'function_call':\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'toolCall',\n\t\t\t\t\tid: item.call_id,\n\t\t\t\t\tname: item.name,\n\t\t\t\t\tinput: parseArguments(item.arguments),\n\t\t\t\t},\n\t\t\t];\n\t\tcase 'apply_patch_call':\n\t\t\t// Only when `apply_patch` was offered; otherwise it is unexpected, as below.\n\t\t\tif (applyPatch !== undefined) {\n\t\t\t\treturn [{ type: 'toolCall', id: item.call_id, name: applyPatch, input: item.operation }];\n\t\t\t}\n\t\t\treturn unmapped(item, logger);\n\t\tdefault:\n\t\t\treturn unmapped(item, logger);\n\t}\n}\n\n/** An item this client does not map, which it reports and leaves out. */\nfunction unmapped(item: ResponseOutputItem, logger: ILogger): MessagePart[] {\n\t// No other built-in tool is offered, so any other item is output this client does not expect.\n\ttreatErrors(\n\t\t() => {\n\t\t\tlogger.warn(item, 'OpenAI returned an output item the client does not map');\n\t\t},\n\t\tclassifyHostFailure,\n\t\t'OpenAI client logger failed while mapping a response',\n\t);\n\treturn [];\n}\n\nfunction toStopReason(response: Response): StopReason {\n\tif (response.status === 'incomplete') {\n\t\treturn response.incomplete_details?.reason === 'content_filter' ? 'refused' : 'truncated';\n\t}\n\tif (response.status !== 'completed') {\n\t\tconst cause =\n\t\t\tresponse.error?.message ??\n\t\t\t`The response ended with status \"${response.status ?? 'unknown'}\".`;\n\t\t// The same failure is retried when it arrives as an SDK error, so it must be here too.\n\t\tif (response.error && transientResponseErrorCodes.includes(response.error.code)) {\n\t\t\tthrow new RecoverableError('The OpenAI response failed', { cause });\n\t\t}\n\t\tthrow new UnrecoverableError('The OpenAI response did not complete', { cause });\n\t}\n\n\tconst refused = response.output.some(\n\t\titem => item.type === 'message' && item.content.some(content => content.type === 'refusal'),\n\t);\n\treturn refused ? 'refused' : 'completed';\n}\n\n/** OpenAI counts both cache reads and cache writes inside `input_tokens`. */\nfunction toTokens(usage: ResponseUsage | undefined, logger: ILogger): Tokens | undefined {\n\tif (!usage) {\n\t\t// Zeros would report a call that may have been billed as free.\n\t\ttreatErrors(\n\t\t\t() => {\n\t\t\t\tlogger.warn('OpenAI returned a response without usage; it cannot be accounted for');\n\t\t\t},\n\t\t\tclassifyHostFailure,\n\t\t\t'OpenAI client logger failed while reading usage',\n\t\t);\n\t\treturn undefined;\n\t}\n\n\tconst { cached_tokens, cache_write_tokens } = usage.input_tokens_details;\n\treturn {\n\t\tinputTokens: usage.input_tokens - cached_tokens - cache_write_tokens,\n\t\treadCacheTokens: cached_tokens,\n\t\twrittenCacheTokens: cache_write_tokens,\n\t\toutputTokens: usage.output_tokens,\n\t};\n}\n\nfunction toLLMResponse(\n\tresponse: Response,\n\tlogger: ILogger,\n\tapplyPatch: string | undefined,\n): LLMResponse {\n\tlet usage: Tokens | undefined;\n\n\ttry {\n\t\t// Inside the try: it warns when the usage is missing, and that warning can throw too.\n\t\tusage = toTokens(response.usage, logger);\n\t\treturn {\n\t\t\tmessage: {\n\t\t\t\trole: 'assistant',\n\t\t\t\tcontent: response.output.flatMap(item => describeItem(item, logger, applyPatch)),\n\t\t\t},\n\t\t\tusage,\n\t\t\tstopReason: toStopReason(response),\n\t\t};\n\t} catch (error) {\n\t\t// The call was billed whether the response failed or a logger did while mapping it, and\n\t\t// an answer without usage leaves the run's count unknown.\n\t\tthrow withSpentTokens(error, usage, !response.usage);\n\t}\n}\n\nfunction classifyOpenAIFailure(error: unknown): Error {\n\tif (error instanceof APIError) {\n\t\tif (error.code === 'context_length_exceeded') {\n\t\t\treturn new MaxContextError('The context no longer fits the OpenAI model', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\t\tif (\n\t\t\texhaustedQuotaCodes.some(code => code === error.code) ||\n\t\t\tunrecoverableStatuses.some(status => status === error.status)\n\t\t) {\n\t\t\treturn new UnrecoverableError('OpenAI rejected the request', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\t}\n\n\treturn classifyProviderFailure(error, 'The OpenAI request failed');\n}\n\n/**\n * A stateless `LLMClient` on the OpenAI Responses API. With `store: false` OpenAI keeps\n * nothing between calls, so every call carries the whole context: the conversation is\n * MiKode's, not the provider's.\n */\nexport class OpenAILLMClient implements LLMClient {\n\tprivate readonly client: OpenAI;\n\tprivate readonly model: OpenAIModel;\n\tprivate readonly reasoningEffort: OpenAIReasoningEffort;\n\tprivate readonly compactAt: number | undefined;\n\treadonly systemPrompt: string;\n\treadonly providerDataSource = openAISource;\n\tprivate readonly logger: ILogger;\n\n\t// `model` and `reasoningEffort` are untyped on purpose: this adapter is the one that knows\n\t// what OpenAI supports.\n\tconstructor({\n\t\tmodel,\n\t\treasoningEffort = 'high',\n\t\tcompactAt,\n\t\tsystemPrompt,\n\t\tlogger,\n\t}: {\n\t\tmodel: string;\n\t\treasoningEffort?: string;\n\t\t/** The input tokens at which OpenAI compacts the context on its side. Without it, never. */\n\t\tcompactAt?: number | undefined;\n\t\tsystemPrompt: string;\n\t\tlogger: ILogger;\n\t}) {\n\t\tif (!isOneOf(openAIModels, model)) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`\"${model}\" is not an OpenAI model; expected one of: ${openAIModels.join(', ')}`,\n\t\t\t);\n\t\t}\n\t\tif (!isOneOf(openAIReasoningEfforts, reasoningEffort)) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`\"${reasoningEffort}\" is not an OpenAI reasoning effort; expected one of: ${openAIReasoningEfforts.join(', ')}`,\n\t\t\t);\n\t\t}\n\t\tif (compactAt !== undefined && !(Number.isInteger(compactAt) && compactAt > 0)) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`compactAt must be a positive whole number of tokens, not ${String(compactAt)}`,\n\t\t\t);\n\t\t}\n\n\t\ttry {\n\t\t\t// The SDK's default retries stay on: they back off and honour `Retry-After`, which\n\t\t\t// `RetryingAgent` does not. See \"The provider SDKs keep their transport retries\" in decisions.md.\n\t\t\tthis.client = new OpenAI();\n\t\t} catch (error) {\n\t\t\t// A missing API key, for example: building the client again cannot fix it.\n\t\t\tthrow new UnrecoverableError('The OpenAI client could not be set up', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\n\t\tthis.model = model;\n\t\tthis.reasoningEffort = reasoningEffort;\n\t\tthis.compactAt = compactAt;\n\t\tthis.systemPrompt = systemPrompt;\n\t\tthis.logger = logger;\n\t}\n\n\tsupportsNative(tool: NativeTool): boolean {\n\t\treturn tool === 'applyPatch';\n\t}\n\n\tasync send(\n\t\t{ context, tools }: { context: Message[]; tools: ToolDefinition[] },\n\t\tsignal: AbortSignal,\n\t): Promise<LLMResponse> {\n\t\tlet response: Response;\n\t\tconst applyPatch = applyPatchName(tools);\n\n\t\ttry {\n\t\t\tresponse = await this.client.responses.create(\n\t\t\t\t{\n\t\t\t\t\tmodel: this.model,\n\t\t\t\t\tinstructions: this.systemPrompt,\n\t\t\t\t\t// The latest compaction carries everything before it, which OpenAI would only ignore.\n\t\t\t\t\tinput: sentContext(context, openAISource).flatMap(message =>\n\t\t\t\t\t\ttoOpenAIInput(message, applyPatch),\n\t\t\t\t\t),\n\t\t\t\t\t// Left out when empty, so a request without tools stays as it always was.\n\t\t\t\t\t...(tools.length > 0 && { tools: tools.map(toOpenAITool) }),\n\t\t\t\t\t// OpenAI compacts inside the call that passes it, and answers with the compaction first.\n\t\t\t\t\t...(this.compactAt !== undefined && {\n\t\t\t\t\t\tcontext_management: [{ type: 'compaction', compact_threshold: this.compactAt }],\n\t\t\t\t\t}),\n\t\t\t\t\tstore: false,\n\t\t\t\t\treasoning: { effort: this.reasoningEffort, summary: 'concise' },\n\t\t\t\t\t// With `store: false` this is the only way to send the reasoning back.\n\t\t\t\t\tinclude: ['reasoning.encrypted_content'],\n\t\t\t\t},\n\t\t\t\t{ signal },\n\t\t\t);\n\t\t} catch (error) {\n\t\t\t// The SDK's abort error is named 'Error', so it would pass for a provider failure.\n\t\t\tsignal.throwIfAborted();\n\t\t\tthrow classifyOpenAIFailure(error);\n\t\t}\n\n\t\treturn treatErrors(\n\t\t\t() => toLLMResponse(response, this.logger, applyPatch),\n\t\t\tclassifyLocalFailure,\n\t\t\t'OpenAI response mapping failed',\n\t\t);\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"openAILLMClient.js","sourceRoot":"","sources":["../../../src/llm/infrastructure/openAILLMClient.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,EAAE,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAa1C,OAAO,EACN,uBAAuB,EACvB,gBAAgB,EAChB,kBAAkB,EAClB,eAAe,GACf,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACN,mBAAmB,EACnB,oBAAoB,EACpB,uBAAuB,EACvB,eAAe,EACf,WAAW,GACX,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,4BAA4B,CAAC;AAGrD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD,OAAO,EAAkC,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACnF,OAAO,EAAmB,QAAQ,EAAuB,MAAM,mBAAmB,CAAC;AAEnF,+EAA+E;AAC/E,MAAM,CAAC,MAAM,YAAY,GAAG;IAC3B,aAAa;IACb,aAAa;IACb,cAAc;IACd,eAAe;CACN,CAAC;AAGX,0FAA0F;AAC1F,MAAM,CAAC,MAAM,sBAAsB,GAAG;IACrC,KAAK;IACL,QAAQ;IACR,MAAM;IACN,OAAO;IACP,KAAK;CACsD,CAAC;AAG7D,kFAAkF;AAClF,MAAM,qBAAqB,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;AAExD,gGAAgG;AAChG,mDAAmD;AACnD,MAAM,mBAAmB,GAAG;IAC3B,oBAAoB;IACpB,0BAA0B;IAC1B,8BAA8B;CAC9B,CAAC;AAEF,gFAAgF;AAChF,MAAM,2BAA2B,GAAG,CAAC,cAAc,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C;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,mFAAmF;YACnF,MAAM,CAAC,cAAc,EAAE,CAAC;YACxB,MAAM,qBAAqB,CAAC,KAAK,CAAC,CAAC;QACpC,CAAC;QAED,OAAO,WAAW,CACjB,GAAG,EAAE,CAAC,aAAa,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,EAAE,UAAU,CAAC,EACtD,oBAAoB,EACpB,gCAAgC,CAChC,CAAC;IACH,CAAC;CACD","sourcesContent":["import OpenAI, { APIError } from 'openai';\nimport type { ReasoningEffort } from 'openai/resources/shared';\nimport type {\n\tApplyPatchTool,\n\tFunctionTool,\n\tResponse,\n\tResponseApplyPatchToolCall,\n\tResponseCompactionItemParam,\n\tResponseInputItem,\n\tResponseOutputItem,\n\tResponseReasoningItem,\n\tResponseUsage,\n} from 'openai/resources/responses/responses';\nimport {\n\tInvalidAgentConfigError,\n\tRecoverableError,\n\tUnrecoverableError,\n\twithSpentTokens,\n} from '#src/shared/domain/errors';\nimport {\n\tclassifyHostFailure,\n\tclassifyLocalFailure,\n\tclassifyProviderFailure,\n\tdescribeFailure,\n\ttreatErrors,\n} from '#src/shared/domain/providerFailure';\nimport { isOneOf } from '#src/shared/domain/isOneOf';\nimport type { ILogger } from '#src/shared/domain/logger';\nimport type { Tokens } from '#src/shared/domain/tokens';\nimport { MaxContextError } from '../domain/errors.ts';\nimport type { LLMClient, LLMResponse, StopReason } from '../domain/llm.ts';\nimport { type Message, type MessagePart, sentContext } from '../domain/message.ts';\nimport { type NativeTool, nativeOf, type ToolDefinition } from '../domain/tool.ts';\n\n// The SDK types `model` as a plain string, so this list is maintained by hand.\nexport const openAIModels = [\n\t'gpt-6-astra',\n\t'gpt-5.6-sol',\n\t'gpt-5.6-luna',\n\t'gpt-5.6-terra',\n] as const;\nexport type OpenAIModel = (typeof openAIModels)[number];\n\n// The efforts both the Responses API and Codex's model catalog list for the models above.\nexport const openAIReasoningEfforts = [\n\t'low',\n\t'medium',\n\t'high',\n\t'xhigh',\n\t'max',\n] as const satisfies readonly NonNullable<ReasoningEffort>[];\nexport type OpenAIReasoningEffort = (typeof openAIReasoningEfforts)[number];\n\n// The request itself is wrong or not allowed, so sending it again cannot succeed.\nconst unrecoverableStatuses = [400, 401, 403, 404, 422];\n\n// Out of credit or over a spend limit. These arrive as a 429 like a rate limit, but the account\n// stays blocked however often the request is sent.\nconst exhaustedQuotaCodes = [\n\t'insufficient_quota',\n\t'credit_balance_exhausted',\n\t'project_spend_limit_exceeded',\n];\n\n// The codes OpenAI gives a failed response that a new attempt can succeed past.\nconst transientResponseErrorCodes = ['server_error', 'rate_limit_exceeded'];\n\n// This client's label on the reasoning items it keeps for replay; see `ProviderDataPart`.\nconst openAISource = 'openai';\n\n// Marks a failed call's output, which would otherwise read the same as a successful one.\nconst failedToolPrefix = 'The tool call failed: ';\n\n/**\n * OpenAI takes a flat list of items, so every part becomes its own, in order. Reasoning crosses\n * back only as the encrypted item this client kept, which OpenAI requires beside the tool calls\n * that followed it; a reasoning part is its summary, kept for narration. A call to the tool\n * offered as `apply_patch`, named `applyPatch` here, and its result go back as that tool's own\n * items.\n */\nfunction toOpenAIItems(\n\tpart: MessagePart,\n\trole: 'user' | 'assistant',\n\tapplyPatch: string | undefined,\n): ResponseInputItem[] {\n\tswitch (part.type) {\n\t\tcase 'text':\n\t\t\treturn part.text ? [{ role, content: part.text }] : [];\n\t\tcase 'toolCall':\n\t\t\tif (part.name === applyPatch) {\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: 'apply_patch_call',\n\t\t\t\t\t\tcall_id: part.id,\n\t\t\t\t\t\t// Kept as OpenAI sent it: the conversation holds the operation unchanged.\n\t\t\t\t\t\toperation: part.input as ResponseApplyPatchToolCall['operation'],\n\t\t\t\t\t\tstatus: 'completed',\n\t\t\t\t\t},\n\t\t\t\t];\n\t\t\t}\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'function_call',\n\t\t\t\t\tcall_id: part.id,\n\t\t\t\t\tname: part.name,\n\t\t\t\t\t// A string is arguments that did not parse, sent back as the model wrote them.\n\t\t\t\t\targuments: typeof part.input === 'string' ? part.input : JSON.stringify(part.input),\n\t\t\t\t},\n\t\t\t];\n\t\tcase 'toolResult':\n\t\t\tif (part.name === applyPatch) {\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: 'apply_patch_call_output',\n\t\t\t\t\t\tcall_id: part.callId,\n\t\t\t\t\t\tstatus: part.isError ? 'failed' : 'completed',\n\t\t\t\t\t\toutput: part.output,\n\t\t\t\t\t},\n\t\t\t\t];\n\t\t\t}\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'function_call_output',\n\t\t\t\t\tcall_id: part.callId,\n\t\t\t\t\t// OpenAI has no error flag, so the text says it; the conversation keeps the output as it was.\n\t\t\t\t\toutput: part.isError ? `${failedToolPrefix}${part.output}` : part.output,\n\t\t\t\t},\n\t\t\t];\n\t\tcase 'providerData':\n\t\t\t// Another provider's item would be rejected; losing it only costs that provider's reasoning.\n\t\t\treturn part.source === openAISource ? [part.data as ResponseReasoningItem] : [];\n\t\tcase 'compaction':\n\t\t\t// Another provider's summary means nothing here; this client sends the turns it replaced.\n\t\t\treturn part.source === openAISource ? [part.data as ResponseCompactionItemParam] : [];\n\t\tcase 'reasoning':\n\t\t\treturn [];\n\t\tcase 'contextSummary':\n\t\t\t// Never sent: the agent sends the context derived from it.\n\t\t\treturn [];\n\t}\n}\n\nfunction toOpenAIInput(message: Message, applyPatch: string | undefined): ResponseInputItem[] {\n\t// A tool message holds only results, which carry no role.\n\tconst role = message.role === 'assistant' ? 'assistant' : 'user';\n\treturn message.content.flatMap(part => toOpenAIItems(part, role, applyPatch));\n}\n\n/**\n * Strict: the API constrains the model to the schema, so its arguments always parse and match.\n * A schema outside what strict mode supports fails the request with a 400. The native\n * `apply_patch` has OpenAI's own schema.\n */\nfunction toOpenAITool(definition: ToolDefinition): FunctionTool | ApplyPatchTool {\n\tconst native = nativeOf(definition);\n\tif (native === 'applyPatch') return { type: 'apply_patch' };\n\tif (native !== undefined) {\n\t\tthrow new InvalidAgentConfigError(`OpenAI has no native tool \"${native}\"`);\n\t}\n\tconst { name, description, inputSchema } = definition;\n\treturn { type: 'function', name, description, parameters: inputSchema, strict: true };\n}\n\n/** The name the tool offered as `apply_patch` has in the conversation, if one is offered. */\nfunction applyPatchName(tools: ToolDefinition[]): string | undefined {\n\treturn tools.find(tool => nativeOf(tool) === 'applyPatch')?.name;\n}\n\n/**\n * Strict mode makes arguments that do not parse rare: a response cut short mid-call ends as\n * `truncated` before any tool runs. Should one arrive, the tool gets the raw string and its\n * rejection lets the model correct itself, instead of the run failing.\n */\nfunction parseArguments(serialized: string): unknown {\n\ttry {\n\t\treturn JSON.parse(serialized);\n\t} catch {\n\t\treturn serialized;\n\t}\n}\n\nfunction describeItem(\n\titem: ResponseOutputItem,\n\tlogger: ILogger,\n\tapplyPatch: string | undefined,\n): MessagePart[] {\n\tswitch (item.type) {\n\t\tcase 'message':\n\t\t\t// A refusal is not an answer: it only sets the stop reason.\n\t\t\treturn item.content.flatMap(content =>\n\t\t\t\tcontent.type === 'output_text' ? [{ type: 'text' as const, text: content.text }] : [],\n\t\t\t);\n\t\tcase 'reasoning': {\n\t\t\t// The summary is the readable part; the encrypted item is what OpenAI reads back.\n\t\t\tconst text = item.summary.map(summary => summary.text).join('\\n');\n\t\t\tconst parts: MessagePart[] = text ? [{ type: 'reasoning', text }] : [];\n\t\t\t// Without its encrypted content the item cannot be replayed: OpenAI stores nothing.\n\t\t\tif (item.encrypted_content) {\n\t\t\t\tconst encrypted: ResponseReasoningItem = {\n\t\t\t\t\ttype: 'reasoning',\n\t\t\t\t\tid: item.id,\n\t\t\t\t\tsummary: item.summary,\n\t\t\t\t\tencrypted_content: item.encrypted_content,\n\t\t\t\t};\n\t\t\t\tparts.push({ type: 'providerData', source: openAISource, data: encrypted });\n\t\t\t}\n\t\t\treturn parts;\n\t\t}\n\t\tcase 'compaction': {\n\t\t\t// Encrypted: OpenAI's summary of the context before it, which it alone reads back.\n\t\t\tconst compaction: ResponseCompactionItemParam = {\n\t\t\t\ttype: 'compaction',\n\t\t\t\tid: item.id,\n\t\t\t\tencrypted_content: item.encrypted_content,\n\t\t\t};\n\t\t\treturn [{ type: 'compaction', source: openAISource, data: compaction }];\n\t\t}\n\t\tcase 'function_call':\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'toolCall',\n\t\t\t\t\tid: item.call_id,\n\t\t\t\t\tname: item.name,\n\t\t\t\t\tinput: parseArguments(item.arguments),\n\t\t\t\t},\n\t\t\t];\n\t\tcase 'apply_patch_call':\n\t\t\t// Only when `apply_patch` was offered; otherwise it is unexpected, as below.\n\t\t\tif (applyPatch !== undefined) {\n\t\t\t\treturn [{ type: 'toolCall', id: item.call_id, name: applyPatch, input: item.operation }];\n\t\t\t}\n\t\t\treturn unmapped(item, logger);\n\t\tdefault:\n\t\t\treturn unmapped(item, logger);\n\t}\n}\n\n/** An item this client does not map, which it reports and leaves out. */\nfunction unmapped(item: ResponseOutputItem, logger: ILogger): MessagePart[] {\n\t// No other built-in tool is offered, so any other item is output this client does not expect.\n\ttreatErrors(\n\t\t() => {\n\t\t\tlogger.warn(item, 'OpenAI returned an output item the client does not map');\n\t\t},\n\t\tclassifyHostFailure,\n\t\t'OpenAI client logger failed while mapping a response',\n\t);\n\treturn [];\n}\n\n// The threshold that compacts a context now: far below what any of its models holds, so a\n// context that no longer fits has long passed it.\nconst compactNowAt = 50_000;\n\nfunction toStopReason(response: Response): StopReason {\n\tif (response.status === 'incomplete') {\n\t\treturn response.incomplete_details?.reason === 'content_filter' ? 'refused' : 'truncated';\n\t}\n\tif (response.status !== 'completed') {\n\t\tconst cause =\n\t\t\tresponse.error?.message ??\n\t\t\t`The response ended with status \"${response.status ?? 'unknown'}\".`;\n\t\t// The same failure is retried when it arrives as an SDK error, so it must be here too.\n\t\tif (response.error && transientResponseErrorCodes.includes(response.error.code)) {\n\t\t\tthrow new RecoverableError('The OpenAI response failed', { cause });\n\t\t}\n\t\tthrow new UnrecoverableError('The OpenAI response did not complete', { cause });\n\t}\n\n\tconst refused = response.output.some(\n\t\titem => item.type === 'message' && item.content.some(content => content.type === 'refusal'),\n\t);\n\treturn refused ? 'refused' : 'completed';\n}\n\n/** OpenAI counts both cache reads and cache writes inside `input_tokens`. */\nfunction toTokens(usage: ResponseUsage | undefined, logger: ILogger): Tokens | undefined {\n\tif (!usage) {\n\t\t// Zeros would report a call that may have been billed as free.\n\t\ttreatErrors(\n\t\t\t() => {\n\t\t\t\tlogger.warn('OpenAI returned a response without usage; it cannot be accounted for');\n\t\t\t},\n\t\t\tclassifyHostFailure,\n\t\t\t'OpenAI client logger failed while reading usage',\n\t\t);\n\t\treturn undefined;\n\t}\n\n\tconst { cached_tokens, cache_write_tokens } = usage.input_tokens_details;\n\treturn {\n\t\tinputTokens: usage.input_tokens - cached_tokens - cache_write_tokens,\n\t\treadCacheTokens: cached_tokens,\n\t\twrittenCacheTokens: cache_write_tokens,\n\t\toutputTokens: usage.output_tokens,\n\t};\n}\n\nfunction toLLMResponse(\n\tresponse: Response,\n\tlogger: ILogger,\n\tapplyPatch: string | undefined,\n): LLMResponse {\n\tlet usage: Tokens | undefined;\n\n\ttry {\n\t\t// Inside the try: it warns when the usage is missing, and that warning can throw too.\n\t\tusage = toTokens(response.usage, logger);\n\t\treturn {\n\t\t\tmessage: {\n\t\t\t\trole: 'assistant',\n\t\t\t\tcontent: response.output.flatMap(item => describeItem(item, logger, applyPatch)),\n\t\t\t},\n\t\t\tusage,\n\t\t\tstopReason: toStopReason(response),\n\t\t\t// OpenAI reports the call that compacted with its whole input, the context before it.\n\t\t\t...(response.usage && response.output.some(item => item.type === 'compaction')\n\t\t\t\t? { compactedContextTokens: response.usage.input_tokens }\n\t\t\t\t: {}),\n\t\t};\n\t} catch (error) {\n\t\t// The call was billed whether the response failed or a logger did while mapping it, and\n\t\t// an answer without usage leaves the run's count unknown.\n\t\tthrow withSpentTokens(error, usage, !response.usage);\n\t}\n}\n\nfunction classifyOpenAIFailure(error: unknown): Error {\n\tif (error instanceof APIError) {\n\t\tif (error.code === 'context_length_exceeded') {\n\t\t\treturn new MaxContextError('The context no longer fits the OpenAI model', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\t\tif (\n\t\t\texhaustedQuotaCodes.some(code => code === error.code) ||\n\t\t\tunrecoverableStatuses.some(status => status === error.status)\n\t\t) {\n\t\t\treturn new UnrecoverableError('OpenAI rejected the request', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\t}\n\n\treturn classifyProviderFailure(error, 'The OpenAI request failed');\n}\n\n/**\n * A stateless `LLMClient` on the OpenAI Responses API. With `store: false` OpenAI keeps\n * nothing between calls, so every call carries the whole context: the conversation is\n * MiKode's, not the provider's.\n */\nexport class OpenAILLMClient implements LLMClient {\n\tprivate readonly client: OpenAI;\n\tprivate readonly model: OpenAIModel;\n\tprivate readonly reasoningEffort: OpenAIReasoningEffort;\n\treadonly systemPrompt: string;\n\treadonly providerDataSource = openAISource;\n\tprivate readonly logger: ILogger;\n\n\t// `model` and `reasoningEffort` are untyped on purpose: this adapter is the one that knows\n\t// what OpenAI supports.\n\tconstructor({\n\t\tmodel,\n\t\treasoningEffort = 'high',\n\t\tsystemPrompt,\n\t\tlogger,\n\t}: {\n\t\tmodel: string;\n\t\treasoningEffort?: string;\n\t\tsystemPrompt: string;\n\t\tlogger: ILogger;\n\t}) {\n\t\tif (!isOneOf(openAIModels, model)) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`\"${model}\" is not an OpenAI model; expected one of: ${openAIModels.join(', ')}`,\n\t\t\t);\n\t\t}\n\t\tif (!isOneOf(openAIReasoningEfforts, reasoningEffort)) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`\"${reasoningEffort}\" is not an OpenAI reasoning effort; expected one of: ${openAIReasoningEfforts.join(', ')}`,\n\t\t\t);\n\t\t}\n\t\ttry {\n\t\t\t// The SDK's default retries stay on: they back off and honour `Retry-After`, which\n\t\t\t// `RetryingAgent` does not. See \"The provider SDKs keep their transport retries\" in decisions.md.\n\t\t\tthis.client = new OpenAI();\n\t\t} catch (error) {\n\t\t\t// A missing API key, for example: building the client again cannot fix it.\n\t\t\tthrow new UnrecoverableError('The OpenAI client could not be set up', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\n\t\tthis.model = model;\n\t\tthis.reasoningEffort = reasoningEffort;\n\t\tthis.systemPrompt = systemPrompt;\n\t\tthis.logger = logger;\n\t}\n\n\tsupportsNative(tool: NativeTool): boolean {\n\t\treturn tool === 'applyPatch';\n\t}\n\n\tcheckCompactAt(compactAt: number): void {\n\t\tif (!(Number.isInteger(compactAt) && compactAt > 0)) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`compactAt must be a positive whole number of tokens, not ${String(compactAt)}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tasync send(\n\t\t{\n\t\t\tcontext,\n\t\t\ttools,\n\t\t\tcompactAt,\n\t\t}: { context: Message[]; tools: ToolDefinition[]; compactAt?: number | 'now' | undefined },\n\t\tsignal: AbortSignal,\n\t): Promise<LLMResponse> {\n\t\tconst threshold = compactAt === 'now' ? compactNowAt : compactAt;\n\t\tlet response: Response;\n\t\tconst applyPatch = applyPatchName(tools);\n\n\t\ttry {\n\t\t\tresponse = await this.client.responses.create(\n\t\t\t\t{\n\t\t\t\t\tmodel: this.model,\n\t\t\t\t\tinstructions: this.systemPrompt,\n\t\t\t\t\t// The latest compaction carries everything before it, which OpenAI would only ignore.\n\t\t\t\t\tinput: sentContext(context, openAISource).flatMap(message =>\n\t\t\t\t\t\ttoOpenAIInput(message, applyPatch),\n\t\t\t\t\t),\n\t\t\t\t\t// Left out when empty, so a request without tools stays as it always was.\n\t\t\t\t\t...(tools.length > 0 && { tools: tools.map(toOpenAITool) }),\n\t\t\t\t\t// OpenAI compacts inside the call that passes it, and answers with the compaction first.\n\t\t\t\t\t...(threshold !== undefined && {\n\t\t\t\t\t\tcontext_management: [{ type: 'compaction', compact_threshold: threshold }],\n\t\t\t\t\t}),\n\t\t\t\t\tstore: false,\n\t\t\t\t\treasoning: { effort: this.reasoningEffort, summary: 'concise' },\n\t\t\t\t\t// With `store: false` this is the only way to send the reasoning back.\n\t\t\t\t\tinclude: ['reasoning.encrypted_content'],\n\t\t\t\t},\n\t\t\t\t{ signal },\n\t\t\t);\n\t\t} catch (error) {\n\t\t\t// The SDK's abort error is named 'Error', so it would pass for a provider failure.\n\t\t\tsignal.throwIfAborted();\n\t\t\tthrow classifyOpenAIFailure(error);\n\t\t}\n\n\t\treturn treatErrors(\n\t\t\t() => toLLMResponse(response, this.logger, applyPatch),\n\t\t\tclassifyLocalFailure,\n\t\t\t'OpenAI response mapping failed',\n\t\t);\n\t}\n}\n"]}
|
|
@@ -14,6 +14,8 @@ export declare class OrchestratorAgent implements Agent {
|
|
|
14
14
|
private reviewerDecisionValidator;
|
|
15
15
|
private maxAttempts;
|
|
16
16
|
private logger;
|
|
17
|
+
private readonly runs;
|
|
18
|
+
private readonly session;
|
|
17
19
|
constructor({ plannerAgent, executorAgent, reviewerAgent, reviewerDecisionValidator, maxAttempts, logger, }: {
|
|
18
20
|
plannerAgent: Agent;
|
|
19
21
|
executorAgent: Agent;
|
|
@@ -26,8 +28,12 @@ export declare class OrchestratorAgent implements Agent {
|
|
|
26
28
|
* Every role, round and retry of one run shares one run context, so what the executor writes
|
|
27
29
|
* is one run of the workspace's history, and the planner's and reviewer's turns are tied to
|
|
28
30
|
* it. The orchestrator ends that context with the run, unless an outer agent owns it.
|
|
31
|
+
*
|
|
32
|
+
* @throws {RunInProgressError} when another run on it is still working, before any role
|
|
33
|
+
* starts.
|
|
29
34
|
*/
|
|
30
35
|
run(prompt: string, options: RunOptions): Promise<AgentResponse>;
|
|
36
|
+
private runAlone;
|
|
31
37
|
/** The run's records end here, but its result stands: what it changed is already on disk. */
|
|
32
38
|
private finishContext;
|
|
33
39
|
private runRounds;
|
|
@@ -35,7 +41,9 @@ export declare class OrchestratorAgent implements Agent {
|
|
|
35
41
|
private warn;
|
|
36
42
|
/**
|
|
37
43
|
* Keep the options object extensible and the private run context intact while making the
|
|
38
|
-
* orchestrator's attribution authoritative over anything a nested agent supplied.
|
|
44
|
+
* orchestrator's attribution authoritative over anything a nested agent supplied. No role
|
|
45
|
+
* reads the inbox, which only a single model-backed agent reads: what was sent stays for the
|
|
46
|
+
* next run.
|
|
39
47
|
*/
|
|
40
48
|
private optionsForRole;
|
|
41
49
|
}
|
|
@@ -3,6 +3,8 @@ import { RecoverableError, UnrecoverableError, withSpentTokens } from '#src/shar
|
|
|
3
3
|
import { classifyHostFailure, describeFailure, treatErrors, } from '#src/shared/domain/providerFailure';
|
|
4
4
|
import { RunContext, runContextOf, withRunContext, } from '#src/agent/domain/runContext';
|
|
5
5
|
import { isAbortError } from '#src/shared/domain/isAbortError';
|
|
6
|
+
import { OneRunAtATime } from '#src/agent/domain/oneRunAtATime';
|
|
7
|
+
import { newSession, sessionOf } from '#src/agent/domain/session';
|
|
6
8
|
// Each role's standing instructions, kept apart from the data of a round so an agent with a
|
|
7
9
|
// system prompt can hold them there instead of receiving them again in every prompt. An agent
|
|
8
10
|
// without one gets them at the head of each prompt; see `InstructedAgent`.
|
|
@@ -103,6 +105,9 @@ export class OrchestratorAgent {
|
|
|
103
105
|
reviewerDecisionValidator;
|
|
104
106
|
maxAttempts;
|
|
105
107
|
logger;
|
|
108
|
+
runs = new OneRunAtATime();
|
|
109
|
+
// The session its runs belong to when their options name none.
|
|
110
|
+
session = newSession();
|
|
106
111
|
constructor({ plannerAgent, executorAgent, reviewerAgent, reviewerDecisionValidator, maxAttempts = 3, logger, }) {
|
|
107
112
|
if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {
|
|
108
113
|
throw new RangeError('maxAttempts must be a positive integer');
|
|
@@ -118,13 +123,20 @@ export class OrchestratorAgent {
|
|
|
118
123
|
* Every role, round and retry of one run shares one run context, so what the executor writes
|
|
119
124
|
* is one run of the workspace's history, and the planner's and reviewer's turns are tied to
|
|
120
125
|
* it. The orchestrator ends that context with the run, unless an outer agent owns it.
|
|
126
|
+
*
|
|
127
|
+
* @throws {RunInProgressError} when another run on it is still working, before any role
|
|
128
|
+
* starts.
|
|
121
129
|
*/
|
|
122
|
-
|
|
130
|
+
run(prompt, options) {
|
|
131
|
+
return this.runs.run(() => this.runAlone(prompt, options));
|
|
132
|
+
}
|
|
133
|
+
async runAlone(prompt, options) {
|
|
123
134
|
const start = Date.now();
|
|
124
135
|
// Per invocation, not per instance: the CLI keeps one orchestrator for a whole session.
|
|
125
136
|
const totals = { tokens: undefined, unreported: false };
|
|
137
|
+
const session = sessionOf(options) ?? this.session;
|
|
126
138
|
const inherited = runContextOf(options);
|
|
127
|
-
const context = inherited ?? new RunContext();
|
|
139
|
+
const context = inherited ?? new RunContext(session);
|
|
128
140
|
let end = 'failed';
|
|
129
141
|
try {
|
|
130
142
|
await this.runRounds(prompt, inherited ? options : withRunContext(options, context), totals);
|
|
@@ -148,6 +160,8 @@ export class OrchestratorAgent {
|
|
|
148
160
|
// The whole run's wall clock, so it matches what the consumer waited.
|
|
149
161
|
duration: (Date.now() - start) / 1000,
|
|
150
162
|
...(!inherited && runId ? { runId } : {}),
|
|
163
|
+
// A copy: a consumer changing it must not change what later runs record.
|
|
164
|
+
session: { ...session },
|
|
151
165
|
};
|
|
152
166
|
}
|
|
153
167
|
/** The run's records end here, but its result stands: what it changed is already on disk. */
|
|
@@ -228,12 +242,15 @@ export class OrchestratorAgent {
|
|
|
228
242
|
}
|
|
229
243
|
/**
|
|
230
244
|
* Keep the options object extensible and the private run context intact while making the
|
|
231
|
-
* orchestrator's attribution authoritative over anything a nested agent supplied.
|
|
245
|
+
* orchestrator's attribution authoritative over anything a nested agent supplied. No role
|
|
246
|
+
* reads the inbox, which only a single model-backed agent reads: what was sent stays for the
|
|
247
|
+
* next run.
|
|
232
248
|
*/
|
|
233
249
|
optionsForRole(options, agent) {
|
|
234
250
|
const onProgress = options.onProgress;
|
|
235
251
|
return {
|
|
236
252
|
...options,
|
|
253
|
+
inbox: undefined,
|
|
237
254
|
onProgress: onProgress
|
|
238
255
|
? (event) => {
|
|
239
256
|
treatErrors(() => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"orchestratorAgent.js","sourceRoot":"","sources":["../../../../src/orchestration/domain/model/orchestratorAgent.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,SAAS,EAAe,MAAM,2BAA2B,CAAC;AACnE,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAIlG,OAAO,EACN,mBAAmB,EACnB,eAAe,EACf,WAAW,GACX,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EACN,UAAU,EAEV,YAAY,EACZ,cAAc,GACd,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AAE/D,4FAA4F;AAC5F,8FAA8F;AAC9F,2EAA2E;AAC3E,MAAM,oBAAoB,GACzB,wYAAwY,CAAC;AAE1Y,MAAM,CAAC,MAAM,mBAAmB,GAAG,uXAAuX,oBAAoB,EAAE,CAAC;AAEjb,MAAM,YAAY,GAAG,2VAA2V,oBAAoB,EAAE,CAAC;AAEvY,6FAA6F;AAC7F,2FAA2F;AAC3F,gCAAgC;AAChC,MAAM,CAAC,MAAM,oBAAoB,GAAG,GAAG,YAAY,6SAA6S,CAAC;AAEjW,2FAA2F;AAC3F,oFAAoF;AACpF,MAAM,CAAC,MAAM,mCAAmC,GAAG,GAAG,YAAY,iRAAiR,CAAC;AAEpV,MAAM,YAAY,GAAG,wxBAAwxB,oBAAoB,EAAE,CAAC;AAEp0B,0FAA0F;AAC1F,2FAA2F;AAC3F,gCAAgC;AAChC,MAAM,CAAC,MAAM,oB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,qBAAqB,MAAM,CAAC,OAAO,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,0CAA0C,EAC1G,kBAAkB,CAClB,CAAC;YACH,CAAC;QACF,CAAC;QAED,MAAM,IAAI,kBAAkB,CAAC,wBAAwB,EAAE;YACtD,KAAK,EAAE,kBAAkB,IAAI,kBAAkB;SAC/C,CAAC,CAAC;IACJ,CAAC;IAEO,IAAI,CAAC,GAAG,IAAe;QAC9B,WAAW,CACV,GAAG,EAAE;YACJ,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC;QAC3B,CAAC,EACD,mBAAmB,EACnB,oDAAoD,CACpD,CAAC;IACH,CAAC;IAED;;;OAGG;IACK,cAAc,CAAC,OAAmB,EAAE,KAAoB;QAC/D,MAAM,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC;QACtC,OAAO;YACN,GAAG,OAAO;YACV,UAAU,EAAE,UAAU;gBACrB,CAAC,CAAC,CAAC,KAAoB,EAAE,EAAE;oBACzB,WAAW,CACV,GAAG,EAAE;wBACJ,UAAU,CAAC,EAAE,GAAG,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;oBACjC,CAAC,EACD,mBAAmB,EACnB,uCAAuC,CACvC,CAAC;gBACH,CAAC;gBACF,CAAC,CAAC,SAAS;SACZ,CAAC;IACH,CAAC;CACD","sourcesContent":["import type {\n\tAgent,\n\tAgentResponse,\n\tProgressAgent,\n\tProgressEvent,\n\tRunOptions,\n} from '#src/agent/domain/agent';\nimport { addTokens, type Tokens } from '#src/shared/domain/tokens';\nimport { RecoverableError, UnrecoverableError, withSpentTokens } from '#src/shared/domain/errors';\nimport type { ReviewerDecision } from './reviewerDecision.ts';\nimport type { Validator } from '#src/shared/domain/validator';\nimport type { ILogger } from '#src/shared/domain/logger';\nimport {\n\tclassifyHostFailure,\n\tdescribeFailure,\n\ttreatErrors,\n} from '#src/shared/domain/providerFailure';\nimport {\n\tRunContext,\n\ttype RunEnd,\n\trunContextOf,\n\twithRunContext,\n} from '#src/agent/domain/runContext';\nimport { isAbortError } from '#src/shared/domain/isAbortError';\n\n// Each role's standing instructions, kept apart from the data of a round so an agent with a\n// system prompt can hold them there instead of receiving them again in every prompt. An agent\n// without one gets them at the head of each prompt; see `InstructedAgent`.\nconst conciseCommunication =\n\t'Communicate tersely and professionally. In reasoning updates, state only the next concrete action or a verified finding, in one short sentence. Do not narrate routine intentions, uncertainty, self-reflection, encouragement, or a desire to be thorough. Do not restate tool results. Once you decide what to do, act immediately. Use only the detail required by your role in the final response.';\n\nexport const plannerInstructions = `You are the planner agent. Read the relevant repository code and create a concise, engineering-grade plan for the executor. Cover the requested behaviour, structural issues, affected files or symbols, API contracts and boundaries, important failure paths, and meaningful tests. Keep the plan focused on the current request and do not require an architecture redesign yet. ${conciseCommunication}`;\n\nconst executorTask = `You are the executor agent. Read the relevant repository code and implement the original user request according to the planner's current plan. Preserve contracts and boundaries, handle important failure paths, keep the change focused, and add or update meaningful tests. Inspect and change the code; do not merely describe what should be done. ${conciseCommunication}`;\n\n// For an executor that can run the project's tests and checks: an Agent SDK one, which has a\n// shell, or a model-API one given commands. The harness cannot tell which command runs the\n// tests, so any command counts.\nexport const executorInstructions = `${executorTask} Before you finish, run the project's tests and checks, and finish only when they pass. Once they pass and the plan is carried out, finish at once: do not add work beyond the plan, because the reviewer asks for what is missing. If you cannot make them pass, finish by saying which ones fail and why.`;\n\n// For a model-API executor with no command, which cannot run anything: told so, it neither\n// spends its steps looking for a way to test nor claims a result it could not have.\nexport const executorInstructionsWithoutCommands = `${executorTask} You have no command that runs the project's tests or checks, so you cannot run them. Once the plan is carried out, finish at once: do not add work beyond the plan, because the reviewer asks for what is missing. Say in your summary that the tests and checks were not run.`;\n\nconst reviewerTask = `Review the code. Independently inspect the repository, the current diff, and relevant surrounding code; do not rely on the executor's narrative. Judge it against the original request, and any issue it names, first: check that the plan is right for it, and that the change fulfills it. Check correctness and logic errors, important failure paths, unused or artificial abstractions, races or shared state, API contract breaks, boundary violations, regressions, scope, and test quality. If it is correct, respond with JSON only: {\"decision\":\"approved\"}. If it is not correct, respond with JSON only: {\"decision\":\"rejected\",\"feedback\":\"list concrete, prioritized findings and the required direction for each\"}. The feedback must contain actionable engineering findings, not a general summary. ${conciseCommunication}`;\n\n// Each goes with the executor instructions of the same name. The executor may finish with\n// failing tests, saying so, and nothing in the harness checks which: the reviewer takes it\n// from the executor's response.\nexport const reviewerInstructions = `You are the reviewer agent. The executor was told to run the project's tests and checks before finishing, and to finish only when they pass, or to say which ones fail and why. Whether they pass is the one thing to take from its response: do not run them yourself, and do not approve a change whose response says that any of them fail. ${reviewerTask}`;\n\nexport const reviewerInstructionsWithoutCommands = `You are the reviewer agent. Nobody has run the tests or checks: the executor had no command for them. Judge from the code whether the tests it added or changed would pass, and do not approve a change whose tests could not. ${reviewerTask}`;\n\nconst getPlannerPrompt = (userPrompt: string, previousFailureReason?: string) => {\n\tconst feedback = previousFailureReason\n\t\t? `\\n\\nFeedback from the previous attempt:\\n---\\n${previousFailureReason}\\n---`\n\t\t: '';\n\n\treturn `Original user request:\n---\n${userPrompt}\n---${feedback}`;\n};\n\nconst getExecutorPrompt = (userPrompt: string, plannerPrompt: string) =>\n\t`Original user request:\n---\n${userPrompt}\n---\n\nCurrent implementation plan:\n---\n${plannerPrompt}\n---`;\n\nconst getReviewerPrompt = (\n\tuserPrompt: string,\n\tplannerPrompt: string,\n\texecutorResult: string,\n\tparseFailureReason?: string,\n) => {\n\tconst retryNotice = parseFailureReason\n\t\t? `\\n\\nYour previous response could not be used: ${parseFailureReason} Respond with JSON only, matching the schema exactly, with no surrounding text and no markdown code fences.`\n\t\t: '';\n\n\treturn `Original user request:\n---\n${userPrompt}\n---\n\nPlanner's current plan:\n---\n${plannerPrompt}\n---\n\nExecutor response (context only; verify it independently):\n---\n${executorResult}\n---${retryNotice}`;\n};\n\ninterface RunTotals {\n\ttokens: Tokens | undefined;\n\t/** A role answered without usage, so the run's total cannot be known. */\n\tunreported: boolean;\n}\n\n// Every role's response counts, even an empty one that starts another round: it was billed.\nfunction addToTotals(totals: RunTotals, response: AgentResponse): void {\n\tif (!response.tokens) totals.unreported = true;\n\ttotals.tokens = addTokens(totals.tokens, response.tokens);\n}\n\n/** Unknown rather than partial: a sum missing a billed call must not look complete. */\nfunction runTokens(totals: RunTotals): Tokens | undefined {\n\treturn totals.unreported ? undefined : totals.tokens;\n}\n\nfunction stripCodeFence(text: string): string {\n\tconst match = /^```(?:json)?\\s*([\\s\\S]*?)\\s*```$/.exec(text.trim());\n\treturn match?.[1] ?? text;\n}\n\nfunction parseReviewerDecision(\n\tresponse: AgentResponse,\n\treviewerDecisionValidator: Validator<ReviewerDecision>,\n): ReviewerDecision {\n\tif (!response.response) {\n\t\tthrow new RecoverableError(\"There's no decision from the reviewer, something went wrong\", {\n\t\t\tcause: 'Reviewer decision is missing.',\n\t\t});\n\t}\n\n\tlet parsedResponse: unknown;\n\ttry {\n\t\tparsedResponse = JSON.parse(stripCodeFence(response.response));\n\t} catch {\n\t\tthrow new RecoverableError('Reviewer returned an invalid decision', {\n\t\t\tcause: 'Reviewer response must be valid JSON.',\n\t\t});\n\t}\n\n\tconst decision = reviewerDecisionValidator.validate(parsedResponse);\n\tif (!decision) {\n\t\tthrow new RecoverableError('Reviewer returned an invalid decision', {\n\t\t\tcause: 'Reviewer response did not match the decision schema.',\n\t\t});\n\t}\n\n\treturn decision;\n}\n\nexport class OrchestratorAgent implements Agent {\n\tprivate plannerAgent: Agent;\n\tprivate executorAgent: Agent;\n\tprivate reviewerAgent: Agent;\n\tprivate reviewerDecisionValidator: Validator<ReviewerDecision>;\n\tprivate maxAttempts: number;\n\tprivate logger: ILogger;\n\n\tconstructor({\n\t\tplannerAgent,\n\t\texecutorAgent,\n\t\treviewerAgent,\n\t\treviewerDecisionValidator,\n\t\tmaxAttempts = 3,\n\t\tlogger,\n\t}: {\n\t\tplannerAgent: Agent;\n\t\texecutorAgent: Agent;\n\t\treviewerAgent: Agent;\n\t\treviewerDecisionValidator: Validator<ReviewerDecision>;\n\t\tmaxAttempts?: number;\n\t\tlogger: ILogger;\n\t}) {\n\t\tif (!Number.isInteger(maxAttempts) || maxAttempts < 1) {\n\t\t\tthrow new RangeError('maxAttempts must be a positive integer');\n\t\t}\n\n\t\tthis.plannerAgent = plannerAgent;\n\t\tthis.executorAgent = executorAgent;\n\t\tthis.reviewerAgent = reviewerAgent;\n\t\tthis.reviewerDecisionValidator = reviewerDecisionValidator;\n\t\tthis.maxAttempts = maxAttempts;\n\t\tthis.logger = logger;\n\t}\n\n\t/**\n\t * Every role, round and retry of one run shares one run context, so what the executor writes\n\t * is one run of the workspace's history, and the planner's and reviewer's turns are tied to\n\t * it. The orchestrator ends that context with the run, unless an outer agent owns it.\n\t */\n\tasync run(prompt: string, options: RunOptions): Promise<AgentResponse> {\n\t\tconst start = Date.now();\n\t\t// Per invocation, not per instance: the CLI keeps one orchestrator for a whole session.\n\t\tconst totals: RunTotals = { tokens: undefined, unreported: false };\n\t\tconst inherited = runContextOf(options);\n\t\tconst context = inherited ?? new RunContext();\n\t\tlet end: RunEnd = 'failed';\n\n\t\ttry {\n\t\t\tawait this.runRounds(prompt, inherited ? options : withRunContext(options, context), totals);\n\t\t\tend = 'completed';\n\t\t} catch (error) {\n\t\t\tif (isAbortError(error)) end = 'cancelled';\n\t\t\t// A failing role carries its own tokens; the roles before it are in the totals.\n\t\t\tthrow withSpentTokens(error, totals.tokens, totals.unreported);\n\t\t} finally {\n\t\t\tif (!inherited) await this.finishContext(context, end);\n\t\t}\n\n\t\t// Read once the run ended: a run that changed nothing left the history then.\n\t\tconst { runId } = context.historyRun;\n\t\treturn {\n\t\t\tresponse: 'All job has finished',\n\t\t\ttokens: runTokens(totals),\n\t\t\t// The whole run's wall clock, so it matches what the consumer waited.\n\t\t\tduration: (Date.now() - start) / 1000,\n\t\t\t...(!inherited && runId ? { runId } : {}),\n\t\t};\n\t}\n\n\t/** The run's records end here, but its result stands: what it changed is already on disk. */\n\tprivate async finishContext(context: RunContext, end: RunEnd): Promise<void> {\n\t\ttry {\n\t\t\tawait context.finish(end);\n\t\t} catch (error) {\n\t\t\tthis.warn(`The run could not close its records: ${describeFailure(error)}`);\n\t\t}\n\t}\n\n\tprivate async runRounds(prompt: string, options: RunOptions, totals: RunTotals): Promise<void> {\n\t\tlet lastFailureReason: string | undefined;\n\n\t\tfor (let attempt = 1; attempt <= this.maxAttempts; attempt++) {\n\t\t\tconst isLastAttempt = attempt === this.maxAttempts;\n\n\t\t\tconst plannerResponse = await this.plannerAgent.run(\n\t\t\t\tgetPlannerPrompt(prompt, lastFailureReason),\n\t\t\t\tthis.optionsForRole(options, 'planner'),\n\t\t\t);\n\t\t\taddToTotals(totals, plannerResponse);\n\n\t\t\tif (!plannerResponse.response) {\n\t\t\t\tlastFailureReason = 'The planner produced no response.';\n\t\t\t\tif (isLastAttempt) {\n\t\t\t\t\tthrow new UnrecoverableError('Max attempts exhausted', { cause: lastFailureReason });\n\t\t\t\t}\n\t\t\t\tthis.warn(\n\t\t\t\t\t`Attempt ${String(attempt)}/${String(this.maxAttempts)}: the planner produced no response; starting another round`,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst executorResponse = await this.executorAgent.run(\n\t\t\t\tgetExecutorPrompt(prompt, plannerResponse.response),\n\t\t\t\tthis.optionsForRole(options, 'executor'),\n\t\t\t);\n\t\t\taddToTotals(totals, executorResponse);\n\n\t\t\tif (!executorResponse.response) {\n\t\t\t\tlastFailureReason = 'The executor produced no response.';\n\t\t\t\tif (isLastAttempt) {\n\t\t\t\t\tthrow new UnrecoverableError('Max attempts exhausted', { cause: lastFailureReason });\n\t\t\t\t}\n\n\t\t\t\tthis.warn(\n\t\t\t\t\t`Attempt ${String(attempt)}/${String(this.maxAttempts)}: the executor produced no response; starting another round`,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst reviewerDecision = await this.getReviewerDecision(\n\t\t\t\tprompt,\n\t\t\t\tplannerResponse.response,\n\t\t\t\texecutorResponse.response,\n\t\t\t\toptions,\n\t\t\t\ttotals,\n\t\t\t);\n\n\t\t\tif (reviewerDecision.decision === 'approved') return;\n\n\t\t\tlastFailureReason = reviewerDecision.feedback;\n\t\t\tif (isLastAttempt) {\n\t\t\t\tthrow new UnrecoverableError('Max attempts exhausted', { cause: lastFailureReason });\n\t\t\t}\n\n\t\t\tthis.warn(\n\t\t\t\t`Attempt ${String(attempt)}/${String(this.maxAttempts)}: the reviewer rejected the round; starting another with its feedback`,\n\t\t\t\tlastFailureReason,\n\t\t\t);\n\t\t}\n\n\t\tthrow new UnrecoverableError('Max attempts exhausted', {\n\t\t\tcause: lastFailureReason ?? 'Unknown failure.',\n\t\t});\n\t}\n\n\t// Retries only the reviewer call on a malformed decision, instead of redoing\n\t// planning/execution — a bad or unparsable reviewer response is not evidence\n\t// the plan or the implementation were wrong.\n\tprivate async getReviewerDecision(\n\t\tuserPrompt: string,\n\t\tplannerPrompt: string,\n\t\texecutorResult: string,\n\t\toptions: RunOptions,\n\t\ttotals: RunTotals,\n\t): Promise<ReviewerDecision> {\n\t\tlet parseFailureReason: string | undefined;\n\n\t\tfor (let attempt = 1; attempt <= this.maxAttempts; attempt++) {\n\t\t\tconst reviewerResponse = await this.reviewerAgent.run(\n\t\t\t\tgetReviewerPrompt(userPrompt, plannerPrompt, executorResult, parseFailureReason),\n\t\t\t\tthis.optionsForRole(options, 'reviewer'),\n\t\t\t);\n\n\t\t\taddToTotals(totals, reviewerResponse);\n\n\t\t\ttry {\n\t\t\t\treturn parseReviewerDecision(reviewerResponse, this.reviewerDecisionValidator);\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof RecoverableError)) throw error;\n\n\t\t\t\tparseFailureReason = error.cause;\n\t\t\t\tif (attempt === this.maxAttempts) {\n\t\t\t\t\tthrow new UnrecoverableError('Max attempts exhausted', { cause: parseFailureReason });\n\t\t\t\t}\n\n\t\t\t\tthis.warn(\n\t\t\t\t\t`Reviewer decision ${String(attempt)}/${String(this.maxAttempts)} was unusable; asking the reviewer again`,\n\t\t\t\t\tparseFailureReason,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tthrow new UnrecoverableError('Max attempts exhausted', {\n\t\t\tcause: parseFailureReason ?? 'Unknown failure.',\n\t\t});\n\t}\n\n\tprivate warn(...args: unknown[]): void {\n\t\ttreatErrors(\n\t\t\t() => {\n\t\t\t\tthis.logger.warn(...args);\n\t\t\t},\n\t\t\tclassifyHostFailure,\n\t\t\t'Orchestrator logger failed while reporting a retry',\n\t\t);\n\t}\n\n\t/**\n\t * Keep the options object extensible and the private run context intact while making the\n\t * orchestrator's attribution authoritative over anything a nested agent supplied.\n\t */\n\tprivate optionsForRole(options: RunOptions, agent: ProgressAgent): RunOptions {\n\t\tconst onProgress = options.onProgress;\n\t\treturn {\n\t\t\t...options,\n\t\t\tonProgress: onProgress\n\t\t\t\t? (event: ProgressEvent) => {\n\t\t\t\t\t\ttreatErrors(\n\t\t\t\t\t\t\t() => {\n\t\t\t\t\t\t\t\tonProgress({ ...event, agent });\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tclassifyHostFailure,\n\t\t\t\t\t\t\t'Orchestrator progress callback failed',\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\t};\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"orchestratorAgent.js","sourceRoot":"","sources":["../../../../src/orchestration/domain/model/orchestratorAgent.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,SAAS,EAAe,MAAM,2BAA2B,CAAC;AACnE,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAIlG,OAAO,EACN,mBAAmB,EACnB,eAAe,EACf,WAAW,GACX,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EACN,UAAU,EAEV,YAAY,EACZ,cAAc,GACd,MAAM,8BAA8B,C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,kBAAkB,CAClB,CAAC;YACH,CAAC;QACF,CAAC;QAED,MAAM,IAAI,kBAAkB,CAAC,wBAAwB,EAAE;YACtD,KAAK,EAAE,kBAAkB,IAAI,kBAAkB;SAC/C,CAAC,CAAC;IACJ,CAAC;IAEO,IAAI,CAAC,GAAG,IAAe;QAC9B,WAAW,CACV,GAAG,EAAE;YACJ,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC;QAC3B,CAAC,EACD,mBAAmB,EACnB,oDAAoD,CACpD,CAAC;IACH,CAAC;IAED;;;;;OAKG;IACK,cAAc,CAAC,OAAmB,EAAE,KAAoB;QAC/D,MAAM,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC;QACtC,OAAO;YACN,GAAG,OAAO;YACV,KAAK,EAAE,SAAS;YAChB,UAAU,EAAE,UAAU;gBACrB,CAAC,CAAC,CAAC,KAAoB,EAAE,EAAE;oBACzB,WAAW,CACV,GAAG,EAAE;wBACJ,UAAU,CAAC,EAAE,GAAG,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;oBACjC,CAAC,EACD,mBAAmB,EACnB,uCAAuC,CACvC,CAAC;gBACH,CAAC;gBACF,CAAC,CAAC,SAAS;SACZ,CAAC;IACH,CAAC;CACD","sourcesContent":["import type {\n\tAgent,\n\tAgentResponse,\n\tProgressAgent,\n\tProgressEvent,\n\tRunOptions,\n} from '#src/agent/domain/agent';\nimport { addTokens, type Tokens } from '#src/shared/domain/tokens';\nimport { RecoverableError, UnrecoverableError, withSpentTokens } from '#src/shared/domain/errors';\nimport type { ReviewerDecision } from './reviewerDecision.ts';\nimport type { Validator } from '#src/shared/domain/validator';\nimport type { ILogger } from '#src/shared/domain/logger';\nimport {\n\tclassifyHostFailure,\n\tdescribeFailure,\n\ttreatErrors,\n} from '#src/shared/domain/providerFailure';\nimport {\n\tRunContext,\n\ttype RunEnd,\n\trunContextOf,\n\twithRunContext,\n} from '#src/agent/domain/runContext';\nimport { isAbortError } from '#src/shared/domain/isAbortError';\nimport { OneRunAtATime } from '#src/agent/domain/oneRunAtATime';\nimport { newSession, sessionOf } from '#src/agent/domain/session';\n\n// Each role's standing instructions, kept apart from the data of a round so an agent with a\n// system prompt can hold them there instead of receiving them again in every prompt. An agent\n// without one gets them at the head of each prompt; see `InstructedAgent`.\nconst conciseCommunication =\n\t'Communicate tersely and professionally. In reasoning updates, state only the next concrete action or a verified finding, in one short sentence. Do not narrate routine intentions, uncertainty, self-reflection, encouragement, or a desire to be thorough. Do not restate tool results. Once you decide what to do, act immediately. Use only the detail required by your role in the final response.';\n\nexport const plannerInstructions = `You are the planner agent. Read the relevant repository code and create a concise, engineering-grade plan for the executor. Cover the requested behaviour, structural issues, affected files or symbols, API contracts and boundaries, important failure paths, and meaningful tests. Keep the plan focused on the current request and do not require an architecture redesign yet. ${conciseCommunication}`;\n\nconst executorTask = `You are the executor agent. Read the relevant repository code and implement the original user request according to the planner's current plan. Preserve contracts and boundaries, handle important failure paths, keep the change focused, and add or update meaningful tests. Inspect and change the code; do not merely describe what should be done. ${conciseCommunication}`;\n\n// For an executor that can run the project's tests and checks: an Agent SDK one, which has a\n// shell, or a model-API one given commands. The harness cannot tell which command runs the\n// tests, so any command counts.\nexport const executorInstructions = `${executorTask} Before you finish, run the project's tests and checks, and finish only when they pass. Once they pass and the plan is carried out, finish at once: do not add work beyond the plan, because the reviewer asks for what is missing. If you cannot make them pass, finish by saying which ones fail and why.`;\n\n// For a model-API executor with no command, which cannot run anything: told so, it neither\n// spends its steps looking for a way to test nor claims a result it could not have.\nexport const executorInstructionsWithoutCommands = `${executorTask} You have no command that runs the project's tests or checks, so you cannot run them. Once the plan is carried out, finish at once: do not add work beyond the plan, because the reviewer asks for what is missing. Say in your summary that the tests and checks were not run.`;\n\nconst reviewerTask = `Review the code. Independently inspect the repository, the current diff, and relevant surrounding code; do not rely on the executor's narrative. Judge it against the original request, and any issue it names, first: check that the plan is right for it, and that the change fulfills it. Check correctness and logic errors, important failure paths, unused or artificial abstractions, races or shared state, API contract breaks, boundary violations, regressions, scope, and test quality. If it is correct, respond with JSON only: {\"decision\":\"approved\"}. If it is not correct, respond with JSON only: {\"decision\":\"rejected\",\"feedback\":\"list concrete, prioritized findings and the required direction for each\"}. The feedback must contain actionable engineering findings, not a general summary. ${conciseCommunication}`;\n\n// Each goes with the executor instructions of the same name. The executor may finish with\n// failing tests, saying so, and nothing in the harness checks which: the reviewer takes it\n// from the executor's response.\nexport const reviewerInstructions = `You are the reviewer agent. The executor was told to run the project's tests and checks before finishing, and to finish only when they pass, or to say which ones fail and why. Whether they pass is the one thing to take from its response: do not run them yourself, and do not approve a change whose response says that any of them fail. ${reviewerTask}`;\n\nexport const reviewerInstructionsWithoutCommands = `You are the reviewer agent. Nobody has run the tests or checks: the executor had no command for them. Judge from the code whether the tests it added or changed would pass, and do not approve a change whose tests could not. ${reviewerTask}`;\n\nconst getPlannerPrompt = (userPrompt: string, previousFailureReason?: string) => {\n\tconst feedback = previousFailureReason\n\t\t? `\\n\\nFeedback from the previous attempt:\\n---\\n${previousFailureReason}\\n---`\n\t\t: '';\n\n\treturn `Original user request:\n---\n${userPrompt}\n---${feedback}`;\n};\n\nconst getExecutorPrompt = (userPrompt: string, plannerPrompt: string) =>\n\t`Original user request:\n---\n${userPrompt}\n---\n\nCurrent implementation plan:\n---\n${plannerPrompt}\n---`;\n\nconst getReviewerPrompt = (\n\tuserPrompt: string,\n\tplannerPrompt: string,\n\texecutorResult: string,\n\tparseFailureReason?: string,\n) => {\n\tconst retryNotice = parseFailureReason\n\t\t? `\\n\\nYour previous response could not be used: ${parseFailureReason} Respond with JSON only, matching the schema exactly, with no surrounding text and no markdown code fences.`\n\t\t: '';\n\n\treturn `Original user request:\n---\n${userPrompt}\n---\n\nPlanner's current plan:\n---\n${plannerPrompt}\n---\n\nExecutor response (context only; verify it independently):\n---\n${executorResult}\n---${retryNotice}`;\n};\n\ninterface RunTotals {\n\ttokens: Tokens | undefined;\n\t/** A role answered without usage, so the run's total cannot be known. */\n\tunreported: boolean;\n}\n\n// Every role's response counts, even an empty one that starts another round: it was billed.\nfunction addToTotals(totals: RunTotals, response: AgentResponse): void {\n\tif (!response.tokens) totals.unreported = true;\n\ttotals.tokens = addTokens(totals.tokens, response.tokens);\n}\n\n/** Unknown rather than partial: a sum missing a billed call must not look complete. */\nfunction runTokens(totals: RunTotals): Tokens | undefined {\n\treturn totals.unreported ? undefined : totals.tokens;\n}\n\nfunction stripCodeFence(text: string): string {\n\tconst match = /^```(?:json)?\\s*([\\s\\S]*?)\\s*```$/.exec(text.trim());\n\treturn match?.[1] ?? text;\n}\n\nfunction parseReviewerDecision(\n\tresponse: AgentResponse,\n\treviewerDecisionValidator: Validator<ReviewerDecision>,\n): ReviewerDecision {\n\tif (!response.response) {\n\t\tthrow new RecoverableError(\"There's no decision from the reviewer, something went wrong\", {\n\t\t\tcause: 'Reviewer decision is missing.',\n\t\t});\n\t}\n\n\tlet parsedResponse: unknown;\n\ttry {\n\t\tparsedResponse = JSON.parse(stripCodeFence(response.response));\n\t} catch {\n\t\tthrow new RecoverableError('Reviewer returned an invalid decision', {\n\t\t\tcause: 'Reviewer response must be valid JSON.',\n\t\t});\n\t}\n\n\tconst decision = reviewerDecisionValidator.validate(parsedResponse);\n\tif (!decision) {\n\t\tthrow new RecoverableError('Reviewer returned an invalid decision', {\n\t\t\tcause: 'Reviewer response did not match the decision schema.',\n\t\t});\n\t}\n\n\treturn decision;\n}\n\nexport class OrchestratorAgent implements Agent {\n\tprivate plannerAgent: Agent;\n\tprivate executorAgent: Agent;\n\tprivate reviewerAgent: Agent;\n\tprivate reviewerDecisionValidator: Validator<ReviewerDecision>;\n\tprivate maxAttempts: number;\n\tprivate logger: ILogger;\n\tprivate readonly runs = new OneRunAtATime();\n\t// The session its runs belong to when their options name none.\n\tprivate readonly session = newSession();\n\n\tconstructor({\n\t\tplannerAgent,\n\t\texecutorAgent,\n\t\treviewerAgent,\n\t\treviewerDecisionValidator,\n\t\tmaxAttempts = 3,\n\t\tlogger,\n\t}: {\n\t\tplannerAgent: Agent;\n\t\texecutorAgent: Agent;\n\t\treviewerAgent: Agent;\n\t\treviewerDecisionValidator: Validator<ReviewerDecision>;\n\t\tmaxAttempts?: number;\n\t\tlogger: ILogger;\n\t}) {\n\t\tif (!Number.isInteger(maxAttempts) || maxAttempts < 1) {\n\t\t\tthrow new RangeError('maxAttempts must be a positive integer');\n\t\t}\n\n\t\tthis.plannerAgent = plannerAgent;\n\t\tthis.executorAgent = executorAgent;\n\t\tthis.reviewerAgent = reviewerAgent;\n\t\tthis.reviewerDecisionValidator = reviewerDecisionValidator;\n\t\tthis.maxAttempts = maxAttempts;\n\t\tthis.logger = logger;\n\t}\n\n\t/**\n\t * Every role, round and retry of one run shares one run context, so what the executor writes\n\t * is one run of the workspace's history, and the planner's and reviewer's turns are tied to\n\t * it. The orchestrator ends that context with the run, unless an outer agent owns it.\n\t *\n\t * @throws {RunInProgressError} when another run on it is still working, before any role\n\t * starts.\n\t */\n\trun(prompt: string, options: RunOptions): Promise<AgentResponse> {\n\t\treturn this.runs.run(() => this.runAlone(prompt, options));\n\t}\n\n\tprivate async runAlone(prompt: string, options: RunOptions): Promise<AgentResponse> {\n\t\tconst start = Date.now();\n\t\t// Per invocation, not per instance: the CLI keeps one orchestrator for a whole session.\n\t\tconst totals: RunTotals = { tokens: undefined, unreported: false };\n\t\tconst session = sessionOf(options) ?? this.session;\n\t\tconst inherited = runContextOf(options);\n\t\tconst context = inherited ?? new RunContext(session);\n\t\tlet end: RunEnd = 'failed';\n\n\t\ttry {\n\t\t\tawait this.runRounds(prompt, inherited ? options : withRunContext(options, context), totals);\n\t\t\tend = 'completed';\n\t\t} catch (error) {\n\t\t\tif (isAbortError(error)) end = 'cancelled';\n\t\t\t// A failing role carries its own tokens; the roles before it are in the totals.\n\t\t\tthrow withSpentTokens(error, totals.tokens, totals.unreported);\n\t\t} finally {\n\t\t\tif (!inherited) await this.finishContext(context, end);\n\t\t}\n\n\t\t// Read once the run ended: a run that changed nothing left the history then.\n\t\tconst { runId } = context.historyRun;\n\t\treturn {\n\t\t\tresponse: 'All job has finished',\n\t\t\ttokens: runTokens(totals),\n\t\t\t// The whole run's wall clock, so it matches what the consumer waited.\n\t\t\tduration: (Date.now() - start) / 1000,\n\t\t\t...(!inherited && runId ? { runId } : {}),\n\t\t\t// A copy: a consumer changing it must not change what later runs record.\n\t\t\tsession: { ...session },\n\t\t};\n\t}\n\n\t/** The run's records end here, but its result stands: what it changed is already on disk. */\n\tprivate async finishContext(context: RunContext, end: RunEnd): Promise<void> {\n\t\ttry {\n\t\t\tawait context.finish(end);\n\t\t} catch (error) {\n\t\t\tthis.warn(`The run could not close its records: ${describeFailure(error)}`);\n\t\t}\n\t}\n\n\tprivate async runRounds(prompt: string, options: RunOptions, totals: RunTotals): Promise<void> {\n\t\tlet lastFailureReason: string | undefined;\n\n\t\tfor (let attempt = 1; attempt <= this.maxAttempts; attempt++) {\n\t\t\tconst isLastAttempt = attempt === this.maxAttempts;\n\n\t\t\tconst plannerResponse = await this.plannerAgent.run(\n\t\t\t\tgetPlannerPrompt(prompt, lastFailureReason),\n\t\t\t\tthis.optionsForRole(options, 'planner'),\n\t\t\t);\n\t\t\taddToTotals(totals, plannerResponse);\n\n\t\t\tif (!plannerResponse.response) {\n\t\t\t\tlastFailureReason = 'The planner produced no response.';\n\t\t\t\tif (isLastAttempt) {\n\t\t\t\t\tthrow new UnrecoverableError('Max attempts exhausted', { cause: lastFailureReason });\n\t\t\t\t}\n\t\t\t\tthis.warn(\n\t\t\t\t\t`Attempt ${String(attempt)}/${String(this.maxAttempts)}: the planner produced no response; starting another round`,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst executorResponse = await this.executorAgent.run(\n\t\t\t\tgetExecutorPrompt(prompt, plannerResponse.response),\n\t\t\t\tthis.optionsForRole(options, 'executor'),\n\t\t\t);\n\t\t\taddToTotals(totals, executorResponse);\n\n\t\t\tif (!executorResponse.response) {\n\t\t\t\tlastFailureReason = 'The executor produced no response.';\n\t\t\t\tif (isLastAttempt) {\n\t\t\t\t\tthrow new UnrecoverableError('Max attempts exhausted', { cause: lastFailureReason });\n\t\t\t\t}\n\n\t\t\t\tthis.warn(\n\t\t\t\t\t`Attempt ${String(attempt)}/${String(this.maxAttempts)}: the executor produced no response; starting another round`,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst reviewerDecision = await this.getReviewerDecision(\n\t\t\t\tprompt,\n\t\t\t\tplannerResponse.response,\n\t\t\t\texecutorResponse.response,\n\t\t\t\toptions,\n\t\t\t\ttotals,\n\t\t\t);\n\n\t\t\tif (reviewerDecision.decision === 'approved') return;\n\n\t\t\tlastFailureReason = reviewerDecision.feedback;\n\t\t\tif (isLastAttempt) {\n\t\t\t\tthrow new UnrecoverableError('Max attempts exhausted', { cause: lastFailureReason });\n\t\t\t}\n\n\t\t\tthis.warn(\n\t\t\t\t`Attempt ${String(attempt)}/${String(this.maxAttempts)}: the reviewer rejected the round; starting another with its feedback`,\n\t\t\t\tlastFailureReason,\n\t\t\t);\n\t\t}\n\n\t\tthrow new UnrecoverableError('Max attempts exhausted', {\n\t\t\tcause: lastFailureReason ?? 'Unknown failure.',\n\t\t});\n\t}\n\n\t// Retries only the reviewer call on a malformed decision, instead of redoing\n\t// planning/execution — a bad or unparsable reviewer response is not evidence\n\t// the plan or the implementation were wrong.\n\tprivate async getReviewerDecision(\n\t\tuserPrompt: string,\n\t\tplannerPrompt: string,\n\t\texecutorResult: string,\n\t\toptions: RunOptions,\n\t\ttotals: RunTotals,\n\t): Promise<ReviewerDecision> {\n\t\tlet parseFailureReason: string | undefined;\n\n\t\tfor (let attempt = 1; attempt <= this.maxAttempts; attempt++) {\n\t\t\tconst reviewerResponse = await this.reviewerAgent.run(\n\t\t\t\tgetReviewerPrompt(userPrompt, plannerPrompt, executorResult, parseFailureReason),\n\t\t\t\tthis.optionsForRole(options, 'reviewer'),\n\t\t\t);\n\n\t\t\taddToTotals(totals, reviewerResponse);\n\n\t\t\ttry {\n\t\t\t\treturn parseReviewerDecision(reviewerResponse, this.reviewerDecisionValidator);\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof RecoverableError)) throw error;\n\n\t\t\t\tparseFailureReason = error.cause;\n\t\t\t\tif (attempt === this.maxAttempts) {\n\t\t\t\t\tthrow new UnrecoverableError('Max attempts exhausted', { cause: parseFailureReason });\n\t\t\t\t}\n\n\t\t\t\tthis.warn(\n\t\t\t\t\t`Reviewer decision ${String(attempt)}/${String(this.maxAttempts)} was unusable; asking the reviewer again`,\n\t\t\t\t\tparseFailureReason,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tthrow new UnrecoverableError('Max attempts exhausted', {\n\t\t\tcause: parseFailureReason ?? 'Unknown failure.',\n\t\t});\n\t}\n\n\tprivate warn(...args: unknown[]): void {\n\t\ttreatErrors(\n\t\t\t() => {\n\t\t\t\tthis.logger.warn(...args);\n\t\t\t},\n\t\t\tclassifyHostFailure,\n\t\t\t'Orchestrator logger failed while reporting a retry',\n\t\t);\n\t}\n\n\t/**\n\t * Keep the options object extensible and the private run context intact while making the\n\t * orchestrator's attribution authoritative over anything a nested agent supplied. No role\n\t * reads the inbox, which only a single model-backed agent reads: what was sent stays for the\n\t * next run.\n\t */\n\tprivate optionsForRole(options: RunOptions, agent: ProgressAgent): RunOptions {\n\t\tconst onProgress = options.onProgress;\n\t\treturn {\n\t\t\t...options,\n\t\t\tinbox: undefined,\n\t\t\tonProgress: onProgress\n\t\t\t\t? (event: ProgressEvent) => {\n\t\t\t\t\t\ttreatErrors(\n\t\t\t\t\t\t\t() => {\n\t\t\t\t\t\t\t\tonProgress({ ...event, agent });\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tclassifyHostFailure,\n\t\t\t\t\t\t\t'Orchestrator progress callback failed',\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\t};\n\t}\n}\n"]}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { Session } from '#src/shared/domain/session';
|
|
1
2
|
import type { MoveOptions, RecoveryStore, RunStatus } from './recoveryStore.ts';
|
|
2
3
|
/** One run that wrote to the workspace. */
|
|
3
4
|
export interface HistoryRun {
|
|
@@ -17,6 +18,12 @@ export interface HistoryRun {
|
|
|
17
18
|
* real path of a file outside it. A host decides whether to show them.
|
|
18
19
|
*/
|
|
19
20
|
files: string[];
|
|
21
|
+
/**
|
|
22
|
+
* The session it came from, so a host can warn before undoing another session's run. Absent
|
|
23
|
+
* for a run recorded before runs recorded one. A run retention chained into this one keeps
|
|
24
|
+
* no session of its own.
|
|
25
|
+
*/
|
|
26
|
+
session?: Session;
|
|
20
27
|
}
|
|
21
28
|
/** One move of the workspace through its history. */
|
|
22
29
|
export interface Move {
|
|
@@ -69,7 +76,7 @@ export interface History {
|
|
|
69
76
|
* host that showed the user what a move will do passes where the workspace was, so a run that
|
|
70
77
|
* ended meanwhile cannot make it do something else.
|
|
71
78
|
*
|
|
72
|
-
* @throws {WorkspaceBusyError} when a run
|
|
79
|
+
* @throws {WorkspaceBusyError} when a run, another move or the removal of its worktree holds the workspace.
|
|
73
80
|
* @throws {WorkspaceMovedError} when the workspace is not at `from`.
|
|
74
81
|
* @throws {UnknownRunError} when `target` is not in the history.
|
|
75
82
|
* @throws {HistoryExpiredError} when retention chained `target` into a later run.
|
|
@@ -79,7 +86,7 @@ export interface History {
|
|
|
79
86
|
* Moves the workspace to the run before the one it is at.
|
|
80
87
|
*
|
|
81
88
|
* @throws {NothingToMoveError} at the start of the history.
|
|
82
|
-
* @throws {WorkspaceBusyError} when a run
|
|
89
|
+
* @throws {WorkspaceBusyError} when a run, another move or the removal of its worktree holds the workspace.
|
|
83
90
|
* @throws {WorkspaceMovedError} when the workspace is not at `from`.
|
|
84
91
|
*/
|
|
85
92
|
undo(options?: MoveOptions): Promise<Move>;
|
|
@@ -88,7 +95,7 @@ export interface History {
|
|
|
88
95
|
* branch.
|
|
89
96
|
*
|
|
90
97
|
* @throws {NothingToMoveError} when no run follows the one it is at.
|
|
91
|
-
* @throws {WorkspaceBusyError} when a run
|
|
98
|
+
* @throws {WorkspaceBusyError} when a run, another move or the removal of its worktree holds the workspace.
|
|
92
99
|
* @throws {WorkspaceMovedError} when the workspace is not at `from`.
|
|
93
100
|
*/
|
|
94
101
|
redo(options?: MoveOptions): Promise<Move>;
|
|
@@ -33,6 +33,7 @@ export class StoreHistory {
|
|
|
33
33
|
startedAt: record.startedAt,
|
|
34
34
|
...(record.finishedAt ? { finishedAt: record.finishedAt } : {}),
|
|
35
35
|
files: [...new Set(files)].map(path => displayPath(record.root, path)),
|
|
36
|
+
...(record.session ? { session: { ...record.session } } : {}),
|
|
36
37
|
});
|
|
37
38
|
}
|
|
38
39
|
return { ...(head ? { head } : {}), runs: listed };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"history.js","sourceRoot":"","sources":["../../../src/recovery/domain/history.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAEzE,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AA2FnD,+FAA+F;AAC/F,MAAM,OAAO,YAAY;IACP,KAAK,CAAgB;IACrB,IAAI,CAAS;IAE9B,YAAY,EAAE,KAAK,EAAE,IAAI,EAA0C;QAClE,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAClB,CAAC;IAED,KAAK,CAAC,IAAI;QACT,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC;QACnD,MAAM,MAAM,GAAiB,EAAE,CAAC;QAChC,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;YACxB,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,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MAAM,EAAE,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACvD,QAAQ,EAAE,QAAQ,CAAC,QAAQ;YAC3B,SAAS,EAAE,QAAQ,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;gBACvD,IAAI,EAAE,WAAW,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC;gBAClC,KAAK;aACL,CAAC,CAAC;SACH,CAAC;IACH,CAAC;CACD","sourcesContent":["import { changedFiles, displayPath, showChanges } from './runChanges.ts';\nimport type { MoveOptions, RecoveryStore, Revision, RunStatus } from './recoveryStore.ts';\nimport { HistoryExpiredError } from './runTree.ts';\n\n/** One run that wrote to the workspace. */\nexport interface HistoryRun {\n\trunId: string;\n\t/** The run the workspace was at when this one started; absent when it started at the start. */\n\tparentRunId?: string;\n\t/**\n\t * Runs whose changes retention chained into this one, oldest first: going back past this run\n\t * goes back past them too. An id an earlier `AgentResponse` gave may be found here.\n\t */\n\tabsorbed?: string[];\n\tstatus: RunStatus;\n\tstartedAt: string;\n\tfinishedAt?: string;\n\t/**\n\t * The files it changed, in the order it first touched each one: relative to the root, or the\n\t * real path of a file outside it. A host decides whether to show them.\n\t */\n\tfiles: string[];\n}\n\n/** One move of the workspace through its history. */\nexport interface Move {\n\t/** The run the workspace was at; absent for the start of the history. */\n\tfrom?: string;\n\t/** The run the workspace is at now; absent for the start of the history. */\n\tto?: string;\n\tat: string;\n\treason?: string;\n\t/** Every file reached the state the history expected. Otherwise `conflicts` names those left. */\n\tcomplete: boolean;\n\t/**\n\t * The files left as they were, and the run whose change could not be undone or redone: one\n\t * that did not hold what the history expected, such as one the user edited since, or one a\n\t * command changed into, or from, something the history cannot copy, such as a file over 64 MB.\n\t */\n\tconflicts: { path: string; runId: string }[];\n}\n\n/**\n * The history of the runs that wrote to one workspace: what each run changed, and moving the\n * workspace back and forward through them. Runs form a tree: going back and writing again\n * starts a new branch, and the earlier one stays reachable with `goTo`.\n */\nexport interface History {\n\t/**\n\t * Every run kept, oldest first, and the run the workspace is at (`head`), absent at the start\n\t * of the history. A run whose process died while writing is `interrupted`.\n\t */\n\tlist(): Promise<{ head?: string; runs: HistoryRun[] }>;\n\t/**\n\t * What a run changed, as a git-style diff per file. What does not fit in `maxLines`, 1000 by\n\t * default, is named instead.\n\t *\n\t * @throws {UnknownRunError} when `runId` was never a run of this workspace.\n\t * @throws {HistoryExpiredError} when retention removed it or chained it into a later run.\n\t */\n\tchanges(runId: string, options?: { maxLines?: number }): Promise<string>;\n\t/**\n\t * Moves the workspace to the state right after `target`, or to how it was before any run with\n\t * `historyStart`. A file that does not hold what the history expects is left as it is, and the\n\t * move is then not `complete`. With `from`, it moves only if the workspace is still there: a\n\t * host that showed the user what a move will do passes where the workspace was, so a run that\n\t * ended meanwhile cannot make it do something else.\n\t *\n\t * @throws {WorkspaceBusyError} when a run or another move holds the workspace.\n\t * @throws {WorkspaceMovedError} when the workspace is not at `from`.\n\t * @throws {UnknownRunError} when `target` is not in the history.\n\t * @throws {HistoryExpiredError} when retention chained `target` into a later run.\n\t */\n\tgoTo(target: string, options?: MoveOptions): Promise<Move>;\n\t/**\n\t * Moves the workspace to the run before the one it is at.\n\t *\n\t * @throws {NothingToMoveError} at the start of the history.\n\t * @throws {WorkspaceBusyError} when a run or another move holds the workspace.\n\t * @throws {WorkspaceMovedError} when the workspace is not at `from`.\n\t */\n\tundo(options?: MoveOptions): Promise<Move>;\n\t/**\n\t * Moves the workspace to the next run: towards where it was most recently, or else the newest\n\t * branch.\n\t *\n\t * @throws {NothingToMoveError} when no run follows the one it is at.\n\t * @throws {WorkspaceBusyError} when a run or another move holds the workspace.\n\t * @throws {WorkspaceMovedError} when the workspace is not at `from`.\n\t */\n\tredo(options?: MoveOptions): Promise<Move>;\n}\n\n/** `History` over a recovery store, with paths shown relative to the workspace's real root. */\nexport class StoreHistory implements History {\n\tprivate readonly store: RecoveryStore;\n\tprivate readonly root: string;\n\n\tconstructor({ store, root }: { store: RecoveryStore; root: string }) {\n\t\tthis.store = store;\n\t\tthis.root = root;\n\t}\n\n\tasync list(): Promise<{ head?: string; runs: HistoryRun[] }> {\n\t\tconst { head, runs } = await this.store.listRuns();\n\t\tconst listed: HistoryRun[] = [];\n\t\tfor (const run of runs) {\n\t\t\tconst read = await this.store.readRun(run.runId).catch((error: unknown) => {\n\t\t\t\t// Retention took it since it was listed: it is no longer in the history.\n\t\t\t\tif (error instanceof HistoryExpiredError) return undefined;\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t\tif (!read) continue;\n\t\t\tconst { record, entries, unrecorded } = read;\n\t\t\tconst files = [\n\t\t\t\t...changedFiles(record, entries).map(change => change.path),\n\t\t\t\t...unrecorded.map(change => change.path),\n\t\t\t];\n\t\t\tlisted.push({\n\t\t\t\trunId: record.runId,\n\t\t\t\t...(record.parentRunId ? { parentRunId: record.parentRunId } : {}),\n\t\t\t\t...(record.absorbed ? { absorbed: [...record.absorbed] } : {}),\n\t\t\t\tstatus: record.status,\n\t\t\t\tstartedAt: record.startedAt,\n\t\t\t\t...(record.finishedAt ? { finishedAt: record.finishedAt } : {}),\n\t\t\t\tfiles: [...new Set(files)].map(path => displayPath(record.root, path)),\n\t\t\t});\n\t\t}\n\t\treturn { ...(head ? { head } : {}), runs: listed };\n\t}\n\n\tchanges(runId: string, options: { maxLines?: number } = {}): Promise<string> {\n\t\treturn showChanges(this.store, runId, options);\n\t}\n\n\tasync goTo(target: string, options: MoveOptions = {}): Promise<Move> {\n\t\treturn this.moveOf(await this.store.goTo(target, options));\n\t}\n\n\tasync undo(options: MoveOptions = {}): Promise<Move> {\n\t\treturn this.moveOf(await this.store.undo(options));\n\t}\n\n\tasync redo(options: MoveOptions = {}): Promise<Move> {\n\t\treturn this.moveOf(await this.store.redo(options));\n\t}\n\n\tprivate moveOf(revision: Revision): Move {\n\t\treturn {\n\t\t\t...(revision.from ? { from: revision.from } : {}),\n\t\t\t...(revision.to ? { to: revision.to } : {}),\n\t\t\tat: revision.at,\n\t\t\t...(revision.reason ? { reason: revision.reason } : {}),\n\t\t\tcomplete: revision.complete,\n\t\t\tconflicts: revision.conflicts.map(({ path, runId }) => ({\n\t\t\t\tpath: displayPath(this.root, path),\n\t\t\t\trunId,\n\t\t\t})),\n\t\t};\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"history.js","sourceRoot":"","sources":["../../../src/recovery/domain/history.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAEzE,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAiGnD,+FAA+F;AAC/F,MAAM,OAAO,YAAY;IACP,KAAK,CAAgB;IACrB,IAAI,CAAS;IAE9B,YAAY,EAAE,KAAK,EAAE,IAAI,EAA0C;QAClE,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAClB,CAAC;IAED,KAAK,CAAC,IAAI;QACT,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC;QACnD,MAAM,MAAM,GAAiB,EAAE,CAAC;QAChC,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;YACxB,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;gBACzE,yEAAyE;gBACzE,IAAI,KAAK,YAAY,mBAAmB;oBAAE,OAAO,SAAS,CAAC;gBAC3D,MAAM,KAAK,CAAC;YACb,CAAC,CAAC,CAAC;YACH,IAAI,CAAC,IAAI;gBAAE,SAAS;YACpB,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,UAAU,EAAE,GAAG,IAAI,CAAC;YAC7C,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AAI,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;gBACvD,IAAI,EAAE,WAAW,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC;gBAClC,KAAK;aACL,CAAC,CAAC;SACH,CAAC;IACH,CAAC;CACD","sourcesContent":["import type { Session } from '#src/shared/domain/session';\nimport { changedFiles, displayPath, showChanges } from './runChanges.ts';\nimport type { MoveOptions, RecoveryStore, Revision, RunStatus } from './recoveryStore.ts';\nimport { HistoryExpiredError } from './runTree.ts';\n\n/** One run that wrote to the workspace. */\nexport interface HistoryRun {\n\trunId: string;\n\t/** The run the workspace was at when this one started; absent when it started at the start. */\n\tparentRunId?: string;\n\t/**\n\t * Runs whose changes retention chained into this one, oldest first: going back past this run\n\t * goes back past them too. An id an earlier `AgentResponse` gave may be found here.\n\t */\n\tabsorbed?: string[];\n\tstatus: RunStatus;\n\tstartedAt: string;\n\tfinishedAt?: string;\n\t/**\n\t * The files it changed, in the order it first touched each one: relative to the root, or the\n\t * real path of a file outside it. A host decides whether to show them.\n\t */\n\tfiles: string[];\n\t/**\n\t * The session it came from, so a host can warn before undoing another session's run. Absent\n\t * for a run recorded before runs recorded one. A run retention chained into this one keeps\n\t * no session of its own.\n\t */\n\tsession?: Session;\n}\n\n/** One move of the workspace through its history. */\nexport interface Move {\n\t/** The run the workspace was at; absent for the start of the history. */\n\tfrom?: string;\n\t/** The run the workspace is at now; absent for the start of the history. */\n\tto?: string;\n\tat: string;\n\treason?: string;\n\t/** Every file reached the state the history expected. Otherwise `conflicts` names those left. */\n\tcomplete: boolean;\n\t/**\n\t * The files left as they were, and the run whose change could not be undone or redone: one\n\t * that did not hold what the history expected, such as one the user edited since, or one a\n\t * command changed into, or from, something the history cannot copy, such as a file over 64 MB.\n\t */\n\tconflicts: { path: string; runId: string }[];\n}\n\n/**\n * The history of the runs that wrote to one workspace: what each run changed, and moving the\n * workspace back and forward through them. Runs form a tree: going back and writing again\n * starts a new branch, and the earlier one stays reachable with `goTo`.\n */\nexport interface History {\n\t/**\n\t * Every run kept, oldest first, and the run the workspace is at (`head`), absent at the start\n\t * of the history. A run whose process died while writing is `interrupted`.\n\t */\n\tlist(): Promise<{ head?: string; runs: HistoryRun[] }>;\n\t/**\n\t * What a run changed, as a git-style diff per file. What does not fit in `maxLines`, 1000 by\n\t * default, is named instead.\n\t *\n\t * @throws {UnknownRunError} when `runId` was never a run of this workspace.\n\t * @throws {HistoryExpiredError} when retention removed it or chained it into a later run.\n\t */\n\tchanges(runId: string, options?: { maxLines?: number }): Promise<string>;\n\t/**\n\t * Moves the workspace to the state right after `target`, or to how it was before any run with\n\t * `historyStart`. A file that does not hold what the history expects is left as it is, and the\n\t * move is then not `complete`. With `from`, it moves only if the workspace is still there: a\n\t * host that showed the user what a move will do passes where the workspace was, so a run that\n\t * ended meanwhile cannot make it do something else.\n\t *\n\t * @throws {WorkspaceBusyError} when a run, another move or the removal of its worktree holds the workspace.\n\t * @throws {WorkspaceMovedError} when the workspace is not at `from`.\n\t * @throws {UnknownRunError} when `target` is not in the history.\n\t * @throws {HistoryExpiredError} when retention chained `target` into a later run.\n\t */\n\tgoTo(target: string, options?: MoveOptions): Promise<Move>;\n\t/**\n\t * Moves the workspace to the run before the one it is at.\n\t *\n\t * @throws {NothingToMoveError} at the start of the history.\n\t * @throws {WorkspaceBusyError} when a run, another move or the removal of its worktree holds the workspace.\n\t * @throws {WorkspaceMovedError} when the workspace is not at `from`.\n\t */\n\tundo(options?: MoveOptions): Promise<Move>;\n\t/**\n\t * Moves the workspace to the next run: towards where it was most recently, or else the newest\n\t * branch.\n\t *\n\t * @throws {NothingToMoveError} when no run follows the one it is at.\n\t * @throws {WorkspaceBusyError} when a run, another move or the removal of its worktree holds the workspace.\n\t * @throws {WorkspaceMovedError} when the workspace is not at `from`.\n\t */\n\tredo(options?: MoveOptions): Promise<Move>;\n}\n\n/** `History` over a recovery store, with paths shown relative to the workspace's real root. */\nexport class StoreHistory implements History {\n\tprivate readonly store: RecoveryStore;\n\tprivate readonly root: string;\n\n\tconstructor({ store, root }: { store: RecoveryStore; root: string }) {\n\t\tthis.store = store;\n\t\tthis.root = root;\n\t}\n\n\tasync list(): Promise<{ head?: string; runs: HistoryRun[] }> {\n\t\tconst { head, runs } = await this.store.listRuns();\n\t\tconst listed: HistoryRun[] = [];\n\t\tfor (const run of runs) {\n\t\t\tconst read = await this.store.readRun(run.runId).catch((error: unknown) => {\n\t\t\t\t// Retention took it since it was listed: it is no longer in the history.\n\t\t\t\tif (error instanceof HistoryExpiredError) return undefined;\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t\tif (!read) continue;\n\t\t\tconst { record, entries, unrecorded } = read;\n\t\t\tconst files = [\n\t\t\t\t...changedFiles(record, entries).map(change => change.path),\n\t\t\t\t...unrecorded.map(change => change.path),\n\t\t\t];\n\t\t\tlisted.push({\n\t\t\t\trunId: record.runId,\n\t\t\t\t...(record.parentRunId ? { parentRunId: record.parentRunId } : {}),\n\t\t\t\t...(record.absorbed ? { absorbed: [...record.absorbed] } : {}),\n\t\t\t\tstatus: record.status,\n\t\t\t\tstartedAt: record.startedAt,\n\t\t\t\t...(record.finishedAt ? { finishedAt: record.finishedAt } : {}),\n\t\t\t\tfiles: [...new Set(files)].map(path => displayPath(record.root, path)),\n\t\t\t\t...(record.session ? { session: { ...record.session } } : {}),\n\t\t\t});\n\t\t}\n\t\treturn { ...(head ? { head } : {}), runs: listed };\n\t}\n\n\tchanges(runId: string, options: { maxLines?: number } = {}): Promise<string> {\n\t\treturn showChanges(this.store, runId, options);\n\t}\n\n\tasync goTo(target: string, options: MoveOptions = {}): Promise<Move> {\n\t\treturn this.moveOf(await this.store.goTo(target, options));\n\t}\n\n\tasync undo(options: MoveOptions = {}): Promise<Move> {\n\t\treturn this.moveOf(await this.store.undo(options));\n\t}\n\n\tasync redo(options: MoveOptions = {}): Promise<Move> {\n\t\treturn this.moveOf(await this.store.redo(options));\n\t}\n\n\tprivate moveOf(revision: Revision): Move {\n\t\treturn {\n\t\t\t...(revision.from ? { from: revision.from } : {}),\n\t\t\t...(revision.to ? { to: revision.to } : {}),\n\t\t\tat: revision.at,\n\t\t\t...(revision.reason ? { reason: revision.reason } : {}),\n\t\t\tcomplete: revision.complete,\n\t\t\tconflicts: revision.conflicts.map(({ path, runId }) => ({\n\t\t\t\tpath: displayPath(this.root, path),\n\t\t\t\trunId,\n\t\t\t})),\n\t\t};\n\t}\n}\n"]}
|