@leitwerk-dev/worker 0.3.1 → 0.4.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/dist/{chunk-4WPLQCF6.js → chunk-KJCBXN5F.js} +1700 -1244
- package/dist/chunk-KJCBXN5F.js.map +1 -0
- package/dist/container-entry-main.js +160 -3
- package/dist/container-entry-main.js.map +1 -1
- package/dist/container-entry.d.ts +1 -0
- package/dist/container-entry.d.ts.map +1 -1
- package/dist/development-tool-environment.d.ts.map +1 -1
- package/dist/diagnostics.d.ts +5 -1
- package/dist/diagnostics.d.ts.map +1 -1
- package/dist/docker-registry-credentials.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/ipc.d.ts.map +1 -1
- package/dist/logical-prompt-runner.d.ts.map +1 -1
- package/dist/missing-tool-recovery-runner.d.ts.map +1 -1
- package/dist/pi-adapter.d.ts +2 -0
- package/dist/pi-adapter.d.ts.map +1 -1
- package/dist/pi-event-reporter.d.ts +2 -0
- package/dist/pi-event-reporter.d.ts.map +1 -1
- package/dist/pi-inspection.d.ts +5 -0
- package/dist/pi-inspection.d.ts.map +1 -0
- package/dist/runtime/bootstrap-session.d.ts +4 -1
- package/dist/runtime/bootstrap-session.d.ts.map +1 -1
- package/dist/runtime/bootstrap.d.ts.map +1 -1
- package/dist/runtime/failure-policy.d.ts.map +1 -1
- package/dist/runtime/index.d.ts.map +1 -1
- package/dist/runtime/llm-turn-execution.d.ts +2 -0
- package/dist/runtime/llm-turn-execution.d.ts.map +1 -1
- package/dist/runtime/turn-execution.d.ts.map +1 -1
- package/dist/session-snapshot-exchange.d.ts.map +1 -1
- package/dist/strict-outcome-schema.d.ts +11 -0
- package/dist/strict-outcome-schema.d.ts.map +1 -0
- package/dist/test-helpers/llm-turn.d.ts +4 -0
- package/dist/test-helpers/llm-turn.d.ts.map +1 -0
- package/dist/test-helpers/pi-provider.d.ts +13 -0
- package/dist/test-helpers/pi-provider.d.ts.map +1 -0
- package/dist/transport-error.d.ts +16 -0
- package/dist/transport-error.d.ts.map +1 -0
- package/dist/turn-outcome-tool-session.d.ts +6 -1
- package/dist/turn-outcome-tool-session.d.ts.map +1 -1
- package/dist/turn-result-markdown.d.ts +5 -0
- package/dist/turn-result-markdown.d.ts.map +1 -1
- package/dist/virtual-machine-docker.d.ts +10 -0
- package/dist/virtual-machine-docker.d.ts.map +1 -0
- package/dist/worker-entry.js +1 -1
- package/dist/workspace/checkout-tool.d.ts +6 -0
- package/dist/workspace/checkout-tool.d.ts.map +1 -0
- package/dist/workspace/manifest.d.ts +2 -0
- package/dist/workspace/manifest.d.ts.map +1 -1
- package/dist/workspace/node-run-root-git-ops.d.ts +1 -0
- package/dist/workspace/node-run-root-git-ops.d.ts.map +1 -1
- package/dist/workspace/run-root.d.ts +5 -3
- package/dist/workspace/run-root.d.ts.map +1 -1
- package/package.json +9 -9
- package/src/container-entry.ts +22 -0
- package/src/development-tool-environment.ts +2 -0
- package/src/diagnostics.ts +6 -1
- package/src/docker-registry-credentials.ts +8 -0
- package/src/ipc.ts +4 -24
- package/src/logical-prompt-runner.ts +45 -41
- package/src/missing-tool-recovery-runner.ts +26 -18
- package/src/pi-adapter.ts +219 -337
- package/src/pi-event-reporter.ts +8 -0
- package/src/pi-inspection.ts +126 -0
- package/src/runtime/bootstrap-session.ts +12 -1
- package/src/runtime/bootstrap.ts +15 -5
- package/src/runtime/failure-policy.ts +20 -2
- package/src/runtime/index.ts +65 -10
- package/src/runtime/llm-turn-execution.ts +28 -1
- package/src/runtime/turn-execution.ts +70 -2
- package/src/session-snapshot-exchange.ts +2 -0
- package/src/strict-outcome-schema.ts +84 -0
- package/src/test-helpers/llm-turn.ts +22 -0
- package/src/test-helpers/pi-provider.ts +126 -0
- package/src/transport-error.ts +92 -0
- package/src/turn-outcome-tool-session.ts +123 -26
- package/src/turn-result-markdown.ts +23 -6
- package/src/virtual-machine-docker.ts +191 -0
- package/src/workspace/checkout-tool.ts +68 -0
- package/src/workspace/manifest.ts +3 -0
- package/src/workspace/node-run-root-git-ops.ts +17 -0
- package/src/workspace/run-root.ts +62 -26
- package/dist/chunk-4WPLQCF6.js.map +0 -1
|
@@ -2,7 +2,11 @@
|
|
|
2
2
|
import { access, mkdir, writeFile } from "fs/promises";
|
|
3
3
|
import path2 from "path";
|
|
4
4
|
import { readFiniteNumber, readNonBlankString as readNonEmptyString } from "@leitwerk-dev/domain";
|
|
5
|
-
import {
|
|
5
|
+
import {
|
|
6
|
+
compileOutcomeParameters,
|
|
7
|
+
hasErrorCode,
|
|
8
|
+
isEnoent
|
|
9
|
+
} from "@leitwerk-dev/process-sdk";
|
|
6
10
|
import { resolvePiAgentDir } from "@leitwerk-dev/process-sdk/pi-config";
|
|
7
11
|
import { parseDurationMs } from "@leitwerk-dev/watcher-utils";
|
|
8
12
|
|
|
@@ -70,6 +74,175 @@ function assertResultStayedOnExecutionBranch(input) {
|
|
|
70
74
|
}
|
|
71
75
|
}
|
|
72
76
|
|
|
77
|
+
// src/pi-inspection.ts
|
|
78
|
+
import { randomUUID } from "crypto";
|
|
79
|
+
|
|
80
|
+
// src/strict-outcome-schema.ts
|
|
81
|
+
import { isUnknownRecord } from "@leitwerk-dev/domain";
|
|
82
|
+
var activeContracts = /* @__PURE__ */ new WeakMap();
|
|
83
|
+
function supportsStrictOutcomeSchemas(api) {
|
|
84
|
+
return api === "openai-responses" || api === "openai-completions";
|
|
85
|
+
}
|
|
86
|
+
function strictOutcomeToolNames(session) {
|
|
87
|
+
return activeContracts.get(session) ?? /* @__PURE__ */ new Set();
|
|
88
|
+
}
|
|
89
|
+
function enforceStrictOutcomePayload(payload, api, tools) {
|
|
90
|
+
if (!supportsStrictOutcomeSchemas(api)) return payload;
|
|
91
|
+
if (!isUnknownRecord(payload))
|
|
92
|
+
throw new Error("Cannot enforce outcome schemas: provider payload is not an object");
|
|
93
|
+
const strict = new Map(
|
|
94
|
+
tools.filter((tool) => tool.strictSchema).map((tool) => [tool.name, tool])
|
|
95
|
+
);
|
|
96
|
+
if (!Array.isArray(payload.tools)) return payload;
|
|
97
|
+
return {
|
|
98
|
+
...payload,
|
|
99
|
+
tools: payload.tools.map((raw) => {
|
|
100
|
+
if (!isUnknownRecord(raw) || raw.type !== "function") return raw;
|
|
101
|
+
const declaration = api === "openai-completions" ? raw.function : raw;
|
|
102
|
+
if (!isUnknownRecord(declaration) || typeof declaration.name !== "string") return raw;
|
|
103
|
+
const tool = strict.get(declaration.name);
|
|
104
|
+
if (!tool) return raw;
|
|
105
|
+
const enforced = { ...declaration, strict: true, parameters: tool.parameters };
|
|
106
|
+
return api === "openai-completions" ? { ...raw, function: enforced } : enforced;
|
|
107
|
+
})
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
function installStrictOutcomeSchemas(session, tools, emit) {
|
|
111
|
+
const optedIn = tools.filter((tool) => tool.strictSchema);
|
|
112
|
+
if (!optedIn.length) return () => {
|
|
113
|
+
};
|
|
114
|
+
const previousNames = activeContracts.get(session);
|
|
115
|
+
activeContracts.set(session, new Set(optedIn.map((tool) => tool.name)));
|
|
116
|
+
const previousPayload = session.agent.onPayload;
|
|
117
|
+
const previousStream = session.agent.streamFunction;
|
|
118
|
+
const reported = /* @__PURE__ */ new Set();
|
|
119
|
+
session.agent.onPayload = async (payload, model) => {
|
|
120
|
+
const resolved = await previousPayload?.(payload, model);
|
|
121
|
+
return enforceStrictOutcomePayload(
|
|
122
|
+
resolved === void 0 ? payload : resolved,
|
|
123
|
+
model.api,
|
|
124
|
+
optedIn
|
|
125
|
+
);
|
|
126
|
+
};
|
|
127
|
+
session.agent.streamFunction = (model, context, options) => {
|
|
128
|
+
if (!supportsStrictOutcomeSchemas(model.api) && !reported.has(model.api)) {
|
|
129
|
+
reported.add(model.api);
|
|
130
|
+
emit({
|
|
131
|
+
level: "warn",
|
|
132
|
+
code: "strict_outcome_schema_unsupported",
|
|
133
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
134
|
+
message: `Provider API '${model.api}' does not support outcome schema enforcement; server validation remains active.`,
|
|
135
|
+
details: { api: model.api, tools: optedIn.map((tool) => tool.name) }
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
return previousStream.call(session.agent, model, context, options);
|
|
139
|
+
};
|
|
140
|
+
return () => {
|
|
141
|
+
session.agent.onPayload = previousPayload;
|
|
142
|
+
session.agent.streamFunction = previousStream;
|
|
143
|
+
if (previousNames) activeContracts.set(session, previousNames);
|
|
144
|
+
else activeContracts.delete(session);
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// src/pi-inspection.ts
|
|
149
|
+
function messageKey(message) {
|
|
150
|
+
const content = typeof message.content === "string" ? [{ type: "text", text: message.content }] : message.content;
|
|
151
|
+
return JSON.stringify([
|
|
152
|
+
message.role === "custom" ? "user" : message.role,
|
|
153
|
+
content,
|
|
154
|
+
message.toolCallId ?? null
|
|
155
|
+
]);
|
|
156
|
+
}
|
|
157
|
+
function installPiInspection(session, emit, getPiTurnId = () => "unknown") {
|
|
158
|
+
const original = session.agent.streamFunction;
|
|
159
|
+
if (typeof original !== "function") return () => {
|
|
160
|
+
};
|
|
161
|
+
const unsubscribe = session.agent.subscribe((event) => {
|
|
162
|
+
if (event.type !== "message_end") return;
|
|
163
|
+
const entry = session.sessionManager.getLeafEntry();
|
|
164
|
+
if (!entry || entry.type !== "message" && entry.type !== "custom_message") return;
|
|
165
|
+
const message = entry.type === "message" ? entry.message : { role: "custom", content: entry.content };
|
|
166
|
+
if (messageKey(message) !== messageKey(event.message)) return;
|
|
167
|
+
emit({
|
|
168
|
+
id: `entry:${entry.id}`,
|
|
169
|
+
version: 1,
|
|
170
|
+
timestamp: entry.timestamp,
|
|
171
|
+
fact: {
|
|
172
|
+
kind: "entry_link",
|
|
173
|
+
entryId: entry.id,
|
|
174
|
+
piTurnId: getPiTurnId(),
|
|
175
|
+
role: event.message.role
|
|
176
|
+
}
|
|
177
|
+
});
|
|
178
|
+
});
|
|
179
|
+
session.agent.streamFunction = async (model, context, options) => {
|
|
180
|
+
const { getCurrentSystemPrompt, getCurrentTools } = await import("@earendil-works/pi-ai");
|
|
181
|
+
const entries = session.sessionManager.getBranch();
|
|
182
|
+
const byContent = /* @__PURE__ */ new Map();
|
|
183
|
+
for (const entry of entries) {
|
|
184
|
+
const message = entry.type === "message" ? entry.message : entry.type === "custom_message" ? { role: "user", content: entry.content } : null;
|
|
185
|
+
if (!message) continue;
|
|
186
|
+
const key = messageKey(message);
|
|
187
|
+
const timestamp = "timestamp" in message && typeof message.timestamp === "number" ? message.timestamp : Date.parse(entry.timestamp);
|
|
188
|
+
byContent.set(key, [...byContent.get(key) ?? [], { id: entry.id, timestamp }]);
|
|
189
|
+
}
|
|
190
|
+
const messages = context.messages.map((message) => {
|
|
191
|
+
const matches = byContent.get(messageKey(message));
|
|
192
|
+
const exact = matches?.filter((match) => match.timestamp === message.timestamp);
|
|
193
|
+
const candidates = exact?.length ? exact : matches;
|
|
194
|
+
return {
|
|
195
|
+
entryId: candidates?.length === 1 ? candidates[0].id : null,
|
|
196
|
+
role: message.role,
|
|
197
|
+
...message.role === "toolResult" ? { toolCallId: message.toolCallId } : {},
|
|
198
|
+
content: { state: "recorded", value: message.content }
|
|
199
|
+
};
|
|
200
|
+
});
|
|
201
|
+
const capture = {
|
|
202
|
+
id: randomUUID(),
|
|
203
|
+
version: 1,
|
|
204
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
205
|
+
fact: {
|
|
206
|
+
kind: "model_input",
|
|
207
|
+
boundaryEntryId: session.sessionManager.getLeafId(),
|
|
208
|
+
model: {
|
|
209
|
+
provider: model.provider,
|
|
210
|
+
id: model.id,
|
|
211
|
+
thinkingLevel: session.thinkingLevel ?? null
|
|
212
|
+
},
|
|
213
|
+
systemPrompt: { state: "recorded", value: getCurrentSystemPrompt(context.messages) },
|
|
214
|
+
appendedInstructions: {
|
|
215
|
+
state: "recorded",
|
|
216
|
+
value: session.resourceLoader.getAppendSystemPrompt()
|
|
217
|
+
},
|
|
218
|
+
contextFiles: {
|
|
219
|
+
state: "recorded",
|
|
220
|
+
value: session.resourceLoader.getAgentsFiles().agentsFiles.map(({ path: path15, content }) => ({ path: path15, content }))
|
|
221
|
+
},
|
|
222
|
+
tools: {
|
|
223
|
+
state: "recorded",
|
|
224
|
+
value: getCurrentTools(context.messages).map(({ name, description, parameters }) => ({
|
|
225
|
+
name,
|
|
226
|
+
description,
|
|
227
|
+
parameters,
|
|
228
|
+
...strictOutcomeToolNames(session).has(name) ? {
|
|
229
|
+
strictSchema: true,
|
|
230
|
+
schemaEnforcement: supportsStrictOutcomeSchemas(model.api) ? "provider" : "server"
|
|
231
|
+
} : {}
|
|
232
|
+
}))
|
|
233
|
+
},
|
|
234
|
+
messages
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
emit(JSON.parse(JSON.stringify(capture)));
|
|
238
|
+
return original.call(session.agent, model, context, options);
|
|
239
|
+
};
|
|
240
|
+
return () => {
|
|
241
|
+
unsubscribe();
|
|
242
|
+
session.agent.streamFunction = original;
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
|
|
73
246
|
// src/repository-bash-tool.ts
|
|
74
247
|
import { sanitizeWorkerSubprocessEnv } from "@leitwerk-dev/process-sdk";
|
|
75
248
|
async function createRepositoryBashTool(cwd) {
|
|
@@ -174,17 +347,9 @@ async function inspectPiTreeForPlanning(input) {
|
|
|
174
347
|
path2.dirname(input.treeFile),
|
|
175
348
|
input.sessionCwd
|
|
176
349
|
);
|
|
177
|
-
const entries = [];
|
|
178
|
-
const visit = (nodes) => {
|
|
179
|
-
for (const node of nodes) {
|
|
180
|
-
entries.push({ id: node.entry.id, parentId: node.entry.parentId });
|
|
181
|
-
visit(node.children);
|
|
182
|
-
}
|
|
183
|
-
};
|
|
184
|
-
visit(manager.getTree());
|
|
185
350
|
return {
|
|
186
351
|
currentLeafId: manager.getLeafId() ?? null,
|
|
187
|
-
entries
|
|
352
|
+
entries: manager.getEntries().map(({ id, parentId }) => ({ id, parentId }))
|
|
188
353
|
};
|
|
189
354
|
}
|
|
190
355
|
function toIsoTimestamp(value) {
|
|
@@ -203,32 +368,7 @@ function toToolSchema(parameters) {
|
|
|
203
368
|
if (isObjectLike(parameters) && parameters.type === "object" && isObjectLike(parameters.properties)) {
|
|
204
369
|
return parameters;
|
|
205
370
|
}
|
|
206
|
-
|
|
207
|
-
const required = [];
|
|
208
|
-
for (const [key, spec] of Object.entries(parameters)) {
|
|
209
|
-
if (isObjectLike(spec)) {
|
|
210
|
-
const {
|
|
211
|
-
required: isRequired,
|
|
212
|
-
requiredErrorCode: _requiredErrorCode,
|
|
213
|
-
invalidErrorCode: _invalidErrorCode,
|
|
214
|
-
minItemsErrorCode: _minItemsErrorCode,
|
|
215
|
-
minimumErrorCode: _minimumErrorCode,
|
|
216
|
-
...jsonSchemaSpec
|
|
217
|
-
} = spec;
|
|
218
|
-
properties[key] = { ...jsonSchemaSpec };
|
|
219
|
-
if (isRequired === true) {
|
|
220
|
-
required.push(key);
|
|
221
|
-
}
|
|
222
|
-
} else {
|
|
223
|
-
properties[key] = { type: "string" };
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
return {
|
|
227
|
-
type: "object",
|
|
228
|
-
properties,
|
|
229
|
-
required,
|
|
230
|
-
additionalProperties: false
|
|
231
|
-
};
|
|
371
|
+
return compileOutcomeParameters(parameters);
|
|
232
372
|
}
|
|
233
373
|
var LEITWERK_TOOL_BOOTSTRAP = {
|
|
234
374
|
name: LEITWERK_TOOL_BOOTSTRAP_NAME,
|
|
@@ -306,14 +446,17 @@ function validateRequestedActiveTools(requestedToolNames, availableToolNames) {
|
|
|
306
446
|
}
|
|
307
447
|
}
|
|
308
448
|
}
|
|
309
|
-
function toPiRunDetails(
|
|
449
|
+
function toPiRunDetails({ resourceLoader }, availableToolNames) {
|
|
310
450
|
return {
|
|
311
|
-
loadedAgentsFiles:
|
|
312
|
-
path:
|
|
313
|
-
sizeBytes: Buffer.byteLength(
|
|
451
|
+
loadedAgentsFiles: resourceLoader.getAgentsFiles().agentsFiles.map(({ path: path15, content }) => ({
|
|
452
|
+
path: path15,
|
|
453
|
+
sizeBytes: Buffer.byteLength(content, "utf8")
|
|
454
|
+
})),
|
|
455
|
+
loadedSkills: resourceLoader.getSkills().skills.map(({ name, filePath }) => ({
|
|
456
|
+
name,
|
|
457
|
+
path: filePath
|
|
314
458
|
})),
|
|
315
|
-
|
|
316
|
-
availableToolNames: [...input.availableToolNames]
|
|
459
|
+
availableToolNames: [...availableToolNames]
|
|
317
460
|
};
|
|
318
461
|
}
|
|
319
462
|
function updateAgentMessagesForCurrentLeaf(session) {
|
|
@@ -457,15 +600,15 @@ var TerminalAcknowledgementRuntime = class {
|
|
|
457
600
|
onTurnCompleted(args) {
|
|
458
601
|
const state = this.control.state();
|
|
459
602
|
if (!this.acknowledgementTurnStarted) {
|
|
460
|
-
if (state !== "outcome_accepted") return
|
|
603
|
+
if (state !== "outcome_accepted") return void 0;
|
|
461
604
|
this.acknowledgementTurnStarted = true;
|
|
462
|
-
return
|
|
605
|
+
return { action: "continue" };
|
|
463
606
|
}
|
|
464
607
|
if (state === "outcome_accepted") {
|
|
465
608
|
const context = isObjectLike(args[0]) ? args[0] : null;
|
|
466
609
|
this.settleFromMessage(context?.message);
|
|
467
610
|
}
|
|
468
|
-
return
|
|
611
|
+
return { action: "end" };
|
|
469
612
|
}
|
|
470
613
|
async run(run) {
|
|
471
614
|
const runOutcome = run().then(
|
|
@@ -674,14 +817,20 @@ function summarizeSessionGlobalDiagnosticDetails(event) {
|
|
|
674
817
|
const keys = listRecordKeys(raw);
|
|
675
818
|
return keys.length > 0 ? { ...base, keys } : base;
|
|
676
819
|
}
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
820
|
+
var SESSION_GLOBAL_EVENT_MESSAGES = /* @__PURE__ */ new Map([
|
|
821
|
+
["session_info_changed", "Pi session info changed"],
|
|
822
|
+
["agent_start", "Pi agent run started"],
|
|
823
|
+
["agent_end", "Pi agent run ended"],
|
|
824
|
+
["agent_settled", "Pi agent run settled"],
|
|
825
|
+
["queue_update", "Pi session queue updated"]
|
|
826
|
+
]);
|
|
827
|
+
var TOOL_CALL_EVENT_TYPES = {
|
|
828
|
+
toolcall_start: "toolcall.start",
|
|
829
|
+
toolcall_delta: "toolcall.delta",
|
|
830
|
+
toolcall_end: "toolcall.end"
|
|
831
|
+
};
|
|
832
|
+
function singlePiEvent(event) {
|
|
833
|
+
return { piEvents: [event], diagnostics: [] };
|
|
685
834
|
}
|
|
686
835
|
function buildUnknownSessionEventDiagnostic(event, state) {
|
|
687
836
|
const eventType = readNonEmptyString(event.type) ?? "unknown";
|
|
@@ -723,16 +872,18 @@ function buildUnknownAssistantEventDiagnostic(input) {
|
|
|
723
872
|
});
|
|
724
873
|
}
|
|
725
874
|
function translateAgentSessionEventEnvelope(event, state) {
|
|
726
|
-
const
|
|
727
|
-
if (
|
|
875
|
+
const globalMessage = SESSION_GLOBAL_EVENT_MESSAGES.get(event.type);
|
|
876
|
+
if (globalMessage) {
|
|
728
877
|
return {
|
|
729
878
|
piEvents: [],
|
|
730
879
|
diagnostics: [
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
880
|
+
buildSessionDiagnostic({
|
|
881
|
+
level: "info",
|
|
882
|
+
code: `pi.${event.type}`,
|
|
883
|
+
message: globalMessage,
|
|
884
|
+
timestamp: readSessionEventTimestamp(event),
|
|
885
|
+
details: summarizeSessionGlobalDiagnosticDetails(event)
|
|
886
|
+
})
|
|
736
887
|
]
|
|
737
888
|
};
|
|
738
889
|
}
|
|
@@ -743,32 +894,22 @@ function translateAgentSessionEventEnvelope(event, state) {
|
|
|
743
894
|
state.turnSequence = turnIndex;
|
|
744
895
|
const turnId = `turn-${turnIndex}`;
|
|
745
896
|
state.currentTurnId = turnId;
|
|
746
|
-
return {
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
timestamp: toIsoTimestamp(event.timestamp)
|
|
753
|
-
}
|
|
754
|
-
],
|
|
755
|
-
diagnostics: []
|
|
756
|
-
};
|
|
897
|
+
return singlePiEvent({
|
|
898
|
+
type: "turn.start",
|
|
899
|
+
turnId,
|
|
900
|
+
data: {},
|
|
901
|
+
timestamp: toIsoTimestamp(event.timestamp)
|
|
902
|
+
});
|
|
757
903
|
}
|
|
758
904
|
case "turn_end": {
|
|
759
905
|
const turnId = state.currentTurnId ?? `turn-${state.turnSequence}`;
|
|
760
906
|
state.currentTurnId = null;
|
|
761
|
-
return {
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
timestamp: toIsoTimestamp(event.message.timestamp)
|
|
768
|
-
}
|
|
769
|
-
],
|
|
770
|
-
diagnostics: []
|
|
771
|
-
};
|
|
907
|
+
return singlePiEvent({
|
|
908
|
+
type: "turn.end",
|
|
909
|
+
turnId,
|
|
910
|
+
data: {},
|
|
911
|
+
timestamp: toIsoTimestamp(event.message.timestamp)
|
|
912
|
+
});
|
|
772
913
|
}
|
|
773
914
|
case "message_start":
|
|
774
915
|
return { piEvents: [], diagnostics: [] };
|
|
@@ -781,71 +922,25 @@ function translateAgentSessionEventEnvelope(event, state) {
|
|
|
781
922
|
const timestamp = toIsoTimestamp(event.message.timestamp);
|
|
782
923
|
switch (event.assistantMessageEvent.type) {
|
|
783
924
|
case "text_delta":
|
|
784
|
-
return {
|
|
785
|
-
piEvents: [
|
|
786
|
-
{
|
|
787
|
-
type: "stream.delta",
|
|
788
|
-
turnId,
|
|
789
|
-
data: {
|
|
790
|
-
text: event.assistantMessageEvent.delta,
|
|
791
|
-
streamType: "text"
|
|
792
|
-
},
|
|
793
|
-
timestamp
|
|
794
|
-
}
|
|
795
|
-
],
|
|
796
|
-
diagnostics: []
|
|
797
|
-
};
|
|
798
925
|
case "thinking_delta":
|
|
799
|
-
return {
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
timestamp
|
|
809
|
-
}
|
|
810
|
-
],
|
|
811
|
-
diagnostics: []
|
|
812
|
-
};
|
|
926
|
+
return singlePiEvent({
|
|
927
|
+
type: "stream.delta",
|
|
928
|
+
turnId,
|
|
929
|
+
data: {
|
|
930
|
+
text: event.assistantMessageEvent.delta,
|
|
931
|
+
streamType: event.assistantMessageEvent.type === "text_delta" ? "text" : "thinking"
|
|
932
|
+
},
|
|
933
|
+
timestamp
|
|
934
|
+
});
|
|
813
935
|
case "toolcall_start":
|
|
814
|
-
return {
|
|
815
|
-
piEvents: [
|
|
816
|
-
{
|
|
817
|
-
type: "toolcall.start",
|
|
818
|
-
turnId,
|
|
819
|
-
data: normalizePiEventData(assistantMessageEvent),
|
|
820
|
-
timestamp
|
|
821
|
-
}
|
|
822
|
-
],
|
|
823
|
-
diagnostics: []
|
|
824
|
-
};
|
|
825
936
|
case "toolcall_delta":
|
|
826
|
-
return {
|
|
827
|
-
piEvents: [
|
|
828
|
-
{
|
|
829
|
-
type: "toolcall.delta",
|
|
830
|
-
turnId,
|
|
831
|
-
data: normalizePiEventData(assistantMessageEvent),
|
|
832
|
-
timestamp
|
|
833
|
-
}
|
|
834
|
-
],
|
|
835
|
-
diagnostics: []
|
|
836
|
-
};
|
|
837
937
|
case "toolcall_end":
|
|
838
|
-
return {
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
timestamp
|
|
845
|
-
}
|
|
846
|
-
],
|
|
847
|
-
diagnostics: []
|
|
848
|
-
};
|
|
938
|
+
return singlePiEvent({
|
|
939
|
+
type: TOOL_CALL_EVENT_TYPES[event.assistantMessageEvent.type],
|
|
940
|
+
turnId,
|
|
941
|
+
data: normalizePiEventData(assistantMessageEvent),
|
|
942
|
+
timestamp
|
|
943
|
+
});
|
|
849
944
|
case "start":
|
|
850
945
|
case "done":
|
|
851
946
|
case "error":
|
|
@@ -910,79 +1005,59 @@ function translateAgentSessionEventEnvelope(event, state) {
|
|
|
910
1005
|
return { piEvents, diagnostics: [] };
|
|
911
1006
|
}
|
|
912
1007
|
case "auto_retry_start":
|
|
913
|
-
return {
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
931
|
-
}
|
|
932
|
-
],
|
|
933
|
-
diagnostics: []
|
|
934
|
-
};
|
|
1008
|
+
return singlePiEvent({
|
|
1009
|
+
type: "retry.start",
|
|
1010
|
+
turnId: activeTurnId(state),
|
|
1011
|
+
data: {
|
|
1012
|
+
attempt: event.attempt,
|
|
1013
|
+
maxAttempts: event.maxAttempts,
|
|
1014
|
+
delayMs: event.delayMs,
|
|
1015
|
+
errorMessage: event.errorMessage,
|
|
1016
|
+
message: describeRetryStart({
|
|
1017
|
+
attempt: event.attempt,
|
|
1018
|
+
maxAttempts: event.maxAttempts,
|
|
1019
|
+
delayMs: event.delayMs,
|
|
1020
|
+
errorMessage: event.errorMessage
|
|
1021
|
+
})
|
|
1022
|
+
},
|
|
1023
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
1024
|
+
});
|
|
935
1025
|
case "auto_retry_end": {
|
|
936
1026
|
const finalError = readNonEmptyString(event.finalError);
|
|
937
|
-
return {
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
953
|
-
}
|
|
954
|
-
],
|
|
955
|
-
diagnostics: []
|
|
956
|
-
};
|
|
1027
|
+
return singlePiEvent({
|
|
1028
|
+
type: "retry.end",
|
|
1029
|
+
turnId: activeTurnId(state),
|
|
1030
|
+
data: {
|
|
1031
|
+
success: event.success,
|
|
1032
|
+
attempt: event.attempt,
|
|
1033
|
+
...finalError ? { finalError } : {},
|
|
1034
|
+
message: describeRetryEnd({
|
|
1035
|
+
success: event.success,
|
|
1036
|
+
attempt: event.attempt,
|
|
1037
|
+
finalError
|
|
1038
|
+
})
|
|
1039
|
+
},
|
|
1040
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
1041
|
+
});
|
|
957
1042
|
}
|
|
958
1043
|
case "tool_execution_start":
|
|
959
|
-
return {
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
970
|
-
}
|
|
971
|
-
],
|
|
972
|
-
diagnostics: []
|
|
973
|
-
};
|
|
1044
|
+
return singlePiEvent({
|
|
1045
|
+
type: "tool.call",
|
|
1046
|
+
turnId: state.currentTurnId ?? `turn-tool-${event.toolCallId}`,
|
|
1047
|
+
data: {
|
|
1048
|
+
toolCallId: event.toolCallId,
|
|
1049
|
+
name: event.toolName,
|
|
1050
|
+
arguments: event.args
|
|
1051
|
+
},
|
|
1052
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
1053
|
+
});
|
|
974
1054
|
case "tool_execution_update":
|
|
975
|
-
return {
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
timestamp: readSessionEventTimestamp(event)
|
|
982
|
-
}
|
|
983
|
-
],
|
|
984
|
-
diagnostics: []
|
|
985
|
-
};
|
|
1055
|
+
return singlePiEvent({
|
|
1056
|
+
type: "tool.update",
|
|
1057
|
+
turnId: state.currentTurnId ?? `turn-tool-${event.toolCallId}`,
|
|
1058
|
+
data: normalizePiEventData(event),
|
|
1059
|
+
timestamp: readSessionEventTimestamp(event)
|
|
1060
|
+
});
|
|
986
1061
|
case "tool_execution_end": {
|
|
987
1062
|
const turnId = state.currentTurnId ?? `turn-tool-${event.toolCallId}`;
|
|
988
1063
|
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
@@ -998,7 +1073,7 @@ function translateAgentSessionEventEnvelope(event, state) {
|
|
|
998
1073
|
timestamp
|
|
999
1074
|
};
|
|
1000
1075
|
if (!event.isError) {
|
|
1001
|
-
return
|
|
1076
|
+
return singlePiEvent(toolResultEvent);
|
|
1002
1077
|
}
|
|
1003
1078
|
return {
|
|
1004
1079
|
piEvents: [
|
|
@@ -1019,57 +1094,13 @@ function translateAgentSessionEventEnvelope(event, state) {
|
|
|
1019
1094
|
};
|
|
1020
1095
|
}
|
|
1021
1096
|
case "compaction_start":
|
|
1022
|
-
return {
|
|
1023
|
-
piEvents: [
|
|
1024
|
-
{
|
|
1025
|
-
type: "compaction.start",
|
|
1026
|
-
turnId: activeTurnId(state),
|
|
1027
|
-
data: normalizePiEventData(event),
|
|
1028
|
-
timestamp: readSessionEventTimestamp(event)
|
|
1029
|
-
}
|
|
1030
|
-
],
|
|
1031
|
-
diagnostics: []
|
|
1032
|
-
};
|
|
1033
1097
|
case "compaction_end":
|
|
1034
|
-
return {
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
timestamp: readSessionEventTimestamp(event)
|
|
1041
|
-
}
|
|
1042
|
-
],
|
|
1043
|
-
diagnostics: []
|
|
1044
|
-
};
|
|
1045
|
-
case "agent_start":
|
|
1046
|
-
return {
|
|
1047
|
-
piEvents: [],
|
|
1048
|
-
diagnostics: [
|
|
1049
|
-
buildKnownSessionGlobalDiagnostic(event, "pi.agent_start", "Pi agent run started")
|
|
1050
|
-
]
|
|
1051
|
-
};
|
|
1052
|
-
case "agent_end":
|
|
1053
|
-
return {
|
|
1054
|
-
piEvents: [],
|
|
1055
|
-
diagnostics: [
|
|
1056
|
-
buildKnownSessionGlobalDiagnostic(event, "pi.agent_end", "Pi agent run ended")
|
|
1057
|
-
]
|
|
1058
|
-
};
|
|
1059
|
-
case "agent_settled":
|
|
1060
|
-
return {
|
|
1061
|
-
piEvents: [],
|
|
1062
|
-
diagnostics: [
|
|
1063
|
-
buildKnownSessionGlobalDiagnostic(event, "pi.agent_settled", "Pi agent run settled")
|
|
1064
|
-
]
|
|
1065
|
-
};
|
|
1066
|
-
case "queue_update":
|
|
1067
|
-
return {
|
|
1068
|
-
piEvents: [],
|
|
1069
|
-
diagnostics: [
|
|
1070
|
-
buildKnownSessionGlobalDiagnostic(event, "pi.queue_update", "Pi session queue updated")
|
|
1071
|
-
]
|
|
1072
|
-
};
|
|
1098
|
+
return singlePiEvent({
|
|
1099
|
+
type: event.type === "compaction_start" ? "compaction.start" : "compaction.end",
|
|
1100
|
+
turnId: activeTurnId(state),
|
|
1101
|
+
data: normalizePiEventData(event),
|
|
1102
|
+
timestamp: readSessionEventTimestamp(event)
|
|
1103
|
+
});
|
|
1073
1104
|
default:
|
|
1074
1105
|
return {
|
|
1075
1106
|
piEvents: [],
|
|
@@ -1090,6 +1121,16 @@ var SdkPiTreeHandle = class {
|
|
|
1090
1121
|
loadedSkills: options.runDetails.loadedSkills.map((skill) => ({ ...skill })),
|
|
1091
1122
|
availableToolNames: [...options.runDetails.availableToolNames]
|
|
1092
1123
|
};
|
|
1124
|
+
this.releaseInspection = installPiInspection(
|
|
1125
|
+
session,
|
|
1126
|
+
(capture) => this.emitSubscribedEvent({
|
|
1127
|
+
type: "inspection",
|
|
1128
|
+
turnId: activeTurnId(this.eventState),
|
|
1129
|
+
timestamp: capture.timestamp,
|
|
1130
|
+
data: { capture }
|
|
1131
|
+
}),
|
|
1132
|
+
() => activeTurnId(this.eventState)
|
|
1133
|
+
);
|
|
1093
1134
|
}
|
|
1094
1135
|
session;
|
|
1095
1136
|
/** @internal */
|
|
@@ -1105,6 +1146,7 @@ var SdkPiTreeHandle = class {
|
|
|
1105
1146
|
continuationRetryAbortController = null;
|
|
1106
1147
|
availableToolNames;
|
|
1107
1148
|
runDetails;
|
|
1149
|
+
releaseInspection;
|
|
1108
1150
|
/** @internal */
|
|
1109
1151
|
getRunDetails() {
|
|
1110
1152
|
return {
|
|
@@ -1189,7 +1231,10 @@ var SdkPiTreeHandle = class {
|
|
|
1189
1231
|
const requestedActiveToolNames = options.activeTools !== void 0 ? [...options.activeTools] : [];
|
|
1190
1232
|
validateRequestedActiveTools(requestedActiveToolNames, this.availableToolNames);
|
|
1191
1233
|
const previousActiveToolNames = this.session.getActiveToolNames();
|
|
1192
|
-
const
|
|
1234
|
+
const needsFinishTurnHook = Boolean(
|
|
1235
|
+
options.terminalAcknowledgement || options.shouldStopAfterTurn
|
|
1236
|
+
);
|
|
1237
|
+
const needsRuntimeHooks = options.shouldBlockToolCall !== void 0 || needsFinishTurnHook;
|
|
1193
1238
|
if (customTools.length === 0 && !needsRuntimeHooks && previousActiveToolNames.length === requestedActiveToolNames.length && previousActiveToolNames.every(
|
|
1194
1239
|
(toolName, index) => toolName === requestedActiveToolNames[index]
|
|
1195
1240
|
)) {
|
|
@@ -1205,8 +1250,7 @@ var SdkPiTreeHandle = class {
|
|
|
1205
1250
|
const previousCustomTools = [...mutableSession._customTools];
|
|
1206
1251
|
const previousBeforeToolCall = mutableAgent.beforeToolCall;
|
|
1207
1252
|
const previousCreateLoopConfig = mutableAgent.createLoopConfig;
|
|
1208
|
-
|
|
1209
|
-
if (options.terminalAcknowledgement && typeof loopConfigHook !== "function") {
|
|
1253
|
+
if (needsFinishTurnHook && typeof previousCreateLoopConfig !== "function") {
|
|
1210
1254
|
throw new Error("Pi SDK version incompatible: agent loop configuration hook unavailable");
|
|
1211
1255
|
}
|
|
1212
1256
|
const terminalAcknowledgement = options.terminalAcknowledgement ? new TerminalAcknowledgementRuntime(
|
|
@@ -1235,26 +1279,27 @@ var SdkPiTreeHandle = class {
|
|
|
1235
1279
|
}
|
|
1236
1280
|
return await previousBeforeToolCall?.(context, signal);
|
|
1237
1281
|
};
|
|
1238
|
-
if (
|
|
1282
|
+
if (needsFinishTurnHook && typeof previousCreateLoopConfig === "function") {
|
|
1239
1283
|
mutableAgent.createLoopConfig = (loopOptions) => {
|
|
1240
|
-
const baseConfig =
|
|
1241
|
-
const
|
|
1284
|
+
const baseConfig = previousCreateLoopConfig.call(mutableAgent, loopOptions);
|
|
1285
|
+
const previousFinishTurn = baseConfig.finishTurn;
|
|
1242
1286
|
return {
|
|
1243
1287
|
...baseConfig,
|
|
1244
|
-
|
|
1245
|
-
const
|
|
1246
|
-
if (
|
|
1247
|
-
return
|
|
1248
|
-
|
|
1249
|
-
if (typeof previousShouldStop === "function") {
|
|
1250
|
-
return await previousShouldStop(...args);
|
|
1251
|
-
}
|
|
1252
|
-
return false;
|
|
1288
|
+
finishTurn: async (...args) => {
|
|
1289
|
+
const context = isObjectLike(args[0]) ? args[0] : null;
|
|
1290
|
+
if (options.shouldStopAfterTurn?.(context?.toolResults ?? []))
|
|
1291
|
+
return { action: "end" };
|
|
1292
|
+
return terminalAcknowledgement?.onTurnCompleted(args) ?? await previousFinishTurn?.(...args);
|
|
1253
1293
|
}
|
|
1254
1294
|
};
|
|
1255
1295
|
};
|
|
1256
1296
|
}
|
|
1257
1297
|
}
|
|
1298
|
+
const restoreStrictSchemas = installStrictOutcomeSchemas(
|
|
1299
|
+
this.session,
|
|
1300
|
+
customTools,
|
|
1301
|
+
(diagnostic) => this.emitSubscribedDiagnostic(diagnostic)
|
|
1302
|
+
);
|
|
1258
1303
|
try {
|
|
1259
1304
|
if (terminalAcknowledgement) {
|
|
1260
1305
|
await terminalAcknowledgement.run(run);
|
|
@@ -1262,6 +1307,7 @@ var SdkPiTreeHandle = class {
|
|
|
1262
1307
|
await run();
|
|
1263
1308
|
}
|
|
1264
1309
|
} finally {
|
|
1310
|
+
restoreStrictSchemas();
|
|
1265
1311
|
terminalAcknowledgement?.dispose();
|
|
1266
1312
|
mutableSession._customTools = previousCustomTools;
|
|
1267
1313
|
mutableAgent.beforeToolCall = previousBeforeToolCall;
|
|
@@ -1449,6 +1495,8 @@ var SdkPiTreeHandle = class {
|
|
|
1449
1495
|
});
|
|
1450
1496
|
}
|
|
1451
1497
|
branch.assertResult("continue", entryId, entryId);
|
|
1498
|
+
const timestamp = this.getEntry(entryId)?.timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
1499
|
+
this.emitEntryLink(entryId, timestamp, "user");
|
|
1452
1500
|
return entryId;
|
|
1453
1501
|
}
|
|
1454
1502
|
/** @internal */
|
|
@@ -1484,7 +1532,32 @@ var SdkPiTreeHandle = class {
|
|
|
1484
1532
|
}
|
|
1485
1533
|
this.sessionUnsubscribe = this.session.subscribe((event) => this.emitSessionEvent(event));
|
|
1486
1534
|
}
|
|
1535
|
+
emitEntryLink(entryId, timestamp, role) {
|
|
1536
|
+
const turnId = activeTurnId(this.eventState);
|
|
1537
|
+
this.emitSubscribedEvent({
|
|
1538
|
+
type: "inspection",
|
|
1539
|
+
turnId,
|
|
1540
|
+
timestamp,
|
|
1541
|
+
data: {
|
|
1542
|
+
capture: {
|
|
1543
|
+
version: 1,
|
|
1544
|
+
id: `entry:${entryId}`,
|
|
1545
|
+
timestamp,
|
|
1546
|
+
fact: { kind: "entry_link", entryId, piTurnId: turnId, role }
|
|
1547
|
+
}
|
|
1548
|
+
}
|
|
1549
|
+
});
|
|
1550
|
+
}
|
|
1487
1551
|
emitSessionEvent(event) {
|
|
1552
|
+
if (event.type === "entry_appended") {
|
|
1553
|
+
const entry = event.entry;
|
|
1554
|
+
this.emitEntryLink(
|
|
1555
|
+
entry.id,
|
|
1556
|
+
entry.timestamp,
|
|
1557
|
+
entry.type === "message" ? entry.message.role : entry.type
|
|
1558
|
+
);
|
|
1559
|
+
return;
|
|
1560
|
+
}
|
|
1488
1561
|
const translated = translateAgentSessionEventEnvelope(event, this.eventState);
|
|
1489
1562
|
for (const piEvent of translated.piEvents) this.emitSubscribedEvent(piEvent);
|
|
1490
1563
|
for (const diagnostic of translated.diagnostics) this.emitSubscribedDiagnostic(diagnostic);
|
|
@@ -1517,6 +1590,7 @@ var SdkPiTreeHandle = class {
|
|
|
1517
1590
|
}
|
|
1518
1591
|
/** @internal */
|
|
1519
1592
|
async close() {
|
|
1593
|
+
this.releaseInspection();
|
|
1520
1594
|
if (this.sessionUnsubscribe) {
|
|
1521
1595
|
this.sessionUnsubscribe();
|
|
1522
1596
|
this.sessionUnsubscribe = null;
|
|
@@ -1568,37 +1642,20 @@ function validateManagedLoadedResources(input) {
|
|
|
1568
1642
|
const skills = input.services.resourceLoader.getSkills().skills;
|
|
1569
1643
|
const prompts = input.services.resourceLoader.getPrompts().prompts;
|
|
1570
1644
|
const agentsFiles = input.services.resourceLoader.getAgentsFiles().agentsFiles;
|
|
1571
|
-
for (const
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
});
|
|
1586
|
-
}
|
|
1587
|
-
for (const prompt of prompts) {
|
|
1588
|
-
assertLoadedPathAllowed({
|
|
1589
|
-
path: prompt.filePath,
|
|
1590
|
-
agentDir: input.agentDir,
|
|
1591
|
-
workspaceRoot: input.workspaceRoot,
|
|
1592
|
-
kind: "prompt"
|
|
1593
|
-
});
|
|
1594
|
-
}
|
|
1595
|
-
for (const agentsFile of agentsFiles) {
|
|
1596
|
-
assertLoadedPathAllowed({
|
|
1597
|
-
path: agentsFile.path,
|
|
1598
|
-
agentDir: input.agentDir,
|
|
1599
|
-
workspaceRoot: input.workspaceRoot,
|
|
1600
|
-
kind: "context file"
|
|
1601
|
-
});
|
|
1645
|
+
for (const [kind, paths] of [
|
|
1646
|
+
["extension", extensions.map((extension) => extension.resolvedPath)],
|
|
1647
|
+
["skill", skills.map((skill) => skill.filePath)],
|
|
1648
|
+
["prompt", prompts.map((prompt) => prompt.filePath)],
|
|
1649
|
+
["context file", agentsFiles.map((file) => file.path)]
|
|
1650
|
+
]) {
|
|
1651
|
+
for (const loadedPath of paths) {
|
|
1652
|
+
assertLoadedPathAllowed({
|
|
1653
|
+
path: loadedPath,
|
|
1654
|
+
agentDir: input.agentDir,
|
|
1655
|
+
workspaceRoot: input.workspaceRoot,
|
|
1656
|
+
kind
|
|
1657
|
+
});
|
|
1658
|
+
}
|
|
1602
1659
|
}
|
|
1603
1660
|
const loadedResourceIds = [];
|
|
1604
1661
|
for (const resource of input.manifest.provenance) {
|
|
@@ -1755,14 +1812,7 @@ var SdkPiTreeHandleFactory = class {
|
|
|
1755
1812
|
agentDir: opts.agentDir,
|
|
1756
1813
|
workspaceRoot: opts.workspaceRoot
|
|
1757
1814
|
});
|
|
1758
|
-
const runDetails = toPiRunDetails(
|
|
1759
|
-
loadedAgentsFiles: services.resourceLoader.getAgentsFiles().agentsFiles,
|
|
1760
|
-
loadedSkills: services.resourceLoader.getSkills().skills.map((skill) => ({
|
|
1761
|
-
name: skill.name,
|
|
1762
|
-
path: skill.filePath
|
|
1763
|
-
})),
|
|
1764
|
-
availableToolNames: opts.piConfig?.availableToolNames ?? []
|
|
1765
|
-
});
|
|
1815
|
+
const runDetails = toPiRunDetails(services, opts.piConfig?.availableToolNames ?? []);
|
|
1766
1816
|
this.preparedServices.set(managedServicesKey(opts.agentDir, opts.sessionCwd), services);
|
|
1767
1817
|
return {
|
|
1768
1818
|
loadedResourceIds,
|
|
@@ -1825,14 +1875,7 @@ var SdkPiTreeHandleFactory = class {
|
|
|
1825
1875
|
noTools: "builtin"
|
|
1826
1876
|
});
|
|
1827
1877
|
getMutableSession(session)._refreshToolRegistry({ activeToolNames: [] });
|
|
1828
|
-
const runDetails = toPiRunDetails(
|
|
1829
|
-
loadedAgentsFiles: services.resourceLoader.getAgentsFiles().agentsFiles,
|
|
1830
|
-
loadedSkills: services.resourceLoader.getSkills().skills.map((skill) => ({
|
|
1831
|
-
name: skill.name,
|
|
1832
|
-
path: skill.filePath
|
|
1833
|
-
})),
|
|
1834
|
-
availableToolNames
|
|
1835
|
-
});
|
|
1878
|
+
const runDetails = toPiRunDetails(services, availableToolNames);
|
|
1836
1879
|
return new SdkPiTreeHandle(session, {
|
|
1837
1880
|
treeFile: opts.treeFile,
|
|
1838
1881
|
isResumed: opts.resume,
|
|
@@ -1843,7 +1886,7 @@ var SdkPiTreeHandleFactory = class {
|
|
|
1843
1886
|
};
|
|
1844
1887
|
|
|
1845
1888
|
// src/pi-resource-bundle.ts
|
|
1846
|
-
import { randomUUID } from "crypto";
|
|
1889
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
1847
1890
|
import { mkdir as mkdir2, open, readFile, rename, rm, writeFile as writeFile2 } from "fs/promises";
|
|
1848
1891
|
import path3 from "path";
|
|
1849
1892
|
import {
|
|
@@ -1860,7 +1903,7 @@ function requireStorageName(value, label) {
|
|
|
1860
1903
|
return value;
|
|
1861
1904
|
}
|
|
1862
1905
|
async function atomicWrite(pathname, content, mode) {
|
|
1863
|
-
const staging = `${pathname}.staging-${process.pid}-${
|
|
1906
|
+
const staging = `${pathname}.staging-${process.pid}-${randomUUID2()}`;
|
|
1864
1907
|
const handle = await open(staging, "wx", mode);
|
|
1865
1908
|
try {
|
|
1866
1909
|
await handle.writeFile(content);
|
|
@@ -1940,7 +1983,7 @@ async function materializeCanonicalPiResourceBundle(input) {
|
|
|
1940
1983
|
}
|
|
1941
1984
|
const staging = path3.join(
|
|
1942
1985
|
parent,
|
|
1943
|
-
`.${path3.basename(targetDir)}.staging-${process.pid}-${
|
|
1986
|
+
`.${path3.basename(targetDir)}.staging-${process.pid}-${randomUUID2()}`
|
|
1944
1987
|
);
|
|
1945
1988
|
try {
|
|
1946
1989
|
await mkdir2(staging, { mode: 448 });
|
|
@@ -1965,6 +2008,9 @@ async function materializeCanonicalPiResourceBundle(input) {
|
|
|
1965
2008
|
}
|
|
1966
2009
|
}
|
|
1967
2010
|
|
|
2011
|
+
// src/runtime/index.ts
|
|
2012
|
+
import { redactInspectionEvidence } from "@leitwerk-dev/domain";
|
|
2013
|
+
|
|
1968
2014
|
// src/development-tool-environment.ts
|
|
1969
2015
|
import { statfsSync } from "fs";
|
|
1970
2016
|
import { mkdir as mkdir3, rename as rename2, writeFile as writeFile3 } from "fs/promises";
|
|
@@ -2123,6 +2169,7 @@ async function runCommand(input) {
|
|
|
2123
2169
|
input.signal?.addEventListener("abort", killGroup, { once: true });
|
|
2124
2170
|
try {
|
|
2125
2171
|
const result = await child;
|
|
2172
|
+
if (input.signal?.aborted || result.isCanceled || result.timedOut) killGroup();
|
|
2126
2173
|
const diagnostics = `${stdout}
|
|
2127
2174
|
${stderr}`.trim();
|
|
2128
2175
|
if (input.signal?.aborted || result.isCanceled) {
|
|
@@ -2569,6 +2616,12 @@ function createPiEventReporter(options) {
|
|
|
2569
2616
|
return {
|
|
2570
2617
|
attach(piHandle) {
|
|
2571
2618
|
piHandle.subscribe((event) => {
|
|
2619
|
+
if (event.type === "inspection") {
|
|
2620
|
+
const turnRecordId = options.getCurrentTurnRecordId?.();
|
|
2621
|
+
if (turnRecordId && !options.getSessionTainted?.())
|
|
2622
|
+
options.reportInspection?.(event.data.capture, turnRecordId);
|
|
2623
|
+
return;
|
|
2624
|
+
}
|
|
2572
2625
|
if (event.type === "turn.start") {
|
|
2573
2626
|
options.onLifecycleObservation?.("pi_turn_started");
|
|
2574
2627
|
resetPiRetryState();
|
|
@@ -2702,7 +2755,7 @@ async function restoreHandleAfterTurn(piHandle, plan) {
|
|
|
2702
2755
|
}
|
|
2703
2756
|
|
|
2704
2757
|
// src/worker-ipc-reporter.ts
|
|
2705
|
-
import { randomUUID as
|
|
2758
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
2706
2759
|
import { createIpcMessage } from "@leitwerk-dev/worker-protocol";
|
|
2707
2760
|
|
|
2708
2761
|
// src/diagnostics.ts
|
|
@@ -2774,7 +2827,7 @@ function createWorkerIpcReporter(options) {
|
|
|
2774
2827
|
options.send(
|
|
2775
2828
|
createIpcMessage({
|
|
2776
2829
|
type: fact.type,
|
|
2777
|
-
messageId:
|
|
2830
|
+
messageId: randomUUID3(),
|
|
2778
2831
|
instanceId: options.instanceId,
|
|
2779
2832
|
workerId: options.workerId,
|
|
2780
2833
|
sentAt: options.now().toISOString(),
|
|
@@ -2808,888 +2861,1060 @@ function createWorkerIpcReporter(options) {
|
|
|
2808
2861
|
};
|
|
2809
2862
|
}
|
|
2810
2863
|
|
|
2811
|
-
// src/
|
|
2812
|
-
import
|
|
2813
|
-
import path9 from "path";
|
|
2864
|
+
// src/workspace/checkout-tool.ts
|
|
2865
|
+
import path6 from "path";
|
|
2814
2866
|
|
|
2815
|
-
// src/
|
|
2816
|
-
import
|
|
2817
|
-
import {
|
|
2818
|
-
|
|
2819
|
-
|
|
2820
|
-
import
|
|
2821
|
-
|
|
2822
|
-
|
|
2823
|
-
|
|
2824
|
-
|
|
2825
|
-
|
|
2826
|
-
|
|
2827
|
-
|
|
2828
|
-
|
|
2829
|
-
|
|
2830
|
-
|
|
2831
|
-
|
|
2832
|
-
|
|
2833
|
-
|
|
2834
|
-
|
|
2835
|
-
|
|
2836
|
-
|
|
2837
|
-
|
|
2838
|
-
|
|
2839
|
-
|
|
2840
|
-
|
|
2867
|
+
// src/workspace/run-root.ts
|
|
2868
|
+
import path5 from "path";
|
|
2869
|
+
import { isPathInside } from "@leitwerk-dev/process-sdk";
|
|
2870
|
+
|
|
2871
|
+
// src/workspace/manifest.ts
|
|
2872
|
+
import * as v from "valibot";
|
|
2873
|
+
function serializeManifest(manifest) {
|
|
2874
|
+
return JSON.stringify(manifest, null, 2);
|
|
2875
|
+
}
|
|
2876
|
+
var jsonObjectSchema = v.custom(
|
|
2877
|
+
(value) => typeof value === "object" && value !== null && !Array.isArray(value),
|
|
2878
|
+
"Expected object"
|
|
2879
|
+
);
|
|
2880
|
+
var componentManifestEntrySchema = v.pipe(
|
|
2881
|
+
jsonObjectSchema,
|
|
2882
|
+
v.object({
|
|
2883
|
+
key: v.string(),
|
|
2884
|
+
repoLocator: v.string(),
|
|
2885
|
+
baseBranch: v.string(),
|
|
2886
|
+
workBranch: v.string(),
|
|
2887
|
+
clonedAt: v.string(),
|
|
2888
|
+
headSha: v.string(),
|
|
2889
|
+
revision: v.optional(v.string())
|
|
2890
|
+
})
|
|
2891
|
+
);
|
|
2892
|
+
var componentManifestSchema = v.pipe(
|
|
2893
|
+
jsonObjectSchema,
|
|
2894
|
+
v.object({
|
|
2895
|
+
version: v.literal(1),
|
|
2896
|
+
instanceId: v.pipe(v.string(), v.minLength(1)),
|
|
2897
|
+
createdAt: v.pipe(v.string(), v.minLength(1)),
|
|
2898
|
+
components: v.array(componentManifestEntrySchema)
|
|
2899
|
+
})
|
|
2900
|
+
);
|
|
2901
|
+
var componentManifestJsonSchema = v.pipe(v.string(), v.parseJson(), componentManifestSchema);
|
|
2902
|
+
function formatManifestValidationError(issues) {
|
|
2903
|
+
const issue = issues[0];
|
|
2904
|
+
if (issue?.type === "parse_json") return "Invalid JSON";
|
|
2905
|
+
const path15 = issue ? v.getDotPath(issue) : null;
|
|
2906
|
+
if (!path15) return "Manifest must be a JSON object";
|
|
2907
|
+
if (path15 === "version") return "Unsupported manifest version";
|
|
2908
|
+
if (path15 === "instanceId") return "Invalid instanceId";
|
|
2909
|
+
if (path15 === "createdAt") return "Invalid createdAt";
|
|
2910
|
+
if (path15 === "components") return "components must be an array";
|
|
2911
|
+
if (path15.match(/^components\.\d+$/)) return "Invalid component entry";
|
|
2912
|
+
const componentField = path15.match(/^components\.\d+\.([^.]*)$/)?.[1];
|
|
2913
|
+
if (componentField) return `Invalid component field: ${componentField}`;
|
|
2914
|
+
return issue?.message ? `Invalid manifest: ${issue.message}` : "Invalid manifest";
|
|
2915
|
+
}
|
|
2916
|
+
function deserializeManifest(content) {
|
|
2917
|
+
const result = v.safeParse(componentManifestJsonSchema, content, { abortEarly: true });
|
|
2918
|
+
if (!result.success) {
|
|
2919
|
+
return { ok: false, error: formatManifestValidationError(result.issues) };
|
|
2920
|
+
}
|
|
2921
|
+
return { ok: true, manifest: result.output };
|
|
2922
|
+
}
|
|
2923
|
+
function diffManifest(existing, serverProjects) {
|
|
2924
|
+
const stale = [];
|
|
2925
|
+
const missing = [];
|
|
2926
|
+
const extra = [];
|
|
2927
|
+
const unchanged = [];
|
|
2928
|
+
const byKey = new Map(existing.components.map((c) => [c.key, c]));
|
|
2929
|
+
const serverByKey = new Map(serverProjects.map((p) => [p.key, p]));
|
|
2930
|
+
for (const p of serverProjects) {
|
|
2931
|
+
const m = byKey.get(p.key);
|
|
2932
|
+
if (!m) {
|
|
2933
|
+
missing.push(p.key);
|
|
2934
|
+
continue;
|
|
2841
2935
|
}
|
|
2842
|
-
|
|
2843
|
-
|
|
2844
|
-
|
|
2845
|
-
|
|
2846
|
-
writeFileSync(`${this.#directory}/auth/config.json`, JSON.stringify({ auths }), {
|
|
2847
|
-
mode: 384,
|
|
2848
|
-
flag: "wx"
|
|
2849
|
-
});
|
|
2850
|
-
this.#previousConfig = process.env.DOCKER_CONFIG;
|
|
2851
|
-
process.env.DOCKER_CONFIG = `${this.#directory}/auth`;
|
|
2852
|
-
if (!process.env.BUILDX_CONFIG) {
|
|
2853
|
-
mkdirSync(`${this.#directory}/buildx`, { mode: 448 });
|
|
2854
|
-
process.env.BUILDX_CONFIG = `${this.#directory}/buildx`;
|
|
2855
|
-
}
|
|
2856
|
-
process.once("exit", this.#onExit);
|
|
2857
|
-
} catch {
|
|
2858
|
-
this.dispose();
|
|
2859
|
-
throw new Error("Cannot materialize private Docker credentials");
|
|
2936
|
+
if (m.repoLocator === p.repoLocator && m.baseBranch === p.baseBranch && m.workBranch === p.workBranch) {
|
|
2937
|
+
unchanged.push(p.key);
|
|
2938
|
+
} else {
|
|
2939
|
+
stale.push(p.key);
|
|
2860
2940
|
}
|
|
2861
2941
|
}
|
|
2862
|
-
|
|
2863
|
-
|
|
2864
|
-
|
|
2865
|
-
if (process.env.BUILDX_CONFIG === `${this.#directory}/buildx`) delete process.env.BUILDX_CONFIG;
|
|
2866
|
-
if (process.env.DOCKER_CONFIG === `${this.#directory}/auth`) {
|
|
2867
|
-
if (this.#previousConfig === void 0) delete process.env.DOCKER_CONFIG;
|
|
2868
|
-
else process.env.DOCKER_CONFIG = this.#previousConfig;
|
|
2942
|
+
for (const c of existing.components) {
|
|
2943
|
+
if (!serverByKey.has(c.key)) {
|
|
2944
|
+
extra.push(c.key);
|
|
2869
2945
|
}
|
|
2870
|
-
rmSync(this.#directory, { recursive: true, force: true });
|
|
2871
|
-
this.#directory = void 0;
|
|
2872
|
-
this.#previousConfig = void 0;
|
|
2873
2946
|
}
|
|
2874
|
-
};
|
|
2875
|
-
|
|
2876
|
-
// src/worker-start-payload.ts
|
|
2877
|
-
function isLlmWorkerStartPayload(payload) {
|
|
2878
|
-
return payload.bootstrap.kind === "llm";
|
|
2947
|
+
return { stale, missing, extra, unchanged };
|
|
2879
2948
|
}
|
|
2880
2949
|
|
|
2881
|
-
// src/
|
|
2882
|
-
|
|
2883
|
-
|
|
2884
|
-
|
|
2885
|
-
} from "@leitwerk-dev/domain";
|
|
2886
|
-
import { repositoryHttpsUrl } from "@leitwerk-dev/process-sdk";
|
|
2887
|
-
import { createTemplateContext, resolveProcessPiConfig } from "@leitwerk-dev/process-sdk/pi-config";
|
|
2888
|
-
|
|
2889
|
-
// src/managed-pi-agent-dir.ts
|
|
2890
|
-
import { randomUUID as randomUUID3 } from "crypto";
|
|
2891
|
-
import { chmod, lstat, mkdir as mkdir4, rename as rename3, writeFile as writeFile4 } from "fs/promises";
|
|
2892
|
-
import { homedir } from "os";
|
|
2893
|
-
import path5 from "path";
|
|
2894
|
-
function safeSegment(value, name) {
|
|
2895
|
-
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(value)) {
|
|
2896
|
-
throw new Error(`Invalid managed Pi ${name}`);
|
|
2897
|
-
}
|
|
2898
|
-
return value;
|
|
2899
|
-
}
|
|
2900
|
-
function resolveManagedPiAgentDir(input) {
|
|
2901
|
-
const root = path5.resolve(input.agentDirRoot);
|
|
2902
|
-
const ambient = path5.resolve(homedir(), ".pi", "agent");
|
|
2903
|
-
if (root === ambient)
|
|
2904
|
-
throw new Error("Managed Pi agent directory must not be ambient ~/.pi/agent");
|
|
2905
|
-
return path5.join(
|
|
2906
|
-
root,
|
|
2907
|
-
safeSegment(input.instanceId, "instance id"),
|
|
2908
|
-
safeSegment(input.startOrLeaseId, "start id")
|
|
2909
|
-
);
|
|
2950
|
+
// src/workspace/resource-aggregator.ts
|
|
2951
|
+
function formatProvenanceMarker(componentKey, filePath) {
|
|
2952
|
+
const normalizedPath = filePath.replace(/\\/g, "/");
|
|
2953
|
+
return `<!-- source: ${componentKey}/${normalizedPath} -->`;
|
|
2910
2954
|
}
|
|
2911
|
-
function
|
|
2912
|
-
|
|
2913
|
-
|
|
2955
|
+
function aggregateAgentsMd(sources) {
|
|
2956
|
+
const sorted = [...sources].sort((a, b) => a.componentKey.localeCompare(b.componentKey));
|
|
2957
|
+
if (sorted.length === 0) {
|
|
2958
|
+
return "";
|
|
2914
2959
|
}
|
|
2915
|
-
const
|
|
2916
|
-
|
|
2917
|
-
|
|
2960
|
+
const parts = [];
|
|
2961
|
+
for (const s of sorted) {
|
|
2962
|
+
parts.push(formatProvenanceMarker(s.componentKey, s.filePath));
|
|
2963
|
+
parts.push(s.content.trimEnd());
|
|
2918
2964
|
}
|
|
2919
|
-
return
|
|
2965
|
+
return `${parts.join("\n\n").trimEnd()}
|
|
2966
|
+
`;
|
|
2920
2967
|
}
|
|
2921
|
-
|
|
2922
|
-
|
|
2923
|
-
for (const
|
|
2924
|
-
|
|
2925
|
-
|
|
2926
|
-
|
|
2927
|
-
throw new Error(`Credential parent is a symlink: ${current}`);
|
|
2928
|
-
} catch (error) {
|
|
2929
|
-
if (error.code !== "ENOENT") throw error;
|
|
2930
|
-
await mkdir4(current, { recursive: false, mode: 448 });
|
|
2968
|
+
function collectSkills(sources) {
|
|
2969
|
+
const out = /* @__PURE__ */ new Map();
|
|
2970
|
+
for (const { skillId, componentKey, content } of sources) {
|
|
2971
|
+
const winner = out.get(skillId);
|
|
2972
|
+
if (!winner || componentKey.localeCompare(winner.source) < 0) {
|
|
2973
|
+
out.set(skillId, { content, source: componentKey });
|
|
2931
2974
|
}
|
|
2932
2975
|
}
|
|
2976
|
+
return out;
|
|
2933
2977
|
}
|
|
2934
|
-
|
|
2935
|
-
|
|
2936
|
-
|
|
2937
|
-
|
|
2978
|
+
|
|
2979
|
+
// src/workspace/run-root.ts
|
|
2980
|
+
var RunRootPreparationError = class extends Error {
|
|
2981
|
+
errors;
|
|
2982
|
+
constructor(errors) {
|
|
2983
|
+
super(`Workspace preparation failed: ${errors.join("; ")}`);
|
|
2984
|
+
this.name = "RunRootPreparationError";
|
|
2985
|
+
this.errors = [...errors];
|
|
2938
2986
|
}
|
|
2939
|
-
|
|
2940
|
-
|
|
2941
|
-
|
|
2942
|
-
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
|
|
2947
|
-
|
|
2948
|
-
|
|
2949
|
-
|
|
2950
|
-
`.${path5.basename(target)}.tmp-${process.pid}-${randomUUID3()}`
|
|
2951
|
-
);
|
|
2952
|
-
await writeFile4(tmp, file.content, { mode: 384, flag: "wx" });
|
|
2953
|
-
await chmod(tmp, 384);
|
|
2954
|
-
await rename3(tmp, target);
|
|
2955
|
-
await chmod(target, 384);
|
|
2987
|
+
};
|
|
2988
|
+
var MANIFEST_REL = path5.join(".leitwerk", "components.json");
|
|
2989
|
+
var AGGREGATED_AGENTS_REL2 = "AGENTS.md";
|
|
2990
|
+
var SKILLS_DIR_REL = path5.join(".leitwerk", "skills");
|
|
2991
|
+
var SKILL_GLOB = "**/.cursor/skills/**/SKILL.md";
|
|
2992
|
+
var AGENTS_GLOB = "**/AGENTS.md";
|
|
2993
|
+
function componentDir(workspaceRoot, childPath) {
|
|
2994
|
+
const root = path5.resolve(workspaceRoot);
|
|
2995
|
+
const target = path5.resolve(root, childPath);
|
|
2996
|
+
if (!isPathInside(root, target)) {
|
|
2997
|
+
throw new Error(`Component key '${childPath}' resolves outside workspace root '${root}'`);
|
|
2956
2998
|
}
|
|
2999
|
+
return target;
|
|
2957
3000
|
}
|
|
2958
|
-
|
|
2959
|
-
|
|
2960
|
-
|
|
2961
|
-
|
|
2962
|
-
import {
|
|
2963
|
-
canonicalJsonEqual,
|
|
2964
|
-
IPC_PROTOCOL_VERSION,
|
|
2965
|
-
parsePiResourceManifest,
|
|
2966
|
-
WORKER_API_VERSION
|
|
2967
|
-
} from "@leitwerk-dev/worker-protocol";
|
|
2968
|
-
function fail2(message) {
|
|
2969
|
-
throw new Error(`Invalid managed Pi resource snapshot: ${message}`);
|
|
3001
|
+
function skillIdFromSkillPath(filePath) {
|
|
3002
|
+
const normalized = filePath.replace(/\\/g, "/");
|
|
3003
|
+
const m = normalized.match(/\.cursor\/skills\/([^/]+)\/SKILL\.md$/);
|
|
3004
|
+
return m?.[1] ?? null;
|
|
2970
3005
|
}
|
|
2971
|
-
function
|
|
2972
|
-
|
|
2973
|
-
|
|
2974
|
-
|
|
2975
|
-
|
|
3006
|
+
function planRunRoot(workspaceRoot, instanceId, projectSnapshots) {
|
|
3007
|
+
return {
|
|
3008
|
+
workspaceRoot,
|
|
3009
|
+
instanceId,
|
|
3010
|
+
components: projectSnapshots.map((p) => ({ ...p }))
|
|
3011
|
+
};
|
|
2976
3012
|
}
|
|
2977
|
-
function
|
|
2978
|
-
|
|
2979
|
-
|
|
3013
|
+
async function materializeComponentEntry(plan, comp, git) {
|
|
3014
|
+
const dir = componentDir(plan.workspaceRoot, comp.key);
|
|
3015
|
+
await git.clone(comp.repoLocator, dir);
|
|
3016
|
+
await git.checkout(dir, comp.baseBranch);
|
|
3017
|
+
if (!await git.branchExists(dir, comp.workBranch)) {
|
|
3018
|
+
await git.createBranch(dir, comp.workBranch, comp.baseBranch);
|
|
2980
3019
|
}
|
|
3020
|
+
await git.checkout(dir, comp.workBranch);
|
|
3021
|
+
return {
|
|
3022
|
+
key: comp.key,
|
|
3023
|
+
repoLocator: comp.repoLocator,
|
|
3024
|
+
baseBranch: comp.baseBranch,
|
|
3025
|
+
workBranch: comp.workBranch,
|
|
3026
|
+
clonedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3027
|
+
headSha: await git.getHeadSha(dir)
|
|
3028
|
+
};
|
|
2981
3029
|
}
|
|
2982
|
-
function
|
|
2983
|
-
|
|
2984
|
-
|
|
2985
|
-
|
|
2986
|
-
|
|
2987
|
-
)
|
|
3030
|
+
async function collectMaterializedEntries(plan, git, errors, reusable = /* @__PURE__ */ new Map()) {
|
|
3031
|
+
const entries = [];
|
|
3032
|
+
for (const comp of plan.components) {
|
|
3033
|
+
try {
|
|
3034
|
+
const retained = reusable.get(comp.key);
|
|
3035
|
+
if (retained?.revision) {
|
|
3036
|
+
if (!git.checkoutRevision) throw new Error("Pinned repository checkout is unavailable");
|
|
3037
|
+
const dir = componentDir(plan.workspaceRoot, comp.key);
|
|
3038
|
+
await git.checkoutRevision(dir, retained.revision);
|
|
3039
|
+
if ((await git.getHeadSha(dir)).toLowerCase() !== retained.revision.toLowerCase())
|
|
3040
|
+
throw new Error("Recovered checkout HEAD does not match captured commit");
|
|
3041
|
+
}
|
|
3042
|
+
entries.push(retained ?? await materializeComponentEntry(plan, comp, git));
|
|
3043
|
+
} catch (e) {
|
|
3044
|
+
errors.push(`${comp.key}: ${e instanceof Error ? e.message : String(e)}`);
|
|
2988
3045
|
}
|
|
2989
3046
|
}
|
|
3047
|
+
return entries;
|
|
2990
3048
|
}
|
|
2991
|
-
async function
|
|
2992
|
-
const
|
|
2993
|
-
|
|
2994
|
-
|
|
2995
|
-
|
|
2996
|
-
);
|
|
2997
|
-
|
|
2998
|
-
|
|
2999
|
-
|
|
3000
|
-
|
|
3001
|
-
|
|
3002
|
-
|
|
3003
|
-
|
|
3004
|
-
|
|
3005
|
-
|
|
3006
|
-
|
|
3049
|
+
async function gatherAgentsAndSkills(plan, git) {
|
|
3050
|
+
const agentSources = [];
|
|
3051
|
+
const skillSources = [];
|
|
3052
|
+
const aggregatedAgentsMdSources = [];
|
|
3053
|
+
for (const comp of plan.components) {
|
|
3054
|
+
const root = componentDir(plan.workspaceRoot, comp.key);
|
|
3055
|
+
const agentPaths = await git.listFiles(root, AGENTS_GLOB);
|
|
3056
|
+
const sortedAgentPaths = [...agentPaths].sort((a, b) => a.localeCompare(b));
|
|
3057
|
+
for (const p of sortedAgentPaths) {
|
|
3058
|
+
const content = await git.readFile(root, p);
|
|
3059
|
+
if (content !== null) {
|
|
3060
|
+
agentSources.push({
|
|
3061
|
+
componentKey: comp.key,
|
|
3062
|
+
filePath: p,
|
|
3063
|
+
content
|
|
3064
|
+
});
|
|
3065
|
+
aggregatedAgentsMdSources.push(`${comp.key}/${p}`);
|
|
3066
|
+
}
|
|
3067
|
+
}
|
|
3068
|
+
const skillPaths = await git.listFiles(root, SKILL_GLOB);
|
|
3069
|
+
for (const p of skillPaths) {
|
|
3070
|
+
const skillId = skillIdFromSkillPath(p);
|
|
3071
|
+
if (!skillId) {
|
|
3072
|
+
continue;
|
|
3073
|
+
}
|
|
3074
|
+
const content = await git.readFile(root, p);
|
|
3075
|
+
if (content !== null) {
|
|
3076
|
+
skillSources.push({ componentKey: comp.key, skillId, content });
|
|
3077
|
+
}
|
|
3078
|
+
}
|
|
3007
3079
|
}
|
|
3080
|
+
const agentsMd = aggregateAgentsMd(agentSources);
|
|
3081
|
+
const skillsMap = collectSkills(skillSources);
|
|
3082
|
+
aggregatedAgentsMdSources.sort((a, b) => a.localeCompare(b));
|
|
3083
|
+
return { aggregatedAgentsMdSources, agentsMd, skillsMap };
|
|
3008
3084
|
}
|
|
3009
|
-
async function
|
|
3010
|
-
const
|
|
3011
|
-
|
|
3012
|
-
|
|
3013
|
-
|
|
3085
|
+
async function writeAggregatedArtifacts(plan, git, manifest, agentsMd, skillsMap) {
|
|
3086
|
+
const root = plan.workspaceRoot;
|
|
3087
|
+
await git.writeFile(root, MANIFEST_REL, serializeManifest(manifest));
|
|
3088
|
+
await git.writeFile(root, AGGREGATED_AGENTS_REL2, agentsMd);
|
|
3089
|
+
for (const [skillId, { content }] of skillsMap) {
|
|
3090
|
+
const rel = path5.join(SKILLS_DIR_REL, `${skillId}.md`);
|
|
3091
|
+
await git.writeFile(root, rel, content);
|
|
3014
3092
|
}
|
|
3015
|
-
|
|
3093
|
+
}
|
|
3094
|
+
async function finalizeRunRoot(plan, git, entries, errors) {
|
|
3095
|
+
const manifest = {
|
|
3096
|
+
version: 1,
|
|
3097
|
+
instanceId: plan.instanceId,
|
|
3098
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3099
|
+
components: entries
|
|
3100
|
+
};
|
|
3101
|
+
const { aggregatedAgentsMdSources, agentsMd, skillsMap } = await gatherAgentsAndSkills(plan, git);
|
|
3102
|
+
const loadedSkills = [...skillsMap.keys()].sort((a, b) => a.localeCompare(b));
|
|
3016
3103
|
try {
|
|
3017
|
-
|
|
3018
|
-
} catch (
|
|
3019
|
-
|
|
3020
|
-
cause: error
|
|
3021
|
-
});
|
|
3104
|
+
await writeAggregatedArtifacts(plan, git, manifest, agentsMd, skillsMap);
|
|
3105
|
+
} catch (e) {
|
|
3106
|
+
errors.push(`write: ${e instanceof Error ? e.message : String(e)}`);
|
|
3022
3107
|
}
|
|
3023
|
-
const
|
|
3024
|
-
|
|
3025
|
-
|
|
3026
|
-
|
|
3027
|
-
assertJsonEqual(
|
|
3028
|
-
manifest.providerWorkerConfig,
|
|
3029
|
-
input.start.providerWorkerConfig,
|
|
3030
|
-
"providerWorkerConfig"
|
|
3031
|
-
);
|
|
3032
|
-
let settings;
|
|
3033
|
-
try {
|
|
3034
|
-
settings = JSON.parse(await readFile2(path6.join(input.agentDir, "settings.json"), "utf8"));
|
|
3035
|
-
} catch (error) {
|
|
3036
|
-
throw new Error("Invalid managed Pi resource snapshot: settings.json is unreadable", {
|
|
3037
|
-
cause: error
|
|
3038
|
-
});
|
|
3108
|
+
const expectedKeys = new Set(plan.components.map((component) => component.key));
|
|
3109
|
+
const hasAllExpectedEntries = entries.length === expectedKeys.size && [...expectedKeys].every((key) => entries.some((entry) => entry.key === key));
|
|
3110
|
+
if (errors.length > 0 || !hasAllExpectedEntries) {
|
|
3111
|
+
throw new RunRootPreparationError(errors);
|
|
3039
3112
|
}
|
|
3040
|
-
|
|
3041
|
-
|
|
3042
|
-
|
|
3043
|
-
|
|
3044
|
-
|
|
3045
|
-
return manifest;
|
|
3113
|
+
return {
|
|
3114
|
+
manifest,
|
|
3115
|
+
aggregatedAgentsMdSources,
|
|
3116
|
+
loadedSkills
|
|
3117
|
+
};
|
|
3046
3118
|
}
|
|
3047
|
-
function
|
|
3048
|
-
|
|
3049
|
-
|
|
3050
|
-
|
|
3051
|
-
|
|
3052
|
-
|
|
3053
|
-
|
|
3054
|
-
|
|
3055
|
-
if (
|
|
3056
|
-
throw new Error(
|
|
3057
|
-
|
|
3058
|
-
|
|
3059
|
-
|
|
3060
|
-
|
|
3061
|
-
|
|
3062
|
-
|
|
3063
|
-
|
|
3064
|
-
|
|
3065
|
-
|
|
3066
|
-
|
|
3067
|
-
|
|
3068
|
-
|
|
3069
|
-
|
|
3070
|
-
|
|
3071
|
-
|
|
3072
|
-
|
|
3073
|
-
|
|
3074
|
-
|
|
3119
|
+
async function materializeRunRoot(plan, git) {
|
|
3120
|
+
const errors = [];
|
|
3121
|
+
const entries = await collectMaterializedEntries(plan, git, errors);
|
|
3122
|
+
return finalizeRunRoot(plan, git, entries, errors);
|
|
3123
|
+
}
|
|
3124
|
+
async function prepareOnDemandRunRoot(plan, git, projectKey, revision) {
|
|
3125
|
+
if (revision !== void 0 && (!projectKey || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(revision)))
|
|
3126
|
+
throw new Error("Use a captured full commit SHA");
|
|
3127
|
+
if (projectKey !== void 0 && !plan.components.some((component) => component.key === projectKey))
|
|
3128
|
+
throw new Error("Repository is outside this process's authorized scope");
|
|
3129
|
+
const validation = await validateRunRoot(plan.workspaceRoot, plan.components, git);
|
|
3130
|
+
const existingKeys = new Set(
|
|
3131
|
+
validation.existingManifest?.components.map((component) => component.key) ?? []
|
|
3132
|
+
);
|
|
3133
|
+
const selected = {
|
|
3134
|
+
...plan,
|
|
3135
|
+
components: plan.components.filter(
|
|
3136
|
+
(component) => existingKeys.has(component.key) || component.key === projectKey
|
|
3137
|
+
)
|
|
3138
|
+
};
|
|
3139
|
+
const result = await repairRunRoot(validation, selected, git);
|
|
3140
|
+
if (revision !== void 0) {
|
|
3141
|
+
if (!git.checkoutRevision) throw new Error("Pinned repository checkout is unavailable");
|
|
3142
|
+
const dir = componentDir(plan.workspaceRoot, projectKey);
|
|
3143
|
+
await git.checkoutRevision(dir, revision);
|
|
3144
|
+
const headSha = await git.getHeadSha(dir);
|
|
3145
|
+
if (headSha.toLowerCase() !== revision.toLowerCase())
|
|
3146
|
+
throw new Error("Checkout HEAD does not match captured commit");
|
|
3147
|
+
return finalizeRunRoot(
|
|
3148
|
+
selected,
|
|
3149
|
+
git,
|
|
3150
|
+
result.manifest.components.map(
|
|
3151
|
+
(entry) => entry.key === projectKey ? { ...entry, headSha, revision } : entry
|
|
3152
|
+
),
|
|
3153
|
+
[]
|
|
3075
3154
|
);
|
|
3076
3155
|
}
|
|
3077
|
-
return
|
|
3078
|
-
path: credentialPath,
|
|
3079
|
-
content: `${JSON.stringify(credentialPath === "auth.json" ? auth : values, null, 2)}
|
|
3080
|
-
`
|
|
3081
|
-
}));
|
|
3156
|
+
return result;
|
|
3082
3157
|
}
|
|
3083
|
-
async function
|
|
3084
|
-
|
|
3085
|
-
|
|
3086
|
-
|
|
3087
|
-
|
|
3088
|
-
|
|
3089
|
-
|
|
3090
|
-
|
|
3091
|
-
|
|
3092
|
-
|
|
3158
|
+
async function validateRunRoot(workspaceRoot, serverProjects, git) {
|
|
3159
|
+
const raw = await git.readFile(workspaceRoot, MANIFEST_REL);
|
|
3160
|
+
const parsed = raw === null ? null : deserializeManifest(raw);
|
|
3161
|
+
if (!parsed?.ok) {
|
|
3162
|
+
return {
|
|
3163
|
+
valid: false,
|
|
3164
|
+
diff: {
|
|
3165
|
+
stale: [],
|
|
3166
|
+
missing: serverProjects.map((p) => p.key),
|
|
3167
|
+
extra: [],
|
|
3168
|
+
unchanged: []
|
|
3169
|
+
},
|
|
3170
|
+
existingManifest: null
|
|
3171
|
+
};
|
|
3093
3172
|
}
|
|
3094
|
-
|
|
3095
|
-
|
|
3096
|
-
|
|
3097
|
-
|
|
3098
|
-
|
|
3099
|
-
|
|
3100
|
-
|
|
3101
|
-
|
|
3102
|
-
|
|
3173
|
+
const diff = diffManifest(parsed.manifest, serverProjects);
|
|
3174
|
+
const valid = diff.stale.length === 0 && diff.missing.length === 0 && diff.extra.length === 0;
|
|
3175
|
+
return {
|
|
3176
|
+
valid,
|
|
3177
|
+
diff,
|
|
3178
|
+
existingManifest: parsed.manifest
|
|
3179
|
+
};
|
|
3180
|
+
}
|
|
3181
|
+
async function repairRunRoot(validation, plan, git) {
|
|
3182
|
+
const errors = [];
|
|
3183
|
+
const reusable = new Map(
|
|
3184
|
+
validation.existingManifest?.components.filter((component) => validation.diff.unchanged.includes(component.key)).map((component) => [component.key, component])
|
|
3185
|
+
);
|
|
3186
|
+
const manifestEntries = await collectMaterializedEntries(plan, git, errors, reusable);
|
|
3187
|
+
return finalizeRunRoot(plan, git, manifestEntries, errors);
|
|
3188
|
+
}
|
|
3189
|
+
|
|
3190
|
+
// src/workspace/checkout-tool.ts
|
|
3191
|
+
function createCheckoutTool(workspaceRoot, instanceId, projects, git) {
|
|
3192
|
+
return {
|
|
3193
|
+
name: "checkout_repository",
|
|
3194
|
+
description: "Materialize a full clone for one authorized project and return its checked-out revision. Repeated calls reuse the checkout. Inspect only; do not publish changes.",
|
|
3195
|
+
parameters: {
|
|
3196
|
+
type: "object",
|
|
3197
|
+
properties: {
|
|
3198
|
+
projectKey: { type: "string" },
|
|
3199
|
+
revision: {
|
|
3200
|
+
type: "string",
|
|
3201
|
+
description: "Captured full commit SHA; refuses local changes."
|
|
3202
|
+
}
|
|
3203
|
+
},
|
|
3204
|
+
required: ["projectKey"],
|
|
3205
|
+
additionalProperties: false
|
|
3206
|
+
},
|
|
3207
|
+
executionMode: "sequential",
|
|
3208
|
+
async execute(args) {
|
|
3209
|
+
if (typeof args.projectKey !== "string") throw new Error("projectKey is required");
|
|
3210
|
+
if (args.revision !== void 0 && (typeof args.revision !== "string" || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(args.revision)))
|
|
3211
|
+
throw new Error("Use a captured full commit SHA");
|
|
3212
|
+
const plan = planRunRoot(
|
|
3213
|
+
workspaceRoot,
|
|
3214
|
+
instanceId,
|
|
3215
|
+
projects.map((project) => ({
|
|
3216
|
+
key: project.key,
|
|
3217
|
+
repoLocator: project.repoLocator,
|
|
3218
|
+
baseBranch: project.baseBranch,
|
|
3219
|
+
workBranch: project.workBranch || project.baseBranch
|
|
3220
|
+
}))
|
|
3103
3221
|
);
|
|
3104
|
-
|
|
3105
|
-
|
|
3106
|
-
|
|
3107
|
-
|
|
3108
|
-
|
|
3109
|
-
} else if (input.credential.values.refresh || input.credential.values.access) {
|
|
3110
|
-
const providerCredential = record(
|
|
3111
|
-
auth[input.credential.providerId],
|
|
3112
|
-
`auth.json.${input.credential.providerId}`
|
|
3222
|
+
const result = await prepareOnDemandRunRoot(
|
|
3223
|
+
plan,
|
|
3224
|
+
git,
|
|
3225
|
+
args.projectKey,
|
|
3226
|
+
args.revision
|
|
3113
3227
|
);
|
|
3114
|
-
|
|
3115
|
-
|
|
3116
|
-
|
|
3117
|
-
|
|
3118
|
-
|
|
3228
|
+
const entry = result.manifest.components.find(
|
|
3229
|
+
(component) => component.key === args.projectKey
|
|
3230
|
+
);
|
|
3231
|
+
if (!entry) throw new Error("Checkout did not produce repository evidence");
|
|
3232
|
+
const repositoryPath = path6.join(workspaceRoot, entry.key);
|
|
3233
|
+
return {
|
|
3234
|
+
...entry,
|
|
3235
|
+
headSha: await git.getHeadSha(repositoryPath),
|
|
3236
|
+
path: repositoryPath,
|
|
3237
|
+
instructions: "Read this repository's AGENTS.md before inspection; revalidate any wiki guidance against this revision. This checkout is retained, not automatically updated to the remote head."
|
|
3238
|
+
};
|
|
3119
3239
|
}
|
|
3120
|
-
}
|
|
3240
|
+
};
|
|
3121
3241
|
}
|
|
3122
3242
|
|
|
3123
|
-
// src/
|
|
3124
|
-
import {
|
|
3125
|
-
|
|
3126
|
-
resolveProcessSemanticRefEntryId
|
|
3127
|
-
} from "@leitwerk-dev/domain";
|
|
3243
|
+
// src/runtime/bootstrap-session.ts
|
|
3244
|
+
import { readFile as readFile3 } from "fs/promises";
|
|
3245
|
+
import path10 from "path";
|
|
3128
3246
|
|
|
3129
|
-
// src/
|
|
3130
|
-
|
|
3131
|
-
|
|
3132
|
-
|
|
3133
|
-
|
|
3134
|
-
|
|
3135
|
-
|
|
3136
|
-
|
|
3137
|
-
|
|
3138
|
-
|
|
3139
|
-
|
|
3140
|
-
|
|
3141
|
-
|
|
3142
|
-
|
|
3143
|
-
|
|
3144
|
-
|
|
3145
|
-
|
|
3146
|
-
}
|
|
3147
|
-
|
|
3148
|
-
|
|
3149
|
-
|
|
3150
|
-
|
|
3151
|
-
|
|
3152
|
-
|
|
3153
|
-
|
|
3154
|
-
|
|
3247
|
+
// src/docker-registry-credentials.ts
|
|
3248
|
+
import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "fs";
|
|
3249
|
+
import {
|
|
3250
|
+
dockerRegistryCredentialSchema
|
|
3251
|
+
} from "@leitwerk-dev/worker-protocol";
|
|
3252
|
+
import { is } from "valibot";
|
|
3253
|
+
var DockerRegistryCredentials = class {
|
|
3254
|
+
#directory;
|
|
3255
|
+
#previousConfig;
|
|
3256
|
+
#previousHelmRegistryConfig;
|
|
3257
|
+
#onExit = () => this.dispose();
|
|
3258
|
+
install(credentials, dockerEnabled) {
|
|
3259
|
+
this.dispose();
|
|
3260
|
+
if (!dockerEnabled) {
|
|
3261
|
+
if (credentials.length)
|
|
3262
|
+
throw new Error("Docker credentials require a Docker-enabled process");
|
|
3263
|
+
return;
|
|
3264
|
+
}
|
|
3265
|
+
const auths = /* @__PURE__ */ Object.create(null);
|
|
3266
|
+
for (const credential of credentials) {
|
|
3267
|
+
if (!is(dockerRegistryCredentialSchema, credential))
|
|
3268
|
+
throw new Error("Invalid Docker registry credentials");
|
|
3269
|
+
if (Object.hasOwn(auths, credential.registry))
|
|
3270
|
+
throw new Error("Duplicate Docker registry credentials");
|
|
3271
|
+
auths[credential.registry] = {
|
|
3272
|
+
auth: Buffer.from(`${credential.username}:${credential.password}`).toString("base64")
|
|
3273
|
+
};
|
|
3274
|
+
}
|
|
3275
|
+
try {
|
|
3276
|
+
this.#directory = mkdtempSync("/tmp/leitwerk-docker-auth-");
|
|
3277
|
+
chmodSync(this.#directory, 448);
|
|
3278
|
+
mkdirSync(`${this.#directory}/auth`, { mode: 448 });
|
|
3279
|
+
writeFileSync(`${this.#directory}/auth/config.json`, JSON.stringify({ auths }), {
|
|
3280
|
+
mode: 384,
|
|
3281
|
+
flag: "wx"
|
|
3282
|
+
});
|
|
3283
|
+
this.#previousConfig = process.env.DOCKER_CONFIG;
|
|
3284
|
+
process.env.DOCKER_CONFIG = `${this.#directory}/auth`;
|
|
3285
|
+
this.#previousHelmRegistryConfig = process.env.HELM_REGISTRY_CONFIG;
|
|
3286
|
+
process.env.HELM_REGISTRY_CONFIG = `${this.#directory}/auth/config.json`;
|
|
3287
|
+
if (!process.env.BUILDX_CONFIG) {
|
|
3288
|
+
mkdirSync(`${this.#directory}/buildx`, { mode: 448 });
|
|
3289
|
+
process.env.BUILDX_CONFIG = `${this.#directory}/buildx`;
|
|
3155
3290
|
}
|
|
3156
|
-
|
|
3291
|
+
process.once("exit", this.#onExit);
|
|
3292
|
+
} catch {
|
|
3293
|
+
this.dispose();
|
|
3294
|
+
throw new Error("Cannot materialize private Docker credentials");
|
|
3157
3295
|
}
|
|
3158
|
-
};
|
|
3159
|
-
visit(handle.getTree());
|
|
3160
|
-
return entries;
|
|
3161
|
-
}
|
|
3162
|
-
function findIdentifiedPrompt(piHandle, identity) {
|
|
3163
|
-
const matches = matchingEntries(piHandle, identity);
|
|
3164
|
-
if (matches.length > 1) {
|
|
3165
|
-
throw new Error(`Pi tree has duplicate Leitwerk prompt identity '${JSON.stringify(identity)}'`);
|
|
3166
3296
|
}
|
|
3167
|
-
|
|
3297
|
+
dispose() {
|
|
3298
|
+
process.off("exit", this.#onExit);
|
|
3299
|
+
if (!this.#directory) return;
|
|
3300
|
+
if (process.env.BUILDX_CONFIG === `${this.#directory}/buildx`) delete process.env.BUILDX_CONFIG;
|
|
3301
|
+
if (process.env.DOCKER_CONFIG === `${this.#directory}/auth`) {
|
|
3302
|
+
if (this.#previousConfig === void 0) delete process.env.DOCKER_CONFIG;
|
|
3303
|
+
else process.env.DOCKER_CONFIG = this.#previousConfig;
|
|
3304
|
+
}
|
|
3305
|
+
if (process.env.HELM_REGISTRY_CONFIG === `${this.#directory}/auth/config.json`) {
|
|
3306
|
+
if (this.#previousHelmRegistryConfig === void 0) delete process.env.HELM_REGISTRY_CONFIG;
|
|
3307
|
+
else process.env.HELM_REGISTRY_CONFIG = this.#previousHelmRegistryConfig;
|
|
3308
|
+
}
|
|
3309
|
+
rmSync(this.#directory, { recursive: true, force: true });
|
|
3310
|
+
this.#directory = void 0;
|
|
3311
|
+
this.#previousConfig = void 0;
|
|
3312
|
+
this.#previousHelmRegistryConfig = void 0;
|
|
3313
|
+
}
|
|
3314
|
+
};
|
|
3315
|
+
|
|
3316
|
+
// src/transport-error.ts
|
|
3317
|
+
var transportCodes = /* @__PURE__ */ new Set([
|
|
3318
|
+
"ECONNREFUSED",
|
|
3319
|
+
"ECONNRESET",
|
|
3320
|
+
"ENOTFOUND",
|
|
3321
|
+
"EAI_AGAIN",
|
|
3322
|
+
"ETIMEDOUT",
|
|
3323
|
+
"ENETUNREACH",
|
|
3324
|
+
"EHOSTUNREACH",
|
|
3325
|
+
"EPIPE",
|
|
3326
|
+
"CERT_HAS_EXPIRED",
|
|
3327
|
+
"DEPTH_ZERO_SELF_SIGNED_CERT",
|
|
3328
|
+
"SELF_SIGNED_CERT_IN_CHAIN",
|
|
3329
|
+
"UNABLE_TO_VERIFY_LEAF_SIGNATURE",
|
|
3330
|
+
"UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
|
|
3331
|
+
"ERR_TLS_CERT_ALTNAME_INVALID",
|
|
3332
|
+
"ERR_TLS_CERT_SIGNATURE_ALGORITHM_UNSUPPORTED",
|
|
3333
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
3334
|
+
"UND_ERR_HEADERS_TIMEOUT",
|
|
3335
|
+
"UND_ERR_BODY_TIMEOUT",
|
|
3336
|
+
"UND_ERR_SOCKET",
|
|
3337
|
+
"UND_ERR_ABORTED",
|
|
3338
|
+
"UND_ERR_DESTROYED",
|
|
3339
|
+
"UND_ERR_CLOSED"
|
|
3340
|
+
]);
|
|
3341
|
+
var transportNames = /* @__PURE__ */ new Set([
|
|
3342
|
+
"Error",
|
|
3343
|
+
"TypeError",
|
|
3344
|
+
"AggregateError",
|
|
3345
|
+
"AbortError",
|
|
3346
|
+
"TimeoutError",
|
|
3347
|
+
"SystemError",
|
|
3348
|
+
"ConnectTimeoutError",
|
|
3349
|
+
"HeadersTimeoutError",
|
|
3350
|
+
"BodyTimeoutError",
|
|
3351
|
+
"SocketError",
|
|
3352
|
+
"RequestAbortedError",
|
|
3353
|
+
"ClientDestroyedError",
|
|
3354
|
+
"ClientClosedError"
|
|
3355
|
+
]);
|
|
3356
|
+
function property(value, key) {
|
|
3357
|
+
try {
|
|
3358
|
+
return value[key];
|
|
3359
|
+
} catch {
|
|
3360
|
+
return void 0;
|
|
3361
|
+
}
|
|
3168
3362
|
}
|
|
3169
|
-
function
|
|
3170
|
-
|
|
3171
|
-
|
|
3172
|
-
|
|
3173
|
-
|
|
3174
|
-
|
|
3175
|
-
|
|
3176
|
-
|
|
3363
|
+
function transportErrorDetails(error) {
|
|
3364
|
+
const causes = [];
|
|
3365
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3366
|
+
let truncated = false;
|
|
3367
|
+
function visit(value, depth, parent) {
|
|
3368
|
+
if (!value || typeof value !== "object" || seen.has(value)) return;
|
|
3369
|
+
if (depth >= 6 || causes.length >= 8) {
|
|
3370
|
+
truncated = true;
|
|
3371
|
+
return;
|
|
3372
|
+
}
|
|
3373
|
+
seen.add(value);
|
|
3374
|
+
const name = property(value, "name"), code = property(value, "code");
|
|
3375
|
+
const index = causes.length;
|
|
3376
|
+
causes.push({
|
|
3377
|
+
...typeof name === "string" && transportNames.has(name) ? { name } : {},
|
|
3378
|
+
...typeof code === "string" && transportCodes.has(code) ? { code } : {},
|
|
3379
|
+
...parent !== void 0 ? { parent } : {}
|
|
3380
|
+
});
|
|
3381
|
+
visit(property(value, "error") ?? property(value, "cause"), depth + 1, index);
|
|
3382
|
+
const children = property(value, "errors");
|
|
3383
|
+
if (value instanceof AggregateError && Array.isArray(children)) {
|
|
3384
|
+
if (children.length > 4) truncated = true;
|
|
3385
|
+
for (const child of children.slice(0, 4)) visit(child, depth + 1, index);
|
|
3386
|
+
}
|
|
3177
3387
|
}
|
|
3178
|
-
|
|
3388
|
+
visit(error, 0);
|
|
3389
|
+
return { causes, ...truncated ? { truncated: true } : {} };
|
|
3179
3390
|
}
|
|
3180
|
-
function
|
|
3181
|
-
|
|
3391
|
+
function transportErrorCode(error) {
|
|
3392
|
+
return transportErrorDetails(error).causes.find((cause) => cause.code)?.code;
|
|
3182
3393
|
}
|
|
3183
|
-
|
|
3184
|
-
|
|
3185
|
-
|
|
3186
|
-
|
|
3187
|
-
|
|
3188
|
-
|
|
3189
|
-
|
|
3190
|
-
|
|
3191
|
-
|
|
3192
|
-
|
|
3193
|
-
|
|
3194
|
-
|
|
3195
|
-
|
|
3196
|
-
|
|
3197
|
-
|
|
3394
|
+
|
|
3395
|
+
// src/worker-start-payload.ts
|
|
3396
|
+
function isLlmWorkerStartPayload(payload) {
|
|
3397
|
+
return payload.bootstrap.kind === "llm";
|
|
3398
|
+
}
|
|
3399
|
+
|
|
3400
|
+
// src/runtime/bootstrap.ts
|
|
3401
|
+
import { mkdir as mkdir5 } from "fs/promises";
|
|
3402
|
+
import path9 from "path";
|
|
3403
|
+
import {
|
|
3404
|
+
readNonBlankString as readNonEmptyString2
|
|
3405
|
+
} from "@leitwerk-dev/domain";
|
|
3406
|
+
import { repositoryHttpsUrl } from "@leitwerk-dev/process-sdk";
|
|
3407
|
+
import { createTemplateContext, resolveProcessPiConfig } from "@leitwerk-dev/process-sdk/pi-config";
|
|
3408
|
+
|
|
3409
|
+
// src/managed-pi-agent-dir.ts
|
|
3410
|
+
import { randomUUID as randomUUID4 } from "crypto";
|
|
3411
|
+
import { chmod, lstat, mkdir as mkdir4, rename as rename3, writeFile as writeFile4 } from "fs/promises";
|
|
3412
|
+
import { homedir } from "os";
|
|
3413
|
+
import path7 from "path";
|
|
3414
|
+
function safeSegment(value, name) {
|
|
3415
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(value)) {
|
|
3416
|
+
throw new Error(`Invalid managed Pi ${name}`);
|
|
3198
3417
|
}
|
|
3199
|
-
|
|
3200
|
-
|
|
3201
|
-
|
|
3418
|
+
return value;
|
|
3419
|
+
}
|
|
3420
|
+
function resolveManagedPiAgentDir(input) {
|
|
3421
|
+
const root = path7.resolve(input.agentDirRoot);
|
|
3422
|
+
const ambient = path7.resolve(homedir(), ".pi", "agent");
|
|
3423
|
+
if (root === ambient)
|
|
3424
|
+
throw new Error("Managed Pi agent directory must not be ambient ~/.pi/agent");
|
|
3425
|
+
return path7.join(
|
|
3426
|
+
root,
|
|
3427
|
+
safeSegment(input.instanceId, "instance id"),
|
|
3428
|
+
safeSegment(input.startOrLeaseId, "start id")
|
|
3429
|
+
);
|
|
3430
|
+
}
|
|
3431
|
+
function normalizeManagedPiCredentialPath(value) {
|
|
3432
|
+
if (!value || path7.posix.isAbsolute(value) || value.includes("\\")) {
|
|
3433
|
+
throw new Error(`Invalid credential file path '${value}'`);
|
|
3202
3434
|
}
|
|
3203
|
-
|
|
3204
|
-
|
|
3205
|
-
|
|
3206
|
-
throw new Error(
|
|
3207
|
-
`Pi tree has mismatched Leitwerk compaction '${JSON.stringify(input.identity)}'`
|
|
3208
|
-
);
|
|
3435
|
+
const normalized = path7.posix.normalize(value);
|
|
3436
|
+
if (normalized === "." || normalized === ".." || normalized.startsWith("../")) {
|
|
3437
|
+
throw new Error(`Invalid credential file path '${value}'`);
|
|
3209
3438
|
}
|
|
3210
|
-
return
|
|
3439
|
+
return normalized;
|
|
3211
3440
|
}
|
|
3212
|
-
async function
|
|
3213
|
-
|
|
3214
|
-
|
|
3215
|
-
|
|
3216
|
-
|
|
3217
|
-
|
|
3441
|
+
async function assertNoSymlinkParents(root, target) {
|
|
3442
|
+
let current = root;
|
|
3443
|
+
for (const part of path7.relative(root, path7.dirname(target)).split(path7.sep).filter(Boolean)) {
|
|
3444
|
+
current = path7.join(current, part);
|
|
3445
|
+
try {
|
|
3446
|
+
if ((await lstat(current)).isSymbolicLink())
|
|
3447
|
+
throw new Error(`Credential parent is a symlink: ${current}`);
|
|
3448
|
+
} catch (error) {
|
|
3449
|
+
if (error.code !== "ENOENT") throw error;
|
|
3450
|
+
await mkdir4(current, { recursive: false, mode: 448 });
|
|
3451
|
+
}
|
|
3218
3452
|
}
|
|
3219
|
-
|
|
3220
|
-
|
|
3453
|
+
}
|
|
3454
|
+
async function writeManagedPiCredentialFiles(agentDir, files) {
|
|
3455
|
+
const root = path7.resolve(agentDir);
|
|
3456
|
+
if ((await lstat(root)).isSymbolicLink()) {
|
|
3457
|
+
throw new Error(`Managed Pi directory is a symlink: ${root}`);
|
|
3221
3458
|
}
|
|
3222
|
-
|
|
3223
|
-
|
|
3224
|
-
|
|
3459
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3460
|
+
for (const file of files) {
|
|
3461
|
+
const relative = normalizeManagedPiCredentialPath(file.path);
|
|
3462
|
+
if (seen.has(relative)) throw new Error(`Duplicate credential file path '${relative}'`);
|
|
3463
|
+
seen.add(relative);
|
|
3464
|
+
const target = path7.resolve(root, relative);
|
|
3465
|
+
if (!target.startsWith(`${root}${path7.sep}`))
|
|
3466
|
+
throw new Error(`Credential path escapes managed directory: ${relative}`);
|
|
3467
|
+
await assertNoSymlinkParents(root, target);
|
|
3468
|
+
const tmp = path7.join(
|
|
3469
|
+
path7.dirname(target),
|
|
3470
|
+
`.${path7.basename(target)}.tmp-${process.pid}-${randomUUID4()}`
|
|
3225
3471
|
);
|
|
3472
|
+
await writeFile4(tmp, file.content, { mode: 384, flag: "wx" });
|
|
3473
|
+
await chmod(tmp, 384);
|
|
3474
|
+
await rename3(tmp, target);
|
|
3475
|
+
await chmod(target, 384);
|
|
3226
3476
|
}
|
|
3227
|
-
if (input.piHandle.getLeafId() !== input.expectedParentId) {
|
|
3228
|
-
throw new Error("Pi tree changed before the identified prompt could be appended");
|
|
3229
|
-
}
|
|
3230
|
-
return await input.piHandle.appendCustomMessage({
|
|
3231
|
-
content: input.content,
|
|
3232
|
-
details: input.identity
|
|
3233
|
-
});
|
|
3234
3477
|
}
|
|
3235
3478
|
|
|
3236
|
-
// src/
|
|
3237
|
-
|
|
3238
|
-
|
|
3479
|
+
// src/managed-pi-bootstrap.ts
|
|
3480
|
+
import { lstat as lstat2, readFile as readFile2 } from "fs/promises";
|
|
3481
|
+
import path8 from "path";
|
|
3482
|
+
import {
|
|
3483
|
+
canonicalJsonEqual,
|
|
3484
|
+
IPC_PROTOCOL_VERSION,
|
|
3485
|
+
parsePiResourceManifest,
|
|
3486
|
+
WORKER_API_VERSION
|
|
3487
|
+
} from "@leitwerk-dev/worker-protocol";
|
|
3488
|
+
function fail2(message) {
|
|
3489
|
+
throw new Error(`Invalid managed Pi resource snapshot: ${message}`);
|
|
3239
3490
|
}
|
|
3240
|
-
function
|
|
3241
|
-
|
|
3491
|
+
function record(value, location) {
|
|
3492
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
3493
|
+
fail2(`${location} must be an object`);
|
|
3494
|
+
}
|
|
3495
|
+
return value;
|
|
3242
3496
|
}
|
|
3243
|
-
function
|
|
3244
|
-
|
|
3245
|
-
|
|
3246
|
-
return `semantic ref '${semanticRef}'`;
|
|
3497
|
+
function assertJsonEqual(actual, expected, location) {
|
|
3498
|
+
if (!canonicalJsonEqual(actual, expected)) {
|
|
3499
|
+
fail2(`${location} does not match the resolved LLM start`);
|
|
3247
3500
|
}
|
|
3248
|
-
return `product '${resolveTargetProductName(target) ?? "<unset>"}'`;
|
|
3249
3501
|
}
|
|
3250
|
-
function
|
|
3251
|
-
const
|
|
3252
|
-
|
|
3253
|
-
|
|
3502
|
+
function assertModelMatchesStart(manifest, start) {
|
|
3503
|
+
for (const key of ["profileId", "providerId", "modelId", "thinkingLevel"]) {
|
|
3504
|
+
if (manifest.model[key] !== start.model[key]) {
|
|
3505
|
+
fail2(
|
|
3506
|
+
`generated.json model ${key} '${manifest.model[key]}' does not match start '${start.model[key]}'`
|
|
3507
|
+
);
|
|
3508
|
+
}
|
|
3254
3509
|
}
|
|
3255
|
-
return null;
|
|
3256
3510
|
}
|
|
3257
|
-
function
|
|
3258
|
-
const
|
|
3259
|
-
if (
|
|
3260
|
-
|
|
3261
|
-
|
|
3262
|
-
|
|
3263
|
-
currentLeafId: input.currentLeafId,
|
|
3264
|
-
rootEntryId: input.rootEntryId,
|
|
3265
|
-
entryExists: input.entryExists
|
|
3266
|
-
});
|
|
3511
|
+
async function assertCompatibility(manifest) {
|
|
3512
|
+
const { VERSION: PI_VERSION } = await import("@earendil-works/pi-coding-agent");
|
|
3513
|
+
if (manifest.compatibility.workerApiVersion !== WORKER_API_VERSION) {
|
|
3514
|
+
fail2(
|
|
3515
|
+
`server snapshot worker API version '${manifest.compatibility.workerApiVersion}' does not match local worker API version '${WORKER_API_VERSION}'`
|
|
3516
|
+
);
|
|
3267
3517
|
}
|
|
3268
|
-
|
|
3269
|
-
|
|
3270
|
-
|
|
3271
|
-
|
|
3272
|
-
|
|
3273
|
-
|
|
3274
|
-
|
|
3275
|
-
|
|
3276
|
-
|
|
3277
|
-
for (const targetedInput of input.inputs) {
|
|
3278
|
-
if (targetedInput.bodyMarkdown.trim() === "") {
|
|
3279
|
-
return `Turn '${input.turnId}' cannot apply queued targeted input '${targetedInput.inputId}' because bodyMarkdown is empty`;
|
|
3280
|
-
}
|
|
3281
|
-
const targetEntryId = resolvePreTurnTargetEntryId({
|
|
3282
|
-
target: targetedInput.target,
|
|
3283
|
-
semanticEntryRefs: input.semanticEntryRefs,
|
|
3284
|
-
productRefs: input.productRefs,
|
|
3285
|
-
currentLeafId: input.currentLeafId,
|
|
3286
|
-
rootEntryId: input.rootEntryId,
|
|
3287
|
-
entryExists: input.entryExists
|
|
3288
|
-
});
|
|
3289
|
-
if (!targetEntryId) {
|
|
3290
|
-
if (resolveTargetSemanticRef(targetedInput.target) === "rootEntry" && input.treePlan.startTarget.kind === "root") {
|
|
3291
|
-
continue;
|
|
3292
|
-
}
|
|
3293
|
-
return `Turn '${input.turnId}' cannot apply queued targeted input '${targetedInput.inputId}' because ${formatTarget(targetedInput.target)} is not resolved`;
|
|
3294
|
-
}
|
|
3295
|
-
if (!expectedEntryId || expectedEntryId !== targetEntryId) {
|
|
3296
|
-
return `Turn '${input.turnId}' cannot apply queued targeted input '${targetedInput.inputId}' for ${formatTarget(targetedInput.target)} because the selected turn is not continuing from that branch`;
|
|
3297
|
-
}
|
|
3518
|
+
if (manifest.compatibility.piVersion !== PI_VERSION) {
|
|
3519
|
+
fail2(
|
|
3520
|
+
`server snapshot Pi version '${manifest.compatibility.piVersion}' does not match local worker Pi version '${PI_VERSION}'`
|
|
3521
|
+
);
|
|
3522
|
+
}
|
|
3523
|
+
if (manifest.compatibility.protocolVersion !== void 0 && manifest.compatibility.protocolVersion !== IPC_PROTOCOL_VERSION) {
|
|
3524
|
+
fail2(
|
|
3525
|
+
`server snapshot protocol version '${manifest.compatibility.protocolVersion}' does not match local worker protocol version '${IPC_PROTOCOL_VERSION}'`
|
|
3526
|
+
);
|
|
3298
3527
|
}
|
|
3299
|
-
return null;
|
|
3300
3528
|
}
|
|
3301
|
-
async function
|
|
3302
|
-
|
|
3303
|
-
|
|
3529
|
+
async function readAndValidateManagedPiResourceManifest(input) {
|
|
3530
|
+
const marker = await readFile2(path8.join(input.agentDir, ".leitwerk-resource-digest"), "utf8");
|
|
3531
|
+
if (marker !== `${input.resourceDigest}
|
|
3532
|
+
`) {
|
|
3533
|
+
fail2("materialized resource digest marker does not match the delivered bundle");
|
|
3304
3534
|
}
|
|
3305
|
-
|
|
3306
|
-
|
|
3307
|
-
|
|
3308
|
-
|
|
3309
|
-
|
|
3310
|
-
|
|
3311
|
-
allowDescendantParent: input.recoveryBaseEntryId !== void 0,
|
|
3312
|
-
requireOnCurrentBranch: input.reuseExistingWithoutBranching,
|
|
3313
|
-
reuseWithoutBranching: input.reuseExistingWithoutBranching,
|
|
3314
|
-
requireExisting: input.requireExisting
|
|
3535
|
+
let parsed;
|
|
3536
|
+
try {
|
|
3537
|
+
parsed = JSON.parse(await readFile2(path8.join(input.agentDir, "generated.json"), "utf8"));
|
|
3538
|
+
} catch (error) {
|
|
3539
|
+
throw new Error("Invalid managed Pi resource snapshot: generated.json is unreadable", {
|
|
3540
|
+
cause: error
|
|
3315
3541
|
});
|
|
3316
|
-
|
|
3317
|
-
|
|
3318
|
-
|
|
3319
|
-
|
|
3320
|
-
|
|
3321
|
-
|
|
3542
|
+
}
|
|
3543
|
+
const manifest = parsePiResourceManifest(parsed);
|
|
3544
|
+
assertModelMatchesStart(manifest, input.start);
|
|
3545
|
+
await assertCompatibility(manifest);
|
|
3546
|
+
assertJsonEqual(manifest.providerOptions, input.start.providerOptions, "providerOptions");
|
|
3547
|
+
assertJsonEqual(
|
|
3548
|
+
manifest.providerWorkerConfig,
|
|
3549
|
+
input.start.providerWorkerConfig,
|
|
3550
|
+
"providerWorkerConfig"
|
|
3551
|
+
);
|
|
3552
|
+
let settings;
|
|
3553
|
+
try {
|
|
3554
|
+
settings = JSON.parse(await readFile2(path8.join(input.agentDir, "settings.json"), "utf8"));
|
|
3555
|
+
} catch (error) {
|
|
3556
|
+
throw new Error("Invalid managed Pi resource snapshot: settings.json is unreadable", {
|
|
3557
|
+
cause: error
|
|
3322
3558
|
});
|
|
3323
3559
|
}
|
|
3560
|
+
assertJsonEqual(
|
|
3561
|
+
settings,
|
|
3562
|
+
{ ...input.start.piSettings, packages: [], defaultProjectTrust: "never" },
|
|
3563
|
+
"settings.json"
|
|
3564
|
+
);
|
|
3565
|
+
return manifest;
|
|
3324
3566
|
}
|
|
3325
|
-
|
|
3326
|
-
|
|
3327
|
-
|
|
3328
|
-
|
|
3329
|
-
|
|
3330
|
-
|
|
3331
|
-
|
|
3332
|
-
|
|
3333
|
-
|
|
3334
|
-
|
|
3335
|
-
|
|
3336
|
-
|
|
3337
|
-
|
|
3338
|
-
|
|
3339
|
-
|
|
3340
|
-
|
|
3341
|
-
|
|
3342
|
-
|
|
3343
|
-
|
|
3344
|
-
|
|
3345
|
-
|
|
3346
|
-
|
|
3347
|
-
|
|
3348
|
-
|
|
3349
|
-
|
|
3350
|
-
|
|
3351
|
-
|
|
3352
|
-
|
|
3353
|
-
|
|
3354
|
-
|
|
3355
|
-
|
|
3356
|
-
|
|
3357
|
-
|
|
3567
|
+
function buildManagedPiCredentialFiles(input) {
|
|
3568
|
+
if (input.credential && input.credential.providerId !== input.providerId) {
|
|
3569
|
+
throw new Error(
|
|
3570
|
+
`Credential provider '${input.credential.providerId}' does not match selected provider '${input.providerId}'`
|
|
3571
|
+
);
|
|
3572
|
+
}
|
|
3573
|
+
const values = input.credential?.values ?? {};
|
|
3574
|
+
const apiKey = values.apiKey;
|
|
3575
|
+
if (apiKey !== void 0 && apiKey.trim() === "") {
|
|
3576
|
+
throw new Error(`Credential apiKey for provider '${input.providerId}' is empty`);
|
|
3577
|
+
}
|
|
3578
|
+
let auth = {};
|
|
3579
|
+
if (apiKey) {
|
|
3580
|
+
auth = { [input.providerId]: { type: "api_key", key: apiKey } };
|
|
3581
|
+
} else if (values.type === "oauth") {
|
|
3582
|
+
const entry = { type: "oauth" };
|
|
3583
|
+
for (const key of ["refresh", "access"]) {
|
|
3584
|
+
if (values[key] !== void 0) entry[key] = values[key];
|
|
3585
|
+
}
|
|
3586
|
+
if (values.expires !== void 0) {
|
|
3587
|
+
const expires = Number(values.expires);
|
|
3588
|
+
entry.expires = Number.isNaN(expires) ? values.expires : expires;
|
|
3589
|
+
}
|
|
3590
|
+
auth = { [input.providerId]: entry };
|
|
3591
|
+
}
|
|
3592
|
+
if (Object.keys(auth).length > 0 && !input.manifest.declaredCredentialPaths.includes("auth.json")) {
|
|
3593
|
+
throw new Error(
|
|
3594
|
+
`Provider '${input.providerId}' standard credential requires declared auth.json`
|
|
3595
|
+
);
|
|
3596
|
+
}
|
|
3597
|
+
return input.manifest.declaredCredentialPaths.map((credentialPath) => ({
|
|
3598
|
+
path: credentialPath,
|
|
3599
|
+
content: `${JSON.stringify(credentialPath === "auth.json" ? auth : values, null, 2)}
|
|
3600
|
+
`
|
|
3358
3601
|
}));
|
|
3359
3602
|
}
|
|
3360
|
-
function
|
|
3361
|
-
const
|
|
3362
|
-
|
|
3363
|
-
|
|
3364
|
-
|
|
3365
|
-
|
|
3366
|
-
|
|
3367
|
-
|
|
3368
|
-
|
|
3369
|
-
|
|
3370
|
-
externalId: processSnapshot.externalId ?? null,
|
|
3371
|
-
externalUrl: processSnapshot.externalUrl ?? null,
|
|
3372
|
-
metadata: processSnapshot.metadata ?? null,
|
|
3373
|
-
defaultModelProfileId: processSnapshot.defaultModelProfileId ?? null,
|
|
3374
|
-
turnConfigsJson: processSnapshot.turnConfigsJson ?? null,
|
|
3375
|
-
selectedTurnModelProfileId: processSnapshot.selectedTurnModelProfileId ?? null,
|
|
3376
|
-
paramsJson: processSnapshot.paramsJson ?? null,
|
|
3377
|
-
stateJson: processSnapshot.stateJson ?? null,
|
|
3378
|
-
createdAt: processSnapshot.createdAt ?? "",
|
|
3379
|
-
updatedAt: processSnapshot.updatedAt ?? ""
|
|
3380
|
-
};
|
|
3381
|
-
}
|
|
3382
|
-
function readProcessSemanticEntryRefs(state) {
|
|
3383
|
-
if (typeof state !== "object" || state === null || Array.isArray(state)) {
|
|
3384
|
-
return null;
|
|
3603
|
+
async function assertManagedPiCredentialFiles(input) {
|
|
3604
|
+
for (const credentialPath of input.manifest.declaredCredentialPaths) {
|
|
3605
|
+
const target = path8.join(input.agentDir, credentialPath);
|
|
3606
|
+
const stat2 = await lstat2(target).catch(() => null);
|
|
3607
|
+
if (!stat2?.isFile() || stat2.isSymbolicLink()) {
|
|
3608
|
+
throw new Error(`Declared credential file '${credentialPath}' is missing or unsafe`);
|
|
3609
|
+
}
|
|
3610
|
+
if ((stat2.mode & 511) !== 384) {
|
|
3611
|
+
throw new Error(`Declared credential file '${credentialPath}' must have mode 0600`);
|
|
3612
|
+
}
|
|
3385
3613
|
}
|
|
3386
|
-
|
|
3387
|
-
|
|
3388
|
-
|
|
3389
|
-
|
|
3390
|
-
|
|
3391
|
-
|
|
3392
|
-
|
|
3614
|
+
if (input.credential && input.manifest.declaredCredentialPaths.includes("auth.json")) {
|
|
3615
|
+
const auth = record(
|
|
3616
|
+
JSON.parse(await readFile2(path8.join(input.agentDir, "auth.json"), "utf8")),
|
|
3617
|
+
"auth.json"
|
|
3618
|
+
);
|
|
3619
|
+
if (input.credential.values.apiKey) {
|
|
3620
|
+
const providerCredential = record(
|
|
3621
|
+
auth[input.credential.providerId],
|
|
3622
|
+
`auth.json.${input.credential.providerId}`
|
|
3623
|
+
);
|
|
3624
|
+
if (providerCredential.type !== "api_key" && providerCredential.type !== void 0 || providerCredential.key !== input.credential.values.apiKey) {
|
|
3625
|
+
throw new Error(
|
|
3626
|
+
`Standard Pi credential for provider '${input.credential.providerId}' was not loaded`
|
|
3627
|
+
);
|
|
3628
|
+
}
|
|
3629
|
+
} else if (input.credential.values.refresh || input.credential.values.access) {
|
|
3630
|
+
const providerCredential = record(
|
|
3631
|
+
auth[input.credential.providerId],
|
|
3632
|
+
`auth.json.${input.credential.providerId}`
|
|
3633
|
+
);
|
|
3634
|
+
if (providerCredential.type !== "oauth" || input.credential.values.refresh && providerCredential.refresh !== input.credential.values.refresh || input.credential.values.access && providerCredential.access !== input.credential.values.access) {
|
|
3635
|
+
throw new Error(
|
|
3636
|
+
`Standard Pi OAuth credential for provider '${input.credential.providerId}' was not loaded`
|
|
3637
|
+
);
|
|
3638
|
+
}
|
|
3639
|
+
}
|
|
3393
3640
|
}
|
|
3394
|
-
return parseProcessProductRefs(state.productRefs);
|
|
3395
|
-
}
|
|
3396
|
-
function parseProcessSemanticEntryRefsFromStateJson(stateJson) {
|
|
3397
|
-
return parseSemanticEntryRefsFromStateJsonStrict(stateJson, "process stateJson");
|
|
3398
3641
|
}
|
|
3399
3642
|
|
|
3400
|
-
// src/
|
|
3401
|
-
import
|
|
3402
|
-
|
|
3643
|
+
// src/pre-turn-targeted-inputs.ts
|
|
3644
|
+
import {
|
|
3645
|
+
resolveProcessProductRefEntryId,
|
|
3646
|
+
resolveProcessSemanticRefEntryId
|
|
3647
|
+
} from "@leitwerk-dev/domain";
|
|
3403
3648
|
|
|
3404
|
-
// src/
|
|
3405
|
-
|
|
3406
|
-
|
|
3407
|
-
return JSON.stringify(manifest, null, 2);
|
|
3649
|
+
// src/identified-pi-entry.ts
|
|
3650
|
+
function isOnCurrentBranch(piHandle, entryId) {
|
|
3651
|
+
return piHandle.getBranch(piHandle.getLeafId() ?? void 0).some((entry) => entry.id === entryId);
|
|
3408
3652
|
}
|
|
3409
|
-
|
|
3410
|
-
(
|
|
3411
|
-
|
|
3412
|
-
);
|
|
3413
|
-
|
|
3414
|
-
jsonObjectSchema,
|
|
3415
|
-
v.object({
|
|
3416
|
-
key: v.string(),
|
|
3417
|
-
repoLocator: v.string(),
|
|
3418
|
-
baseBranch: v.string(),
|
|
3419
|
-
workBranch: v.string(),
|
|
3420
|
-
clonedAt: v.string(),
|
|
3421
|
-
headSha: v.string()
|
|
3422
|
-
})
|
|
3423
|
-
);
|
|
3424
|
-
var componentManifestSchema = v.pipe(
|
|
3425
|
-
jsonObjectSchema,
|
|
3426
|
-
v.object({
|
|
3427
|
-
version: v.literal(1),
|
|
3428
|
-
instanceId: v.pipe(v.string(), v.minLength(1)),
|
|
3429
|
-
createdAt: v.pipe(v.string(), v.minLength(1)),
|
|
3430
|
-
components: v.array(componentManifestEntrySchema)
|
|
3431
|
-
})
|
|
3432
|
-
);
|
|
3433
|
-
var componentManifestJsonSchema = v.pipe(v.string(), v.parseJson(), componentManifestSchema);
|
|
3434
|
-
function formatManifestValidationError(issues) {
|
|
3435
|
-
const issue = issues[0];
|
|
3436
|
-
if (issue?.type === "parse_json") return "Invalid JSON";
|
|
3437
|
-
const path14 = issue ? v.getDotPath(issue) : null;
|
|
3438
|
-
if (!path14) return "Manifest must be a JSON object";
|
|
3439
|
-
if (path14 === "version") return "Unsupported manifest version";
|
|
3440
|
-
if (path14 === "instanceId") return "Invalid instanceId";
|
|
3441
|
-
if (path14 === "createdAt") return "Invalid createdAt";
|
|
3442
|
-
if (path14 === "components") return "components must be an array";
|
|
3443
|
-
if (path14.match(/^components\.\d+$/)) return "Invalid component entry";
|
|
3444
|
-
const componentField = path14.match(/^components\.\d+\.([^.]*)$/)?.[1];
|
|
3445
|
-
if (componentField) return `Invalid component field: ${componentField}`;
|
|
3446
|
-
return issue?.message ? `Invalid manifest: ${issue.message}` : "Invalid manifest";
|
|
3653
|
+
function matchesParent(input) {
|
|
3654
|
+
if (input.parentId === input.expectedParentId) return true;
|
|
3655
|
+
if (!input.allowDescendantParent || input.parentId === null) return false;
|
|
3656
|
+
if (input.expectedParentId === null) return isOnCurrentBranch(input.piHandle, input.parentId);
|
|
3657
|
+
return input.piHandle.getBranch(input.parentId).some((entry) => entry.id === input.expectedParentId);
|
|
3447
3658
|
}
|
|
3448
|
-
function
|
|
3449
|
-
|
|
3450
|
-
|
|
3451
|
-
|
|
3452
|
-
|
|
3453
|
-
|
|
3659
|
+
function sameIdentity(left, right) {
|
|
3660
|
+
if (!left || typeof left !== "object") return false;
|
|
3661
|
+
const value = left;
|
|
3662
|
+
if (value.kind !== right.kind) return false;
|
|
3663
|
+
if (right.kind === "process_input") return value.processInputId === right.processInputId;
|
|
3664
|
+
if (right.kind === "turn_compaction") return value.startRecordId === right.startRecordId;
|
|
3665
|
+
return value.startRecordId === right.startRecordId && value.purpose === right.purpose;
|
|
3454
3666
|
}
|
|
3455
|
-
function
|
|
3456
|
-
const
|
|
3457
|
-
const
|
|
3458
|
-
|
|
3459
|
-
|
|
3460
|
-
|
|
3461
|
-
|
|
3462
|
-
|
|
3463
|
-
|
|
3464
|
-
|
|
3465
|
-
missing.push(p.key);
|
|
3466
|
-
continue;
|
|
3467
|
-
}
|
|
3468
|
-
if (m.repoLocator === p.repoLocator && m.baseBranch === p.baseBranch && m.workBranch === p.workBranch) {
|
|
3469
|
-
unchanged.push(p.key);
|
|
3470
|
-
} else {
|
|
3471
|
-
stale.push(p.key);
|
|
3667
|
+
function matchingEntries(handle, identity) {
|
|
3668
|
+
const entries = [];
|
|
3669
|
+
const visit = (nodes) => {
|
|
3670
|
+
for (const node of nodes) {
|
|
3671
|
+
const isMatchingPrompt = node.entry.type === "custom_message" && node.entry.customType === "leitwerk";
|
|
3672
|
+
const isMatchingCompaction = node.entry.type === "compaction";
|
|
3673
|
+
if ((isMatchingPrompt || isMatchingCompaction) && sameIdentity(node.entry.details, identity)) {
|
|
3674
|
+
entries.push(node.entry);
|
|
3675
|
+
}
|
|
3676
|
+
visit(node.children);
|
|
3472
3677
|
}
|
|
3678
|
+
};
|
|
3679
|
+
visit(handle.getTree());
|
|
3680
|
+
return entries;
|
|
3681
|
+
}
|
|
3682
|
+
function findIdentifiedPrompt(piHandle, identity) {
|
|
3683
|
+
const matches = matchingEntries(piHandle, identity);
|
|
3684
|
+
if (matches.length > 1) {
|
|
3685
|
+
throw new Error(`Pi tree has duplicate Leitwerk prompt identity '${JSON.stringify(identity)}'`);
|
|
3473
3686
|
}
|
|
3474
|
-
|
|
3475
|
-
|
|
3476
|
-
|
|
3477
|
-
|
|
3687
|
+
return matches[0] ?? null;
|
|
3688
|
+
}
|
|
3689
|
+
function assertIdentifiedPrompt(match, input) {
|
|
3690
|
+
if (match?.type === "custom_message" && match.customType === "leitwerk" && match.content === input.content && matchesParent({
|
|
3691
|
+
piHandle: input.piHandle,
|
|
3692
|
+
parentId: match.parentId,
|
|
3693
|
+
expectedParentId: input.expectedParentId,
|
|
3694
|
+
allowDescendantParent: input.allowDescendantParent
|
|
3695
|
+
}) && (!input.requireOnCurrentBranch || isOnCurrentBranch(input.piHandle, match.id))) {
|
|
3696
|
+
return;
|
|
3478
3697
|
}
|
|
3479
|
-
|
|
3698
|
+
throw new Error(`Pi tree has mismatched Leitwerk prompt '${JSON.stringify(input.identity)}'`);
|
|
3480
3699
|
}
|
|
3481
|
-
|
|
3482
|
-
|
|
3483
|
-
function formatProvenanceMarker(componentKey, filePath) {
|
|
3484
|
-
const normalizedPath = filePath.replace(/\\/g, "/");
|
|
3485
|
-
return `<!-- source: ${componentKey}/${normalizedPath} -->`;
|
|
3700
|
+
function validateIdentifiedPrompt(input) {
|
|
3701
|
+
assertIdentifiedPrompt(findIdentifiedPrompt(input.piHandle, input.identity), input);
|
|
3486
3702
|
}
|
|
3487
|
-
function
|
|
3488
|
-
const
|
|
3489
|
-
if (
|
|
3490
|
-
|
|
3703
|
+
async function ensureIdentifiedCompaction(input) {
|
|
3704
|
+
const match = findIdentifiedPrompt(input.piHandle, input.identity);
|
|
3705
|
+
if (match) {
|
|
3706
|
+
if (match.type !== "compaction" || !matchesParent({
|
|
3707
|
+
piHandle: input.piHandle,
|
|
3708
|
+
parentId: match.parentId,
|
|
3709
|
+
expectedParentId: input.expectedParentId,
|
|
3710
|
+
allowDescendantParent: input.allowDescendantParent
|
|
3711
|
+
}) || input.requireOnCurrentBranch && !isOnCurrentBranch(input.piHandle, match.id)) {
|
|
3712
|
+
throw new Error(
|
|
3713
|
+
`Pi tree has mismatched Leitwerk compaction '${JSON.stringify(input.identity)}'`
|
|
3714
|
+
);
|
|
3715
|
+
}
|
|
3716
|
+
if (!input.reuseWithoutBranching) await input.piHandle.branch(match.id);
|
|
3717
|
+
return match.id;
|
|
3491
3718
|
}
|
|
3492
|
-
|
|
3493
|
-
|
|
3494
|
-
|
|
3495
|
-
parts.push(s.content.trimEnd());
|
|
3719
|
+
if (!input.piHandle.compact) throw new Error("Pi handle does not support compaction");
|
|
3720
|
+
if (input.piHandle.getLeafId() !== input.expectedParentId) {
|
|
3721
|
+
throw new Error("Pi tree changed before the identified compaction could be appended");
|
|
3496
3722
|
}
|
|
3497
|
-
|
|
3498
|
-
|
|
3499
|
-
|
|
3500
|
-
|
|
3501
|
-
|
|
3502
|
-
|
|
3503
|
-
const winner = out.get(skillId);
|
|
3504
|
-
if (!winner || componentKey.localeCompare(winner.source) < 0) {
|
|
3505
|
-
out.set(skillId, { content, source: componentKey });
|
|
3506
|
-
}
|
|
3723
|
+
await input.piHandle.compact(void 0, input.identity);
|
|
3724
|
+
const appended = findIdentifiedPrompt(input.piHandle, input.identity);
|
|
3725
|
+
if (!appended || appended.type !== "compaction" || appended.parentId !== input.expectedParentId) {
|
|
3726
|
+
throw new Error(
|
|
3727
|
+
`Pi tree has mismatched Leitwerk compaction '${JSON.stringify(input.identity)}'`
|
|
3728
|
+
);
|
|
3507
3729
|
}
|
|
3508
|
-
return
|
|
3730
|
+
return appended.id;
|
|
3509
3731
|
}
|
|
3510
|
-
|
|
3511
|
-
|
|
3512
|
-
|
|
3513
|
-
|
|
3514
|
-
|
|
3515
|
-
|
|
3516
|
-
this.name = "RunRootPreparationError";
|
|
3517
|
-
this.errors = [...errors];
|
|
3732
|
+
async function ensureIdentifiedPrompt(input) {
|
|
3733
|
+
const match = findIdentifiedPrompt(input.piHandle, input.identity);
|
|
3734
|
+
if (match) {
|
|
3735
|
+
assertIdentifiedPrompt(match, input);
|
|
3736
|
+
if (!input.reuseWithoutBranching) await input.piHandle.branch(match.id);
|
|
3737
|
+
return match.id;
|
|
3518
3738
|
}
|
|
3519
|
-
|
|
3520
|
-
|
|
3521
|
-
var AGGREGATED_AGENTS_REL2 = "AGENTS.md";
|
|
3522
|
-
var SKILLS_DIR_REL = path7.join(".leitwerk", "skills");
|
|
3523
|
-
var SKILL_GLOB = "**/.cursor/skills/**/SKILL.md";
|
|
3524
|
-
var AGENTS_GLOB = "**/AGENTS.md";
|
|
3525
|
-
function componentDir(workspaceRoot, childPath) {
|
|
3526
|
-
const root = path7.resolve(workspaceRoot);
|
|
3527
|
-
const target = path7.resolve(root, childPath);
|
|
3528
|
-
if (!isPathInside(root, target)) {
|
|
3529
|
-
throw new Error(`Component key '${childPath}' resolves outside workspace root '${root}'`);
|
|
3739
|
+
if (!input.piHandle.appendCustomMessage) {
|
|
3740
|
+
throw new Error("Pi handle does not support identified custom messages");
|
|
3530
3741
|
}
|
|
3531
|
-
|
|
3532
|
-
|
|
3533
|
-
|
|
3534
|
-
|
|
3535
|
-
|
|
3536
|
-
|
|
3742
|
+
if (input.requireExisting) {
|
|
3743
|
+
throw new Error(
|
|
3744
|
+
`Pi tree is missing retained Leitwerk prompt '${JSON.stringify(input.identity)}'`
|
|
3745
|
+
);
|
|
3746
|
+
}
|
|
3747
|
+
if (input.piHandle.getLeafId() !== input.expectedParentId) {
|
|
3748
|
+
throw new Error("Pi tree changed before the identified prompt could be appended");
|
|
3749
|
+
}
|
|
3750
|
+
return await input.piHandle.appendCustomMessage({
|
|
3751
|
+
content: input.content,
|
|
3752
|
+
details: input.identity
|
|
3753
|
+
});
|
|
3537
3754
|
}
|
|
3538
|
-
|
|
3539
|
-
|
|
3540
|
-
|
|
3541
|
-
|
|
3542
|
-
components: projectSnapshots.map((p) => ({ ...p }))
|
|
3543
|
-
};
|
|
3755
|
+
|
|
3756
|
+
// src/pre-turn-targeted-inputs.ts
|
|
3757
|
+
function resolveTargetSemanticRef(target) {
|
|
3758
|
+
return typeof target.semanticRef === "string" ? target.semanticRef : null;
|
|
3544
3759
|
}
|
|
3545
|
-
|
|
3546
|
-
|
|
3547
|
-
await git.clone(comp.repoLocator, dir);
|
|
3548
|
-
await git.checkout(dir, comp.baseBranch);
|
|
3549
|
-
if (!await git.branchExists(dir, comp.workBranch)) {
|
|
3550
|
-
await git.createBranch(dir, comp.workBranch, comp.baseBranch);
|
|
3551
|
-
}
|
|
3552
|
-
await git.checkout(dir, comp.workBranch);
|
|
3553
|
-
return {
|
|
3554
|
-
key: comp.key,
|
|
3555
|
-
repoLocator: comp.repoLocator,
|
|
3556
|
-
baseBranch: comp.baseBranch,
|
|
3557
|
-
workBranch: comp.workBranch,
|
|
3558
|
-
clonedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3559
|
-
headSha: await git.getHeadSha(dir)
|
|
3560
|
-
};
|
|
3760
|
+
function resolveTargetProductName(target) {
|
|
3761
|
+
return typeof target.productName === "string" ? target.productName : null;
|
|
3561
3762
|
}
|
|
3562
|
-
|
|
3563
|
-
const
|
|
3564
|
-
|
|
3565
|
-
|
|
3566
|
-
const existing = existingEntryForKey?.(comp.key) ?? null;
|
|
3567
|
-
if (existing) {
|
|
3568
|
-
entries.push(existing);
|
|
3569
|
-
} else {
|
|
3570
|
-
errors.push(`${comp.key}: no existing manifest entry for unchanged key`);
|
|
3571
|
-
}
|
|
3572
|
-
continue;
|
|
3573
|
-
}
|
|
3574
|
-
try {
|
|
3575
|
-
entries.push(await materializeComponentEntry(plan, comp, git));
|
|
3576
|
-
} catch (e) {
|
|
3577
|
-
errors.push(`${comp.key}: ${e instanceof Error ? e.message : String(e)}`);
|
|
3578
|
-
}
|
|
3763
|
+
function formatTarget(target) {
|
|
3764
|
+
const semanticRef = resolveTargetSemanticRef(target);
|
|
3765
|
+
if (semanticRef) {
|
|
3766
|
+
return `semantic ref '${semanticRef}'`;
|
|
3579
3767
|
}
|
|
3580
|
-
return
|
|
3768
|
+
return `product '${resolveTargetProductName(target) ?? "<unset>"}'`;
|
|
3581
3769
|
}
|
|
3582
|
-
|
|
3583
|
-
const
|
|
3584
|
-
|
|
3585
|
-
|
|
3586
|
-
for (const comp of plan.components) {
|
|
3587
|
-
const root = componentDir(plan.workspaceRoot, comp.key);
|
|
3588
|
-
const agentPaths = await git.listFiles(root, AGENTS_GLOB);
|
|
3589
|
-
const sortedAgentPaths = [...agentPaths].sort((a, b) => a.localeCompare(b));
|
|
3590
|
-
for (const p of sortedAgentPaths) {
|
|
3591
|
-
const content = await git.readFile(root, p);
|
|
3592
|
-
if (content !== null) {
|
|
3593
|
-
agentSources.push({
|
|
3594
|
-
componentKey: comp.key,
|
|
3595
|
-
filePath: p,
|
|
3596
|
-
content
|
|
3597
|
-
});
|
|
3598
|
-
aggregatedAgentsMdSources.push(`${comp.key}/${p}`);
|
|
3599
|
-
}
|
|
3600
|
-
}
|
|
3601
|
-
const skillPaths = await git.listFiles(root, SKILL_GLOB);
|
|
3602
|
-
for (const p of skillPaths) {
|
|
3603
|
-
const skillId = skillIdFromSkillPath(p);
|
|
3604
|
-
if (!skillId) {
|
|
3605
|
-
continue;
|
|
3606
|
-
}
|
|
3607
|
-
const content = await git.readFile(root, p);
|
|
3608
|
-
if (content !== null) {
|
|
3609
|
-
skillSources.push({ componentKey: comp.key, skillId, content });
|
|
3610
|
-
}
|
|
3611
|
-
}
|
|
3770
|
+
function resolvePreTurnTargetStartSelection(inputs) {
|
|
3771
|
+
const target = inputs[0]?.target;
|
|
3772
|
+
if (target && resolveTargetSemanticRef(target) === "currentPrimaryPathLeaf") {
|
|
3773
|
+
return { kind: "semantic_ref", ref: "currentPrimaryPathLeaf" };
|
|
3612
3774
|
}
|
|
3613
|
-
|
|
3614
|
-
const skillsMap = collectSkills(skillSources);
|
|
3615
|
-
aggregatedAgentsMdSources.sort((a, b) => a.localeCompare(b));
|
|
3616
|
-
return { aggregatedAgentsMdSources, agentsMd, skillsMap };
|
|
3775
|
+
return null;
|
|
3617
3776
|
}
|
|
3618
|
-
|
|
3619
|
-
const
|
|
3620
|
-
|
|
3621
|
-
|
|
3622
|
-
|
|
3623
|
-
|
|
3624
|
-
|
|
3777
|
+
function resolvePreTurnTargetEntryId(input) {
|
|
3778
|
+
const semanticRef = resolveTargetSemanticRef(input.target);
|
|
3779
|
+
if (semanticRef) {
|
|
3780
|
+
return resolveProcessSemanticRefEntryId({
|
|
3781
|
+
ref: semanticRef,
|
|
3782
|
+
semanticEntryRefs: input.semanticEntryRefs,
|
|
3783
|
+
currentLeafId: input.currentLeafId,
|
|
3784
|
+
rootEntryId: input.rootEntryId,
|
|
3785
|
+
entryExists: input.entryExists
|
|
3786
|
+
});
|
|
3625
3787
|
}
|
|
3788
|
+
const productName = resolveTargetProductName(input.target);
|
|
3789
|
+
return productName ? resolveProcessProductRefEntryId({
|
|
3790
|
+
productName,
|
|
3791
|
+
productRefs: input.productRefs,
|
|
3792
|
+
entryExists: input.entryExists
|
|
3793
|
+
}) : null;
|
|
3626
3794
|
}
|
|
3627
|
-
|
|
3628
|
-
const
|
|
3629
|
-
|
|
3630
|
-
|
|
3631
|
-
|
|
3632
|
-
|
|
3633
|
-
|
|
3634
|
-
|
|
3635
|
-
|
|
3636
|
-
|
|
3637
|
-
|
|
3638
|
-
|
|
3639
|
-
|
|
3795
|
+
function validatePreTurnTargetedInputs(input) {
|
|
3796
|
+
const expectedEntryId = input.treePlan.startTarget.kind === "entry" ? input.treePlan.startTarget.entryId : input.treePlan.startTarget.kind === "current_leaf" ? input.currentLeafId : input.rootEntryId;
|
|
3797
|
+
for (const targetedInput of input.inputs) {
|
|
3798
|
+
if (targetedInput.bodyMarkdown.trim() === "") {
|
|
3799
|
+
return `Turn '${input.turnId}' cannot apply queued targeted input '${targetedInput.inputId}' because bodyMarkdown is empty`;
|
|
3800
|
+
}
|
|
3801
|
+
const targetEntryId = resolvePreTurnTargetEntryId({
|
|
3802
|
+
target: targetedInput.target,
|
|
3803
|
+
semanticEntryRefs: input.semanticEntryRefs,
|
|
3804
|
+
productRefs: input.productRefs,
|
|
3805
|
+
currentLeafId: input.currentLeafId,
|
|
3806
|
+
rootEntryId: input.rootEntryId,
|
|
3807
|
+
entryExists: input.entryExists
|
|
3808
|
+
});
|
|
3809
|
+
if (!targetEntryId) {
|
|
3810
|
+
if (resolveTargetSemanticRef(targetedInput.target) === "rootEntry" && input.treePlan.startTarget.kind === "root") {
|
|
3811
|
+
continue;
|
|
3812
|
+
}
|
|
3813
|
+
return `Turn '${input.turnId}' cannot apply queued targeted input '${targetedInput.inputId}' because ${formatTarget(targetedInput.target)} is not resolved`;
|
|
3814
|
+
}
|
|
3815
|
+
if (!expectedEntryId || expectedEntryId !== targetEntryId) {
|
|
3816
|
+
return `Turn '${input.turnId}' cannot apply queued targeted input '${targetedInput.inputId}' for ${formatTarget(targetedInput.target)} because the selected turn is not continuing from that branch`;
|
|
3817
|
+
}
|
|
3640
3818
|
}
|
|
3641
|
-
|
|
3642
|
-
|
|
3643
|
-
|
|
3644
|
-
|
|
3819
|
+
return null;
|
|
3820
|
+
}
|
|
3821
|
+
async function applyPreTurnTargetedInputs(input) {
|
|
3822
|
+
if (input.inputs.length === 0) {
|
|
3823
|
+
return;
|
|
3824
|
+
}
|
|
3825
|
+
for (const targetedInput of input.inputs) {
|
|
3826
|
+
const targetEntryId = await ensureIdentifiedPrompt({
|
|
3827
|
+
piHandle: input.piHandle,
|
|
3828
|
+
identity: { kind: "process_input", processInputId: targetedInput.inputId },
|
|
3829
|
+
content: targetedInput.bodyMarkdown,
|
|
3830
|
+
expectedParentId: input.recoveryBaseEntryId ?? input.piHandle.getLeafId(),
|
|
3831
|
+
allowDescendantParent: input.recoveryBaseEntryId !== void 0,
|
|
3832
|
+
requireOnCurrentBranch: input.reuseExistingWithoutBranching,
|
|
3833
|
+
reuseWithoutBranching: input.reuseExistingWithoutBranching,
|
|
3834
|
+
requireExisting: input.requireExisting
|
|
3835
|
+
});
|
|
3836
|
+
const semanticRef = resolveTargetSemanticRef(targetedInput.target);
|
|
3837
|
+
input.onApplied?.(targetedInput.inputId, targetedInput.sequence, {
|
|
3838
|
+
...input.pathType === "primary" ? { currentPrimaryPathLeafId: targetEntryId } : {},
|
|
3839
|
+
rootEntryId: resolveRootEntryIdFromHandle(input.piHandle),
|
|
3840
|
+
...semanticRef ? { targetSemanticRef: semanticRef } : { targetProductName: resolveTargetProductName(targetedInput.target) },
|
|
3841
|
+
targetEntryId
|
|
3842
|
+
});
|
|
3645
3843
|
}
|
|
3844
|
+
}
|
|
3845
|
+
|
|
3846
|
+
// src/worker-payloads.ts
|
|
3847
|
+
import {
|
|
3848
|
+
detectRepoLocatorKind,
|
|
3849
|
+
parseProcessProductRefs,
|
|
3850
|
+
parseSemanticEntryRefsFromStateJsonStrict,
|
|
3851
|
+
parseSemanticEntryRefsLenient
|
|
3852
|
+
} from "@leitwerk-dev/domain";
|
|
3853
|
+
function inputDeliveryToItem(delivery) {
|
|
3646
3854
|
return {
|
|
3647
|
-
|
|
3648
|
-
|
|
3649
|
-
|
|
3650
|
-
|
|
3651
|
-
|
|
3855
|
+
inputId: delivery.inputId,
|
|
3856
|
+
sequence: delivery.sequence,
|
|
3857
|
+
source: delivery.source,
|
|
3858
|
+
kind: delivery.kind,
|
|
3859
|
+
target: delivery.target,
|
|
3860
|
+
bodyMarkdown: delivery.bodyMarkdown
|
|
3652
3861
|
};
|
|
3653
3862
|
}
|
|
3654
|
-
|
|
3655
|
-
|
|
3656
|
-
|
|
3657
|
-
|
|
3863
|
+
function projectSnapshotsFromPayload(raw) {
|
|
3864
|
+
return raw.map((project) => ({
|
|
3865
|
+
id: project.id ?? "",
|
|
3866
|
+
instanceId: project.instanceId ?? "",
|
|
3867
|
+
key: project.key,
|
|
3868
|
+
repoLocator: project.repoLocator,
|
|
3869
|
+
repoLocatorKind: project.repoLocatorKind ?? detectRepoLocatorKind(project.repoLocator) ?? "remote_url",
|
|
3870
|
+
baseBranch: project.baseBranch,
|
|
3871
|
+
workBranch: project.workBranch ?? "",
|
|
3872
|
+
externalId: project.externalId ?? null,
|
|
3873
|
+
externalUrl: project.externalUrl ?? null,
|
|
3874
|
+
metadata: project.metadata ?? null,
|
|
3875
|
+
pipelineStatus: project.pipelineStatus ?? null,
|
|
3876
|
+
createdAt: project.createdAt ?? "",
|
|
3877
|
+
updatedAt: project.updatedAt ?? ""
|
|
3878
|
+
}));
|
|
3658
3879
|
}
|
|
3659
|
-
|
|
3660
|
-
const
|
|
3661
|
-
const parsed = raw === null ? null : deserializeManifest(raw);
|
|
3662
|
-
if (!parsed?.ok) {
|
|
3663
|
-
return {
|
|
3664
|
-
valid: false,
|
|
3665
|
-
diff: {
|
|
3666
|
-
stale: [],
|
|
3667
|
-
missing: serverProjects.map((p) => p.key),
|
|
3668
|
-
extra: [],
|
|
3669
|
-
unchanged: []
|
|
3670
|
-
},
|
|
3671
|
-
existingManifest: null
|
|
3672
|
-
};
|
|
3673
|
-
}
|
|
3674
|
-
const diff = diffManifest(parsed.manifest, serverProjects);
|
|
3675
|
-
const valid = diff.stale.length === 0 && diff.missing.length === 0 && diff.extra.length === 0;
|
|
3880
|
+
function buildProcessSnapshotSeed(processId, processSnapshot) {
|
|
3881
|
+
const resolvedProcessId = processSnapshot.processId ?? processId;
|
|
3676
3882
|
return {
|
|
3677
|
-
|
|
3678
|
-
|
|
3679
|
-
|
|
3883
|
+
id: processSnapshot.id ?? "",
|
|
3884
|
+
processId: resolvedProcessId,
|
|
3885
|
+
selectedTurnId: processSnapshot.selectedTurnId ?? null,
|
|
3886
|
+
lifecycleStatus: processSnapshot.lifecycleStatus ?? "discovered",
|
|
3887
|
+
currentExecution: processSnapshot.currentExecution ?? null,
|
|
3888
|
+
planRevision: processSnapshot.planRevision ?? 0,
|
|
3889
|
+
title: processSnapshot.title ?? null,
|
|
3890
|
+
externalId: processSnapshot.externalId ?? null,
|
|
3891
|
+
externalUrl: processSnapshot.externalUrl ?? null,
|
|
3892
|
+
metadata: processSnapshot.metadata ?? null,
|
|
3893
|
+
defaultModelProfileId: processSnapshot.defaultModelProfileId ?? null,
|
|
3894
|
+
turnConfigsJson: processSnapshot.turnConfigsJson ?? null,
|
|
3895
|
+
selectedTurnModelProfileId: processSnapshot.selectedTurnModelProfileId ?? null,
|
|
3896
|
+
paramsJson: processSnapshot.paramsJson ?? null,
|
|
3897
|
+
stateJson: processSnapshot.stateJson ?? null,
|
|
3898
|
+
createdAt: processSnapshot.createdAt ?? "",
|
|
3899
|
+
updatedAt: processSnapshot.updatedAt ?? ""
|
|
3680
3900
|
};
|
|
3681
3901
|
}
|
|
3682
|
-
|
|
3683
|
-
|
|
3684
|
-
|
|
3685
|
-
|
|
3686
|
-
|
|
3687
|
-
|
|
3688
|
-
errors,
|
|
3689
|
-
(componentKey) => toRepair.has(componentKey),
|
|
3690
|
-
(componentKey) => validation.existingManifest?.components.find((component) => component.key === componentKey) ?? null
|
|
3902
|
+
function readProcessSemanticEntryRefs(state) {
|
|
3903
|
+
if (typeof state !== "object" || state === null || Array.isArray(state)) {
|
|
3904
|
+
return null;
|
|
3905
|
+
}
|
|
3906
|
+
return parseSemanticEntryRefsLenient(
|
|
3907
|
+
state.semanticEntryRefs
|
|
3691
3908
|
);
|
|
3692
|
-
|
|
3909
|
+
}
|
|
3910
|
+
function readProcessProductRefs(state) {
|
|
3911
|
+
if (typeof state !== "object" || state === null || Array.isArray(state)) {
|
|
3912
|
+
return null;
|
|
3913
|
+
}
|
|
3914
|
+
return parseProcessProductRefs(state.productRefs);
|
|
3915
|
+
}
|
|
3916
|
+
function parseProcessSemanticEntryRefsFromStateJson(stateJson) {
|
|
3917
|
+
return parseSemanticEntryRefsFromStateJsonStrict(stateJson, "process stateJson");
|
|
3693
3918
|
}
|
|
3694
3919
|
|
|
3695
3920
|
// src/runtime/bootstrap.ts
|
|
@@ -3922,8 +4147,11 @@ async function bootstrapWorkerRuntime(deps) {
|
|
|
3922
4147
|
workBranch: project.workBranch ?? ""
|
|
3923
4148
|
}));
|
|
3924
4149
|
const plan = planRunRoot(workspaceRoot, deps.instanceId, runRootProjects);
|
|
3925
|
-
const runRootPreparation =
|
|
3926
|
-
|
|
4150
|
+
const runRootPreparation = resolvedWorkerProcess?.runtime?.repositoryCheckout === "none" ? mkdir5(workspaceRoot, { recursive: true }).then(() => ({
|
|
4151
|
+
aggregatedAgentsMdSources: [],
|
|
4152
|
+
loadedSkills: []
|
|
4153
|
+
})) : resolvedWorkerProcess?.runtime?.repositoryCheckout === "on_demand" ? prepareOnDemandRunRoot(plan, deps.gitOps) : deps.payload.resume ? validateRunRoot(workspaceRoot, runRootProjects, deps.gitOps).then(
|
|
4154
|
+
(validation) => repairRunRoot(validation, plan, deps.gitOps)
|
|
3927
4155
|
) : materializeRunRoot(plan, deps.gitOps);
|
|
3928
4156
|
const resolvedPiConfig = llmPayload ? resolveProcessPiConfig({
|
|
3929
4157
|
processId,
|
|
@@ -3936,7 +4164,7 @@ async function bootstrapWorkerRuntime(deps) {
|
|
|
3936
4164
|
projects: projectSnapshots
|
|
3937
4165
|
})
|
|
3938
4166
|
}) : { systemPrompt: "", availableToolNames: [] };
|
|
3939
|
-
const sessionCwd = resolvedPiConfig.sessionCwd ?
|
|
4167
|
+
const sessionCwd = resolvedPiConfig.sessionCwd ? path9.resolve(workspaceRoot, resolvedPiConfig.sessionCwd) : workspaceRoot;
|
|
3940
4168
|
const pendingInputs = (deps.payload.pendingInputs ?? []).map(inputDeliveryToItem);
|
|
3941
4169
|
const diagnostics = [];
|
|
3942
4170
|
let managedAgentDir = null;
|
|
@@ -3955,7 +4183,7 @@ async function bootstrapWorkerRuntime(deps) {
|
|
|
3955
4183
|
config: deps.payload.developmentTools,
|
|
3956
4184
|
repositories: projectSnapshots.map((project) => ({
|
|
3957
4185
|
repositoryKey: project.key,
|
|
3958
|
-
workingDirectory:
|
|
4186
|
+
workingDirectory: path9.join(workspaceRoot, project.key)
|
|
3959
4187
|
})),
|
|
3960
4188
|
signal: deps.toolPreparationSignal,
|
|
3961
4189
|
onProgress: deps.onToolPreparationProgress,
|
|
@@ -4151,11 +4379,13 @@ function validatePreparedSession(input) {
|
|
|
4151
4379
|
);
|
|
4152
4380
|
}
|
|
4153
4381
|
const base = {
|
|
4382
|
+
outcomeContract: turnStartState.start?.kind === "llm" ? turnStartState.start.outcomeContract : void 0,
|
|
4154
4383
|
processSnapshot: bootstrapped.processSnapshot,
|
|
4155
4384
|
projectSnapshots: bootstrapped.projectSnapshots,
|
|
4156
4385
|
resolvedWorkerProcess: process2,
|
|
4157
4386
|
selectedTurnId,
|
|
4158
4387
|
startRecordId: payload.turnStart.id,
|
|
4388
|
+
scopedSettings: turnStartState.start?.kind === "llm" ? turnStartState.start.scopedSettings : void 0,
|
|
4159
4389
|
proposedTurnRecordId: payload.turnStart.proposedTurnRecordId,
|
|
4160
4390
|
acceptedTurnRecordId: payload.turnStart.state.kind === "accepted" ? payload.turnStart.state.turnRecordId : null,
|
|
4161
4391
|
startKind: payload.turnStart.startKind,
|
|
@@ -4164,6 +4394,7 @@ function validatePreparedSession(input) {
|
|
|
4164
4394
|
workspaceRoot: payload.treePaths.workspaceRoot,
|
|
4165
4395
|
turnResultMarkdownBySemanticRef: payload.turnResultMarkdownBySemanticRef,
|
|
4166
4396
|
turnResultMarkdownByProduct: payload.turnResultMarkdownByProduct,
|
|
4397
|
+
inspectionProducts: payload.inspectionProducts,
|
|
4167
4398
|
settings,
|
|
4168
4399
|
integrationTools: payload.integrationTools ?? [],
|
|
4169
4400
|
...payload.iteration ? { iteration: payload.iteration } : {}
|
|
@@ -4270,14 +4501,15 @@ var WorkerLiveResources = class {
|
|
|
4270
4501
|
level: "warn",
|
|
4271
4502
|
code: "session_snapshot.upload_failed",
|
|
4272
4503
|
message: `Session snapshot upload failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
4273
|
-
details: { attempt, reason }
|
|
4504
|
+
details: { attempt, reason, transport: transportErrorDetails(error) }
|
|
4274
4505
|
});
|
|
4275
4506
|
if (attempt < 3) await this.deps.scheduler.sleep(100 * attempt);
|
|
4276
4507
|
}
|
|
4277
4508
|
}
|
|
4278
4509
|
if (!metadata.required) return;
|
|
4279
4510
|
throw new Error(
|
|
4280
|
-
`Mandatory session snapshot upload failed before ${reason}: ${lastError instanceof Error ? lastError.message : String(lastError)}
|
|
4511
|
+
`Mandatory session snapshot upload failed before ${reason}: ${lastError instanceof Error ? lastError.message : String(lastError)}`,
|
|
4512
|
+
{ cause: lastError }
|
|
4281
4513
|
);
|
|
4282
4514
|
}
|
|
4283
4515
|
async runTurn(operation) {
|
|
@@ -4314,7 +4546,7 @@ var WorkerLiveResources = class {
|
|
|
4314
4546
|
async function sampleCredentialFiles(descriptor) {
|
|
4315
4547
|
const values = {};
|
|
4316
4548
|
for (const credentialPath of descriptor.declaredCredentialPaths) {
|
|
4317
|
-
const json = JSON.parse(await readFile3(
|
|
4549
|
+
const json = JSON.parse(await readFile3(path10.join(descriptor.agentDir, credentialPath), "utf8"));
|
|
4318
4550
|
if (!json || typeof json !== "object" || Array.isArray(json)) {
|
|
4319
4551
|
throw new Error(`Credential file '${credentialPath}' must contain a JSON object`);
|
|
4320
4552
|
}
|
|
@@ -4397,6 +4629,13 @@ function extractSecretValuesFromPayload(payload) {
|
|
|
4397
4629
|
}
|
|
4398
4630
|
}
|
|
4399
4631
|
for (const value of extractDockerRegistrySecretValues(payload)) secrets.add(value);
|
|
4632
|
+
for (const credential of payload.repositoryCredentials ?? []) {
|
|
4633
|
+
const value = credential.kind === "git_ssh" ? credential.privateKey : credential.password;
|
|
4634
|
+
if (value) {
|
|
4635
|
+
secrets.add(value);
|
|
4636
|
+
secrets.add(encodeURIComponent(value));
|
|
4637
|
+
}
|
|
4638
|
+
}
|
|
4400
4639
|
return Array.from(secrets);
|
|
4401
4640
|
}
|
|
4402
4641
|
function extractDockerRegistrySecretValues(payload) {
|
|
@@ -4440,7 +4679,7 @@ function normalizeWorkerFailure(failure2) {
|
|
|
4440
4679
|
if (failure2.kind === "turn" || failure2.kind === "mandatory_snapshot") {
|
|
4441
4680
|
const correlation = failure2.correlation;
|
|
4442
4681
|
const turnError = failure2.kind === "turn" ? failure2.error : null;
|
|
4443
|
-
const summary2 = failure2.kind === "mandatory_snapshot" ? `Mandatory session snapshot upload failed before ${failure2.point}: ${message}` : turnError?.message ?? message;
|
|
4682
|
+
const summary2 = failure2.kind === "mandatory_snapshot" ? message.startsWith(`Mandatory session snapshot upload failed before ${failure2.point}: `) ? message : `Mandatory session snapshot upload failed before ${failure2.point}: ${message}` : turnError?.message ?? message;
|
|
4444
4683
|
const errorClass = turnError?.errorClass ?? classified.errorClass;
|
|
4445
4684
|
const payload = {
|
|
4446
4685
|
turnRecordId: correlation.turnRecordId,
|
|
@@ -4452,7 +4691,12 @@ function normalizeWorkerFailure(failure2) {
|
|
|
4452
4691
|
forkPiEntryId: correlation.forkPiEntryId ?? null,
|
|
4453
4692
|
resultPiEntryId: correlation.resultPiEntryId ?? null,
|
|
4454
4693
|
...turnError?.failureCode ? { failureCode: turnError.failureCode } : {},
|
|
4455
|
-
...failure2.kind === "mandatory_snapshot" ? {
|
|
4694
|
+
...failure2.kind === "mandatory_snapshot" ? {
|
|
4695
|
+
failureDetails: {
|
|
4696
|
+
reason: failure2.point,
|
|
4697
|
+
transport: transportErrorDetails(failure2.error)
|
|
4698
|
+
}
|
|
4699
|
+
} : turnError?.failureDetails ? { failureDetails: turnError.failureDetails } : {},
|
|
4456
4700
|
...turnError?.recoveryContext ? { recoveryContext: turnError.recoveryContext } : {}
|
|
4457
4701
|
};
|
|
4458
4702
|
return {
|
|
@@ -4462,7 +4706,8 @@ function normalizeWorkerFailure(failure2) {
|
|
|
4462
4706
|
message: failure2.kind === "mandatory_snapshot" ? summary2 : `Turn execution failed: ${summary2}`,
|
|
4463
4707
|
errorClass,
|
|
4464
4708
|
turnRecordId: correlation.turnRecordId,
|
|
4465
|
-
turnId: correlation.turnId
|
|
4709
|
+
turnId: correlation.turnId,
|
|
4710
|
+
...failure2.kind === "mandatory_snapshot" ? { details: payload.failureDetails ?? void 0 } : {}
|
|
4466
4711
|
},
|
|
4467
4712
|
stderrMessage: summary2,
|
|
4468
4713
|
terminal: {
|
|
@@ -5613,7 +5858,12 @@ function resolveWorkerRuntimeSettings(config, payload) {
|
|
|
5613
5858
|
}
|
|
5614
5859
|
|
|
5615
5860
|
// src/runtime/turn-execution.ts
|
|
5616
|
-
import {
|
|
5861
|
+
import { randomUUID as randomUUID6 } from "crypto";
|
|
5862
|
+
import {
|
|
5863
|
+
applyOutcomeContract,
|
|
5864
|
+
assertValidLlmTurnDefinition,
|
|
5865
|
+
resolveOutcomeContract
|
|
5866
|
+
} from "@leitwerk-dev/process-sdk";
|
|
5617
5867
|
|
|
5618
5868
|
// src/turn-execution-result.ts
|
|
5619
5869
|
var TurnExecutionFailure = class extends Error {
|
|
@@ -5638,12 +5888,12 @@ var TurnExecutionFailure = class extends Error {
|
|
|
5638
5888
|
};
|
|
5639
5889
|
|
|
5640
5890
|
// src/turn-record-id.ts
|
|
5641
|
-
import { randomUUID as
|
|
5891
|
+
import { randomUUID as randomUUID5 } from "crypto";
|
|
5642
5892
|
function resolveTurnRecordIdForExecution(process2, turnId, acceptedTurnRecordId) {
|
|
5643
5893
|
if (process2.selectedTurnId === turnId && typeof acceptedTurnRecordId === "string" && acceptedTurnRecordId.trim() !== "") {
|
|
5644
5894
|
return acceptedTurnRecordId;
|
|
5645
5895
|
}
|
|
5646
|
-
return `trn_${
|
|
5896
|
+
return `trn_${randomUUID5().replace(/-/g, "")}`;
|
|
5647
5897
|
}
|
|
5648
5898
|
|
|
5649
5899
|
// src/automatic-turn-executor.ts
|
|
@@ -6070,6 +6320,15 @@ function resolvePromptlessTurnResumeReason(input) {
|
|
|
6070
6320
|
}
|
|
6071
6321
|
|
|
6072
6322
|
// src/turn-outcome-tool-session.ts
|
|
6323
|
+
import {
|
|
6324
|
+
asUnknownRecord,
|
|
6325
|
+
isUnknownRecord as isUnknownRecord2
|
|
6326
|
+
} from "@leitwerk-dev/domain";
|
|
6327
|
+
import {
|
|
6328
|
+
compileOutcomeParameters as compileOutcomeParameters2,
|
|
6329
|
+
outcomeCallParameters,
|
|
6330
|
+
validateOutcomeParameters
|
|
6331
|
+
} from "@leitwerk-dev/process-sdk";
|
|
6073
6332
|
import { resolveTurnActiveToolNames } from "@leitwerk-dev/process-sdk/pi-config";
|
|
6074
6333
|
|
|
6075
6334
|
// src/question-tool.ts
|
|
@@ -6319,12 +6578,13 @@ function resolveMissingTurnToolCallRecovery(input) {
|
|
|
6319
6578
|
return null;
|
|
6320
6579
|
}
|
|
6321
6580
|
return {
|
|
6322
|
-
failureCode: missingMarkdownResult && missingOutcomeToolNames.length > 0 ? "missing_required_tool_calls" : missingMarkdownResult ? "missing_markdown_result" : "missing_outcome_tool",
|
|
6581
|
+
failureCode: input.rejectedOutcome && missingOutcomeToolNames.length > 0 ? "outcome_rejected" : missingMarkdownResult && missingOutcomeToolNames.length > 0 ? "missing_required_tool_calls" : missingMarkdownResult ? "missing_markdown_result" : "missing_outcome_tool",
|
|
6323
6582
|
missingToolNames: [
|
|
6324
6583
|
...missingMarkdownResult ? [MARKDOWN_RESULT_TOOL_NAME] : [],
|
|
6325
6584
|
...missingOutcomeToolNames
|
|
6326
6585
|
],
|
|
6327
6586
|
missingOutcomeToolNames,
|
|
6587
|
+
...input.rejectedOutcome && missingOutcomeToolNames.length > 0 ? { rejectedOutcome: input.rejectedOutcome } : {},
|
|
6328
6588
|
missingMarkdownResult,
|
|
6329
6589
|
requiresOutcomeToolMarkdown: Boolean(outcomeToolMarkdownParameterName),
|
|
6330
6590
|
...outcomeToolMarkdownParameterName ? { outcomeToolMarkdownParameterName } : {}
|
|
@@ -6332,9 +6592,15 @@ function resolveMissingTurnToolCallRecovery(input) {
|
|
|
6332
6592
|
}
|
|
6333
6593
|
function buildMissingTurnToolCallRecoveryPrompt(recovery) {
|
|
6334
6594
|
const lines = [
|
|
6335
|
-
"Your previous reply did not finish this turn because it missed required tool calls.",
|
|
6595
|
+
recovery.rejectedOutcome ? `Your ${recovery.rejectedOutcome.outcome} submission was rejected. The turn is still open.` : "Your previous reply did not finish this turn because it missed required tool calls.",
|
|
6336
6596
|
"Continue from your previous work without starting over."
|
|
6337
6597
|
];
|
|
6598
|
+
if (recovery.rejectedOutcome)
|
|
6599
|
+
lines.push(
|
|
6600
|
+
"Correct the rejected submission using these validation errors:",
|
|
6601
|
+
...recovery.rejectedOutcome.errors.map((error) => `- ${error}`),
|
|
6602
|
+
"Preserve your findings and correct the reported fields before submitting again."
|
|
6603
|
+
);
|
|
6338
6604
|
if (recovery.missingMarkdownResult && recovery.missingOutcomeToolNames.length > 0) {
|
|
6339
6605
|
lines.push(
|
|
6340
6606
|
"Call markdown_result now with the operator-facing markdown for this turn, then call the required outcome tool to finish."
|
|
@@ -6360,6 +6626,8 @@ function buildMissingTurnToolCallRecoveryPrompt(recovery) {
|
|
|
6360
6626
|
return lines.join("\n");
|
|
6361
6627
|
}
|
|
6362
6628
|
function describeMissingTurnToolCallRecovery(recovery) {
|
|
6629
|
+
if (recovery.rejectedOutcome)
|
|
6630
|
+
return `rejected '${recovery.rejectedOutcome.outcome}' submission: ${recovery.rejectedOutcome.errors.join("; ")}`;
|
|
6363
6631
|
if (recovery.missingMarkdownResult && recovery.missingOutcomeToolNames.length > 0) {
|
|
6364
6632
|
return `missing required tool calls (${MARKDOWN_RESULT_TOOL_NAME} and one outcome tool: ${recovery.missingOutcomeToolNames.join(", ")})`;
|
|
6365
6633
|
}
|
|
@@ -6399,10 +6667,14 @@ function cloneTurnResultMarkdownState(state) {
|
|
|
6399
6667
|
}
|
|
6400
6668
|
function createTurnOutcomeToolSession(input) {
|
|
6401
6669
|
let selectedOutcome = null;
|
|
6670
|
+
let abortReason;
|
|
6671
|
+
let rejectedOutcome;
|
|
6402
6672
|
let terminalAcknowledgement = { kind: "open" };
|
|
6403
6673
|
const turnResultMarkdownStateRef = { current: createTurnResultMarkdownState() };
|
|
6404
6674
|
const outcomeToolEntries = Object.entries(input.turnDef.outcomes ?? {});
|
|
6405
6675
|
const outcomeToolNames = outcomeToolEntries.map(([outcome]) => outcome);
|
|
6676
|
+
if (outcomeToolNames.includes("abort_turn") || input.integrationTools?.some((tool) => tool.name === "abort_turn"))
|
|
6677
|
+
throw new Error("Tool name 'abort_turn' is reserved for turn failure");
|
|
6406
6678
|
const usesOutcomeTools = outcomeToolEntries.length > 0;
|
|
6407
6679
|
const requiresMarkdownResultToolCall = input.turnDef.turnResultMarkdown?.mode === "tool_call" && input.turnDef.turnResultMarkdown.toolName === "markdown_result" && input.turnDef.turnResultMarkdown.required === true;
|
|
6408
6680
|
const hasResultImageTool = Boolean(
|
|
@@ -6412,31 +6684,39 @@ function createTurnOutcomeToolSession(input) {
|
|
|
6412
6684
|
const outcomeActions = outcomeToolEntries.map(([outcome, spec]) => {
|
|
6413
6685
|
const markdownParameterName = spec.turnResultMarkdownParameter ?? outcomeToolMarkdownParameterName;
|
|
6414
6686
|
const injectsGlobalMarkdownParameter = Boolean(outcomeToolMarkdownParameterName) && !spec.turnResultMarkdownParameter;
|
|
6687
|
+
const parameters = outcomeCallParameters(spec, outcomeToolMarkdownParameterName);
|
|
6415
6688
|
return {
|
|
6416
6689
|
name: outcome,
|
|
6417
6690
|
description: spec.description,
|
|
6418
|
-
|
|
6419
|
-
|
|
6420
|
-
...injectsGlobalMarkdownParameter ? {
|
|
6421
|
-
resultSummary: {
|
|
6422
|
-
type: "string",
|
|
6423
|
-
description: "Concise result summary for this attempt."
|
|
6424
|
-
}
|
|
6425
|
-
} : {},
|
|
6426
|
-
...injectsGlobalMarkdownParameter && outcomeToolMarkdownParameterName ? {
|
|
6427
|
-
[outcomeToolMarkdownParameterName]: {
|
|
6428
|
-
type: "string",
|
|
6429
|
-
description: "Operator-facing markdown result for this turn. Pass raw markdown only and do not wrap the entire markdown in triple backticks.",
|
|
6430
|
-
required: true,
|
|
6431
|
-
requiredErrorCode: `${outcomeToolMarkdownParameterName}_required`
|
|
6432
|
-
}
|
|
6433
|
-
} : {}
|
|
6434
|
-
},
|
|
6691
|
+
strictSchema: spec.strictSchema,
|
|
6692
|
+
parameters: compileOutcomeParameters2(parameters, spec.strictSchema),
|
|
6435
6693
|
executionMode: "sequential",
|
|
6436
6694
|
execute: async (args) => {
|
|
6695
|
+
if (abortReason) return { ok: false, status: "aborted", reason: abortReason };
|
|
6437
6696
|
const result = { status: "ok", outcome };
|
|
6438
6697
|
const acceptsOutcome = selectedOutcome === null;
|
|
6439
6698
|
if (acceptsOutcome) {
|
|
6699
|
+
const structuralErrors = validateOutcomeParameters(parameters, args).map(
|
|
6700
|
+
(issue) => issue.message
|
|
6701
|
+
);
|
|
6702
|
+
if (structuralErrors.length) {
|
|
6703
|
+
rejectedOutcome = { outcome, errors: structuralErrors };
|
|
6704
|
+
return { ok: false, status: "invalid", errors: structuralErrors };
|
|
6705
|
+
}
|
|
6706
|
+
if (input.validateOutcome) {
|
|
6707
|
+
let errors;
|
|
6708
|
+
try {
|
|
6709
|
+
errors = await input.validateOutcome({ outcome, params: args });
|
|
6710
|
+
} catch (error) {
|
|
6711
|
+
errors = [
|
|
6712
|
+
error instanceof Error ? error.message : "Outcome validation failed. Correct the submission and try again."
|
|
6713
|
+
];
|
|
6714
|
+
}
|
|
6715
|
+
if (errors.length) {
|
|
6716
|
+
rejectedOutcome = { outcome, errors: [...errors] };
|
|
6717
|
+
return { ok: false, status: "invalid", errors };
|
|
6718
|
+
}
|
|
6719
|
+
}
|
|
6440
6720
|
let outcomeParams = args;
|
|
6441
6721
|
if (spec.resultSummaryParameter && typeof args[spec.resultSummaryParameter] === "string")
|
|
6442
6722
|
turnResultMarkdownStateRef.current.resultSummary = String(
|
|
@@ -6449,6 +6729,7 @@ function createTurnOutcomeToolSession(input) {
|
|
|
6449
6729
|
spec.resultSummaryParameter ? args[spec.resultSummaryParameter] : injectsGlobalMarkdownParameter ? args.resultSummary : void 0
|
|
6450
6730
|
);
|
|
6451
6731
|
if (!published.response.ok) {
|
|
6732
|
+
rejectedOutcome = { outcome, errors: [published.response.message] };
|
|
6452
6733
|
return published.response;
|
|
6453
6734
|
}
|
|
6454
6735
|
turnResultMarkdownStateRef.current = published.state;
|
|
@@ -6459,6 +6740,7 @@ function createTurnOutcomeToolSession(input) {
|
|
|
6459
6740
|
}
|
|
6460
6741
|
}
|
|
6461
6742
|
selectedOutcome = { outcome, params: outcomeParams };
|
|
6743
|
+
rejectedOutcome = void 0;
|
|
6462
6744
|
}
|
|
6463
6745
|
maybeCaptureTurnResultMarkdownFromToolCall({
|
|
6464
6746
|
behavior: input.turnDef.turnResultMarkdown,
|
|
@@ -6474,7 +6756,7 @@ function createTurnOutcomeToolSession(input) {
|
|
|
6474
6756
|
}
|
|
6475
6757
|
};
|
|
6476
6758
|
});
|
|
6477
|
-
const questionTool = input.turnDef.askQuestions && input.turnRecordId && input.requestQuestions ? createAskQuestionsTool({
|
|
6759
|
+
const questionTool = input.turnDef.askQuestions && input.questionsEnabled !== false && input.turnRecordId && input.requestQuestions ? createAskQuestionsTool({
|
|
6478
6760
|
turnRecordId: input.turnRecordId,
|
|
6479
6761
|
request: input.requestQuestions
|
|
6480
6762
|
}) : null;
|
|
@@ -6482,8 +6764,28 @@ function createTurnOutcomeToolSession(input) {
|
|
|
6482
6764
|
...hasResultImageTool && input.resultImageTool ? [input.resultImageTool] : [],
|
|
6483
6765
|
...input.turnDef.turnResultMarkdown?.mode === "tool_call" && input.turnDef.turnResultMarkdown.toolName === "markdown_result" ? [createMarkdownResultTool(turnResultMarkdownStateRef)] : [],
|
|
6484
6766
|
...outcomeActions,
|
|
6767
|
+
{
|
|
6768
|
+
name: "abort_turn",
|
|
6769
|
+
description: "Stop this turn as an error when the requested work cannot be completed. Explain the blocker in reason. Preserves the workspace for recovery and does not advance the process.",
|
|
6770
|
+
parameters: {
|
|
6771
|
+
type: "object",
|
|
6772
|
+
properties: { reason: { type: "string", minLength: 1 } },
|
|
6773
|
+
required: ["reason"],
|
|
6774
|
+
additionalProperties: false
|
|
6775
|
+
},
|
|
6776
|
+
executionMode: "sequential",
|
|
6777
|
+
execute: async (args) => {
|
|
6778
|
+
if (selectedOutcome)
|
|
6779
|
+
return { ok: false, message: "An outcome has already been accepted for this turn." };
|
|
6780
|
+
const reason = typeof args.reason === "string" ? args.reason.trim() : "";
|
|
6781
|
+
if (!reason) return { ok: false, message: "A non-empty abort reason is required." };
|
|
6782
|
+
abortReason ??= reason;
|
|
6783
|
+
rejectedOutcome = void 0;
|
|
6784
|
+
return { status: "aborted", reason: abortReason };
|
|
6785
|
+
}
|
|
6786
|
+
},
|
|
6485
6787
|
...questionTool ? [questionTool] : [],
|
|
6486
|
-
...input.integrationTools ?? []
|
|
6788
|
+
...(input.integrationTools ?? []).filter((tool) => tool.modelVisible !== false)
|
|
6487
6789
|
];
|
|
6488
6790
|
const activeTools = resolveTurnActiveToolNames({
|
|
6489
6791
|
turnId: input.turnId,
|
|
@@ -6520,10 +6822,13 @@ function createTurnOutcomeToolSession(input) {
|
|
|
6520
6822
|
usesOutcomeTools,
|
|
6521
6823
|
hasResultImageTool
|
|
6522
6824
|
});
|
|
6825
|
+
next += "\n\nIf the requested work cannot be completed, call abort_turn with a concrete reason instead of a success outcome. This stops the current turn in error without advancing the process. Aborting requires no result Markdown or completion tool call.";
|
|
6523
6826
|
return next;
|
|
6524
6827
|
},
|
|
6525
6828
|
reset(baseState) {
|
|
6526
6829
|
selectedOutcome = cloneSelectedOutcome(baseState?.selectedOutcome ?? null);
|
|
6830
|
+
abortReason = baseState?.abortReason;
|
|
6831
|
+
rejectedOutcome = baseState?.rejectedOutcome ? structuredClone(baseState.rejectedOutcome) : void 0;
|
|
6527
6832
|
terminalAcknowledgement = selectedOutcome === null ? { kind: "open" } : { kind: "acknowledgement_succeeded" };
|
|
6528
6833
|
turnResultMarkdownStateRef.current = cloneTurnResultMarkdownState(
|
|
6529
6834
|
baseState?.markdownState ?? createTurnResultMarkdownState()
|
|
@@ -6532,10 +6837,30 @@ function createTurnOutcomeToolSession(input) {
|
|
|
6532
6837
|
getCompletionState() {
|
|
6533
6838
|
return {
|
|
6534
6839
|
selectedOutcome: cloneSelectedOutcome(selectedOutcome),
|
|
6535
|
-
markdownState: cloneTurnResultMarkdownState(turnResultMarkdownStateRef.current)
|
|
6840
|
+
markdownState: cloneTurnResultMarkdownState(turnResultMarkdownStateRef.current),
|
|
6841
|
+
...abortReason ? { abortReason } : {},
|
|
6842
|
+
...rejectedOutcome ? { rejectedOutcome: structuredClone(rejectedOutcome) } : {}
|
|
6843
|
+
};
|
|
6844
|
+
},
|
|
6845
|
+
recordToolResult(value) {
|
|
6846
|
+
if (abortReason) return true;
|
|
6847
|
+
const message = asUnknownRecord(value);
|
|
6848
|
+
if (selectedOutcome || !message) return false;
|
|
6849
|
+
if (message.role !== "toolResult" || typeof message.toolName !== "string" || !outcomeToolNames.includes(message.toolName))
|
|
6850
|
+
return false;
|
|
6851
|
+
const details = isUnknownRecord2(message.details) ? message.details : {};
|
|
6852
|
+
if (message.isError !== true && details.ok !== false) return false;
|
|
6853
|
+
const errors = Array.isArray(details.errors) ? details.errors.filter((error) => typeof error === "string") : Array.isArray(message.content) ? message.content.flatMap(
|
|
6854
|
+
(block) => isUnknownRecord2(block) && block.type === "text" && typeof block.text === "string" ? [block.text] : []
|
|
6855
|
+
) : [];
|
|
6856
|
+
rejectedOutcome = {
|
|
6857
|
+
outcome: message.toolName,
|
|
6858
|
+
errors: errors.length ? errors : ["Tool rejected the submission; correct its arguments using the tool schema."]
|
|
6536
6859
|
};
|
|
6860
|
+
return true;
|
|
6537
6861
|
},
|
|
6538
6862
|
shouldBlockToolCall(toolName) {
|
|
6863
|
+
if (abortReason) return `Tool '${toolName}' was skipped because this turn was aborted.`;
|
|
6539
6864
|
if (selectedOutcome === null) {
|
|
6540
6865
|
return null;
|
|
6541
6866
|
}
|
|
@@ -6545,6 +6870,7 @@ function createTurnOutcomeToolSession(input) {
|
|
|
6545
6870
|
return `Tool '${toolName}' was skipped because an outcome has already been accepted for this turn.`;
|
|
6546
6871
|
},
|
|
6547
6872
|
resolveOutcome(turnDef) {
|
|
6873
|
+
if (abortReason) return null;
|
|
6548
6874
|
if (usesOutcomeTools) {
|
|
6549
6875
|
return selectedOutcome;
|
|
6550
6876
|
}
|
|
@@ -6554,11 +6880,13 @@ function createTurnOutcomeToolSession(input) {
|
|
|
6554
6880
|
} : null;
|
|
6555
6881
|
},
|
|
6556
6882
|
resolveMissingToolRecovery(completionState) {
|
|
6883
|
+
if (completionState.abortReason) return null;
|
|
6557
6884
|
return resolveMissingTurnToolCallRecovery({
|
|
6558
6885
|
selectedOutcome: completionState.selectedOutcome,
|
|
6559
6886
|
outcomeToolNames,
|
|
6560
6887
|
turnResultMarkdownBehavior: input.turnDef.turnResultMarkdown,
|
|
6561
|
-
turnResultMarkdownState: completionState.markdownState
|
|
6888
|
+
turnResultMarkdownState: completionState.markdownState,
|
|
6889
|
+
rejectedOutcome: completionState.rejectedOutcome
|
|
6562
6890
|
});
|
|
6563
6891
|
},
|
|
6564
6892
|
buildRecoveryContext(recovery) {
|
|
@@ -6566,7 +6894,7 @@ function createTurnOutcomeToolSession(input) {
|
|
|
6566
6894
|
strategy: "continue",
|
|
6567
6895
|
suggestedContinuePrompt: buildMissingTurnToolCallRecoveryPrompt(recovery),
|
|
6568
6896
|
failureCode: recovery.failureCode,
|
|
6569
|
-
|
|
6897
|
+
...!recovery.rejectedOutcome && recovery.missingToolNames.length > 0 ? { missingToolNames: recovery.missingToolNames } : {}
|
|
6570
6898
|
};
|
|
6571
6899
|
},
|
|
6572
6900
|
describeRecovery: describeMissingTurnToolCallRecovery,
|
|
@@ -6618,6 +6946,18 @@ async function executeLogicalPromptPlan(input) {
|
|
|
6618
6946
|
const taint = (reason) => input.emit?.({ kind: "session_tainted", reason });
|
|
6619
6947
|
let currentPlan = input.plan;
|
|
6620
6948
|
let compactionContinueAttempts = 0;
|
|
6949
|
+
const requestCompactionContinuation = (resultPiEntryId, afterError = false) => {
|
|
6950
|
+
compactionContinueAttempts += 1;
|
|
6951
|
+
trace({
|
|
6952
|
+
level: "info",
|
|
6953
|
+
code: afterError ? "turn.compaction_error_continue_requested" : "turn.compaction_continue_requested",
|
|
6954
|
+
message: `Turn '${input.turnId}' requested an explicit continue after ${afterError ? "context-window compaction" : "compaction"}`,
|
|
6955
|
+
turnRecordId: input.turnRecordId,
|
|
6956
|
+
turnId: input.turnId,
|
|
6957
|
+
details: { attempt: compactionContinueAttempts, resultPiEntryId }
|
|
6958
|
+
});
|
|
6959
|
+
currentPlan = DEFAULT_CONTINUATION_PLAN;
|
|
6960
|
+
};
|
|
6621
6961
|
const reportFailure = (error, args) => {
|
|
6622
6962
|
const failure2 = buildTurnFailureReport(error, {
|
|
6623
6963
|
turnId: input.turnId,
|
|
@@ -6649,17 +6989,24 @@ async function executeLogicalPromptPlan(input) {
|
|
|
6649
6989
|
for (; ; ) {
|
|
6650
6990
|
const plan = currentPlan;
|
|
6651
6991
|
const guardSuspension = new PromptGuardSuspension();
|
|
6652
|
-
const promptOptions =
|
|
6992
|
+
const promptOptions = {
|
|
6653
6993
|
tools: input.toolSession.tools,
|
|
6654
6994
|
activeTools: input.toolSession.activeTools,
|
|
6655
6995
|
shouldBlockToolCall: (toolName) => input.toolSession.shouldBlockToolCall(toolName),
|
|
6996
|
+
shouldStopAfterTurn: (toolResults) => {
|
|
6997
|
+
let rejected = false;
|
|
6998
|
+
for (const message of toolResults) {
|
|
6999
|
+
rejected = input.toolSession.recordToolResult(message) || rejected;
|
|
7000
|
+
}
|
|
7001
|
+
return rejected || Boolean(input.toolSession.getCompletionState().abortReason);
|
|
7002
|
+
},
|
|
6656
7003
|
suspendPromptGuards: () => guardSuspension.suspend(),
|
|
6657
7004
|
terminalAcknowledgement: {
|
|
6658
7005
|
...input.toolSession.terminalAcknowledgement,
|
|
6659
7006
|
timeoutMs: TERMINAL_ACKNOWLEDGEMENT_TIMEOUT_MS,
|
|
6660
7007
|
isOperatorAbortRequested: () => input.operatorAbortSignal?.aborted === true
|
|
6661
7008
|
}
|
|
6662
|
-
}
|
|
7009
|
+
};
|
|
6663
7010
|
let runPrompt = () => plan.kind === "continue" ? input.piHandle.continueTurn(promptOptions) : input.piHandle.prompt(plan.promptText ?? "", promptOptions);
|
|
6664
7011
|
if (plan.kind === "continue") {
|
|
6665
7012
|
try {
|
|
@@ -6717,7 +7064,11 @@ async function executeLogicalPromptPlan(input) {
|
|
|
6717
7064
|
"Terminal acknowledgement did not complete and was ignored"
|
|
6718
7065
|
);
|
|
6719
7066
|
}
|
|
7067
|
+
for (const entryId of attempt.result.createdEntryIds) {
|
|
7068
|
+
input.toolSession.recordToolResult(input.piHandle.getEntry(entryId)?.message);
|
|
7069
|
+
}
|
|
6720
7070
|
const completionState = input.toolSession.getCompletionState();
|
|
7071
|
+
if (completionState.abortReason) throw new Error(completionState.abortReason);
|
|
6721
7072
|
const acknowledgementFailure = input.toolSession.terminalAcknowledgement.failureReason();
|
|
6722
7073
|
if (acknowledgementFailure) {
|
|
6723
7074
|
trace({
|
|
@@ -6734,19 +7085,7 @@ async function executeLogicalPromptPlan(input) {
|
|
|
6734
7085
|
sawCompaction: attempt.sawCompaction,
|
|
6735
7086
|
compactionContinueAttempts
|
|
6736
7087
|
})) {
|
|
6737
|
-
|
|
6738
|
-
trace({
|
|
6739
|
-
level: "info",
|
|
6740
|
-
code: "turn.compaction_continue_requested",
|
|
6741
|
-
message: `Turn '${input.turnId}' requested an explicit continue after compaction`,
|
|
6742
|
-
turnRecordId: input.turnRecordId,
|
|
6743
|
-
turnId: input.turnId,
|
|
6744
|
-
details: {
|
|
6745
|
-
attempt: compactionContinueAttempts,
|
|
6746
|
-
resultPiEntryId: attempt.result.resultEntryId
|
|
6747
|
-
}
|
|
6748
|
-
});
|
|
6749
|
-
currentPlan = DEFAULT_CONTINUATION_PLAN;
|
|
7088
|
+
requestCompactionContinuation(attempt.result.resultEntryId);
|
|
6750
7089
|
continue;
|
|
6751
7090
|
}
|
|
6752
7091
|
return {
|
|
@@ -6755,24 +7094,19 @@ async function executeLogicalPromptPlan(input) {
|
|
|
6755
7094
|
resolvedOutcome
|
|
6756
7095
|
};
|
|
6757
7096
|
} catch (error) {
|
|
7097
|
+
const { abortReason } = input.toolSession.getCompletionState();
|
|
7098
|
+
if (abortReason)
|
|
7099
|
+
return input.reportFailedTurn(
|
|
7100
|
+
"llm_error",
|
|
7101
|
+
`Turn aborted by LLM: ${abortReason}`,
|
|
7102
|
+
input.piHandle.getLeafId()
|
|
7103
|
+
);
|
|
6758
7104
|
if (shouldAutoContinueAfterCompactionError({
|
|
6759
7105
|
error,
|
|
6760
7106
|
piHandle: input.piHandle,
|
|
6761
7107
|
compactionContinueAttempts
|
|
6762
7108
|
})) {
|
|
6763
|
-
|
|
6764
|
-
trace({
|
|
6765
|
-
level: "info",
|
|
6766
|
-
code: "turn.compaction_error_continue_requested",
|
|
6767
|
-
message: `Turn '${input.turnId}' requested an explicit continue after context-window compaction`,
|
|
6768
|
-
turnRecordId: input.turnRecordId,
|
|
6769
|
-
turnId: input.turnId,
|
|
6770
|
-
details: {
|
|
6771
|
-
attempt: compactionContinueAttempts,
|
|
6772
|
-
resultPiEntryId: input.piHandle.getLeafId()
|
|
6773
|
-
}
|
|
6774
|
-
});
|
|
6775
|
-
currentPlan = DEFAULT_CONTINUATION_PLAN;
|
|
7109
|
+
requestCompactionContinuation(input.piHandle.getLeafId(), true);
|
|
6776
7110
|
continue;
|
|
6777
7111
|
}
|
|
6778
7112
|
return reportFailure(error, {
|
|
@@ -6790,60 +7124,64 @@ var MAX_MISSING_TOOL_CALL_RECOVERY_ATTEMPTS = 3;
|
|
|
6790
7124
|
async function runMissingToolRecovery(input) {
|
|
6791
7125
|
const trace = (payload) => input.emit?.({ kind: "trace", payload });
|
|
6792
7126
|
const reportError = (payload) => input.emit?.({ kind: "error", payload });
|
|
6793
|
-
|
|
6794
|
-
|
|
6795
|
-
);
|
|
6796
|
-
if (!baseMissingToolRecovery) {
|
|
7127
|
+
let recovery = input.toolSession.resolveMissingToolRecovery(input.initialAttempt.completionState);
|
|
7128
|
+
if (!recovery) {
|
|
6797
7129
|
return { finalAttempt: input.initialAttempt };
|
|
6798
7130
|
}
|
|
6799
|
-
|
|
6800
|
-
|
|
7131
|
+
let recoveryContext = input.toolSession.buildRecoveryContext(recovery);
|
|
7132
|
+
let description = input.toolSession.describeRecovery(recovery);
|
|
6801
7133
|
reportError({
|
|
6802
7134
|
level: "warn",
|
|
6803
|
-
code: "turn.required_tool_call_missing",
|
|
6804
|
-
message: `Turn '${input.turnId}'
|
|
7135
|
+
code: recovery.rejectedOutcome ? "turn.outcome_rejected" : "turn.required_tool_call_missing",
|
|
7136
|
+
message: `Turn '${input.turnId}' did not complete: ${description}`,
|
|
6805
7137
|
turnRecordId: input.turnRecordId,
|
|
6806
7138
|
turnId: input.turnId,
|
|
6807
7139
|
errorClass: "protocol_error",
|
|
6808
7140
|
details: {
|
|
6809
7141
|
attemptBudget: MAX_MISSING_TOOL_CALL_RECOVERY_ATTEMPTS,
|
|
6810
|
-
missingToolNames:
|
|
7142
|
+
missingToolNames: recovery.missingToolNames
|
|
6811
7143
|
}
|
|
6812
7144
|
});
|
|
6813
7145
|
let finalAttempt = input.initialAttempt;
|
|
7146
|
+
let unchangedRejections = 0;
|
|
6814
7147
|
for (let recoveryAttempt = 1; recoveryAttempt <= MAX_MISSING_TOOL_CALL_RECOVERY_ATTEMPTS; recoveryAttempt += 1) {
|
|
6815
7148
|
trace({
|
|
6816
7149
|
level: "info",
|
|
6817
7150
|
code: "turn.required_tool_call_retry_requested",
|
|
6818
|
-
message: `Turn '${input.turnId}' is retrying
|
|
7151
|
+
message: `Turn '${input.turnId}' is retrying: ${description}`,
|
|
6819
7152
|
turnRecordId: input.turnRecordId,
|
|
6820
7153
|
turnId: input.turnId,
|
|
6821
7154
|
details: {
|
|
6822
7155
|
recoveryAttempt,
|
|
6823
|
-
missingToolNames:
|
|
7156
|
+
missingToolNames: recovery.missingToolNames
|
|
6824
7157
|
}
|
|
6825
7158
|
});
|
|
7159
|
+
const previousAttempt = finalAttempt;
|
|
6826
7160
|
finalAttempt = await input.executeLogicalPromptPlan(
|
|
6827
7161
|
{
|
|
6828
7162
|
kind: "continue",
|
|
6829
7163
|
continueUserPrompt: recoveryContext.suggestedContinuePrompt,
|
|
6830
|
-
prepareForContinuation: async () => await input.piHandle.branch(
|
|
7164
|
+
prepareForContinuation: async () => await input.piHandle.branch(previousAttempt.promptResult.resultEntryId)
|
|
6831
7165
|
},
|
|
6832
|
-
{ baseState:
|
|
7166
|
+
{ baseState: previousAttempt.completionState }
|
|
6833
7167
|
);
|
|
6834
|
-
|
|
6835
|
-
|
|
6836
|
-
|
|
7168
|
+
const nextRecovery = input.toolSession.resolveMissingToolRecovery(finalAttempt.completionState);
|
|
7169
|
+
if (!nextRecovery) return { finalAttempt };
|
|
7170
|
+
unchangedRejections = recovery.rejectedOutcome && JSON.stringify(recovery.rejectedOutcome) === JSON.stringify(nextRecovery.rejectedOutcome) ? unchangedRejections + 1 : 0;
|
|
7171
|
+
recovery = nextRecovery;
|
|
7172
|
+
recoveryContext = input.toolSession.buildRecoveryContext(recovery);
|
|
7173
|
+
description = input.toolSession.describeRecovery(recovery);
|
|
7174
|
+
if (unchangedRejections >= 2) break;
|
|
6837
7175
|
}
|
|
6838
7176
|
reportError({
|
|
6839
7177
|
level: "error",
|
|
6840
7178
|
code: "turn.required_tool_call_retry_exhausted",
|
|
6841
|
-
message: `Turn '${input.turnId}'
|
|
7179
|
+
message: `Turn '${input.turnId}' stopped automatic recovery: ${description}`,
|
|
6842
7180
|
turnRecordId: input.turnRecordId,
|
|
6843
7181
|
turnId: input.turnId,
|
|
6844
7182
|
errorClass: "protocol_error",
|
|
6845
7183
|
details: {
|
|
6846
|
-
missingToolNames:
|
|
7184
|
+
missingToolNames: recovery.missingToolNames
|
|
6847
7185
|
}
|
|
6848
7186
|
});
|
|
6849
7187
|
return {
|
|
@@ -7020,6 +7358,24 @@ async function executeLlmTurn(input) {
|
|
|
7020
7358
|
turnId,
|
|
7021
7359
|
turnRecordId,
|
|
7022
7360
|
turnDef: input.turnDef,
|
|
7361
|
+
questionsEnabled: input.turnDef.resolveAskQuestions?.({
|
|
7362
|
+
...input.ctx,
|
|
7363
|
+
prepared: input.prepared
|
|
7364
|
+
}),
|
|
7365
|
+
...input.turnDef.validateOutcome ? {
|
|
7366
|
+
validateOutcome: async (outcome) => input.turnDef.validateOutcome(
|
|
7367
|
+
{
|
|
7368
|
+
...input.ctx,
|
|
7369
|
+
prepared: input.prepared,
|
|
7370
|
+
callIntegrationTool: input.callbacks.callIntegrationTool ?? (async () => {
|
|
7371
|
+
throw new Error("Integration tools unavailable");
|
|
7372
|
+
}),
|
|
7373
|
+
reportProgress: input.callbacks.reportProgress ?? (() => {
|
|
7374
|
+
})
|
|
7375
|
+
},
|
|
7376
|
+
outcome
|
|
7377
|
+
)
|
|
7378
|
+
} : {},
|
|
7023
7379
|
requestQuestions: input.callbacks.requestQuestions,
|
|
7024
7380
|
integrationTools: input.callbacks.integrationTools,
|
|
7025
7381
|
resultImageTool: input.resultImageTools.create({
|
|
@@ -7270,7 +7626,7 @@ async function executeLlmTurn(input) {
|
|
|
7270
7626
|
const { recoveryContext, description } = recoveryResult.failure;
|
|
7271
7627
|
return reportFailedTurn(
|
|
7272
7628
|
"protocol_error",
|
|
7273
|
-
`Turn '${turnId}'
|
|
7629
|
+
`Turn '${turnId}' did not complete within the recovery budget of ${MAX_MISSING_TOOL_CALL_RECOVERY_ATTEMPTS} attempts: ${description}`,
|
|
7274
7630
|
finalPromptResult.resultEntryId,
|
|
7275
7631
|
{
|
|
7276
7632
|
recoveryContext,
|
|
@@ -7359,6 +7715,44 @@ async function executeSelectedTurn(input) {
|
|
|
7359
7715
|
}
|
|
7360
7716
|
const handler = resolvedWorkerProcess.definition.turns.get(currentTurnId);
|
|
7361
7717
|
if (!handler) throw new Error(`Validated turn handler '${currentTurnId}' is unavailable`);
|
|
7718
|
+
const supplyId = randomUUID6();
|
|
7719
|
+
input.emit({
|
|
7720
|
+
kind: "inspection",
|
|
7721
|
+
turnRecordId: input.turnRecordId,
|
|
7722
|
+
capture: {
|
|
7723
|
+
id: supplyId,
|
|
7724
|
+
version: 1,
|
|
7725
|
+
timestamp: input.scheduler.now().toISOString(),
|
|
7726
|
+
fact: {
|
|
7727
|
+
kind: "supplied_context",
|
|
7728
|
+
origin: input.session.kind === "llm" ? input.session.preparedTurnStart : null,
|
|
7729
|
+
products: input.session.inspectionProducts ?? []
|
|
7730
|
+
}
|
|
7731
|
+
}
|
|
7732
|
+
});
|
|
7733
|
+
const products = input.session.turnResultMarkdownByProduct;
|
|
7734
|
+
const observedProducts = products ? Object.fromEntries(Object.keys(products).map((name) => [name, products[name]])) : void 0;
|
|
7735
|
+
const consumedProducts = /* @__PURE__ */ new Set();
|
|
7736
|
+
for (const name of Object.keys(observedProducts ?? {})) {
|
|
7737
|
+
Object.defineProperty(observedProducts, name, {
|
|
7738
|
+
enumerable: true,
|
|
7739
|
+
get() {
|
|
7740
|
+
if (consumedProducts.has(name)) return products?.[name];
|
|
7741
|
+
consumedProducts.add(name);
|
|
7742
|
+
input.emit({
|
|
7743
|
+
kind: "inspection",
|
|
7744
|
+
turnRecordId: input.turnRecordId,
|
|
7745
|
+
capture: {
|
|
7746
|
+
id: `${supplyId}:product:${name}`,
|
|
7747
|
+
version: 1,
|
|
7748
|
+
timestamp: input.scheduler.now().toISOString(),
|
|
7749
|
+
fact: { kind: "product_consumed", supplyId, name }
|
|
7750
|
+
}
|
|
7751
|
+
});
|
|
7752
|
+
return products?.[name];
|
|
7753
|
+
}
|
|
7754
|
+
});
|
|
7755
|
+
}
|
|
7362
7756
|
let automaticIntegrationCallIndex = 0;
|
|
7363
7757
|
let latestProgressReport = null;
|
|
7364
7758
|
const reportProgress = (report) => {
|
|
@@ -7377,12 +7771,24 @@ async function executeSelectedTurn(input) {
|
|
|
7377
7771
|
});
|
|
7378
7772
|
};
|
|
7379
7773
|
const ctx = {
|
|
7774
|
+
reportDiagnostic(report) {
|
|
7775
|
+
input.emit({
|
|
7776
|
+
kind: "trace",
|
|
7777
|
+
payload: {
|
|
7778
|
+
...report,
|
|
7779
|
+
turnRecordId: input.turnRecordId,
|
|
7780
|
+
turnId: currentTurnId,
|
|
7781
|
+
timestamp: input.scheduler.now().toISOString()
|
|
7782
|
+
}
|
|
7783
|
+
});
|
|
7784
|
+
},
|
|
7785
|
+
scopedSettings: input.session.scopedSettings,
|
|
7380
7786
|
process: processSnapshot,
|
|
7381
7787
|
projects: projectSnapshots,
|
|
7382
7788
|
params: resolvedWorkerProcess.params,
|
|
7383
7789
|
state: resolvedWorkerProcess.state,
|
|
7384
7790
|
turnResultMarkdownBySemanticRef: input.session.turnResultMarkdownBySemanticRef,
|
|
7385
|
-
turnResultMarkdownByProduct:
|
|
7791
|
+
turnResultMarkdownByProduct: observedProducts,
|
|
7386
7792
|
workspaceRoot: input.session.workspaceRoot,
|
|
7387
7793
|
...input.session.iteration ? { iteration: input.session.iteration } : {},
|
|
7388
7794
|
...selectedTurnType === "automatic" ? {
|
|
@@ -7411,6 +7817,14 @@ async function executeSelectedTurn(input) {
|
|
|
7411
7817
|
`Selected turn '${currentTurnId}' of type '${selectedTurnType}' cannot call run.turn()`
|
|
7412
7818
|
);
|
|
7413
7819
|
}
|
|
7820
|
+
turnDef = applyOutcomeContract(
|
|
7821
|
+
turnDef,
|
|
7822
|
+
input.session.outcomeContract ?? resolveOutcomeContract(
|
|
7823
|
+
turnDef,
|
|
7824
|
+
{ params: ctx.params, state: ctx.state },
|
|
7825
|
+
input.session.iteration
|
|
7826
|
+
)
|
|
7827
|
+
);
|
|
7414
7828
|
assertValidLlmTurnDefinition(currentTurnId, turnDef);
|
|
7415
7829
|
if (!piHandle) {
|
|
7416
7830
|
throw new TurnExecutionError(
|
|
@@ -7466,6 +7880,8 @@ async function executeSelectedTurn(input) {
|
|
|
7466
7880
|
callbacks: {
|
|
7467
7881
|
requestQuestions: input.requestQuestions,
|
|
7468
7882
|
integrationTools: input.integrationTools,
|
|
7883
|
+
callIntegrationTool,
|
|
7884
|
+
reportProgress,
|
|
7469
7885
|
onPreTurnTargetedInputApplied(inputId, sequence, meta) {
|
|
7470
7886
|
appliedTargetedInputs.push({ inputId, sequence, ...meta ? { meta } : {} });
|
|
7471
7887
|
},
|
|
@@ -7556,6 +7972,11 @@ function createWorkerRuntime(options) {
|
|
|
7556
7972
|
const sampleCredentials = adapters.sampleCredentials ?? sampleCredentialFiles;
|
|
7557
7973
|
const ipc = adapters.transport;
|
|
7558
7974
|
const deliveredSecrets = /* @__PURE__ */ new Set();
|
|
7975
|
+
const inspectionSecrets = /* @__PURE__ */ new Set();
|
|
7976
|
+
const redactInspectionText = (text) => redactSecrets(
|
|
7977
|
+
text,
|
|
7978
|
+
[...inspectionSecrets].sort((a, b) => b.length - a.length)
|
|
7979
|
+
);
|
|
7559
7980
|
const redact = (text) => redactSecrets(
|
|
7560
7981
|
text,
|
|
7561
7982
|
[...deliveredSecrets].sort((a, b) => b.length - a.length)
|
|
@@ -7589,11 +8010,26 @@ function createWorkerRuntime(options) {
|
|
|
7589
8010
|
});
|
|
7590
8011
|
const questionBridge = new WorkerQuestionBridge(reporter);
|
|
7591
8012
|
const integrationToolBridge = new WorkerIntegrationToolBridge(reporter);
|
|
8013
|
+
const reportInspection = (capture, turnRecordId, selectedTurnId) => {
|
|
8014
|
+
reporter.project({
|
|
8015
|
+
kind: "protocol",
|
|
8016
|
+
type: "worker.event",
|
|
8017
|
+
payload: {
|
|
8018
|
+
eventType: "execution.inspection",
|
|
8019
|
+
selectedTurnId,
|
|
8020
|
+
data: { turnRecordId, capture: redactInspectionEvidence(capture, redactInspectionText) }
|
|
8021
|
+
}
|
|
8022
|
+
});
|
|
8023
|
+
};
|
|
7592
8024
|
let dispatch;
|
|
7593
8025
|
const piEvents = createPiEventReporter({
|
|
7594
8026
|
reporter,
|
|
7595
8027
|
emitExtensionEvent,
|
|
7596
8028
|
getCurrentSelectedTurnId: () => state.session?.selectedTurnId ?? null,
|
|
8029
|
+
getCurrentTurnRecordId: () => state.phase.kind === "active" ? state.phase.turnRecordId : null,
|
|
8030
|
+
reportInspection(capture, turnRecordId) {
|
|
8031
|
+
reportInspection(capture, turnRecordId, state.session?.selectedTurnId ?? null);
|
|
8032
|
+
},
|
|
7597
8033
|
getSessionTainted: () => state.sessionTainted,
|
|
7598
8034
|
onLifecycleObservation(kind) {
|
|
7599
8035
|
dispatch({ kind });
|
|
@@ -7720,10 +8156,20 @@ function createWorkerRuntime(options) {
|
|
|
7720
8156
|
(signal) => executeSelectedTurn({
|
|
7721
8157
|
session: command.session,
|
|
7722
8158
|
requestQuestions: (request) => questionBridge.request(request),
|
|
7723
|
-
integrationTools:
|
|
7724
|
-
|
|
7725
|
-
|
|
7726
|
-
|
|
8159
|
+
integrationTools: [
|
|
8160
|
+
...integrationToolBridge.createTools(
|
|
8161
|
+
command.session.integrationTools,
|
|
8162
|
+
command.turnRecordId
|
|
8163
|
+
),
|
|
8164
|
+
...command.session.resolvedWorkerProcess.runtime?.repositoryCheckout === "on_demand" ? [
|
|
8165
|
+
createCheckoutTool(
|
|
8166
|
+
command.session.workspaceRoot,
|
|
8167
|
+
command.session.processSnapshot.id,
|
|
8168
|
+
command.session.projectSnapshots,
|
|
8169
|
+
adapters.gitOps
|
|
8170
|
+
)
|
|
8171
|
+
] : []
|
|
8172
|
+
],
|
|
7727
8173
|
piHandle: resources.piHandle,
|
|
7728
8174
|
turnRecordId: command.turnRecordId,
|
|
7729
8175
|
targetedInputs: command.targetedInputs,
|
|
@@ -7731,7 +8177,13 @@ function createWorkerRuntime(options) {
|
|
|
7731
8177
|
resultImageTools: adapters.resultImageTools,
|
|
7732
8178
|
signal,
|
|
7733
8179
|
emit(emission) {
|
|
7734
|
-
if (emission.kind === "
|
|
8180
|
+
if (emission.kind === "inspection") {
|
|
8181
|
+
reportInspection(
|
|
8182
|
+
emission.capture,
|
|
8183
|
+
emission.turnRecordId,
|
|
8184
|
+
command.session.selectedTurnId
|
|
8185
|
+
);
|
|
8186
|
+
} else if (emission.kind === "session_tainted") {
|
|
7735
8187
|
complete({ kind: "session_tainted", reason: emission.reason });
|
|
7736
8188
|
} else if (emission.kind === "trace") {
|
|
7737
8189
|
reporter.workerTrace(emission.payload, command.session.selectedTurnId);
|
|
@@ -7776,13 +8228,15 @@ function createWorkerRuntime(options) {
|
|
|
7776
8228
|
);
|
|
7777
8229
|
return;
|
|
7778
8230
|
case "sample_credentials":
|
|
7779
|
-
void sampleCredentials(command.descriptor).then(
|
|
7780
|
-
(
|
|
8231
|
+
void sampleCredentials(command.descriptor).then((sample) => {
|
|
8232
|
+
for (const value of Object.values(sample.values))
|
|
8233
|
+
if (value) inspectionSecrets.add(value);
|
|
8234
|
+
complete({
|
|
7781
8235
|
kind: "credential_sampled",
|
|
7782
8236
|
providerId: command.descriptor.providerId,
|
|
7783
8237
|
...sample
|
|
7784
|
-
})
|
|
7785
|
-
).catch(
|
|
8238
|
+
});
|
|
8239
|
+
}).catch(
|
|
7786
8240
|
(error) => complete({
|
|
7787
8241
|
kind: "credential_sample_failed",
|
|
7788
8242
|
providerId: command.descriptor.providerId,
|
|
@@ -7851,9 +8305,12 @@ function createWorkerRuntime(options) {
|
|
|
7851
8305
|
drain();
|
|
7852
8306
|
};
|
|
7853
8307
|
const receive = (message) => {
|
|
7854
|
-
if (message.type === "worker.start")
|
|
8308
|
+
if (message.type === "worker.start") {
|
|
8309
|
+
for (const secret of extractSecretValuesFromPayload(message.payload))
|
|
8310
|
+
inspectionSecrets.add(secret);
|
|
7855
8311
|
for (const secret of extractDockerRegistrySecretValues(message.payload))
|
|
7856
8312
|
deliveredSecrets.add(secret);
|
|
8313
|
+
}
|
|
7857
8314
|
if (message.type === "worker.integration_tool_result") {
|
|
7858
8315
|
integrationToolBridge.handle(message);
|
|
7859
8316
|
return;
|
|
@@ -7896,7 +8353,7 @@ function createWorkerRuntime(options) {
|
|
|
7896
8353
|
|
|
7897
8354
|
// src/entry-runtime.ts
|
|
7898
8355
|
import { existsSync as existsSync5, readFileSync as readFileSync3 } from "fs";
|
|
7899
|
-
import
|
|
8356
|
+
import path14 from "path";
|
|
7900
8357
|
import { isUnknownRecord as isRecord } from "@leitwerk-dev/domain";
|
|
7901
8358
|
import {
|
|
7902
8359
|
buildExtensionCatalog,
|
|
@@ -7923,10 +8380,10 @@ import {
|
|
|
7923
8380
|
|
|
7924
8381
|
// src/extension-entry-roots.ts
|
|
7925
8382
|
import { existsSync as existsSync2, realpathSync } from "fs";
|
|
7926
|
-
import
|
|
8383
|
+
import path11 from "path";
|
|
7927
8384
|
function isWithinDirectory(parentDir, candidatePath) {
|
|
7928
|
-
const relative =
|
|
7929
|
-
return relative === "" || !relative.startsWith("..") && !
|
|
8385
|
+
const relative = path11.relative(parentDir, candidatePath);
|
|
8386
|
+
return relative === "" || !relative.startsWith("..") && !path11.isAbsolute(relative);
|
|
7930
8387
|
}
|
|
7931
8388
|
function parseExtensionAllowedRoots(value) {
|
|
7932
8389
|
if (!value) return [];
|
|
@@ -7938,7 +8395,7 @@ function parseExtensionAllowedRoots(value) {
|
|
|
7938
8395
|
}
|
|
7939
8396
|
if (!Array.isArray(parsed) || parsed.some((entry) => typeof entry !== "string")) return [];
|
|
7940
8397
|
return parsed.flatMap((entry) => {
|
|
7941
|
-
if (!
|
|
8398
|
+
if (!path11.isAbsolute(entry) || !existsSync2(entry)) return [];
|
|
7942
8399
|
return [realpathSync(entry)];
|
|
7943
8400
|
});
|
|
7944
8401
|
}
|
|
@@ -8016,27 +8473,6 @@ function webSocketDataToText(data) {
|
|
|
8016
8473
|
}
|
|
8017
8474
|
return data.toString("utf8");
|
|
8018
8475
|
}
|
|
8019
|
-
var connectionErrorCodes = /* @__PURE__ */ new Set([
|
|
8020
|
-
"ECONNREFUSED",
|
|
8021
|
-
"ECONNRESET",
|
|
8022
|
-
"ENOTFOUND",
|
|
8023
|
-
"EAI_AGAIN",
|
|
8024
|
-
"ETIMEDOUT",
|
|
8025
|
-
"ENETUNREACH",
|
|
8026
|
-
"EHOSTUNREACH",
|
|
8027
|
-
"CERT_HAS_EXPIRED",
|
|
8028
|
-
"DEPTH_ZERO_SELF_SIGNED_CERT"
|
|
8029
|
-
]);
|
|
8030
|
-
function connectionErrorCode(value) {
|
|
8031
|
-
for (let depth = 0; depth < 4 && value && typeof value === "object"; depth += 1) {
|
|
8032
|
-
const error = value;
|
|
8033
|
-
if (typeof error.code === "string" && connectionErrorCodes.has(error.code)) {
|
|
8034
|
-
return error.code;
|
|
8035
|
-
}
|
|
8036
|
-
value = error.error ?? error.cause;
|
|
8037
|
-
}
|
|
8038
|
-
return "websocket_error";
|
|
8039
|
-
}
|
|
8040
8476
|
function createWebSocketWorkerIpc(input) {
|
|
8041
8477
|
let messageHandler;
|
|
8042
8478
|
let errorHandler;
|
|
@@ -8153,7 +8589,9 @@ function createWebSocketWorkerIpc(input) {
|
|
|
8153
8589
|
socket.addEventListener("message", (event) => deliverText(webSocketDataToText(event.data)));
|
|
8154
8590
|
socket.addEventListener("error", (event) => {
|
|
8155
8591
|
if (stopping) return;
|
|
8156
|
-
input.onDiagnostic?.(
|
|
8592
|
+
input.onDiagnostic?.(
|
|
8593
|
+
diagnostic(`error=${transportErrorCode(event) ?? "websocket_error"}`)
|
|
8594
|
+
);
|
|
8157
8595
|
if (!reconnectEnabled) {
|
|
8158
8596
|
emitError(event instanceof Error ? event : new Error("Worker WebSocket error"));
|
|
8159
8597
|
}
|
|
@@ -8216,7 +8654,7 @@ function createWorkerIpcFromEnvironment(input) {
|
|
|
8216
8654
|
// src/result-image-upload.ts
|
|
8217
8655
|
import { constants } from "fs";
|
|
8218
8656
|
import { open as open2, realpath, stat } from "fs/promises";
|
|
8219
|
-
import
|
|
8657
|
+
import path12 from "path";
|
|
8220
8658
|
import { setTimeout as sleep } from "timers/promises";
|
|
8221
8659
|
import {
|
|
8222
8660
|
buildWorkerResultImageUploadPath,
|
|
@@ -8240,12 +8678,12 @@ function failure(entry, code, message) {
|
|
|
8240
8678
|
return { ...entry, status: "failed", code, message };
|
|
8241
8679
|
}
|
|
8242
8680
|
function isWithinRoot(rootReal, fileReal) {
|
|
8243
|
-
const relative =
|
|
8244
|
-
return relative !== ".." && !relative.startsWith(`..${
|
|
8681
|
+
const relative = path12.relative(rootReal, fileReal);
|
|
8682
|
+
return relative !== ".." && !relative.startsWith(`..${path12.sep}`) && !path12.isAbsolute(relative);
|
|
8245
8683
|
}
|
|
8246
8684
|
async function readBoundedWorkspaceFile(entry, workspaceRoot, maxSizeBytes) {
|
|
8247
8685
|
const rootReal = await realpath(workspaceRoot);
|
|
8248
|
-
const candidatePath =
|
|
8686
|
+
const candidatePath = path12.resolve(workspaceRoot, entry.path);
|
|
8249
8687
|
const fileReal = await realpath(candidatePath);
|
|
8250
8688
|
if (!isWithinRoot(rootReal, fileReal)) {
|
|
8251
8689
|
return failure(
|
|
@@ -8453,6 +8891,8 @@ function createWorkerSessionSnapshotExchange(input) {
|
|
|
8453
8891
|
},
|
|
8454
8892
|
body: content,
|
|
8455
8893
|
signal: AbortSignal.timeout(timeoutMs)
|
|
8894
|
+
}).catch((cause) => {
|
|
8895
|
+
throw new Error("Session snapshot transport failed", { cause });
|
|
8456
8896
|
});
|
|
8457
8897
|
if (!response.ok) {
|
|
8458
8898
|
throw new Error(`Session snapshot upload failed with HTTP ${response.status}`);
|
|
@@ -8494,7 +8934,7 @@ import {
|
|
|
8494
8934
|
writeFileSync as writeFileSync3
|
|
8495
8935
|
} from "fs";
|
|
8496
8936
|
import { tmpdir } from "os";
|
|
8497
|
-
import
|
|
8937
|
+
import path13 from "path";
|
|
8498
8938
|
import {
|
|
8499
8939
|
clearRepositoryGitHttpsHelpers,
|
|
8500
8940
|
clearRepositoryGitSshWrappers,
|
|
@@ -8512,17 +8952,17 @@ var NodeRunRootGitOps = class {
|
|
|
8512
8952
|
configureRepositoryCredentials(credentials) {
|
|
8513
8953
|
this.cleanupRepositoryCredentials();
|
|
8514
8954
|
if (credentials.length === 0) return;
|
|
8515
|
-
const root = mkdtempSync2(
|
|
8955
|
+
const root = mkdtempSync2(path13.join(tmpdir(), "leitwerk-repo-auth-"));
|
|
8516
8956
|
chmodSync2(root, 448);
|
|
8517
8957
|
this.#credentialDir = root;
|
|
8518
8958
|
try {
|
|
8519
8959
|
for (const credential of credentials) {
|
|
8520
|
-
const dir =
|
|
8960
|
+
const dir = path13.join(root, encodeURIComponent(credential.projectKey));
|
|
8521
8961
|
mkdirSync2(dir, { mode: 448 });
|
|
8522
8962
|
if (credential.kind === "git_https") {
|
|
8523
8963
|
const url = repositoryHttpsUrl2(credential.repositoryUrl);
|
|
8524
8964
|
writeFileSync3(
|
|
8525
|
-
|
|
8965
|
+
path13.join(dir, "credential.json"),
|
|
8526
8966
|
JSON.stringify({
|
|
8527
8967
|
host: url.host,
|
|
8528
8968
|
path: url.pathname.slice(1),
|
|
@@ -8531,14 +8971,14 @@ var NodeRunRootGitOps = class {
|
|
|
8531
8971
|
}),
|
|
8532
8972
|
{ mode: 384 }
|
|
8533
8973
|
);
|
|
8534
|
-
const helper =
|
|
8974
|
+
const helper = path13.join(dir, "credential.cjs");
|
|
8535
8975
|
writeFileSync3(helper, HTTPS_CREDENTIAL_HELPER, { mode: 448 });
|
|
8536
8976
|
setRepositoryGitHttpsHelper(credential.projectKey, helper);
|
|
8537
8977
|
continue;
|
|
8538
8978
|
}
|
|
8539
|
-
const key =
|
|
8540
|
-
const hosts =
|
|
8541
|
-
const wrapper =
|
|
8979
|
+
const key = path13.join(dir, "identity");
|
|
8980
|
+
const hosts = path13.join(dir, "known_hosts");
|
|
8981
|
+
const wrapper = path13.join(dir, "ssh");
|
|
8542
8982
|
writeFileSync3(key, `${credential.privateKey.trim()}
|
|
8543
8983
|
`, { mode: 384 });
|
|
8544
8984
|
writeFileSync3(hosts, `${credential.knownHosts.trim()}
|
|
@@ -8565,7 +9005,7 @@ exec ssh -F /dev/null -o IdentitiesOnly=yes -o IdentityFile="${key}" -o UserKnow
|
|
|
8565
9005
|
}
|
|
8566
9006
|
async runGit(args, cwd, projectKey) {
|
|
8567
9007
|
const result = await execa2(resolveGitBinary(), repositoryGitArgs(args), {
|
|
8568
|
-
...cwd ? { cwd:
|
|
9008
|
+
...cwd ? { cwd: path13.resolve(cwd) } : {},
|
|
8569
9009
|
env: repositoryGitSubprocessEnv(projectKey ?? "", { GIT_TERMINAL_PROMPT: "0" }),
|
|
8570
9010
|
extendEnv: false,
|
|
8571
9011
|
stdin: "ignore"
|
|
@@ -8573,30 +9013,46 @@ exec ssh -F /dev/null -o IdentitiesOnly=yes -o IdentityFile="${key}" -o UserKnow
|
|
|
8573
9013
|
return result.stdout;
|
|
8574
9014
|
}
|
|
8575
9015
|
async writeFile(repoDir, filePath, content) {
|
|
8576
|
-
const absolutePath =
|
|
8577
|
-
mkdirSync2(
|
|
9016
|
+
const absolutePath = path13.resolve(path13.join(repoDir, filePath));
|
|
9017
|
+
mkdirSync2(path13.dirname(absolutePath), { recursive: true });
|
|
8578
9018
|
writeFileSync3(absolutePath, content, "utf8");
|
|
8579
9019
|
}
|
|
8580
9020
|
async readFile(repoDir, filePath) {
|
|
8581
|
-
const absolutePath =
|
|
9021
|
+
const absolutePath = path13.resolve(path13.join(repoDir, filePath));
|
|
8582
9022
|
if (!existsSync4(absolutePath)) {
|
|
8583
9023
|
return null;
|
|
8584
9024
|
}
|
|
8585
9025
|
return readFileSync2(absolutePath, "utf8");
|
|
8586
9026
|
}
|
|
8587
9027
|
async clone(repoLocator, targetDir) {
|
|
8588
|
-
const absoluteTargetDir =
|
|
9028
|
+
const absoluteTargetDir = path13.resolve(targetDir);
|
|
8589
9029
|
rmSync2(absoluteTargetDir, { recursive: true, force: true });
|
|
8590
|
-
mkdirSync2(
|
|
9030
|
+
mkdirSync2(path13.dirname(absoluteTargetDir), { recursive: true });
|
|
8591
9031
|
await this.runGit(
|
|
8592
9032
|
["clone", repoLocator, absoluteTargetDir],
|
|
8593
9033
|
void 0,
|
|
8594
|
-
|
|
9034
|
+
path13.basename(absoluteTargetDir)
|
|
8595
9035
|
);
|
|
8596
9036
|
}
|
|
8597
9037
|
async checkout(repoDir, branch) {
|
|
8598
9038
|
await this.runGit(["checkout", branch], repoDir);
|
|
8599
9039
|
}
|
|
9040
|
+
async checkoutRevision(repoDir, revision) {
|
|
9041
|
+
if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(revision))
|
|
9042
|
+
throw new Error("Use a captured full commit SHA");
|
|
9043
|
+
if ((await this.runGit(["status", "--porcelain", "--untracked-files=all"], repoDir)).trim())
|
|
9044
|
+
throw new Error(
|
|
9045
|
+
"Repository has local changes; preserve or remove them before retrying inspection"
|
|
9046
|
+
);
|
|
9047
|
+
try {
|
|
9048
|
+
await this.runGit(["cat-file", "-e", `${revision}^{commit}`], repoDir);
|
|
9049
|
+
} catch {
|
|
9050
|
+
await this.runGit(["fetch", "origin", revision], repoDir, path13.basename(repoDir));
|
|
9051
|
+
}
|
|
9052
|
+
await this.runGit(["checkout", "--detach", revision], repoDir);
|
|
9053
|
+
if ((await this.getHeadSha(repoDir)).toLowerCase() !== revision.toLowerCase())
|
|
9054
|
+
throw new Error("Checkout HEAD does not match captured commit");
|
|
9055
|
+
}
|
|
8600
9056
|
async createBranch(repoDir, branchName, startPoint) {
|
|
8601
9057
|
await this.runGit(["branch", branchName, startPoint], repoDir);
|
|
8602
9058
|
}
|
|
@@ -8615,7 +9071,7 @@ exec ssh -F /dev/null -o IdentitiesOnly=yes -o IdentityFile="${key}" -o UserKnow
|
|
|
8615
9071
|
return (await this.runGit(["rev-parse", "HEAD"], repoDir)).trim();
|
|
8616
9072
|
}
|
|
8617
9073
|
async listFiles(repoDir, pattern) {
|
|
8618
|
-
const absoluteRoot =
|
|
9074
|
+
const absoluteRoot = path13.resolve(repoDir);
|
|
8619
9075
|
if (!existsSync4(absoluteRoot)) {
|
|
8620
9076
|
return [];
|
|
8621
9077
|
}
|
|
@@ -8658,9 +9114,9 @@ function listWorkspacePatterns(workspaces) {
|
|
|
8658
9114
|
return [];
|
|
8659
9115
|
}
|
|
8660
9116
|
function findWorkspaceRoot(startDir) {
|
|
8661
|
-
let current =
|
|
9117
|
+
let current = path14.resolve(startDir);
|
|
8662
9118
|
while (true) {
|
|
8663
|
-
const packageJsonPath =
|
|
9119
|
+
const packageJsonPath = path14.join(current, "package.json");
|
|
8664
9120
|
if (existsSync5(packageJsonPath)) {
|
|
8665
9121
|
try {
|
|
8666
9122
|
const parsed = JSON.parse(readFileSync3(packageJsonPath, "utf8"));
|
|
@@ -8670,7 +9126,7 @@ function findWorkspaceRoot(startDir) {
|
|
|
8670
9126
|
} catch {
|
|
8671
9127
|
}
|
|
8672
9128
|
}
|
|
8673
|
-
const parent =
|
|
9129
|
+
const parent = path14.dirname(current);
|
|
8674
9130
|
if (parent === current) {
|
|
8675
9131
|
return null;
|
|
8676
9132
|
}
|
|
@@ -8796,4 +9252,4 @@ export {
|
|
|
8796
9252
|
createWorkerRuntime,
|
|
8797
9253
|
createWorkerEntryRuntime
|
|
8798
9254
|
};
|
|
8799
|
-
//# sourceMappingURL=chunk-
|
|
9255
|
+
//# sourceMappingURL=chunk-KJCBXN5F.js.map
|