@leitwerk-dev/worker 0.3.0 → 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-4WNVRNE5.js → chunk-KJCBXN5F.js} +1856 -1394
- 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.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -3
- 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 +5 -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/pi-resource-bundle.d.ts +8 -1
- package/dist/pi-resource-bundle.d.ts.map +1 -1
- package/dist/runtime/bootstrap-session.d.ts +5 -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/index.ts +1 -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 +222 -337
- package/src/pi-event-reporter.ts +8 -0
- package/src/pi-inspection.ts +126 -0
- package/src/pi-resource-bundle.ts +12 -2
- package/src/runtime/bootstrap-session.ts +14 -1
- package/src/runtime/bootstrap.ts +16 -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 +71 -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 +19 -0
- package/src/workspace/run-root.ts +62 -26
- package/dist/chunk-4WNVRNE5.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,
|
|
@@ -1842,29 +1885,155 @@ var SdkPiTreeHandleFactory = class {
|
|
|
1842
1885
|
}
|
|
1843
1886
|
};
|
|
1844
1887
|
|
|
1845
|
-
// src/
|
|
1846
|
-
import {
|
|
1847
|
-
import { mkdir as mkdir2, rename, writeFile as writeFile2 } from "fs/promises";
|
|
1888
|
+
// src/pi-resource-bundle.ts
|
|
1889
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
1890
|
+
import { mkdir as mkdir2, open, readFile, rename, rm, writeFile as writeFile2 } from "fs/promises";
|
|
1848
1891
|
import path3 from "path";
|
|
1849
|
-
import {
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1892
|
+
import {
|
|
1893
|
+
createCanonicalPiResourceBundle,
|
|
1894
|
+
sha256Digest,
|
|
1895
|
+
validateResourceRelativePath,
|
|
1896
|
+
verifyCanonicalPiResourceBundle
|
|
1897
|
+
} from "@leitwerk-dev/worker-protocol";
|
|
1898
|
+
function fail(message) {
|
|
1899
|
+
throw new Error(`Invalid Pi resource bundle: ${message}`);
|
|
1900
|
+
}
|
|
1901
|
+
function requireStorageName(value, label) {
|
|
1902
|
+
if (!/^[a-zA-Z0-9_-]+$/u.test(value)) fail(`unsafe ${label}: ${value}`);
|
|
1903
|
+
return value;
|
|
1904
|
+
}
|
|
1905
|
+
async function atomicWrite(pathname, content, mode) {
|
|
1906
|
+
const staging = `${pathname}.staging-${process.pid}-${randomUUID2()}`;
|
|
1907
|
+
const handle = await open(staging, "wx", mode);
|
|
1908
|
+
try {
|
|
1909
|
+
await handle.writeFile(content);
|
|
1910
|
+
await handle.sync();
|
|
1911
|
+
} finally {
|
|
1912
|
+
await handle.close();
|
|
1913
|
+
}
|
|
1914
|
+
try {
|
|
1915
|
+
await rename(staging, pathname);
|
|
1916
|
+
} catch (error) {
|
|
1917
|
+
await rm(staging, { force: true });
|
|
1918
|
+
throw error;
|
|
1919
|
+
}
|
|
1920
|
+
}
|
|
1921
|
+
async function persistPiResourceBundleForStart(input) {
|
|
1922
|
+
const digest = requireStorageName(input.digest, "resource digest");
|
|
1923
|
+
const startRecordId = requireStorageName(input.startRecordId, "turn-start id");
|
|
1924
|
+
const bundlesDir = path3.resolve(input.bundlesDir);
|
|
1925
|
+
const startsDir = path3.join(bundlesDir, "starts");
|
|
1926
|
+
const bundlePath = path3.join(bundlesDir, `${digest}.tar`);
|
|
1927
|
+
await mkdir2(startsDir, { recursive: true, mode: 448 });
|
|
1928
|
+
let bundle = null;
|
|
1929
|
+
let reused = false;
|
|
1930
|
+
try {
|
|
1931
|
+
const existing = await readFile(bundlePath);
|
|
1932
|
+
verifyCanonicalPiResourceBundle(existing, digest);
|
|
1933
|
+
bundle = existing;
|
|
1934
|
+
reused = true;
|
|
1935
|
+
} catch (error) {
|
|
1936
|
+
if (error.code !== "ENOENT" && input.archiveBase64 === void 0) {
|
|
1937
|
+
throw error;
|
|
1938
|
+
}
|
|
1939
|
+
}
|
|
1940
|
+
if (!bundle) {
|
|
1941
|
+
if (!input.deliveredBundle && input.archiveBase64 === void 0) {
|
|
1942
|
+
throw new Error(`Pi resource bundle '${digest}' is unavailable on the process volume`);
|
|
1943
|
+
}
|
|
1944
|
+
bundle = input.deliveredBundle ?? Buffer.from(input.archiveBase64, "base64");
|
|
1945
|
+
verifyCanonicalPiResourceBundle(bundle, digest);
|
|
1946
|
+
await atomicWrite(bundlePath, bundle, 384);
|
|
1947
|
+
}
|
|
1948
|
+
const manifest = Buffer.from(
|
|
1949
|
+
`${JSON.stringify({ startRecordId, digest, persistedAt: (/* @__PURE__ */ new Date()).toISOString() })}
|
|
1950
|
+
`,
|
|
1951
|
+
"utf8"
|
|
1952
|
+
);
|
|
1953
|
+
await atomicWrite(path3.join(startsDir, `${startRecordId}.json`), manifest, 384);
|
|
1954
|
+
return { bundle, reused };
|
|
1955
|
+
}
|
|
1956
|
+
async function writeExtractedFiles(root, files) {
|
|
1957
|
+
for (const file of files) {
|
|
1958
|
+
const output = path3.resolve(root, file.path);
|
|
1959
|
+
if (path3.relative(root, output).startsWith("..") || path3.isAbsolute(path3.relative(root, output))) {
|
|
1960
|
+
fail(`path escapes materialization root: ${file.path}`);
|
|
1961
|
+
}
|
|
1962
|
+
await mkdir2(path3.dirname(output), { recursive: true, mode: 448 });
|
|
1963
|
+
await writeFile2(output, file.content, { mode: 420, flag: "wx" });
|
|
1964
|
+
}
|
|
1965
|
+
}
|
|
1966
|
+
async function materializeCanonicalPiResourceBundle(input) {
|
|
1967
|
+
const files = verifyCanonicalPiResourceBundle(input.bundle, input.digest);
|
|
1968
|
+
const targetDir = path3.resolve(input.targetDir);
|
|
1969
|
+
const parent = path3.dirname(targetDir);
|
|
1970
|
+
await mkdir2(parent, { recursive: true, mode: 448 });
|
|
1971
|
+
const marker = path3.join(targetDir, ".leitwerk-resource-digest");
|
|
1972
|
+
try {
|
|
1973
|
+
const current = await import("fs/promises").then(
|
|
1974
|
+
({ readFile: readFile5 }) => readFile5(marker, "utf8")
|
|
1975
|
+
);
|
|
1976
|
+
if (current === `${input.digest}
|
|
1977
|
+
`) return { targetDir, reused: true };
|
|
1978
|
+
throw new Error(
|
|
1979
|
+
`Managed Pi directory already exists with a different resource digest: ${targetDir}`
|
|
1980
|
+
);
|
|
1981
|
+
} catch (error) {
|
|
1982
|
+
if (error.code !== "ENOENT") throw error;
|
|
1983
|
+
}
|
|
1984
|
+
const staging = path3.join(
|
|
1985
|
+
parent,
|
|
1986
|
+
`.${path3.basename(targetDir)}.staging-${process.pid}-${randomUUID2()}`
|
|
1987
|
+
);
|
|
1988
|
+
try {
|
|
1989
|
+
await mkdir2(staging, { mode: 448 });
|
|
1990
|
+
await writeExtractedFiles(staging, files);
|
|
1991
|
+
await writeFile2(path3.join(staging, ".leitwerk-resource-digest"), `${input.digest}
|
|
1992
|
+
`, {
|
|
1993
|
+
mode: 384,
|
|
1994
|
+
flag: "wx"
|
|
1995
|
+
});
|
|
1996
|
+
await rename(staging, targetDir);
|
|
1997
|
+
return { targetDir, reused: false };
|
|
1998
|
+
} catch (error) {
|
|
1999
|
+
await rm(staging, { recursive: true, force: true });
|
|
2000
|
+
if (error.code === "EEXIST") {
|
|
2001
|
+
const current = await import("fs/promises").then(
|
|
2002
|
+
({ readFile: readFile5 }) => readFile5(marker, "utf8")
|
|
2003
|
+
);
|
|
2004
|
+
if (current === `${input.digest}
|
|
2005
|
+
`) return { targetDir, reused: true };
|
|
2006
|
+
}
|
|
2007
|
+
throw error;
|
|
2008
|
+
}
|
|
2009
|
+
}
|
|
2010
|
+
|
|
2011
|
+
// src/runtime/index.ts
|
|
2012
|
+
import { redactInspectionEvidence } from "@leitwerk-dev/domain";
|
|
2013
|
+
|
|
2014
|
+
// src/development-tool-environment.ts
|
|
2015
|
+
import { statfsSync } from "fs";
|
|
2016
|
+
import { mkdir as mkdir3, rename as rename2, writeFile as writeFile3 } from "fs/promises";
|
|
2017
|
+
import path4 from "path";
|
|
2018
|
+
import { execa } from "execa";
|
|
2019
|
+
var PINNED_MISE_VERSION = "2026.8.14";
|
|
2020
|
+
var OUTPUT_LIMIT_BYTES = 64 * 1024;
|
|
2021
|
+
var JSON_LIMIT_BYTES = 1024 * 1024;
|
|
2022
|
+
var TRACE_CHUNK_LENGTH = 16 * 1024;
|
|
2023
|
+
var DevelopmentToolPreparationError = class extends Error {
|
|
2024
|
+
/** @internal */
|
|
2025
|
+
constructor(message, code, diagnostics = "") {
|
|
2026
|
+
super(message);
|
|
2027
|
+
this.code = code;
|
|
2028
|
+
this.diagnostics = diagnostics;
|
|
2029
|
+
this.name = "DevelopmentToolPreparationError";
|
|
2030
|
+
}
|
|
2031
|
+
code;
|
|
2032
|
+
diagnostics;
|
|
2033
|
+
};
|
|
2034
|
+
function parseVersion(value) {
|
|
2035
|
+
const match = /(?:^|\s)(\d{4})\.(\d+)\.(\d+)(?:\s|$)/.exec(value);
|
|
2036
|
+
return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
|
|
1868
2037
|
}
|
|
1869
2038
|
function compareVersion(a, b) {
|
|
1870
2039
|
for (let index = 0; index < 3; index++) {
|
|
@@ -1926,18 +2095,18 @@ function buildMiseSubprocessEnvironment(base, config) {
|
|
|
1926
2095
|
}
|
|
1927
2096
|
}
|
|
1928
2097
|
if (config.runner === "isolated") {
|
|
1929
|
-
const miseRoot =
|
|
2098
|
+
const miseRoot = path4.join(config.processStorageRoot, "tooling", "mise");
|
|
1930
2099
|
env.MISE_DATA_DIR = miseRoot;
|
|
1931
|
-
env.MISE_INSTALLS_DIR =
|
|
1932
|
-
env.MISE_CACHE_DIR =
|
|
1933
|
-
env.MISE_STATE_DIR =
|
|
2100
|
+
env.MISE_INSTALLS_DIR = path4.join(miseRoot, "installs");
|
|
2101
|
+
env.MISE_CACHE_DIR = path4.join(miseRoot, "cache");
|
|
2102
|
+
env.MISE_STATE_DIR = path4.join(miseRoot, "state");
|
|
1934
2103
|
}
|
|
1935
2104
|
return env;
|
|
1936
2105
|
}
|
|
1937
2106
|
function localShimDirectory(env) {
|
|
1938
|
-
if (env.MISE_DATA_DIR) return
|
|
1939
|
-
if (env.XDG_DATA_HOME) return
|
|
1940
|
-
return
|
|
2107
|
+
if (env.MISE_DATA_DIR) return path4.join(env.MISE_DATA_DIR, "shims");
|
|
2108
|
+
if (env.XDG_DATA_HOME) return path4.join(env.XDG_DATA_HOME, "mise", "shims");
|
|
2109
|
+
return path4.join(env.HOME ?? "", ".local", "share", "mise", "shims");
|
|
1941
2110
|
}
|
|
1942
2111
|
function emitDiagnosticTrace(trace, value) {
|
|
1943
2112
|
if (!trace) return;
|
|
@@ -2000,6 +2169,7 @@ async function runCommand(input) {
|
|
|
2000
2169
|
input.signal?.addEventListener("abort", killGroup, { once: true });
|
|
2001
2170
|
try {
|
|
2002
2171
|
const result = await child;
|
|
2172
|
+
if (input.signal?.aborted || result.isCanceled || result.timedOut) killGroup();
|
|
2003
2173
|
const diagnostics = `${stdout}
|
|
2004
2174
|
${stderr}`.trim();
|
|
2005
2175
|
if (input.signal?.aborted || result.isCanceled) {
|
|
@@ -2112,11 +2282,11 @@ var MiseDevelopmentToolEnvironment = class {
|
|
|
2112
2282
|
);
|
|
2113
2283
|
if (input.config.runner === "isolated") {
|
|
2114
2284
|
await Promise.all(
|
|
2115
|
-
[env.MISE_DATA_DIR, env.MISE_INSTALLS_DIR, env.MISE_CACHE_DIR, env.MISE_STATE_DIR].filter((value) => Boolean(value)).map((directory) =>
|
|
2285
|
+
[env.MISE_DATA_DIR, env.MISE_INSTALLS_DIR, env.MISE_CACHE_DIR, env.MISE_STATE_DIR].filter((value) => Boolean(value)).map((directory) => mkdir3(directory, { recursive: true }))
|
|
2116
2286
|
);
|
|
2117
2287
|
}
|
|
2118
|
-
const shimDirectory = input.config.runner === "isolated" ?
|
|
2119
|
-
env.PATH = [shimDirectory, env.PATH].filter(Boolean).join(
|
|
2288
|
+
const shimDirectory = input.config.runner === "isolated" ? path4.join(env.MISE_DATA_DIR, "shims") : localShimDirectory({ ...this.baseEnv, ...env });
|
|
2289
|
+
env.PATH = [shimDirectory, env.PATH].filter(Boolean).join(path4.delimiter);
|
|
2120
2290
|
const repositories = [];
|
|
2121
2291
|
const warnings = [];
|
|
2122
2292
|
for (const repository of [...input.repositories].sort(
|
|
@@ -2188,20 +2358,20 @@ var MiseDevelopmentToolEnvironment = class {
|
|
|
2188
2358
|
const commandEnvironment = {
|
|
2189
2359
|
...this.baseEnv,
|
|
2190
2360
|
...Object.fromEntries(Object.entries(env).filter(([key]) => key.startsWith("MISE_"))),
|
|
2191
|
-
PATH: [shimDirectory, this.baseEnv.PATH].filter(Boolean).join(
|
|
2361
|
+
PATH: [shimDirectory, this.baseEnv.PATH].filter(Boolean).join(path4.delimiter)
|
|
2192
2362
|
};
|
|
2193
|
-
const evidenceDir =
|
|
2194
|
-
await
|
|
2363
|
+
const evidenceDir = path4.join(input.config.processStorageRoot, "tooling", "mise-preparation");
|
|
2364
|
+
await mkdir3(evidenceDir, { recursive: true });
|
|
2195
2365
|
const evidence = {
|
|
2196
2366
|
schemaVersion: 1,
|
|
2197
2367
|
preparedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2198
2368
|
miseVersion,
|
|
2199
2369
|
repositories
|
|
2200
2370
|
};
|
|
2201
|
-
const temporary =
|
|
2202
|
-
await
|
|
2371
|
+
const temporary = path4.join(evidenceDir, `.latest-${process.pid}.json`);
|
|
2372
|
+
await writeFile3(temporary, `${JSON.stringify(evidence, null, 2)}
|
|
2203
2373
|
`, { mode: 384 });
|
|
2204
|
-
await
|
|
2374
|
+
await rename2(temporary, path4.join(evidenceDir, "latest.json"));
|
|
2205
2375
|
return { miseVersion, commandEnvironment, repositories, warnings };
|
|
2206
2376
|
}
|
|
2207
2377
|
};
|
|
@@ -2446,6 +2616,12 @@ function createPiEventReporter(options) {
|
|
|
2446
2616
|
return {
|
|
2447
2617
|
attach(piHandle) {
|
|
2448
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
|
+
}
|
|
2449
2625
|
if (event.type === "turn.start") {
|
|
2450
2626
|
options.onLifecycleObservation?.("pi_turn_started");
|
|
2451
2627
|
resetPiRetryState();
|
|
@@ -2579,7 +2755,7 @@ async function restoreHandleAfterTurn(piHandle, plan) {
|
|
|
2579
2755
|
}
|
|
2580
2756
|
|
|
2581
2757
|
// src/worker-ipc-reporter.ts
|
|
2582
|
-
import { randomUUID } from "crypto";
|
|
2758
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
2583
2759
|
import { createIpcMessage } from "@leitwerk-dev/worker-protocol";
|
|
2584
2760
|
|
|
2585
2761
|
// src/diagnostics.ts
|
|
@@ -2651,7 +2827,7 @@ function createWorkerIpcReporter(options) {
|
|
|
2651
2827
|
options.send(
|
|
2652
2828
|
createIpcMessage({
|
|
2653
2829
|
type: fact.type,
|
|
2654
|
-
messageId:
|
|
2830
|
+
messageId: randomUUID3(),
|
|
2655
2831
|
instanceId: options.instanceId,
|
|
2656
2832
|
workerId: options.workerId,
|
|
2657
2833
|
sentAt: options.now().toISOString(),
|
|
@@ -2685,438 +2861,782 @@ function createWorkerIpcReporter(options) {
|
|
|
2685
2861
|
};
|
|
2686
2862
|
}
|
|
2687
2863
|
|
|
2688
|
-
// src/
|
|
2689
|
-
import
|
|
2690
|
-
import path9 from "path";
|
|
2864
|
+
// src/workspace/checkout-tool.ts
|
|
2865
|
+
import path6 from "path";
|
|
2691
2866
|
|
|
2692
|
-
// src/
|
|
2693
|
-
import
|
|
2694
|
-
import {
|
|
2695
|
-
|
|
2696
|
-
|
|
2697
|
-
import
|
|
2698
|
-
|
|
2699
|
-
|
|
2700
|
-
|
|
2701
|
-
|
|
2702
|
-
|
|
2703
|
-
|
|
2704
|
-
|
|
2705
|
-
|
|
2706
|
-
|
|
2707
|
-
|
|
2708
|
-
|
|
2709
|
-
|
|
2710
|
-
|
|
2711
|
-
|
|
2712
|
-
|
|
2713
|
-
|
|
2714
|
-
|
|
2715
|
-
|
|
2716
|
-
|
|
2717
|
-
|
|
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;
|
|
2718
2935
|
}
|
|
2719
|
-
|
|
2720
|
-
|
|
2721
|
-
|
|
2722
|
-
|
|
2723
|
-
writeFileSync(`${this.#directory}/auth/config.json`, JSON.stringify({ auths }), {
|
|
2724
|
-
mode: 384,
|
|
2725
|
-
flag: "wx"
|
|
2726
|
-
});
|
|
2727
|
-
this.#previousConfig = process.env.DOCKER_CONFIG;
|
|
2728
|
-
process.env.DOCKER_CONFIG = `${this.#directory}/auth`;
|
|
2729
|
-
if (!process.env.BUILDX_CONFIG) {
|
|
2730
|
-
mkdirSync(`${this.#directory}/buildx`, { mode: 448 });
|
|
2731
|
-
process.env.BUILDX_CONFIG = `${this.#directory}/buildx`;
|
|
2732
|
-
}
|
|
2733
|
-
process.once("exit", this.#onExit);
|
|
2734
|
-
} catch {
|
|
2735
|
-
this.dispose();
|
|
2736
|
-
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);
|
|
2737
2940
|
}
|
|
2738
2941
|
}
|
|
2739
|
-
|
|
2740
|
-
|
|
2741
|
-
|
|
2742
|
-
if (process.env.BUILDX_CONFIG === `${this.#directory}/buildx`) delete process.env.BUILDX_CONFIG;
|
|
2743
|
-
if (process.env.DOCKER_CONFIG === `${this.#directory}/auth`) {
|
|
2744
|
-
if (this.#previousConfig === void 0) delete process.env.DOCKER_CONFIG;
|
|
2745
|
-
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);
|
|
2746
2945
|
}
|
|
2747
|
-
rmSync(this.#directory, { recursive: true, force: true });
|
|
2748
|
-
this.#directory = void 0;
|
|
2749
|
-
this.#previousConfig = void 0;
|
|
2750
2946
|
}
|
|
2751
|
-
};
|
|
2752
|
-
|
|
2753
|
-
// src/worker-start-payload.ts
|
|
2754
|
-
function isLlmWorkerStartPayload(payload) {
|
|
2755
|
-
return payload.bootstrap.kind === "llm";
|
|
2947
|
+
return { stale, missing, extra, unchanged };
|
|
2756
2948
|
}
|
|
2757
2949
|
|
|
2758
|
-
// src/
|
|
2759
|
-
|
|
2760
|
-
|
|
2761
|
-
|
|
2762
|
-
} from "@leitwerk-dev/domain";
|
|
2763
|
-
import { repositoryHttpsUrl } from "@leitwerk-dev/process-sdk";
|
|
2764
|
-
import { createTemplateContext, resolveProcessPiConfig } from "@leitwerk-dev/process-sdk/pi-config";
|
|
2765
|
-
|
|
2766
|
-
// src/managed-pi-agent-dir.ts
|
|
2767
|
-
import { randomUUID as randomUUID2 } from "crypto";
|
|
2768
|
-
import { chmod, lstat, mkdir as mkdir3, rename as rename2, writeFile as writeFile3 } from "fs/promises";
|
|
2769
|
-
import { homedir } from "os";
|
|
2770
|
-
import path4 from "path";
|
|
2771
|
-
function safeSegment(value, name) {
|
|
2772
|
-
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(value)) {
|
|
2773
|
-
throw new Error(`Invalid managed Pi ${name}`);
|
|
2774
|
-
}
|
|
2775
|
-
return value;
|
|
2776
|
-
}
|
|
2777
|
-
function resolveManagedPiAgentDir(input) {
|
|
2778
|
-
const root = path4.resolve(input.agentDirRoot);
|
|
2779
|
-
const ambient = path4.resolve(homedir(), ".pi", "agent");
|
|
2780
|
-
if (root === ambient)
|
|
2781
|
-
throw new Error("Managed Pi agent directory must not be ambient ~/.pi/agent");
|
|
2782
|
-
return path4.join(
|
|
2783
|
-
root,
|
|
2784
|
-
safeSegment(input.instanceId, "instance id"),
|
|
2785
|
-
safeSegment(input.startOrLeaseId, "start id")
|
|
2786
|
-
);
|
|
2950
|
+
// src/workspace/resource-aggregator.ts
|
|
2951
|
+
function formatProvenanceMarker(componentKey, filePath) {
|
|
2952
|
+
const normalizedPath = filePath.replace(/\\/g, "/");
|
|
2953
|
+
return `<!-- source: ${componentKey}/${normalizedPath} -->`;
|
|
2787
2954
|
}
|
|
2788
|
-
function
|
|
2789
|
-
|
|
2790
|
-
|
|
2955
|
+
function aggregateAgentsMd(sources) {
|
|
2956
|
+
const sorted = [...sources].sort((a, b) => a.componentKey.localeCompare(b.componentKey));
|
|
2957
|
+
if (sorted.length === 0) {
|
|
2958
|
+
return "";
|
|
2791
2959
|
}
|
|
2792
|
-
const
|
|
2793
|
-
|
|
2794
|
-
|
|
2960
|
+
const parts = [];
|
|
2961
|
+
for (const s of sorted) {
|
|
2962
|
+
parts.push(formatProvenanceMarker(s.componentKey, s.filePath));
|
|
2963
|
+
parts.push(s.content.trimEnd());
|
|
2795
2964
|
}
|
|
2796
|
-
return
|
|
2965
|
+
return `${parts.join("\n\n").trimEnd()}
|
|
2966
|
+
`;
|
|
2797
2967
|
}
|
|
2798
|
-
|
|
2799
|
-
|
|
2800
|
-
for (const
|
|
2801
|
-
|
|
2802
|
-
|
|
2803
|
-
|
|
2804
|
-
throw new Error(`Credential parent is a symlink: ${current}`);
|
|
2805
|
-
} catch (error) {
|
|
2806
|
-
if (error.code !== "ENOENT") throw error;
|
|
2807
|
-
await mkdir3(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 });
|
|
2808
2974
|
}
|
|
2809
2975
|
}
|
|
2976
|
+
return out;
|
|
2810
2977
|
}
|
|
2811
|
-
|
|
2812
|
-
|
|
2813
|
-
|
|
2814
|
-
|
|
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];
|
|
2815
2986
|
}
|
|
2816
|
-
|
|
2817
|
-
|
|
2818
|
-
|
|
2819
|
-
|
|
2820
|
-
|
|
2821
|
-
|
|
2822
|
-
|
|
2823
|
-
|
|
2824
|
-
|
|
2825
|
-
|
|
2826
|
-
|
|
2827
|
-
`.${path4.basename(target)}.tmp-${process.pid}-${randomUUID2()}`
|
|
2828
|
-
);
|
|
2829
|
-
await writeFile3(tmp, file.content, { mode: 384, flag: "wx" });
|
|
2830
|
-
await chmod(tmp, 384);
|
|
2831
|
-
await rename2(tmp, target);
|
|
2832
|
-
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}'`);
|
|
2833
2998
|
}
|
|
2999
|
+
return target;
|
|
2834
3000
|
}
|
|
2835
|
-
|
|
2836
|
-
|
|
2837
|
-
|
|
2838
|
-
|
|
2839
|
-
import {
|
|
2840
|
-
canonicalJsonEqual,
|
|
2841
|
-
IPC_PROTOCOL_VERSION,
|
|
2842
|
-
parsePiResourceManifest,
|
|
2843
|
-
WORKER_API_VERSION
|
|
2844
|
-
} from "@leitwerk-dev/worker-protocol";
|
|
2845
|
-
function fail(message) {
|
|
2846
|
-
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;
|
|
2847
3005
|
}
|
|
2848
|
-
function
|
|
2849
|
-
|
|
2850
|
-
|
|
2851
|
-
|
|
2852
|
-
|
|
3006
|
+
function planRunRoot(workspaceRoot, instanceId, projectSnapshots) {
|
|
3007
|
+
return {
|
|
3008
|
+
workspaceRoot,
|
|
3009
|
+
instanceId,
|
|
3010
|
+
components: projectSnapshots.map((p) => ({ ...p }))
|
|
3011
|
+
};
|
|
2853
3012
|
}
|
|
2854
|
-
function
|
|
2855
|
-
|
|
2856
|
-
|
|
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);
|
|
2857
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
|
+
};
|
|
2858
3029
|
}
|
|
2859
|
-
function
|
|
2860
|
-
|
|
2861
|
-
|
|
2862
|
-
|
|
2863
|
-
|
|
2864
|
-
)
|
|
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)}`);
|
|
2865
3045
|
}
|
|
2866
3046
|
}
|
|
3047
|
+
return entries;
|
|
2867
3048
|
}
|
|
2868
|
-
async function
|
|
2869
|
-
const
|
|
2870
|
-
|
|
2871
|
-
|
|
2872
|
-
|
|
2873
|
-
);
|
|
2874
|
-
|
|
2875
|
-
|
|
2876
|
-
|
|
2877
|
-
|
|
2878
|
-
|
|
2879
|
-
|
|
2880
|
-
|
|
2881
|
-
|
|
2882
|
-
|
|
2883
|
-
|
|
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
|
+
}
|
|
2884
3079
|
}
|
|
3080
|
+
const agentsMd = aggregateAgentsMd(agentSources);
|
|
3081
|
+
const skillsMap = collectSkills(skillSources);
|
|
3082
|
+
aggregatedAgentsMdSources.sort((a, b) => a.localeCompare(b));
|
|
3083
|
+
return { aggregatedAgentsMdSources, agentsMd, skillsMap };
|
|
2885
3084
|
}
|
|
2886
|
-
async function
|
|
2887
|
-
const
|
|
2888
|
-
|
|
2889
|
-
|
|
2890
|
-
|
|
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);
|
|
2891
3092
|
}
|
|
2892
|
-
|
|
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));
|
|
2893
3103
|
try {
|
|
2894
|
-
|
|
2895
|
-
} catch (
|
|
2896
|
-
|
|
2897
|
-
cause: error
|
|
2898
|
-
});
|
|
3104
|
+
await writeAggregatedArtifacts(plan, git, manifest, agentsMd, skillsMap);
|
|
3105
|
+
} catch (e) {
|
|
3106
|
+
errors.push(`write: ${e instanceof Error ? e.message : String(e)}`);
|
|
2899
3107
|
}
|
|
2900
|
-
const
|
|
2901
|
-
|
|
2902
|
-
|
|
2903
|
-
|
|
2904
|
-
assertJsonEqual(
|
|
2905
|
-
manifest.providerWorkerConfig,
|
|
2906
|
-
input.start.providerWorkerConfig,
|
|
2907
|
-
"providerWorkerConfig"
|
|
2908
|
-
);
|
|
2909
|
-
let settings;
|
|
2910
|
-
try {
|
|
2911
|
-
settings = JSON.parse(await readFile(path5.join(input.agentDir, "settings.json"), "utf8"));
|
|
2912
|
-
} catch (error) {
|
|
2913
|
-
throw new Error("Invalid managed Pi resource snapshot: settings.json is unreadable", {
|
|
2914
|
-
cause: error
|
|
2915
|
-
});
|
|
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);
|
|
2916
3112
|
}
|
|
2917
|
-
|
|
2918
|
-
|
|
2919
|
-
|
|
2920
|
-
|
|
2921
|
-
|
|
2922
|
-
return manifest;
|
|
3113
|
+
return {
|
|
3114
|
+
manifest,
|
|
3115
|
+
aggregatedAgentsMdSources,
|
|
3116
|
+
loadedSkills
|
|
3117
|
+
};
|
|
2923
3118
|
}
|
|
2924
|
-
function
|
|
2925
|
-
|
|
2926
|
-
|
|
2927
|
-
|
|
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
|
+
[]
|
|
2928
3154
|
);
|
|
2929
3155
|
}
|
|
2930
|
-
|
|
2931
|
-
const apiKey = values.apiKey;
|
|
2932
|
-
if (apiKey !== void 0 && apiKey.trim() === "") {
|
|
2933
|
-
throw new Error(`Credential apiKey for provider '${input.providerId}' is empty`);
|
|
2934
|
-
}
|
|
2935
|
-
let auth = {};
|
|
2936
|
-
if (apiKey) {
|
|
2937
|
-
auth = { [input.providerId]: { type: "api_key", key: apiKey } };
|
|
2938
|
-
} else if (values.type === "oauth") {
|
|
2939
|
-
const entry = { type: "oauth" };
|
|
2940
|
-
for (const key of ["refresh", "access"]) {
|
|
2941
|
-
if (values[key] !== void 0) entry[key] = values[key];
|
|
2942
|
-
}
|
|
2943
|
-
if (values.expires !== void 0) {
|
|
2944
|
-
const expires = Number(values.expires);
|
|
2945
|
-
entry.expires = Number.isNaN(expires) ? values.expires : expires;
|
|
2946
|
-
}
|
|
2947
|
-
auth = { [input.providerId]: entry };
|
|
2948
|
-
}
|
|
2949
|
-
if (Object.keys(auth).length > 0 && !input.manifest.declaredCredentialPaths.includes("auth.json")) {
|
|
2950
|
-
throw new Error(
|
|
2951
|
-
`Provider '${input.providerId}' standard credential requires declared auth.json`
|
|
2952
|
-
);
|
|
2953
|
-
}
|
|
2954
|
-
return input.manifest.declaredCredentialPaths.map((credentialPath) => ({
|
|
2955
|
-
path: credentialPath,
|
|
2956
|
-
content: `${JSON.stringify(credentialPath === "auth.json" ? auth : values, null, 2)}
|
|
2957
|
-
`
|
|
2958
|
-
}));
|
|
3156
|
+
return result;
|
|
2959
3157
|
}
|
|
2960
|
-
async function
|
|
2961
|
-
|
|
2962
|
-
|
|
2963
|
-
|
|
2964
|
-
|
|
2965
|
-
|
|
2966
|
-
|
|
2967
|
-
|
|
2968
|
-
|
|
2969
|
-
|
|
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
|
+
};
|
|
2970
3172
|
}
|
|
2971
|
-
|
|
2972
|
-
|
|
2973
|
-
|
|
2974
|
-
|
|
2975
|
-
|
|
2976
|
-
|
|
2977
|
-
|
|
2978
|
-
|
|
2979
|
-
|
|
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
|
+
}))
|
|
2980
3221
|
);
|
|
2981
|
-
|
|
2982
|
-
|
|
2983
|
-
|
|
2984
|
-
|
|
2985
|
-
|
|
2986
|
-
} else if (input.credential.values.refresh || input.credential.values.access) {
|
|
2987
|
-
const providerCredential = record(
|
|
2988
|
-
auth[input.credential.providerId],
|
|
2989
|
-
`auth.json.${input.credential.providerId}`
|
|
3222
|
+
const result = await prepareOnDemandRunRoot(
|
|
3223
|
+
plan,
|
|
3224
|
+
git,
|
|
3225
|
+
args.projectKey,
|
|
3226
|
+
args.revision
|
|
2990
3227
|
);
|
|
2991
|
-
|
|
2992
|
-
|
|
2993
|
-
|
|
2994
|
-
|
|
2995
|
-
|
|
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
|
+
};
|
|
2996
3239
|
}
|
|
2997
|
-
}
|
|
3240
|
+
};
|
|
2998
3241
|
}
|
|
2999
3242
|
|
|
3000
|
-
// src/
|
|
3001
|
-
import {
|
|
3002
|
-
import
|
|
3003
|
-
|
|
3243
|
+
// src/runtime/bootstrap-session.ts
|
|
3244
|
+
import { readFile as readFile3 } from "fs/promises";
|
|
3245
|
+
import path10 from "path";
|
|
3246
|
+
|
|
3247
|
+
// src/docker-registry-credentials.ts
|
|
3248
|
+
import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "fs";
|
|
3004
3249
|
import {
|
|
3005
|
-
|
|
3006
|
-
sha256Digest,
|
|
3007
|
-
validateResourceRelativePath,
|
|
3008
|
-
verifyCanonicalPiResourceBundle
|
|
3250
|
+
dockerRegistryCredentialSchema
|
|
3009
3251
|
} from "@leitwerk-dev/worker-protocol";
|
|
3010
|
-
|
|
3011
|
-
|
|
3012
|
-
|
|
3013
|
-
|
|
3014
|
-
|
|
3015
|
-
|
|
3016
|
-
|
|
3017
|
-
|
|
3018
|
-
|
|
3019
|
-
|
|
3020
|
-
|
|
3021
|
-
|
|
3022
|
-
|
|
3023
|
-
|
|
3024
|
-
|
|
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`;
|
|
3290
|
+
}
|
|
3291
|
+
process.once("exit", this.#onExit);
|
|
3292
|
+
} catch {
|
|
3293
|
+
this.dispose();
|
|
3294
|
+
throw new Error("Cannot materialize private Docker credentials");
|
|
3295
|
+
}
|
|
3296
|
+
}
|
|
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;
|
|
3025
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) {
|
|
3026
3357
|
try {
|
|
3027
|
-
|
|
3028
|
-
} catch
|
|
3029
|
-
|
|
3030
|
-
throw error;
|
|
3358
|
+
return value[key];
|
|
3359
|
+
} catch {
|
|
3360
|
+
return void 0;
|
|
3031
3361
|
}
|
|
3032
3362
|
}
|
|
3033
|
-
|
|
3034
|
-
const
|
|
3035
|
-
const
|
|
3036
|
-
|
|
3037
|
-
|
|
3038
|
-
|
|
3039
|
-
|
|
3040
|
-
|
|
3041
|
-
|
|
3042
|
-
try {
|
|
3043
|
-
const existing = await readFile2(bundlePath);
|
|
3044
|
-
verifyCanonicalPiResourceBundle(existing, digest);
|
|
3045
|
-
bundle = existing;
|
|
3046
|
-
reused = true;
|
|
3047
|
-
} catch (error) {
|
|
3048
|
-
if (error.code !== "ENOENT" && input.archiveBase64 === void 0) {
|
|
3049
|
-
throw error;
|
|
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;
|
|
3050
3372
|
}
|
|
3051
|
-
|
|
3052
|
-
|
|
3053
|
-
|
|
3054
|
-
|
|
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);
|
|
3055
3386
|
}
|
|
3056
|
-
bundle = input.deliveredBundle ?? Buffer.from(input.archiveBase64, "base64");
|
|
3057
|
-
verifyCanonicalPiResourceBundle(bundle, digest);
|
|
3058
|
-
await atomicWrite(bundlePath, bundle, 384);
|
|
3059
3387
|
}
|
|
3060
|
-
|
|
3061
|
-
|
|
3062
|
-
`,
|
|
3063
|
-
"utf8"
|
|
3064
|
-
);
|
|
3065
|
-
await atomicWrite(path6.join(startsDir, `${startRecordId}.json`), manifest, 384);
|
|
3066
|
-
return { bundle, reused };
|
|
3388
|
+
visit(error, 0);
|
|
3389
|
+
return { causes, ...truncated ? { truncated: true } : {} };
|
|
3067
3390
|
}
|
|
3068
|
-
|
|
3069
|
-
|
|
3070
|
-
|
|
3071
|
-
|
|
3072
|
-
|
|
3073
|
-
|
|
3074
|
-
|
|
3075
|
-
|
|
3391
|
+
function transportErrorCode(error) {
|
|
3392
|
+
return transportErrorDetails(error).causes.find((cause) => cause.code)?.code;
|
|
3393
|
+
}
|
|
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}`);
|
|
3076
3417
|
}
|
|
3418
|
+
return value;
|
|
3077
3419
|
}
|
|
3078
|
-
|
|
3079
|
-
const
|
|
3080
|
-
const
|
|
3081
|
-
|
|
3082
|
-
|
|
3083
|
-
|
|
3084
|
-
|
|
3085
|
-
|
|
3086
|
-
|
|
3087
|
-
|
|
3088
|
-
|
|
3089
|
-
|
|
3090
|
-
|
|
3091
|
-
|
|
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}'`);
|
|
3434
|
+
}
|
|
3435
|
+
const normalized = path7.posix.normalize(value);
|
|
3436
|
+
if (normalized === "." || normalized === ".." || normalized.startsWith("../")) {
|
|
3437
|
+
throw new Error(`Invalid credential file path '${value}'`);
|
|
3438
|
+
}
|
|
3439
|
+
return normalized;
|
|
3440
|
+
}
|
|
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
|
+
}
|
|
3452
|
+
}
|
|
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}`);
|
|
3458
|
+
}
|
|
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()}`
|
|
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);
|
|
3476
|
+
}
|
|
3477
|
+
}
|
|
3478
|
+
|
|
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}`);
|
|
3490
|
+
}
|
|
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;
|
|
3496
|
+
}
|
|
3497
|
+
function assertJsonEqual(actual, expected, location) {
|
|
3498
|
+
if (!canonicalJsonEqual(actual, expected)) {
|
|
3499
|
+
fail2(`${location} does not match the resolved LLM start`);
|
|
3500
|
+
}
|
|
3501
|
+
}
|
|
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
|
+
}
|
|
3509
|
+
}
|
|
3510
|
+
}
|
|
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
|
+
);
|
|
3517
|
+
}
|
|
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}'`
|
|
3092
3526
|
);
|
|
3527
|
+
}
|
|
3528
|
+
}
|
|
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");
|
|
3534
|
+
}
|
|
3535
|
+
let parsed;
|
|
3536
|
+
try {
|
|
3537
|
+
parsed = JSON.parse(await readFile2(path8.join(input.agentDir, "generated.json"), "utf8"));
|
|
3093
3538
|
} catch (error) {
|
|
3094
|
-
|
|
3539
|
+
throw new Error("Invalid managed Pi resource snapshot: generated.json is unreadable", {
|
|
3540
|
+
cause: error
|
|
3541
|
+
});
|
|
3095
3542
|
}
|
|
3096
|
-
const
|
|
3097
|
-
|
|
3098
|
-
|
|
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"
|
|
3099
3551
|
);
|
|
3552
|
+
let settings;
|
|
3100
3553
|
try {
|
|
3101
|
-
await
|
|
3102
|
-
await writeExtractedFiles(staging, files);
|
|
3103
|
-
await writeFile4(path6.join(staging, ".leitwerk-resource-digest"), `${input.digest}
|
|
3104
|
-
`, {
|
|
3105
|
-
mode: 384,
|
|
3106
|
-
flag: "wx"
|
|
3107
|
-
});
|
|
3108
|
-
await rename3(staging, targetDir);
|
|
3109
|
-
return { targetDir, reused: false };
|
|
3554
|
+
settings = JSON.parse(await readFile2(path8.join(input.agentDir, "settings.json"), "utf8"));
|
|
3110
3555
|
} catch (error) {
|
|
3111
|
-
|
|
3112
|
-
|
|
3113
|
-
|
|
3114
|
-
|
|
3556
|
+
throw new Error("Invalid managed Pi resource snapshot: settings.json is unreadable", {
|
|
3557
|
+
cause: error
|
|
3558
|
+
});
|
|
3559
|
+
}
|
|
3560
|
+
assertJsonEqual(
|
|
3561
|
+
settings,
|
|
3562
|
+
{ ...input.start.piSettings, packages: [], defaultProjectTrust: "never" },
|
|
3563
|
+
"settings.json"
|
|
3564
|
+
);
|
|
3565
|
+
return manifest;
|
|
3566
|
+
}
|
|
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
|
+
`
|
|
3601
|
+
}));
|
|
3602
|
+
}
|
|
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
|
+
}
|
|
3613
|
+
}
|
|
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}`
|
|
3115
3623
|
);
|
|
3116
|
-
if (
|
|
3117
|
-
|
|
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
|
+
}
|
|
3118
3639
|
}
|
|
3119
|
-
throw error;
|
|
3120
3640
|
}
|
|
3121
3641
|
}
|
|
3122
3642
|
|
|
@@ -3149,547 +3669,252 @@ function matchingEntries(handle, identity) {
|
|
|
3149
3669
|
const visit = (nodes) => {
|
|
3150
3670
|
for (const node of nodes) {
|
|
3151
3671
|
const isMatchingPrompt = node.entry.type === "custom_message" && node.entry.customType === "leitwerk";
|
|
3152
|
-
const isMatchingCompaction = node.entry.type === "compaction";
|
|
3153
|
-
if ((isMatchingPrompt || isMatchingCompaction) && sameIdentity(node.entry.details, identity)) {
|
|
3154
|
-
entries.push(node.entry);
|
|
3155
|
-
}
|
|
3156
|
-
visit(node.children);
|
|
3157
|
-
}
|
|
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
|
-
}
|
|
3167
|
-
return matches[0] ?? null;
|
|
3168
|
-
}
|
|
3169
|
-
function assertIdentifiedPrompt(match, input) {
|
|
3170
|
-
if (match?.type === "custom_message" && match.customType === "leitwerk" && match.content === input.content && matchesParent({
|
|
3171
|
-
piHandle: input.piHandle,
|
|
3172
|
-
parentId: match.parentId,
|
|
3173
|
-
expectedParentId: input.expectedParentId,
|
|
3174
|
-
allowDescendantParent: input.allowDescendantParent
|
|
3175
|
-
}) && (!input.requireOnCurrentBranch || isOnCurrentBranch(input.piHandle, match.id))) {
|
|
3176
|
-
return;
|
|
3177
|
-
}
|
|
3178
|
-
throw new Error(`Pi tree has mismatched Leitwerk prompt '${JSON.stringify(input.identity)}'`);
|
|
3179
|
-
}
|
|
3180
|
-
function validateIdentifiedPrompt(input) {
|
|
3181
|
-
assertIdentifiedPrompt(findIdentifiedPrompt(input.piHandle, input.identity), input);
|
|
3182
|
-
}
|
|
3183
|
-
async function ensureIdentifiedCompaction(input) {
|
|
3184
|
-
const match = findIdentifiedPrompt(input.piHandle, input.identity);
|
|
3185
|
-
if (match) {
|
|
3186
|
-
if (match.type !== "compaction" || !matchesParent({
|
|
3187
|
-
piHandle: input.piHandle,
|
|
3188
|
-
parentId: match.parentId,
|
|
3189
|
-
expectedParentId: input.expectedParentId,
|
|
3190
|
-
allowDescendantParent: input.allowDescendantParent
|
|
3191
|
-
}) || input.requireOnCurrentBranch && !isOnCurrentBranch(input.piHandle, match.id)) {
|
|
3192
|
-
throw new Error(
|
|
3193
|
-
`Pi tree has mismatched Leitwerk compaction '${JSON.stringify(input.identity)}'`
|
|
3194
|
-
);
|
|
3195
|
-
}
|
|
3196
|
-
if (!input.reuseWithoutBranching) await input.piHandle.branch(match.id);
|
|
3197
|
-
return match.id;
|
|
3198
|
-
}
|
|
3199
|
-
if (!input.piHandle.compact) throw new Error("Pi handle does not support compaction");
|
|
3200
|
-
if (input.piHandle.getLeafId() !== input.expectedParentId) {
|
|
3201
|
-
throw new Error("Pi tree changed before the identified compaction could be appended");
|
|
3202
|
-
}
|
|
3203
|
-
await input.piHandle.compact(void 0, input.identity);
|
|
3204
|
-
const appended = findIdentifiedPrompt(input.piHandle, input.identity);
|
|
3205
|
-
if (!appended || appended.type !== "compaction" || appended.parentId !== input.expectedParentId) {
|
|
3206
|
-
throw new Error(
|
|
3207
|
-
`Pi tree has mismatched Leitwerk compaction '${JSON.stringify(input.identity)}'`
|
|
3208
|
-
);
|
|
3209
|
-
}
|
|
3210
|
-
return appended.id;
|
|
3211
|
-
}
|
|
3212
|
-
async function ensureIdentifiedPrompt(input) {
|
|
3213
|
-
const match = findIdentifiedPrompt(input.piHandle, input.identity);
|
|
3214
|
-
if (match) {
|
|
3215
|
-
assertIdentifiedPrompt(match, input);
|
|
3216
|
-
if (!input.reuseWithoutBranching) await input.piHandle.branch(match.id);
|
|
3217
|
-
return match.id;
|
|
3218
|
-
}
|
|
3219
|
-
if (!input.piHandle.appendCustomMessage) {
|
|
3220
|
-
throw new Error("Pi handle does not support identified custom messages");
|
|
3221
|
-
}
|
|
3222
|
-
if (input.requireExisting) {
|
|
3223
|
-
throw new Error(
|
|
3224
|
-
`Pi tree is missing retained Leitwerk prompt '${JSON.stringify(input.identity)}'`
|
|
3225
|
-
);
|
|
3226
|
-
}
|
|
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
|
-
}
|
|
3235
|
-
|
|
3236
|
-
// src/pre-turn-targeted-inputs.ts
|
|
3237
|
-
function resolveTargetSemanticRef(target) {
|
|
3238
|
-
return typeof target.semanticRef === "string" ? target.semanticRef : null;
|
|
3239
|
-
}
|
|
3240
|
-
function resolveTargetProductName(target) {
|
|
3241
|
-
return typeof target.productName === "string" ? target.productName : null;
|
|
3242
|
-
}
|
|
3243
|
-
function formatTarget(target) {
|
|
3244
|
-
const semanticRef = resolveTargetSemanticRef(target);
|
|
3245
|
-
if (semanticRef) {
|
|
3246
|
-
return `semantic ref '${semanticRef}'`;
|
|
3247
|
-
}
|
|
3248
|
-
return `product '${resolveTargetProductName(target) ?? "<unset>"}'`;
|
|
3249
|
-
}
|
|
3250
|
-
function resolvePreTurnTargetStartSelection(inputs) {
|
|
3251
|
-
const target = inputs[0]?.target;
|
|
3252
|
-
if (target && resolveTargetSemanticRef(target) === "currentPrimaryPathLeaf") {
|
|
3253
|
-
return { kind: "semantic_ref", ref: "currentPrimaryPathLeaf" };
|
|
3254
|
-
}
|
|
3255
|
-
return null;
|
|
3256
|
-
}
|
|
3257
|
-
function resolvePreTurnTargetEntryId(input) {
|
|
3258
|
-
const semanticRef = resolveTargetSemanticRef(input.target);
|
|
3259
|
-
if (semanticRef) {
|
|
3260
|
-
return resolveProcessSemanticRefEntryId({
|
|
3261
|
-
ref: semanticRef,
|
|
3262
|
-
semanticEntryRefs: input.semanticEntryRefs,
|
|
3263
|
-
currentLeafId: input.currentLeafId,
|
|
3264
|
-
rootEntryId: input.rootEntryId,
|
|
3265
|
-
entryExists: input.entryExists
|
|
3266
|
-
});
|
|
3267
|
-
}
|
|
3268
|
-
const productName = resolveTargetProductName(input.target);
|
|
3269
|
-
return productName ? resolveProcessProductRefEntryId({
|
|
3270
|
-
productName,
|
|
3271
|
-
productRefs: input.productRefs,
|
|
3272
|
-
entryExists: input.entryExists
|
|
3273
|
-
}) : null;
|
|
3274
|
-
}
|
|
3275
|
-
function validatePreTurnTargetedInputs(input) {
|
|
3276
|
-
const expectedEntryId = input.treePlan.startTarget.kind === "entry" ? input.treePlan.startTarget.entryId : input.treePlan.startTarget.kind === "current_leaf" ? input.currentLeafId : input.rootEntryId;
|
|
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
|
-
}
|
|
3298
|
-
}
|
|
3299
|
-
return null;
|
|
3300
|
-
}
|
|
3301
|
-
async function applyPreTurnTargetedInputs(input) {
|
|
3302
|
-
if (input.inputs.length === 0) {
|
|
3303
|
-
return;
|
|
3304
|
-
}
|
|
3305
|
-
for (const targetedInput of input.inputs) {
|
|
3306
|
-
const targetEntryId = await ensureIdentifiedPrompt({
|
|
3307
|
-
piHandle: input.piHandle,
|
|
3308
|
-
identity: { kind: "process_input", processInputId: targetedInput.inputId },
|
|
3309
|
-
content: targetedInput.bodyMarkdown,
|
|
3310
|
-
expectedParentId: input.recoveryBaseEntryId ?? input.piHandle.getLeafId(),
|
|
3311
|
-
allowDescendantParent: input.recoveryBaseEntryId !== void 0,
|
|
3312
|
-
requireOnCurrentBranch: input.reuseExistingWithoutBranching,
|
|
3313
|
-
reuseWithoutBranching: input.reuseExistingWithoutBranching,
|
|
3314
|
-
requireExisting: input.requireExisting
|
|
3315
|
-
});
|
|
3316
|
-
const semanticRef = resolveTargetSemanticRef(targetedInput.target);
|
|
3317
|
-
input.onApplied?.(targetedInput.inputId, targetedInput.sequence, {
|
|
3318
|
-
...input.pathType === "primary" ? { currentPrimaryPathLeafId: targetEntryId } : {},
|
|
3319
|
-
rootEntryId: resolveRootEntryIdFromHandle(input.piHandle),
|
|
3320
|
-
...semanticRef ? { targetSemanticRef: semanticRef } : { targetProductName: resolveTargetProductName(targetedInput.target) },
|
|
3321
|
-
targetEntryId
|
|
3322
|
-
});
|
|
3323
|
-
}
|
|
3324
|
-
}
|
|
3325
|
-
|
|
3326
|
-
// src/worker-payloads.ts
|
|
3327
|
-
import {
|
|
3328
|
-
detectRepoLocatorKind,
|
|
3329
|
-
parseProcessProductRefs,
|
|
3330
|
-
parseSemanticEntryRefsFromStateJsonStrict,
|
|
3331
|
-
parseSemanticEntryRefsLenient
|
|
3332
|
-
} from "@leitwerk-dev/domain";
|
|
3333
|
-
function inputDeliveryToItem(delivery) {
|
|
3334
|
-
return {
|
|
3335
|
-
inputId: delivery.inputId,
|
|
3336
|
-
sequence: delivery.sequence,
|
|
3337
|
-
source: delivery.source,
|
|
3338
|
-
kind: delivery.kind,
|
|
3339
|
-
target: delivery.target,
|
|
3340
|
-
bodyMarkdown: delivery.bodyMarkdown
|
|
3341
|
-
};
|
|
3342
|
-
}
|
|
3343
|
-
function projectSnapshotsFromPayload(raw) {
|
|
3344
|
-
return raw.map((project) => ({
|
|
3345
|
-
id: project.id ?? "",
|
|
3346
|
-
instanceId: project.instanceId ?? "",
|
|
3347
|
-
key: project.key,
|
|
3348
|
-
repoLocator: project.repoLocator,
|
|
3349
|
-
repoLocatorKind: project.repoLocatorKind ?? detectRepoLocatorKind(project.repoLocator) ?? "remote_url",
|
|
3350
|
-
baseBranch: project.baseBranch,
|
|
3351
|
-
workBranch: project.workBranch ?? "",
|
|
3352
|
-
externalId: project.externalId ?? null,
|
|
3353
|
-
externalUrl: project.externalUrl ?? null,
|
|
3354
|
-
metadata: project.metadata ?? null,
|
|
3355
|
-
pipelineStatus: project.pipelineStatus ?? null,
|
|
3356
|
-
createdAt: project.createdAt ?? "",
|
|
3357
|
-
updatedAt: project.updatedAt ?? ""
|
|
3358
|
-
}));
|
|
3359
|
-
}
|
|
3360
|
-
function buildProcessSnapshotSeed(processId, processSnapshot) {
|
|
3361
|
-
const resolvedProcessId = processSnapshot.processId ?? processId;
|
|
3362
|
-
return {
|
|
3363
|
-
id: processSnapshot.id ?? "",
|
|
3364
|
-
processId: resolvedProcessId,
|
|
3365
|
-
selectedTurnId: processSnapshot.selectedTurnId ?? null,
|
|
3366
|
-
lifecycleStatus: processSnapshot.lifecycleStatus ?? "discovered",
|
|
3367
|
-
currentExecution: processSnapshot.currentExecution ?? null,
|
|
3368
|
-
planRevision: processSnapshot.planRevision ?? 0,
|
|
3369
|
-
title: processSnapshot.title ?? null,
|
|
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;
|
|
3385
|
-
}
|
|
3386
|
-
return parseSemanticEntryRefsLenient(
|
|
3387
|
-
state.semanticEntryRefs
|
|
3388
|
-
);
|
|
3389
|
-
}
|
|
3390
|
-
function readProcessProductRefs(state) {
|
|
3391
|
-
if (typeof state !== "object" || state === null || Array.isArray(state)) {
|
|
3392
|
-
return null;
|
|
3393
|
-
}
|
|
3394
|
-
return parseProcessProductRefs(state.productRefs);
|
|
3395
|
-
}
|
|
3396
|
-
function parseProcessSemanticEntryRefsFromStateJson(stateJson) {
|
|
3397
|
-
return parseSemanticEntryRefsFromStateJsonStrict(stateJson, "process stateJson");
|
|
3398
|
-
}
|
|
3399
|
-
|
|
3400
|
-
// src/workspace/run-root.ts
|
|
3401
|
-
import path7 from "path";
|
|
3402
|
-
import { isPathInside } from "@leitwerk-dev/process-sdk";
|
|
3403
|
-
|
|
3404
|
-
// src/workspace/manifest.ts
|
|
3405
|
-
import * as v from "valibot";
|
|
3406
|
-
function serializeManifest(manifest) {
|
|
3407
|
-
return JSON.stringify(manifest, null, 2);
|
|
3408
|
-
}
|
|
3409
|
-
var jsonObjectSchema = v.custom(
|
|
3410
|
-
(value) => typeof value === "object" && value !== null && !Array.isArray(value),
|
|
3411
|
-
"Expected object"
|
|
3412
|
-
);
|
|
3413
|
-
var componentManifestEntrySchema = v.pipe(
|
|
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";
|
|
3447
|
-
}
|
|
3448
|
-
function deserializeManifest(content) {
|
|
3449
|
-
const result = v.safeParse(componentManifestJsonSchema, content, { abortEarly: true });
|
|
3450
|
-
if (!result.success) {
|
|
3451
|
-
return { ok: false, error: formatManifestValidationError(result.issues) };
|
|
3452
|
-
}
|
|
3453
|
-
return { ok: true, manifest: result.output };
|
|
3454
|
-
}
|
|
3455
|
-
function diffManifest(existing, serverProjects) {
|
|
3456
|
-
const stale = [];
|
|
3457
|
-
const missing = [];
|
|
3458
|
-
const extra = [];
|
|
3459
|
-
const unchanged = [];
|
|
3460
|
-
const byKey = new Map(existing.components.map((c) => [c.key, c]));
|
|
3461
|
-
const serverByKey = new Map(serverProjects.map((p) => [p.key, p]));
|
|
3462
|
-
for (const p of serverProjects) {
|
|
3463
|
-
const m = byKey.get(p.key);
|
|
3464
|
-
if (!m) {
|
|
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);
|
|
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
|
|
@@ -3876,7 +4101,8 @@ async function activatePreparedStart(input) {
|
|
|
3876
4101
|
agentDir: prepared.managedAgentDir,
|
|
3877
4102
|
configSnapshot: prepared.startPayload.configSnapshot,
|
|
3878
4103
|
modelProfileId: prepared.managedModelProfileId,
|
|
3879
|
-
piConfig: prepared.resolvedPiConfig
|
|
4104
|
+
piConfig: prepared.resolvedPiConfig,
|
|
4105
|
+
...prepared.startPayload.iteration ? { iteration: prepared.startPayload.iteration } : {}
|
|
3880
4106
|
});
|
|
3881
4107
|
const diagnostics = await restorePrimaryPathLeaf(
|
|
3882
4108
|
piHandle,
|
|
@@ -3921,8 +4147,11 @@ async function bootstrapWorkerRuntime(deps) {
|
|
|
3921
4147
|
workBranch: project.workBranch ?? ""
|
|
3922
4148
|
}));
|
|
3923
4149
|
const plan = planRunRoot(workspaceRoot, deps.instanceId, runRootProjects);
|
|
3924
|
-
const runRootPreparation =
|
|
3925
|
-
|
|
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)
|
|
3926
4155
|
) : materializeRunRoot(plan, deps.gitOps);
|
|
3927
4156
|
const resolvedPiConfig = llmPayload ? resolveProcessPiConfig({
|
|
3928
4157
|
processId,
|
|
@@ -3935,7 +4164,7 @@ async function bootstrapWorkerRuntime(deps) {
|
|
|
3935
4164
|
projects: projectSnapshots
|
|
3936
4165
|
})
|
|
3937
4166
|
}) : { systemPrompt: "", availableToolNames: [] };
|
|
3938
|
-
const sessionCwd = resolvedPiConfig.sessionCwd ?
|
|
4167
|
+
const sessionCwd = resolvedPiConfig.sessionCwd ? path9.resolve(workspaceRoot, resolvedPiConfig.sessionCwd) : workspaceRoot;
|
|
3939
4168
|
const pendingInputs = (deps.payload.pendingInputs ?? []).map(inputDeliveryToItem);
|
|
3940
4169
|
const diagnostics = [];
|
|
3941
4170
|
let managedAgentDir = null;
|
|
@@ -3954,7 +4183,7 @@ async function bootstrapWorkerRuntime(deps) {
|
|
|
3954
4183
|
config: deps.payload.developmentTools,
|
|
3955
4184
|
repositories: projectSnapshots.map((project) => ({
|
|
3956
4185
|
repositoryKey: project.key,
|
|
3957
|
-
workingDirectory:
|
|
4186
|
+
workingDirectory: path9.join(workspaceRoot, project.key)
|
|
3958
4187
|
})),
|
|
3959
4188
|
signal: deps.toolPreparationSignal,
|
|
3960
4189
|
onProgress: deps.onToolPreparationProgress,
|
|
@@ -4150,11 +4379,13 @@ function validatePreparedSession(input) {
|
|
|
4150
4379
|
);
|
|
4151
4380
|
}
|
|
4152
4381
|
const base = {
|
|
4382
|
+
outcomeContract: turnStartState.start?.kind === "llm" ? turnStartState.start.outcomeContract : void 0,
|
|
4153
4383
|
processSnapshot: bootstrapped.processSnapshot,
|
|
4154
4384
|
projectSnapshots: bootstrapped.projectSnapshots,
|
|
4155
4385
|
resolvedWorkerProcess: process2,
|
|
4156
4386
|
selectedTurnId,
|
|
4157
4387
|
startRecordId: payload.turnStart.id,
|
|
4388
|
+
scopedSettings: turnStartState.start?.kind === "llm" ? turnStartState.start.scopedSettings : void 0,
|
|
4158
4389
|
proposedTurnRecordId: payload.turnStart.proposedTurnRecordId,
|
|
4159
4390
|
acceptedTurnRecordId: payload.turnStart.state.kind === "accepted" ? payload.turnStart.state.turnRecordId : null,
|
|
4160
4391
|
startKind: payload.turnStart.startKind,
|
|
@@ -4163,8 +4394,10 @@ function validatePreparedSession(input) {
|
|
|
4163
4394
|
workspaceRoot: payload.treePaths.workspaceRoot,
|
|
4164
4395
|
turnResultMarkdownBySemanticRef: payload.turnResultMarkdownBySemanticRef,
|
|
4165
4396
|
turnResultMarkdownByProduct: payload.turnResultMarkdownByProduct,
|
|
4397
|
+
inspectionProducts: payload.inspectionProducts,
|
|
4166
4398
|
settings,
|
|
4167
|
-
integrationTools: payload.integrationTools ?? []
|
|
4399
|
+
integrationTools: payload.integrationTools ?? [],
|
|
4400
|
+
...payload.iteration ? { iteration: payload.iteration } : {}
|
|
4168
4401
|
};
|
|
4169
4402
|
if (binding.definition.kind === "automatic") {
|
|
4170
4403
|
return { ...base, kind: "automatic", piAvailable: false, activeModelProfileId: null };
|
|
@@ -4268,14 +4501,15 @@ var WorkerLiveResources = class {
|
|
|
4268
4501
|
level: "warn",
|
|
4269
4502
|
code: "session_snapshot.upload_failed",
|
|
4270
4503
|
message: `Session snapshot upload failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
4271
|
-
details: { attempt, reason }
|
|
4504
|
+
details: { attempt, reason, transport: transportErrorDetails(error) }
|
|
4272
4505
|
});
|
|
4273
4506
|
if (attempt < 3) await this.deps.scheduler.sleep(100 * attempt);
|
|
4274
4507
|
}
|
|
4275
4508
|
}
|
|
4276
4509
|
if (!metadata.required) return;
|
|
4277
4510
|
throw new Error(
|
|
4278
|
-
`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 }
|
|
4279
4513
|
);
|
|
4280
4514
|
}
|
|
4281
4515
|
async runTurn(operation) {
|
|
@@ -4312,7 +4546,7 @@ var WorkerLiveResources = class {
|
|
|
4312
4546
|
async function sampleCredentialFiles(descriptor) {
|
|
4313
4547
|
const values = {};
|
|
4314
4548
|
for (const credentialPath of descriptor.declaredCredentialPaths) {
|
|
4315
|
-
const json = JSON.parse(await readFile3(
|
|
4549
|
+
const json = JSON.parse(await readFile3(path10.join(descriptor.agentDir, credentialPath), "utf8"));
|
|
4316
4550
|
if (!json || typeof json !== "object" || Array.isArray(json)) {
|
|
4317
4551
|
throw new Error(`Credential file '${credentialPath}' must contain a JSON object`);
|
|
4318
4552
|
}
|
|
@@ -4395,6 +4629,13 @@ function extractSecretValuesFromPayload(payload) {
|
|
|
4395
4629
|
}
|
|
4396
4630
|
}
|
|
4397
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
|
+
}
|
|
4398
4639
|
return Array.from(secrets);
|
|
4399
4640
|
}
|
|
4400
4641
|
function extractDockerRegistrySecretValues(payload) {
|
|
@@ -4438,7 +4679,7 @@ function normalizeWorkerFailure(failure2) {
|
|
|
4438
4679
|
if (failure2.kind === "turn" || failure2.kind === "mandatory_snapshot") {
|
|
4439
4680
|
const correlation = failure2.correlation;
|
|
4440
4681
|
const turnError = failure2.kind === "turn" ? failure2.error : null;
|
|
4441
|
-
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;
|
|
4442
4683
|
const errorClass = turnError?.errorClass ?? classified.errorClass;
|
|
4443
4684
|
const payload = {
|
|
4444
4685
|
turnRecordId: correlation.turnRecordId,
|
|
@@ -4450,7 +4691,12 @@ function normalizeWorkerFailure(failure2) {
|
|
|
4450
4691
|
forkPiEntryId: correlation.forkPiEntryId ?? null,
|
|
4451
4692
|
resultPiEntryId: correlation.resultPiEntryId ?? null,
|
|
4452
4693
|
...turnError?.failureCode ? { failureCode: turnError.failureCode } : {},
|
|
4453
|
-
...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 } : {},
|
|
4454
4700
|
...turnError?.recoveryContext ? { recoveryContext: turnError.recoveryContext } : {}
|
|
4455
4701
|
};
|
|
4456
4702
|
return {
|
|
@@ -4460,7 +4706,8 @@ function normalizeWorkerFailure(failure2) {
|
|
|
4460
4706
|
message: failure2.kind === "mandatory_snapshot" ? summary2 : `Turn execution failed: ${summary2}`,
|
|
4461
4707
|
errorClass,
|
|
4462
4708
|
turnRecordId: correlation.turnRecordId,
|
|
4463
|
-
turnId: correlation.turnId
|
|
4709
|
+
turnId: correlation.turnId,
|
|
4710
|
+
...failure2.kind === "mandatory_snapshot" ? { details: payload.failureDetails ?? void 0 } : {}
|
|
4464
4711
|
},
|
|
4465
4712
|
stderrMessage: summary2,
|
|
4466
4713
|
terminal: {
|
|
@@ -5611,7 +5858,12 @@ function resolveWorkerRuntimeSettings(config, payload) {
|
|
|
5611
5858
|
}
|
|
5612
5859
|
|
|
5613
5860
|
// src/runtime/turn-execution.ts
|
|
5614
|
-
import {
|
|
5861
|
+
import { randomUUID as randomUUID6 } from "crypto";
|
|
5862
|
+
import {
|
|
5863
|
+
applyOutcomeContract,
|
|
5864
|
+
assertValidLlmTurnDefinition,
|
|
5865
|
+
resolveOutcomeContract
|
|
5866
|
+
} from "@leitwerk-dev/process-sdk";
|
|
5615
5867
|
|
|
5616
5868
|
// src/turn-execution-result.ts
|
|
5617
5869
|
var TurnExecutionFailure = class extends Error {
|
|
@@ -5636,12 +5888,12 @@ var TurnExecutionFailure = class extends Error {
|
|
|
5636
5888
|
};
|
|
5637
5889
|
|
|
5638
5890
|
// src/turn-record-id.ts
|
|
5639
|
-
import { randomUUID as
|
|
5891
|
+
import { randomUUID as randomUUID5 } from "crypto";
|
|
5640
5892
|
function resolveTurnRecordIdForExecution(process2, turnId, acceptedTurnRecordId) {
|
|
5641
5893
|
if (process2.selectedTurnId === turnId && typeof acceptedTurnRecordId === "string" && acceptedTurnRecordId.trim() !== "") {
|
|
5642
5894
|
return acceptedTurnRecordId;
|
|
5643
5895
|
}
|
|
5644
|
-
return `trn_${
|
|
5896
|
+
return `trn_${randomUUID5().replace(/-/g, "")}`;
|
|
5645
5897
|
}
|
|
5646
5898
|
|
|
5647
5899
|
// src/automatic-turn-executor.ts
|
|
@@ -6068,6 +6320,15 @@ function resolvePromptlessTurnResumeReason(input) {
|
|
|
6068
6320
|
}
|
|
6069
6321
|
|
|
6070
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";
|
|
6071
6332
|
import { resolveTurnActiveToolNames } from "@leitwerk-dev/process-sdk/pi-config";
|
|
6072
6333
|
|
|
6073
6334
|
// src/question-tool.ts
|
|
@@ -6317,12 +6578,13 @@ function resolveMissingTurnToolCallRecovery(input) {
|
|
|
6317
6578
|
return null;
|
|
6318
6579
|
}
|
|
6319
6580
|
return {
|
|
6320
|
-
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",
|
|
6321
6582
|
missingToolNames: [
|
|
6322
6583
|
...missingMarkdownResult ? [MARKDOWN_RESULT_TOOL_NAME] : [],
|
|
6323
6584
|
...missingOutcomeToolNames
|
|
6324
6585
|
],
|
|
6325
6586
|
missingOutcomeToolNames,
|
|
6587
|
+
...input.rejectedOutcome && missingOutcomeToolNames.length > 0 ? { rejectedOutcome: input.rejectedOutcome } : {},
|
|
6326
6588
|
missingMarkdownResult,
|
|
6327
6589
|
requiresOutcomeToolMarkdown: Boolean(outcomeToolMarkdownParameterName),
|
|
6328
6590
|
...outcomeToolMarkdownParameterName ? { outcomeToolMarkdownParameterName } : {}
|
|
@@ -6330,9 +6592,15 @@ function resolveMissingTurnToolCallRecovery(input) {
|
|
|
6330
6592
|
}
|
|
6331
6593
|
function buildMissingTurnToolCallRecoveryPrompt(recovery) {
|
|
6332
6594
|
const lines = [
|
|
6333
|
-
"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.",
|
|
6334
6596
|
"Continue from your previous work without starting over."
|
|
6335
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
|
+
);
|
|
6336
6604
|
if (recovery.missingMarkdownResult && recovery.missingOutcomeToolNames.length > 0) {
|
|
6337
6605
|
lines.push(
|
|
6338
6606
|
"Call markdown_result now with the operator-facing markdown for this turn, then call the required outcome tool to finish."
|
|
@@ -6358,6 +6626,8 @@ function buildMissingTurnToolCallRecoveryPrompt(recovery) {
|
|
|
6358
6626
|
return lines.join("\n");
|
|
6359
6627
|
}
|
|
6360
6628
|
function describeMissingTurnToolCallRecovery(recovery) {
|
|
6629
|
+
if (recovery.rejectedOutcome)
|
|
6630
|
+
return `rejected '${recovery.rejectedOutcome.outcome}' submission: ${recovery.rejectedOutcome.errors.join("; ")}`;
|
|
6361
6631
|
if (recovery.missingMarkdownResult && recovery.missingOutcomeToolNames.length > 0) {
|
|
6362
6632
|
return `missing required tool calls (${MARKDOWN_RESULT_TOOL_NAME} and one outcome tool: ${recovery.missingOutcomeToolNames.join(", ")})`;
|
|
6363
6633
|
}
|
|
@@ -6397,10 +6667,14 @@ function cloneTurnResultMarkdownState(state) {
|
|
|
6397
6667
|
}
|
|
6398
6668
|
function createTurnOutcomeToolSession(input) {
|
|
6399
6669
|
let selectedOutcome = null;
|
|
6670
|
+
let abortReason;
|
|
6671
|
+
let rejectedOutcome;
|
|
6400
6672
|
let terminalAcknowledgement = { kind: "open" };
|
|
6401
6673
|
const turnResultMarkdownStateRef = { current: createTurnResultMarkdownState() };
|
|
6402
6674
|
const outcomeToolEntries = Object.entries(input.turnDef.outcomes ?? {});
|
|
6403
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");
|
|
6404
6678
|
const usesOutcomeTools = outcomeToolEntries.length > 0;
|
|
6405
6679
|
const requiresMarkdownResultToolCall = input.turnDef.turnResultMarkdown?.mode === "tool_call" && input.turnDef.turnResultMarkdown.toolName === "markdown_result" && input.turnDef.turnResultMarkdown.required === true;
|
|
6406
6680
|
const hasResultImageTool = Boolean(
|
|
@@ -6410,31 +6684,39 @@ function createTurnOutcomeToolSession(input) {
|
|
|
6410
6684
|
const outcomeActions = outcomeToolEntries.map(([outcome, spec]) => {
|
|
6411
6685
|
const markdownParameterName = spec.turnResultMarkdownParameter ?? outcomeToolMarkdownParameterName;
|
|
6412
6686
|
const injectsGlobalMarkdownParameter = Boolean(outcomeToolMarkdownParameterName) && !spec.turnResultMarkdownParameter;
|
|
6687
|
+
const parameters = outcomeCallParameters(spec, outcomeToolMarkdownParameterName);
|
|
6413
6688
|
return {
|
|
6414
6689
|
name: outcome,
|
|
6415
6690
|
description: spec.description,
|
|
6416
|
-
|
|
6417
|
-
|
|
6418
|
-
...injectsGlobalMarkdownParameter ? {
|
|
6419
|
-
resultSummary: {
|
|
6420
|
-
type: "string",
|
|
6421
|
-
description: "Concise result summary for this attempt."
|
|
6422
|
-
}
|
|
6423
|
-
} : {},
|
|
6424
|
-
...injectsGlobalMarkdownParameter && outcomeToolMarkdownParameterName ? {
|
|
6425
|
-
[outcomeToolMarkdownParameterName]: {
|
|
6426
|
-
type: "string",
|
|
6427
|
-
description: "Operator-facing markdown result for this turn. Pass raw markdown only and do not wrap the entire markdown in triple backticks.",
|
|
6428
|
-
required: true,
|
|
6429
|
-
requiredErrorCode: `${outcomeToolMarkdownParameterName}_required`
|
|
6430
|
-
}
|
|
6431
|
-
} : {}
|
|
6432
|
-
},
|
|
6691
|
+
strictSchema: spec.strictSchema,
|
|
6692
|
+
parameters: compileOutcomeParameters2(parameters, spec.strictSchema),
|
|
6433
6693
|
executionMode: "sequential",
|
|
6434
6694
|
execute: async (args) => {
|
|
6695
|
+
if (abortReason) return { ok: false, status: "aborted", reason: abortReason };
|
|
6435
6696
|
const result = { status: "ok", outcome };
|
|
6436
6697
|
const acceptsOutcome = selectedOutcome === null;
|
|
6437
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
|
+
}
|
|
6438
6720
|
let outcomeParams = args;
|
|
6439
6721
|
if (spec.resultSummaryParameter && typeof args[spec.resultSummaryParameter] === "string")
|
|
6440
6722
|
turnResultMarkdownStateRef.current.resultSummary = String(
|
|
@@ -6447,6 +6729,7 @@ function createTurnOutcomeToolSession(input) {
|
|
|
6447
6729
|
spec.resultSummaryParameter ? args[spec.resultSummaryParameter] : injectsGlobalMarkdownParameter ? args.resultSummary : void 0
|
|
6448
6730
|
);
|
|
6449
6731
|
if (!published.response.ok) {
|
|
6732
|
+
rejectedOutcome = { outcome, errors: [published.response.message] };
|
|
6450
6733
|
return published.response;
|
|
6451
6734
|
}
|
|
6452
6735
|
turnResultMarkdownStateRef.current = published.state;
|
|
@@ -6457,6 +6740,7 @@ function createTurnOutcomeToolSession(input) {
|
|
|
6457
6740
|
}
|
|
6458
6741
|
}
|
|
6459
6742
|
selectedOutcome = { outcome, params: outcomeParams };
|
|
6743
|
+
rejectedOutcome = void 0;
|
|
6460
6744
|
}
|
|
6461
6745
|
maybeCaptureTurnResultMarkdownFromToolCall({
|
|
6462
6746
|
behavior: input.turnDef.turnResultMarkdown,
|
|
@@ -6472,7 +6756,7 @@ function createTurnOutcomeToolSession(input) {
|
|
|
6472
6756
|
}
|
|
6473
6757
|
};
|
|
6474
6758
|
});
|
|
6475
|
-
const questionTool = input.turnDef.askQuestions && input.turnRecordId && input.requestQuestions ? createAskQuestionsTool({
|
|
6759
|
+
const questionTool = input.turnDef.askQuestions && input.questionsEnabled !== false && input.turnRecordId && input.requestQuestions ? createAskQuestionsTool({
|
|
6476
6760
|
turnRecordId: input.turnRecordId,
|
|
6477
6761
|
request: input.requestQuestions
|
|
6478
6762
|
}) : null;
|
|
@@ -6480,8 +6764,28 @@ function createTurnOutcomeToolSession(input) {
|
|
|
6480
6764
|
...hasResultImageTool && input.resultImageTool ? [input.resultImageTool] : [],
|
|
6481
6765
|
...input.turnDef.turnResultMarkdown?.mode === "tool_call" && input.turnDef.turnResultMarkdown.toolName === "markdown_result" ? [createMarkdownResultTool(turnResultMarkdownStateRef)] : [],
|
|
6482
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
|
+
},
|
|
6483
6787
|
...questionTool ? [questionTool] : [],
|
|
6484
|
-
...input.integrationTools ?? []
|
|
6788
|
+
...(input.integrationTools ?? []).filter((tool) => tool.modelVisible !== false)
|
|
6485
6789
|
];
|
|
6486
6790
|
const activeTools = resolveTurnActiveToolNames({
|
|
6487
6791
|
turnId: input.turnId,
|
|
@@ -6518,10 +6822,13 @@ function createTurnOutcomeToolSession(input) {
|
|
|
6518
6822
|
usesOutcomeTools,
|
|
6519
6823
|
hasResultImageTool
|
|
6520
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.";
|
|
6521
6826
|
return next;
|
|
6522
6827
|
},
|
|
6523
6828
|
reset(baseState) {
|
|
6524
6829
|
selectedOutcome = cloneSelectedOutcome(baseState?.selectedOutcome ?? null);
|
|
6830
|
+
abortReason = baseState?.abortReason;
|
|
6831
|
+
rejectedOutcome = baseState?.rejectedOutcome ? structuredClone(baseState.rejectedOutcome) : void 0;
|
|
6525
6832
|
terminalAcknowledgement = selectedOutcome === null ? { kind: "open" } : { kind: "acknowledgement_succeeded" };
|
|
6526
6833
|
turnResultMarkdownStateRef.current = cloneTurnResultMarkdownState(
|
|
6527
6834
|
baseState?.markdownState ?? createTurnResultMarkdownState()
|
|
@@ -6530,10 +6837,30 @@ function createTurnOutcomeToolSession(input) {
|
|
|
6530
6837
|
getCompletionState() {
|
|
6531
6838
|
return {
|
|
6532
6839
|
selectedOutcome: cloneSelectedOutcome(selectedOutcome),
|
|
6533
|
-
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."]
|
|
6534
6859
|
};
|
|
6860
|
+
return true;
|
|
6535
6861
|
},
|
|
6536
6862
|
shouldBlockToolCall(toolName) {
|
|
6863
|
+
if (abortReason) return `Tool '${toolName}' was skipped because this turn was aborted.`;
|
|
6537
6864
|
if (selectedOutcome === null) {
|
|
6538
6865
|
return null;
|
|
6539
6866
|
}
|
|
@@ -6543,6 +6870,7 @@ function createTurnOutcomeToolSession(input) {
|
|
|
6543
6870
|
return `Tool '${toolName}' was skipped because an outcome has already been accepted for this turn.`;
|
|
6544
6871
|
},
|
|
6545
6872
|
resolveOutcome(turnDef) {
|
|
6873
|
+
if (abortReason) return null;
|
|
6546
6874
|
if (usesOutcomeTools) {
|
|
6547
6875
|
return selectedOutcome;
|
|
6548
6876
|
}
|
|
@@ -6552,11 +6880,13 @@ function createTurnOutcomeToolSession(input) {
|
|
|
6552
6880
|
} : null;
|
|
6553
6881
|
},
|
|
6554
6882
|
resolveMissingToolRecovery(completionState) {
|
|
6883
|
+
if (completionState.abortReason) return null;
|
|
6555
6884
|
return resolveMissingTurnToolCallRecovery({
|
|
6556
6885
|
selectedOutcome: completionState.selectedOutcome,
|
|
6557
6886
|
outcomeToolNames,
|
|
6558
6887
|
turnResultMarkdownBehavior: input.turnDef.turnResultMarkdown,
|
|
6559
|
-
turnResultMarkdownState: completionState.markdownState
|
|
6888
|
+
turnResultMarkdownState: completionState.markdownState,
|
|
6889
|
+
rejectedOutcome: completionState.rejectedOutcome
|
|
6560
6890
|
});
|
|
6561
6891
|
},
|
|
6562
6892
|
buildRecoveryContext(recovery) {
|
|
@@ -6564,7 +6894,7 @@ function createTurnOutcomeToolSession(input) {
|
|
|
6564
6894
|
strategy: "continue",
|
|
6565
6895
|
suggestedContinuePrompt: buildMissingTurnToolCallRecoveryPrompt(recovery),
|
|
6566
6896
|
failureCode: recovery.failureCode,
|
|
6567
|
-
|
|
6897
|
+
...!recovery.rejectedOutcome && recovery.missingToolNames.length > 0 ? { missingToolNames: recovery.missingToolNames } : {}
|
|
6568
6898
|
};
|
|
6569
6899
|
},
|
|
6570
6900
|
describeRecovery: describeMissingTurnToolCallRecovery,
|
|
@@ -6616,6 +6946,18 @@ async function executeLogicalPromptPlan(input) {
|
|
|
6616
6946
|
const taint = (reason) => input.emit?.({ kind: "session_tainted", reason });
|
|
6617
6947
|
let currentPlan = input.plan;
|
|
6618
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
|
+
};
|
|
6619
6961
|
const reportFailure = (error, args) => {
|
|
6620
6962
|
const failure2 = buildTurnFailureReport(error, {
|
|
6621
6963
|
turnId: input.turnId,
|
|
@@ -6647,17 +6989,24 @@ async function executeLogicalPromptPlan(input) {
|
|
|
6647
6989
|
for (; ; ) {
|
|
6648
6990
|
const plan = currentPlan;
|
|
6649
6991
|
const guardSuspension = new PromptGuardSuspension();
|
|
6650
|
-
const promptOptions =
|
|
6992
|
+
const promptOptions = {
|
|
6651
6993
|
tools: input.toolSession.tools,
|
|
6652
6994
|
activeTools: input.toolSession.activeTools,
|
|
6653
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
|
+
},
|
|
6654
7003
|
suspendPromptGuards: () => guardSuspension.suspend(),
|
|
6655
7004
|
terminalAcknowledgement: {
|
|
6656
7005
|
...input.toolSession.terminalAcknowledgement,
|
|
6657
7006
|
timeoutMs: TERMINAL_ACKNOWLEDGEMENT_TIMEOUT_MS,
|
|
6658
7007
|
isOperatorAbortRequested: () => input.operatorAbortSignal?.aborted === true
|
|
6659
7008
|
}
|
|
6660
|
-
}
|
|
7009
|
+
};
|
|
6661
7010
|
let runPrompt = () => plan.kind === "continue" ? input.piHandle.continueTurn(promptOptions) : input.piHandle.prompt(plan.promptText ?? "", promptOptions);
|
|
6662
7011
|
if (plan.kind === "continue") {
|
|
6663
7012
|
try {
|
|
@@ -6715,7 +7064,11 @@ async function executeLogicalPromptPlan(input) {
|
|
|
6715
7064
|
"Terminal acknowledgement did not complete and was ignored"
|
|
6716
7065
|
);
|
|
6717
7066
|
}
|
|
7067
|
+
for (const entryId of attempt.result.createdEntryIds) {
|
|
7068
|
+
input.toolSession.recordToolResult(input.piHandle.getEntry(entryId)?.message);
|
|
7069
|
+
}
|
|
6718
7070
|
const completionState = input.toolSession.getCompletionState();
|
|
7071
|
+
if (completionState.abortReason) throw new Error(completionState.abortReason);
|
|
6719
7072
|
const acknowledgementFailure = input.toolSession.terminalAcknowledgement.failureReason();
|
|
6720
7073
|
if (acknowledgementFailure) {
|
|
6721
7074
|
trace({
|
|
@@ -6732,19 +7085,7 @@ async function executeLogicalPromptPlan(input) {
|
|
|
6732
7085
|
sawCompaction: attempt.sawCompaction,
|
|
6733
7086
|
compactionContinueAttempts
|
|
6734
7087
|
})) {
|
|
6735
|
-
|
|
6736
|
-
trace({
|
|
6737
|
-
level: "info",
|
|
6738
|
-
code: "turn.compaction_continue_requested",
|
|
6739
|
-
message: `Turn '${input.turnId}' requested an explicit continue after compaction`,
|
|
6740
|
-
turnRecordId: input.turnRecordId,
|
|
6741
|
-
turnId: input.turnId,
|
|
6742
|
-
details: {
|
|
6743
|
-
attempt: compactionContinueAttempts,
|
|
6744
|
-
resultPiEntryId: attempt.result.resultEntryId
|
|
6745
|
-
}
|
|
6746
|
-
});
|
|
6747
|
-
currentPlan = DEFAULT_CONTINUATION_PLAN;
|
|
7088
|
+
requestCompactionContinuation(attempt.result.resultEntryId);
|
|
6748
7089
|
continue;
|
|
6749
7090
|
}
|
|
6750
7091
|
return {
|
|
@@ -6753,24 +7094,19 @@ async function executeLogicalPromptPlan(input) {
|
|
|
6753
7094
|
resolvedOutcome
|
|
6754
7095
|
};
|
|
6755
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
|
+
);
|
|
6756
7104
|
if (shouldAutoContinueAfterCompactionError({
|
|
6757
7105
|
error,
|
|
6758
7106
|
piHandle: input.piHandle,
|
|
6759
7107
|
compactionContinueAttempts
|
|
6760
7108
|
})) {
|
|
6761
|
-
|
|
6762
|
-
trace({
|
|
6763
|
-
level: "info",
|
|
6764
|
-
code: "turn.compaction_error_continue_requested",
|
|
6765
|
-
message: `Turn '${input.turnId}' requested an explicit continue after context-window compaction`,
|
|
6766
|
-
turnRecordId: input.turnRecordId,
|
|
6767
|
-
turnId: input.turnId,
|
|
6768
|
-
details: {
|
|
6769
|
-
attempt: compactionContinueAttempts,
|
|
6770
|
-
resultPiEntryId: input.piHandle.getLeafId()
|
|
6771
|
-
}
|
|
6772
|
-
});
|
|
6773
|
-
currentPlan = DEFAULT_CONTINUATION_PLAN;
|
|
7109
|
+
requestCompactionContinuation(input.piHandle.getLeafId(), true);
|
|
6774
7110
|
continue;
|
|
6775
7111
|
}
|
|
6776
7112
|
return reportFailure(error, {
|
|
@@ -6788,60 +7124,64 @@ var MAX_MISSING_TOOL_CALL_RECOVERY_ATTEMPTS = 3;
|
|
|
6788
7124
|
async function runMissingToolRecovery(input) {
|
|
6789
7125
|
const trace = (payload) => input.emit?.({ kind: "trace", payload });
|
|
6790
7126
|
const reportError = (payload) => input.emit?.({ kind: "error", payload });
|
|
6791
|
-
|
|
6792
|
-
|
|
6793
|
-
);
|
|
6794
|
-
if (!baseMissingToolRecovery) {
|
|
7127
|
+
let recovery = input.toolSession.resolveMissingToolRecovery(input.initialAttempt.completionState);
|
|
7128
|
+
if (!recovery) {
|
|
6795
7129
|
return { finalAttempt: input.initialAttempt };
|
|
6796
7130
|
}
|
|
6797
|
-
|
|
6798
|
-
|
|
7131
|
+
let recoveryContext = input.toolSession.buildRecoveryContext(recovery);
|
|
7132
|
+
let description = input.toolSession.describeRecovery(recovery);
|
|
6799
7133
|
reportError({
|
|
6800
7134
|
level: "warn",
|
|
6801
|
-
code: "turn.required_tool_call_missing",
|
|
6802
|
-
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}`,
|
|
6803
7137
|
turnRecordId: input.turnRecordId,
|
|
6804
7138
|
turnId: input.turnId,
|
|
6805
7139
|
errorClass: "protocol_error",
|
|
6806
7140
|
details: {
|
|
6807
7141
|
attemptBudget: MAX_MISSING_TOOL_CALL_RECOVERY_ATTEMPTS,
|
|
6808
|
-
missingToolNames:
|
|
7142
|
+
missingToolNames: recovery.missingToolNames
|
|
6809
7143
|
}
|
|
6810
7144
|
});
|
|
6811
7145
|
let finalAttempt = input.initialAttempt;
|
|
7146
|
+
let unchangedRejections = 0;
|
|
6812
7147
|
for (let recoveryAttempt = 1; recoveryAttempt <= MAX_MISSING_TOOL_CALL_RECOVERY_ATTEMPTS; recoveryAttempt += 1) {
|
|
6813
7148
|
trace({
|
|
6814
7149
|
level: "info",
|
|
6815
7150
|
code: "turn.required_tool_call_retry_requested",
|
|
6816
|
-
message: `Turn '${input.turnId}' is retrying
|
|
7151
|
+
message: `Turn '${input.turnId}' is retrying: ${description}`,
|
|
6817
7152
|
turnRecordId: input.turnRecordId,
|
|
6818
7153
|
turnId: input.turnId,
|
|
6819
7154
|
details: {
|
|
6820
7155
|
recoveryAttempt,
|
|
6821
|
-
missingToolNames:
|
|
7156
|
+
missingToolNames: recovery.missingToolNames
|
|
6822
7157
|
}
|
|
6823
7158
|
});
|
|
7159
|
+
const previousAttempt = finalAttempt;
|
|
6824
7160
|
finalAttempt = await input.executeLogicalPromptPlan(
|
|
6825
7161
|
{
|
|
6826
7162
|
kind: "continue",
|
|
6827
7163
|
continueUserPrompt: recoveryContext.suggestedContinuePrompt,
|
|
6828
|
-
prepareForContinuation: async () => await input.piHandle.branch(
|
|
7164
|
+
prepareForContinuation: async () => await input.piHandle.branch(previousAttempt.promptResult.resultEntryId)
|
|
6829
7165
|
},
|
|
6830
|
-
{ baseState:
|
|
7166
|
+
{ baseState: previousAttempt.completionState }
|
|
6831
7167
|
);
|
|
6832
|
-
|
|
6833
|
-
|
|
6834
|
-
|
|
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;
|
|
6835
7175
|
}
|
|
6836
7176
|
reportError({
|
|
6837
7177
|
level: "error",
|
|
6838
7178
|
code: "turn.required_tool_call_retry_exhausted",
|
|
6839
|
-
message: `Turn '${input.turnId}'
|
|
7179
|
+
message: `Turn '${input.turnId}' stopped automatic recovery: ${description}`,
|
|
6840
7180
|
turnRecordId: input.turnRecordId,
|
|
6841
7181
|
turnId: input.turnId,
|
|
6842
7182
|
errorClass: "protocol_error",
|
|
6843
7183
|
details: {
|
|
6844
|
-
missingToolNames:
|
|
7184
|
+
missingToolNames: recovery.missingToolNames
|
|
6845
7185
|
}
|
|
6846
7186
|
});
|
|
6847
7187
|
return {
|
|
@@ -7018,6 +7358,24 @@ async function executeLlmTurn(input) {
|
|
|
7018
7358
|
turnId,
|
|
7019
7359
|
turnRecordId,
|
|
7020
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
|
+
} : {},
|
|
7021
7379
|
requestQuestions: input.callbacks.requestQuestions,
|
|
7022
7380
|
integrationTools: input.callbacks.integrationTools,
|
|
7023
7381
|
resultImageTool: input.resultImageTools.create({
|
|
@@ -7268,7 +7626,7 @@ async function executeLlmTurn(input) {
|
|
|
7268
7626
|
const { recoveryContext, description } = recoveryResult.failure;
|
|
7269
7627
|
return reportFailedTurn(
|
|
7270
7628
|
"protocol_error",
|
|
7271
|
-
`Turn '${turnId}'
|
|
7629
|
+
`Turn '${turnId}' did not complete within the recovery budget of ${MAX_MISSING_TOOL_CALL_RECOVERY_ATTEMPTS} attempts: ${description}`,
|
|
7272
7630
|
finalPromptResult.resultEntryId,
|
|
7273
7631
|
{
|
|
7274
7632
|
recoveryContext,
|
|
@@ -7357,6 +7715,44 @@ async function executeSelectedTurn(input) {
|
|
|
7357
7715
|
}
|
|
7358
7716
|
const handler = resolvedWorkerProcess.definition.turns.get(currentTurnId);
|
|
7359
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
|
+
}
|
|
7360
7756
|
let automaticIntegrationCallIndex = 0;
|
|
7361
7757
|
let latestProgressReport = null;
|
|
7362
7758
|
const reportProgress = (report) => {
|
|
@@ -7375,13 +7771,26 @@ async function executeSelectedTurn(input) {
|
|
|
7375
7771
|
});
|
|
7376
7772
|
};
|
|
7377
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,
|
|
7378
7786
|
process: processSnapshot,
|
|
7379
7787
|
projects: projectSnapshots,
|
|
7380
7788
|
params: resolvedWorkerProcess.params,
|
|
7381
7789
|
state: resolvedWorkerProcess.state,
|
|
7382
7790
|
turnResultMarkdownBySemanticRef: input.session.turnResultMarkdownBySemanticRef,
|
|
7383
|
-
turnResultMarkdownByProduct:
|
|
7791
|
+
turnResultMarkdownByProduct: observedProducts,
|
|
7384
7792
|
workspaceRoot: input.session.workspaceRoot,
|
|
7793
|
+
...input.session.iteration ? { iteration: input.session.iteration } : {},
|
|
7385
7794
|
...selectedTurnType === "automatic" ? {
|
|
7386
7795
|
reportProgress,
|
|
7387
7796
|
callIntegrationTool
|
|
@@ -7408,6 +7817,14 @@ async function executeSelectedTurn(input) {
|
|
|
7408
7817
|
`Selected turn '${currentTurnId}' of type '${selectedTurnType}' cannot call run.turn()`
|
|
7409
7818
|
);
|
|
7410
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
|
+
);
|
|
7411
7828
|
assertValidLlmTurnDefinition(currentTurnId, turnDef);
|
|
7412
7829
|
if (!piHandle) {
|
|
7413
7830
|
throw new TurnExecutionError(
|
|
@@ -7463,6 +7880,8 @@ async function executeSelectedTurn(input) {
|
|
|
7463
7880
|
callbacks: {
|
|
7464
7881
|
requestQuestions: input.requestQuestions,
|
|
7465
7882
|
integrationTools: input.integrationTools,
|
|
7883
|
+
callIntegrationTool,
|
|
7884
|
+
reportProgress,
|
|
7466
7885
|
onPreTurnTargetedInputApplied(inputId, sequence, meta) {
|
|
7467
7886
|
appliedTargetedInputs.push({ inputId, sequence, ...meta ? { meta } : {} });
|
|
7468
7887
|
},
|
|
@@ -7553,6 +7972,11 @@ function createWorkerRuntime(options) {
|
|
|
7553
7972
|
const sampleCredentials = adapters.sampleCredentials ?? sampleCredentialFiles;
|
|
7554
7973
|
const ipc = adapters.transport;
|
|
7555
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
|
+
);
|
|
7556
7980
|
const redact = (text) => redactSecrets(
|
|
7557
7981
|
text,
|
|
7558
7982
|
[...deliveredSecrets].sort((a, b) => b.length - a.length)
|
|
@@ -7586,11 +8010,26 @@ function createWorkerRuntime(options) {
|
|
|
7586
8010
|
});
|
|
7587
8011
|
const questionBridge = new WorkerQuestionBridge(reporter);
|
|
7588
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
|
+
};
|
|
7589
8024
|
let dispatch;
|
|
7590
8025
|
const piEvents = createPiEventReporter({
|
|
7591
8026
|
reporter,
|
|
7592
8027
|
emitExtensionEvent,
|
|
7593
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
|
+
},
|
|
7594
8033
|
getSessionTainted: () => state.sessionTainted,
|
|
7595
8034
|
onLifecycleObservation(kind) {
|
|
7596
8035
|
dispatch({ kind });
|
|
@@ -7717,10 +8156,20 @@ function createWorkerRuntime(options) {
|
|
|
7717
8156
|
(signal) => executeSelectedTurn({
|
|
7718
8157
|
session: command.session,
|
|
7719
8158
|
requestQuestions: (request) => questionBridge.request(request),
|
|
7720
|
-
integrationTools:
|
|
7721
|
-
|
|
7722
|
-
|
|
7723
|
-
|
|
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
|
+
],
|
|
7724
8173
|
piHandle: resources.piHandle,
|
|
7725
8174
|
turnRecordId: command.turnRecordId,
|
|
7726
8175
|
targetedInputs: command.targetedInputs,
|
|
@@ -7728,7 +8177,13 @@ function createWorkerRuntime(options) {
|
|
|
7728
8177
|
resultImageTools: adapters.resultImageTools,
|
|
7729
8178
|
signal,
|
|
7730
8179
|
emit(emission) {
|
|
7731
|
-
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") {
|
|
7732
8187
|
complete({ kind: "session_tainted", reason: emission.reason });
|
|
7733
8188
|
} else if (emission.kind === "trace") {
|
|
7734
8189
|
reporter.workerTrace(emission.payload, command.session.selectedTurnId);
|
|
@@ -7773,13 +8228,15 @@ function createWorkerRuntime(options) {
|
|
|
7773
8228
|
);
|
|
7774
8229
|
return;
|
|
7775
8230
|
case "sample_credentials":
|
|
7776
|
-
void sampleCredentials(command.descriptor).then(
|
|
7777
|
-
(
|
|
8231
|
+
void sampleCredentials(command.descriptor).then((sample) => {
|
|
8232
|
+
for (const value of Object.values(sample.values))
|
|
8233
|
+
if (value) inspectionSecrets.add(value);
|
|
8234
|
+
complete({
|
|
7778
8235
|
kind: "credential_sampled",
|
|
7779
8236
|
providerId: command.descriptor.providerId,
|
|
7780
8237
|
...sample
|
|
7781
|
-
})
|
|
7782
|
-
).catch(
|
|
8238
|
+
});
|
|
8239
|
+
}).catch(
|
|
7783
8240
|
(error) => complete({
|
|
7784
8241
|
kind: "credential_sample_failed",
|
|
7785
8242
|
providerId: command.descriptor.providerId,
|
|
@@ -7848,9 +8305,12 @@ function createWorkerRuntime(options) {
|
|
|
7848
8305
|
drain();
|
|
7849
8306
|
};
|
|
7850
8307
|
const receive = (message) => {
|
|
7851
|
-
if (message.type === "worker.start")
|
|
8308
|
+
if (message.type === "worker.start") {
|
|
8309
|
+
for (const secret of extractSecretValuesFromPayload(message.payload))
|
|
8310
|
+
inspectionSecrets.add(secret);
|
|
7852
8311
|
for (const secret of extractDockerRegistrySecretValues(message.payload))
|
|
7853
8312
|
deliveredSecrets.add(secret);
|
|
8313
|
+
}
|
|
7854
8314
|
if (message.type === "worker.integration_tool_result") {
|
|
7855
8315
|
integrationToolBridge.handle(message);
|
|
7856
8316
|
return;
|
|
@@ -7893,7 +8353,7 @@ function createWorkerRuntime(options) {
|
|
|
7893
8353
|
|
|
7894
8354
|
// src/entry-runtime.ts
|
|
7895
8355
|
import { existsSync as existsSync5, readFileSync as readFileSync3 } from "fs";
|
|
7896
|
-
import
|
|
8356
|
+
import path14 from "path";
|
|
7897
8357
|
import { isUnknownRecord as isRecord } from "@leitwerk-dev/domain";
|
|
7898
8358
|
import {
|
|
7899
8359
|
buildExtensionCatalog,
|
|
@@ -7920,10 +8380,10 @@ import {
|
|
|
7920
8380
|
|
|
7921
8381
|
// src/extension-entry-roots.ts
|
|
7922
8382
|
import { existsSync as existsSync2, realpathSync } from "fs";
|
|
7923
|
-
import
|
|
8383
|
+
import path11 from "path";
|
|
7924
8384
|
function isWithinDirectory(parentDir, candidatePath) {
|
|
7925
|
-
const relative =
|
|
7926
|
-
return relative === "" || !relative.startsWith("..") && !
|
|
8385
|
+
const relative = path11.relative(parentDir, candidatePath);
|
|
8386
|
+
return relative === "" || !relative.startsWith("..") && !path11.isAbsolute(relative);
|
|
7927
8387
|
}
|
|
7928
8388
|
function parseExtensionAllowedRoots(value) {
|
|
7929
8389
|
if (!value) return [];
|
|
@@ -7935,7 +8395,7 @@ function parseExtensionAllowedRoots(value) {
|
|
|
7935
8395
|
}
|
|
7936
8396
|
if (!Array.isArray(parsed) || parsed.some((entry) => typeof entry !== "string")) return [];
|
|
7937
8397
|
return parsed.flatMap((entry) => {
|
|
7938
|
-
if (!
|
|
8398
|
+
if (!path11.isAbsolute(entry) || !existsSync2(entry)) return [];
|
|
7939
8399
|
return [realpathSync(entry)];
|
|
7940
8400
|
});
|
|
7941
8401
|
}
|
|
@@ -8013,27 +8473,6 @@ function webSocketDataToText(data) {
|
|
|
8013
8473
|
}
|
|
8014
8474
|
return data.toString("utf8");
|
|
8015
8475
|
}
|
|
8016
|
-
var connectionErrorCodes = /* @__PURE__ */ new Set([
|
|
8017
|
-
"ECONNREFUSED",
|
|
8018
|
-
"ECONNRESET",
|
|
8019
|
-
"ENOTFOUND",
|
|
8020
|
-
"EAI_AGAIN",
|
|
8021
|
-
"ETIMEDOUT",
|
|
8022
|
-
"ENETUNREACH",
|
|
8023
|
-
"EHOSTUNREACH",
|
|
8024
|
-
"CERT_HAS_EXPIRED",
|
|
8025
|
-
"DEPTH_ZERO_SELF_SIGNED_CERT"
|
|
8026
|
-
]);
|
|
8027
|
-
function connectionErrorCode(value) {
|
|
8028
|
-
for (let depth = 0; depth < 4 && value && typeof value === "object"; depth += 1) {
|
|
8029
|
-
const error = value;
|
|
8030
|
-
if (typeof error.code === "string" && connectionErrorCodes.has(error.code)) {
|
|
8031
|
-
return error.code;
|
|
8032
|
-
}
|
|
8033
|
-
value = error.error ?? error.cause;
|
|
8034
|
-
}
|
|
8035
|
-
return "websocket_error";
|
|
8036
|
-
}
|
|
8037
8476
|
function createWebSocketWorkerIpc(input) {
|
|
8038
8477
|
let messageHandler;
|
|
8039
8478
|
let errorHandler;
|
|
@@ -8150,7 +8589,9 @@ function createWebSocketWorkerIpc(input) {
|
|
|
8150
8589
|
socket.addEventListener("message", (event) => deliverText(webSocketDataToText(event.data)));
|
|
8151
8590
|
socket.addEventListener("error", (event) => {
|
|
8152
8591
|
if (stopping) return;
|
|
8153
|
-
input.onDiagnostic?.(
|
|
8592
|
+
input.onDiagnostic?.(
|
|
8593
|
+
diagnostic(`error=${transportErrorCode(event) ?? "websocket_error"}`)
|
|
8594
|
+
);
|
|
8154
8595
|
if (!reconnectEnabled) {
|
|
8155
8596
|
emitError(event instanceof Error ? event : new Error("Worker WebSocket error"));
|
|
8156
8597
|
}
|
|
@@ -8213,7 +8654,7 @@ function createWorkerIpcFromEnvironment(input) {
|
|
|
8213
8654
|
// src/result-image-upload.ts
|
|
8214
8655
|
import { constants } from "fs";
|
|
8215
8656
|
import { open as open2, realpath, stat } from "fs/promises";
|
|
8216
|
-
import
|
|
8657
|
+
import path12 from "path";
|
|
8217
8658
|
import { setTimeout as sleep } from "timers/promises";
|
|
8218
8659
|
import {
|
|
8219
8660
|
buildWorkerResultImageUploadPath,
|
|
@@ -8237,12 +8678,12 @@ function failure(entry, code, message) {
|
|
|
8237
8678
|
return { ...entry, status: "failed", code, message };
|
|
8238
8679
|
}
|
|
8239
8680
|
function isWithinRoot(rootReal, fileReal) {
|
|
8240
|
-
const relative =
|
|
8241
|
-
return relative !== ".." && !relative.startsWith(`..${
|
|
8681
|
+
const relative = path12.relative(rootReal, fileReal);
|
|
8682
|
+
return relative !== ".." && !relative.startsWith(`..${path12.sep}`) && !path12.isAbsolute(relative);
|
|
8242
8683
|
}
|
|
8243
8684
|
async function readBoundedWorkspaceFile(entry, workspaceRoot, maxSizeBytes) {
|
|
8244
8685
|
const rootReal = await realpath(workspaceRoot);
|
|
8245
|
-
const candidatePath =
|
|
8686
|
+
const candidatePath = path12.resolve(workspaceRoot, entry.path);
|
|
8246
8687
|
const fileReal = await realpath(candidatePath);
|
|
8247
8688
|
if (!isWithinRoot(rootReal, fileReal)) {
|
|
8248
8689
|
return failure(
|
|
@@ -8450,6 +8891,8 @@ function createWorkerSessionSnapshotExchange(input) {
|
|
|
8450
8891
|
},
|
|
8451
8892
|
body: content,
|
|
8452
8893
|
signal: AbortSignal.timeout(timeoutMs)
|
|
8894
|
+
}).catch((cause) => {
|
|
8895
|
+
throw new Error("Session snapshot transport failed", { cause });
|
|
8453
8896
|
});
|
|
8454
8897
|
if (!response.ok) {
|
|
8455
8898
|
throw new Error(`Session snapshot upload failed with HTTP ${response.status}`);
|
|
@@ -8491,7 +8934,7 @@ import {
|
|
|
8491
8934
|
writeFileSync as writeFileSync3
|
|
8492
8935
|
} from "fs";
|
|
8493
8936
|
import { tmpdir } from "os";
|
|
8494
|
-
import
|
|
8937
|
+
import path13 from "path";
|
|
8495
8938
|
import {
|
|
8496
8939
|
clearRepositoryGitHttpsHelpers,
|
|
8497
8940
|
clearRepositoryGitSshWrappers,
|
|
@@ -8509,17 +8952,17 @@ var NodeRunRootGitOps = class {
|
|
|
8509
8952
|
configureRepositoryCredentials(credentials) {
|
|
8510
8953
|
this.cleanupRepositoryCredentials();
|
|
8511
8954
|
if (credentials.length === 0) return;
|
|
8512
|
-
const root = mkdtempSync2(
|
|
8955
|
+
const root = mkdtempSync2(path13.join(tmpdir(), "leitwerk-repo-auth-"));
|
|
8513
8956
|
chmodSync2(root, 448);
|
|
8514
8957
|
this.#credentialDir = root;
|
|
8515
8958
|
try {
|
|
8516
8959
|
for (const credential of credentials) {
|
|
8517
|
-
const dir =
|
|
8960
|
+
const dir = path13.join(root, encodeURIComponent(credential.projectKey));
|
|
8518
8961
|
mkdirSync2(dir, { mode: 448 });
|
|
8519
8962
|
if (credential.kind === "git_https") {
|
|
8520
8963
|
const url = repositoryHttpsUrl2(credential.repositoryUrl);
|
|
8521
8964
|
writeFileSync3(
|
|
8522
|
-
|
|
8965
|
+
path13.join(dir, "credential.json"),
|
|
8523
8966
|
JSON.stringify({
|
|
8524
8967
|
host: url.host,
|
|
8525
8968
|
path: url.pathname.slice(1),
|
|
@@ -8528,14 +8971,14 @@ var NodeRunRootGitOps = class {
|
|
|
8528
8971
|
}),
|
|
8529
8972
|
{ mode: 384 }
|
|
8530
8973
|
);
|
|
8531
|
-
const helper =
|
|
8974
|
+
const helper = path13.join(dir, "credential.cjs");
|
|
8532
8975
|
writeFileSync3(helper, HTTPS_CREDENTIAL_HELPER, { mode: 448 });
|
|
8533
8976
|
setRepositoryGitHttpsHelper(credential.projectKey, helper);
|
|
8534
8977
|
continue;
|
|
8535
8978
|
}
|
|
8536
|
-
const key =
|
|
8537
|
-
const hosts =
|
|
8538
|
-
const wrapper =
|
|
8979
|
+
const key = path13.join(dir, "identity");
|
|
8980
|
+
const hosts = path13.join(dir, "known_hosts");
|
|
8981
|
+
const wrapper = path13.join(dir, "ssh");
|
|
8539
8982
|
writeFileSync3(key, `${credential.privateKey.trim()}
|
|
8540
8983
|
`, { mode: 384 });
|
|
8541
8984
|
writeFileSync3(hosts, `${credential.knownHosts.trim()}
|
|
@@ -8562,7 +9005,7 @@ exec ssh -F /dev/null -o IdentitiesOnly=yes -o IdentityFile="${key}" -o UserKnow
|
|
|
8562
9005
|
}
|
|
8563
9006
|
async runGit(args, cwd, projectKey) {
|
|
8564
9007
|
const result = await execa2(resolveGitBinary(), repositoryGitArgs(args), {
|
|
8565
|
-
...cwd ? { cwd:
|
|
9008
|
+
...cwd ? { cwd: path13.resolve(cwd) } : {},
|
|
8566
9009
|
env: repositoryGitSubprocessEnv(projectKey ?? "", { GIT_TERMINAL_PROMPT: "0" }),
|
|
8567
9010
|
extendEnv: false,
|
|
8568
9011
|
stdin: "ignore"
|
|
@@ -8570,30 +9013,46 @@ exec ssh -F /dev/null -o IdentitiesOnly=yes -o IdentityFile="${key}" -o UserKnow
|
|
|
8570
9013
|
return result.stdout;
|
|
8571
9014
|
}
|
|
8572
9015
|
async writeFile(repoDir, filePath, content) {
|
|
8573
|
-
const absolutePath =
|
|
8574
|
-
mkdirSync2(
|
|
9016
|
+
const absolutePath = path13.resolve(path13.join(repoDir, filePath));
|
|
9017
|
+
mkdirSync2(path13.dirname(absolutePath), { recursive: true });
|
|
8575
9018
|
writeFileSync3(absolutePath, content, "utf8");
|
|
8576
9019
|
}
|
|
8577
9020
|
async readFile(repoDir, filePath) {
|
|
8578
|
-
const absolutePath =
|
|
9021
|
+
const absolutePath = path13.resolve(path13.join(repoDir, filePath));
|
|
8579
9022
|
if (!existsSync4(absolutePath)) {
|
|
8580
9023
|
return null;
|
|
8581
9024
|
}
|
|
8582
9025
|
return readFileSync2(absolutePath, "utf8");
|
|
8583
9026
|
}
|
|
8584
9027
|
async clone(repoLocator, targetDir) {
|
|
8585
|
-
const absoluteTargetDir =
|
|
9028
|
+
const absoluteTargetDir = path13.resolve(targetDir);
|
|
8586
9029
|
rmSync2(absoluteTargetDir, { recursive: true, force: true });
|
|
8587
|
-
mkdirSync2(
|
|
9030
|
+
mkdirSync2(path13.dirname(absoluteTargetDir), { recursive: true });
|
|
8588
9031
|
await this.runGit(
|
|
8589
9032
|
["clone", repoLocator, absoluteTargetDir],
|
|
8590
9033
|
void 0,
|
|
8591
|
-
|
|
9034
|
+
path13.basename(absoluteTargetDir)
|
|
8592
9035
|
);
|
|
8593
9036
|
}
|
|
8594
9037
|
async checkout(repoDir, branch) {
|
|
8595
9038
|
await this.runGit(["checkout", branch], repoDir);
|
|
8596
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
|
+
}
|
|
8597
9056
|
async createBranch(repoDir, branchName, startPoint) {
|
|
8598
9057
|
await this.runGit(["branch", branchName, startPoint], repoDir);
|
|
8599
9058
|
}
|
|
@@ -8612,7 +9071,7 @@ exec ssh -F /dev/null -o IdentitiesOnly=yes -o IdentityFile="${key}" -o UserKnow
|
|
|
8612
9071
|
return (await this.runGit(["rev-parse", "HEAD"], repoDir)).trim();
|
|
8613
9072
|
}
|
|
8614
9073
|
async listFiles(repoDir, pattern) {
|
|
8615
|
-
const absoluteRoot =
|
|
9074
|
+
const absoluteRoot = path13.resolve(repoDir);
|
|
8616
9075
|
if (!existsSync4(absoluteRoot)) {
|
|
8617
9076
|
return [];
|
|
8618
9077
|
}
|
|
@@ -8632,6 +9091,8 @@ for (const line of input.split('\\n')) {
|
|
|
8632
9091
|
const i = line.indexOf('=');
|
|
8633
9092
|
if (i < 0) continue;
|
|
8634
9093
|
const key = line.slice(0, i);
|
|
9094
|
+
// Git >= 2.46 advertises repeatable capability[] lines; only single-valued keys are matched.
|
|
9095
|
+
if (key.endsWith('[]')) continue;
|
|
8635
9096
|
if (Object.hasOwn(fields, key)) process.exit(0);
|
|
8636
9097
|
fields[key] = line.slice(i + 1);
|
|
8637
9098
|
}
|
|
@@ -8653,9 +9114,9 @@ function listWorkspacePatterns(workspaces) {
|
|
|
8653
9114
|
return [];
|
|
8654
9115
|
}
|
|
8655
9116
|
function findWorkspaceRoot(startDir) {
|
|
8656
|
-
let current =
|
|
9117
|
+
let current = path14.resolve(startDir);
|
|
8657
9118
|
while (true) {
|
|
8658
|
-
const packageJsonPath =
|
|
9119
|
+
const packageJsonPath = path14.join(current, "package.json");
|
|
8659
9120
|
if (existsSync5(packageJsonPath)) {
|
|
8660
9121
|
try {
|
|
8661
9122
|
const parsed = JSON.parse(readFileSync3(packageJsonPath, "utf8"));
|
|
@@ -8665,7 +9126,7 @@ function findWorkspaceRoot(startDir) {
|
|
|
8665
9126
|
} catch {
|
|
8666
9127
|
}
|
|
8667
9128
|
}
|
|
8668
|
-
const parent =
|
|
9129
|
+
const parent = path14.dirname(current);
|
|
8669
9130
|
if (parent === current) {
|
|
8670
9131
|
return null;
|
|
8671
9132
|
}
|
|
@@ -8787,7 +9248,8 @@ function createWorkerEntryRuntime(overrides = {}) {
|
|
|
8787
9248
|
|
|
8788
9249
|
export {
|
|
8789
9250
|
SdkPiTreeHandleFactory,
|
|
9251
|
+
persistPiResourceBundleForStart,
|
|
8790
9252
|
createWorkerRuntime,
|
|
8791
9253
|
createWorkerEntryRuntime
|
|
8792
9254
|
};
|
|
8793
|
-
//# sourceMappingURL=chunk-
|
|
9255
|
+
//# sourceMappingURL=chunk-KJCBXN5F.js.map
|