@leitwerk-dev/worker 0.3.1 → 0.4.1

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.
Files changed (82) hide show
  1. package/dist/{chunk-4WPLQCF6.js → chunk-KJCBXN5F.js} +1700 -1244
  2. package/dist/chunk-KJCBXN5F.js.map +1 -0
  3. package/dist/container-entry-main.js +160 -3
  4. package/dist/container-entry-main.js.map +1 -1
  5. package/dist/container-entry.d.ts +1 -0
  6. package/dist/container-entry.d.ts.map +1 -1
  7. package/dist/development-tool-environment.d.ts.map +1 -1
  8. package/dist/diagnostics.d.ts +5 -1
  9. package/dist/diagnostics.d.ts.map +1 -1
  10. package/dist/docker-registry-credentials.d.ts.map +1 -1
  11. package/dist/index.js +1 -1
  12. package/dist/ipc.d.ts.map +1 -1
  13. package/dist/logical-prompt-runner.d.ts.map +1 -1
  14. package/dist/missing-tool-recovery-runner.d.ts.map +1 -1
  15. package/dist/pi-adapter.d.ts +2 -0
  16. package/dist/pi-adapter.d.ts.map +1 -1
  17. package/dist/pi-event-reporter.d.ts +2 -0
  18. package/dist/pi-event-reporter.d.ts.map +1 -1
  19. package/dist/pi-inspection.d.ts +5 -0
  20. package/dist/pi-inspection.d.ts.map +1 -0
  21. package/dist/runtime/bootstrap-session.d.ts +4 -1
  22. package/dist/runtime/bootstrap-session.d.ts.map +1 -1
  23. package/dist/runtime/bootstrap.d.ts.map +1 -1
  24. package/dist/runtime/failure-policy.d.ts.map +1 -1
  25. package/dist/runtime/index.d.ts.map +1 -1
  26. package/dist/runtime/llm-turn-execution.d.ts +2 -0
  27. package/dist/runtime/llm-turn-execution.d.ts.map +1 -1
  28. package/dist/runtime/turn-execution.d.ts.map +1 -1
  29. package/dist/session-snapshot-exchange.d.ts.map +1 -1
  30. package/dist/strict-outcome-schema.d.ts +11 -0
  31. package/dist/strict-outcome-schema.d.ts.map +1 -0
  32. package/dist/test-helpers/llm-turn.d.ts +4 -0
  33. package/dist/test-helpers/llm-turn.d.ts.map +1 -0
  34. package/dist/test-helpers/pi-provider.d.ts +13 -0
  35. package/dist/test-helpers/pi-provider.d.ts.map +1 -0
  36. package/dist/transport-error.d.ts +16 -0
  37. package/dist/transport-error.d.ts.map +1 -0
  38. package/dist/turn-outcome-tool-session.d.ts +6 -1
  39. package/dist/turn-outcome-tool-session.d.ts.map +1 -1
  40. package/dist/turn-result-markdown.d.ts +5 -0
  41. package/dist/turn-result-markdown.d.ts.map +1 -1
  42. package/dist/virtual-machine-docker.d.ts +10 -0
  43. package/dist/virtual-machine-docker.d.ts.map +1 -0
  44. package/dist/worker-entry.js +1 -1
  45. package/dist/workspace/checkout-tool.d.ts +6 -0
  46. package/dist/workspace/checkout-tool.d.ts.map +1 -0
  47. package/dist/workspace/manifest.d.ts +2 -0
  48. package/dist/workspace/manifest.d.ts.map +1 -1
  49. package/dist/workspace/node-run-root-git-ops.d.ts +1 -0
  50. package/dist/workspace/node-run-root-git-ops.d.ts.map +1 -1
  51. package/dist/workspace/run-root.d.ts +5 -3
  52. package/dist/workspace/run-root.d.ts.map +1 -1
  53. package/package.json +9 -9
  54. package/src/container-entry.ts +22 -0
  55. package/src/development-tool-environment.ts +2 -0
  56. package/src/diagnostics.ts +6 -1
  57. package/src/docker-registry-credentials.ts +8 -0
  58. package/src/ipc.ts +4 -24
  59. package/src/logical-prompt-runner.ts +45 -41
  60. package/src/missing-tool-recovery-runner.ts +26 -18
  61. package/src/pi-adapter.ts +219 -337
  62. package/src/pi-event-reporter.ts +8 -0
  63. package/src/pi-inspection.ts +126 -0
  64. package/src/runtime/bootstrap-session.ts +12 -1
  65. package/src/runtime/bootstrap.ts +15 -5
  66. package/src/runtime/failure-policy.ts +20 -2
  67. package/src/runtime/index.ts +65 -10
  68. package/src/runtime/llm-turn-execution.ts +28 -1
  69. package/src/runtime/turn-execution.ts +70 -2
  70. package/src/session-snapshot-exchange.ts +2 -0
  71. package/src/strict-outcome-schema.ts +84 -0
  72. package/src/test-helpers/llm-turn.ts +22 -0
  73. package/src/test-helpers/pi-provider.ts +128 -0
  74. package/src/transport-error.ts +92 -0
  75. package/src/turn-outcome-tool-session.ts +123 -26
  76. package/src/turn-result-markdown.ts +23 -6
  77. package/src/virtual-machine-docker.ts +191 -0
  78. package/src/workspace/checkout-tool.ts +68 -0
  79. package/src/workspace/manifest.ts +3 -0
  80. package/src/workspace/node-run-root-git-ops.ts +17 -0
  81. package/src/workspace/run-root.ts +62 -26
  82. package/dist/chunk-4WPLQCF6.js.map +0 -1
@@ -12,6 +12,8 @@ export interface PiEventReporterOptions {
12
12
  reporter: Pick<WorkerIpcReporter, "workerEvent" | "workerTrace" | "workerError">;
13
13
  emitExtensionEvent?(event: string, payload: unknown): void;
14
14
  getCurrentSelectedTurnId?(): string | null;
15
+ getCurrentTurnRecordId?(): string | null;
16
+ reportInspection?(capture: unknown, turnRecordId: string): void;
15
17
  getSessionTainted?(): boolean;
16
18
  onLifecycleObservation?(kind: "pi_turn_started" | "pi_turn_ended"): void;
17
19
  }
@@ -112,6 +114,12 @@ export function createPiEventReporter(options: PiEventReporterOptions): PiEventR
112
114
  return {
113
115
  attach(piHandle) {
114
116
  piHandle.subscribe((event) => {
117
+ if (event.type === "inspection") {
118
+ const turnRecordId = options.getCurrentTurnRecordId?.();
119
+ if (turnRecordId && !options.getSessionTainted?.())
120
+ options.reportInspection?.(event.data.capture, turnRecordId);
121
+ return;
122
+ }
115
123
  if (event.type === "turn.start") {
116
124
  options.onLifecycleObservation?.("pi_turn_started");
117
125
  resetPiRetryState();
@@ -0,0 +1,126 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type { AgentSession } from "@earendil-works/pi-coding-agent";
3
+ import type { ExecutionInspectionCapture, InspectionMessage } from "@leitwerk-dev/domain";
4
+ import { strictOutcomeToolNames, supportsStrictOutcomeSchemas } from "./strict-outcome-schema.js";
5
+
6
+ function messageKey(message: { role?: unknown; content?: unknown; toolCallId?: unknown }) {
7
+ const content =
8
+ typeof message.content === "string"
9
+ ? [{ type: "text", text: message.content }]
10
+ : message.content;
11
+ return JSON.stringify([
12
+ message.role === "custom" ? "user" : message.role,
13
+ content,
14
+ message.toolCallId ?? null,
15
+ ]);
16
+ }
17
+
18
+ /** Observe the model-facing context without reading request options (which contain credentials). */
19
+ export function installPiInspection(
20
+ session: AgentSession,
21
+ emit: (capture: ExecutionInspectionCapture) => void,
22
+ getPiTurnId: () => string = () => "unknown",
23
+ ): () => void {
24
+ const original = session.agent.streamFunction;
25
+ if (typeof original !== "function") return () => {};
26
+ // AgentSession's earlier, awaited listener persists message_end after notifying
27
+ // its own subscribers. Observe agent-core after that listener has settled.
28
+ const unsubscribe = session.agent.subscribe((event) => {
29
+ if (event.type !== "message_end") return;
30
+ const entry = session.sessionManager.getLeafEntry();
31
+ if (!entry || (entry.type !== "message" && entry.type !== "custom_message")) return;
32
+ const message =
33
+ entry.type === "message" ? entry.message : { role: "custom", content: entry.content };
34
+ if (messageKey(message) !== messageKey(event.message)) return;
35
+ emit({
36
+ id: `entry:${entry.id}`,
37
+ version: 1,
38
+ timestamp: entry.timestamp,
39
+ fact: {
40
+ kind: "entry_link",
41
+ entryId: entry.id,
42
+ piTurnId: getPiTurnId(),
43
+ role: event.message.role,
44
+ },
45
+ });
46
+ });
47
+ session.agent.streamFunction = async (model, context, options) => {
48
+ const { getCurrentSystemPrompt, getCurrentTools } = await import("@earendil-works/pi-ai");
49
+ const entries = session.sessionManager.getBranch();
50
+ const byContent = new Map<string, Array<{ id: string; timestamp: number }>>();
51
+ for (const entry of entries) {
52
+ const message =
53
+ entry.type === "message"
54
+ ? entry.message
55
+ : entry.type === "custom_message"
56
+ ? { role: "user", content: entry.content }
57
+ : null;
58
+ if (!message) continue;
59
+ const key = messageKey(message);
60
+ const timestamp =
61
+ "timestamp" in message && typeof message.timestamp === "number"
62
+ ? message.timestamp
63
+ : Date.parse(entry.timestamp);
64
+ byContent.set(key, [...(byContent.get(key) ?? []), { id: entry.id, timestamp }]);
65
+ }
66
+ const messages: InspectionMessage[] = context.messages.map((message) => {
67
+ const matches = byContent.get(messageKey(message));
68
+ const exact = matches?.filter((match) => match.timestamp === message.timestamp);
69
+ const candidates = exact?.length ? exact : matches;
70
+ return {
71
+ entryId: candidates?.length === 1 ? candidates[0].id : null,
72
+ role: message.role,
73
+ ...(message.role === "toolResult" ? { toolCallId: message.toolCallId } : {}),
74
+ content: { state: "recorded", value: message.content },
75
+ };
76
+ });
77
+ const capture: ExecutionInspectionCapture = {
78
+ id: randomUUID(),
79
+ version: 1,
80
+ timestamp: new Date().toISOString(),
81
+ fact: {
82
+ kind: "model_input",
83
+ boundaryEntryId: session.sessionManager.getLeafId(),
84
+ model: {
85
+ provider: model.provider,
86
+ id: model.id,
87
+ thinkingLevel: session.thinkingLevel ?? null,
88
+ },
89
+ systemPrompt: { state: "recorded", value: getCurrentSystemPrompt(context.messages) },
90
+ appendedInstructions: {
91
+ state: "recorded",
92
+ value: session.resourceLoader.getAppendSystemPrompt(),
93
+ },
94
+ contextFiles: {
95
+ state: "recorded",
96
+ value: session.resourceLoader
97
+ .getAgentsFiles()
98
+ .agentsFiles.map(({ path, content }) => ({ path, content })),
99
+ },
100
+ tools: {
101
+ state: "recorded",
102
+ value: getCurrentTools(context.messages).map(({ name, description, parameters }) => ({
103
+ name,
104
+ description,
105
+ parameters,
106
+ ...(strictOutcomeToolNames(session).has(name)
107
+ ? {
108
+ strictSchema: true,
109
+ schemaEnforcement: supportsStrictOutcomeSchemas(model.api)
110
+ ? ("provider" as const)
111
+ : ("server" as const),
112
+ }
113
+ : {}),
114
+ })),
115
+ },
116
+ messages,
117
+ },
118
+ };
119
+ emit(JSON.parse(JSON.stringify(capture)) as ExecutionInspectionCapture);
120
+ return original.call(session.agent, model, context, options);
121
+ };
122
+ return () => {
123
+ unsubscribe();
124
+ session.agent.streamFunction = original;
125
+ };
126
+ }
@@ -1,6 +1,7 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import type {
4
+ InspectionProduct,
4
5
  PreparedTurnStart,
5
6
  ProcessInstance,
6
7
  ProcessProject,
@@ -14,6 +15,7 @@ import { DockerRegistryCredentials } from "../docker-registry-credentials.js";
14
15
  import type { InputItem } from "../input-consumer.js";
15
16
  import type { PiTreeHandle, PiTreeHandleFactory } from "../pi-adapter.js";
16
17
  import type { WorkerSessionSnapshotExchange } from "../session-snapshot-exchange.js";
18
+ import { transportErrorDetails } from "../transport-error.js";
17
19
  import { isLlmWorkerStartPayload } from "../worker-start-payload.js";
18
20
  import type { RunRootGitOps } from "../workspace/run-root.js";
19
21
  import type { WorkerRuntimeScheduler } from "./adapters.js";
@@ -26,6 +28,8 @@ import {
26
28
  import type { WorkerRuntimeSettings } from "./settings.js";
27
29
 
28
30
  interface PreparedSessionBase {
31
+ outcomeContract?: Record<string, unknown>;
32
+ scopedSettings?: import("@leitwerk-dev/domain").ScopedSettingsSnapshot;
29
33
  processSnapshot: ProcessInstance;
30
34
  projectSnapshots: ProcessProject[];
31
35
  resolvedWorkerProcess: ResolvedWorkerProcess;
@@ -39,6 +43,7 @@ interface PreparedSessionBase {
39
43
  workspaceRoot: string;
40
44
  turnResultMarkdownBySemanticRef?: Partial<Record<ProcessSemanticEntryRefKey, string>>;
41
45
  turnResultMarkdownByProduct?: Record<string, string>;
46
+ inspectionProducts?: InspectionProduct[];
42
47
  settings: WorkerRuntimeSettings;
43
48
  integrationTools: NonNullable<WorkerStartPayload["integrationTools"]>;
44
49
  iteration?: NonNullable<WorkerStartPayload["iteration"]>;
@@ -97,11 +102,15 @@ function validatePreparedSession(input: {
97
102
  );
98
103
  }
99
104
  const base = {
105
+ outcomeContract:
106
+ turnStartState.start?.kind === "llm" ? turnStartState.start.outcomeContract : undefined,
100
107
  processSnapshot: bootstrapped.processSnapshot,
101
108
  projectSnapshots: bootstrapped.projectSnapshots,
102
109
  resolvedWorkerProcess: process,
103
110
  selectedTurnId,
104
111
  startRecordId: payload.turnStart.id,
112
+ scopedSettings:
113
+ turnStartState.start?.kind === "llm" ? turnStartState.start.scopedSettings : undefined,
105
114
  proposedTurnRecordId: payload.turnStart.proposedTurnRecordId,
106
115
  acceptedTurnRecordId:
107
116
  payload.turnStart.state.kind === "accepted" ? payload.turnStart.state.turnRecordId : null,
@@ -111,6 +120,7 @@ function validatePreparedSession(input: {
111
120
  workspaceRoot: payload.treePaths.workspaceRoot,
112
121
  turnResultMarkdownBySemanticRef: payload.turnResultMarkdownBySemanticRef,
113
122
  turnResultMarkdownByProduct: payload.turnResultMarkdownByProduct,
123
+ inspectionProducts: payload.inspectionProducts,
114
124
  settings,
115
125
  integrationTools: payload.integrationTools ?? [],
116
126
  ...(payload.iteration ? { iteration: payload.iteration } : {}),
@@ -247,7 +257,7 @@ export class WorkerLiveResources {
247
257
  level: "warn",
248
258
  code: "session_snapshot.upload_failed",
249
259
  message: `Session snapshot upload failed: ${error instanceof Error ? error.message : String(error)}`,
250
- details: { attempt, reason },
260
+ details: { attempt, reason, transport: transportErrorDetails(error) },
251
261
  });
252
262
  if (attempt < 3) await this.deps.scheduler.sleep(100 * attempt);
253
263
  }
@@ -255,6 +265,7 @@ export class WorkerLiveResources {
255
265
  if (!metadata.required) return;
256
266
  throw new Error(
257
267
  `Mandatory session snapshot upload failed before ${reason}: ${lastError instanceof Error ? lastError.message : String(lastError)}`,
268
+ { cause: lastError },
258
269
  );
259
270
  }
260
271
 
@@ -1,3 +1,4 @@
1
+ import { mkdir } from "node:fs/promises";
1
2
  import path from "node:path";
2
3
  import {
3
4
  type PreparedTurnStart,
@@ -53,6 +54,7 @@ import { isLlmWorkerStartPayload } from "../worker-start-payload.js";
53
54
  import {
54
55
  materializeRunRoot,
55
56
  planRunRoot,
57
+ prepareOnDemandRunRoot,
56
58
  type RunRootGitOps,
57
59
  repairRunRoot,
58
60
  validateRunRoot,
@@ -462,11 +464,19 @@ export async function bootstrapWorkerRuntime(
462
464
  }));
463
465
  const plan = planRunRoot(workspaceRoot, deps.instanceId, runRootProjects);
464
466
 
465
- const runRootPreparation = deps.payload.resume
466
- ? validateRunRoot(workspaceRoot, runRootProjects, deps.gitOps).then((validation) =>
467
- repairRunRoot(workspaceRoot, validation, plan, deps.gitOps),
468
- )
469
- : materializeRunRoot(plan, deps.gitOps);
467
+ const runRootPreparation =
468
+ resolvedWorkerProcess?.runtime?.repositoryCheckout === "none"
469
+ ? mkdir(workspaceRoot, { recursive: true }).then(() => ({
470
+ aggregatedAgentsMdSources: [],
471
+ loadedSkills: [],
472
+ }))
473
+ : resolvedWorkerProcess?.runtime?.repositoryCheckout === "on_demand"
474
+ ? prepareOnDemandRunRoot(plan, deps.gitOps)
475
+ : deps.payload.resume
476
+ ? validateRunRoot(workspaceRoot, runRootProjects, deps.gitOps).then((validation) =>
477
+ repairRunRoot(validation, plan, deps.gitOps),
478
+ )
479
+ : materializeRunRoot(plan, deps.gitOps);
470
480
 
471
481
  const resolvedPiConfig = llmPayload
472
482
  ? resolveProcessPiConfig({
@@ -6,6 +6,7 @@ import type {
6
6
  WorkerTurnFailedPayload,
7
7
  } from "@leitwerk-dev/worker-protocol";
8
8
  import type { WorkerDiagnosticPayload } from "../diagnostics.js";
9
+ import { transportErrorDetails } from "../transport-error.js";
9
10
  import { classifyRuntimeError, type TurnExecutionError } from "../turn-execution-error.js";
10
11
  import type { WorkerRuntimeState } from "./lifecycle-reducer.js";
11
12
  import type { WorkerSnapshotPoint } from "./snapshot-policy.js";
@@ -86,6 +87,13 @@ export function extractSecretValuesFromPayload(
86
87
  }
87
88
  }
88
89
  for (const value of extractDockerRegistrySecretValues(payload)) secrets.add(value);
90
+ for (const credential of payload.repositoryCredentials ?? []) {
91
+ const value = credential.kind === "git_ssh" ? credential.privateKey : credential.password;
92
+ if (value) {
93
+ secrets.add(value);
94
+ secrets.add(encodeURIComponent(value));
95
+ }
96
+ }
89
97
  return Array.from(secrets);
90
98
  }
91
99
 
@@ -141,7 +149,9 @@ export function normalizeWorkerFailure(failure: WorkerFailure): WorkerFailureDis
141
149
  const turnError = failure.kind === "turn" ? failure.error : null;
142
150
  const summary =
143
151
  failure.kind === "mandatory_snapshot"
144
- ? `Mandatory session snapshot upload failed before ${failure.point}: ${message}`
152
+ ? message.startsWith(`Mandatory session snapshot upload failed before ${failure.point}: `)
153
+ ? message
154
+ : `Mandatory session snapshot upload failed before ${failure.point}: ${message}`
145
155
  : (turnError?.message ?? message);
146
156
  const errorClass = turnError?.errorClass ?? classified.errorClass;
147
157
  const payload: WorkerTurnFailedPayload = {
@@ -155,7 +165,12 @@ export function normalizeWorkerFailure(failure: WorkerFailure): WorkerFailureDis
155
165
  resultPiEntryId: correlation.resultPiEntryId ?? null,
156
166
  ...(turnError?.failureCode ? { failureCode: turnError.failureCode } : {}),
157
167
  ...(failure.kind === "mandatory_snapshot"
158
- ? { failureDetails: { reason: failure.point } }
168
+ ? {
169
+ failureDetails: {
170
+ reason: failure.point,
171
+ transport: transportErrorDetails(failure.error),
172
+ },
173
+ }
159
174
  : turnError?.failureDetails
160
175
  ? { failureDetails: turnError.failureDetails }
161
176
  : {}),
@@ -173,6 +188,9 @@ export function normalizeWorkerFailure(failure: WorkerFailure): WorkerFailureDis
173
188
  errorClass,
174
189
  turnRecordId: correlation.turnRecordId,
175
190
  turnId: correlation.turnId,
191
+ ...(failure.kind === "mandatory_snapshot"
192
+ ? { details: payload.failureDetails ?? undefined }
193
+ : {}),
176
194
  },
177
195
  stderrMessage: summary,
178
196
  terminal: {
@@ -1,3 +1,4 @@
1
+ import { redactInspectionEvidence } from "@leitwerk-dev/domain";
1
2
  import type { ServerToWorkerMessage } from "@leitwerk-dev/worker-protocol";
2
3
  import { MiseDevelopmentToolEnvironment } from "../development-tool-environment.js";
3
4
  import { deliverBatch } from "../input-consumer.js";
@@ -7,9 +8,14 @@ import { createPiEventReporter } from "../pi-event-reporter.js";
7
8
  import { WorkerQuestionBridge } from "../question-bridge.js";
8
9
  import { resolveRootEntryIdFromHandle } from "../turn-tree-strategy.js";
9
10
  import { createWorkerIpcReporter } from "../worker-ipc-reporter.js";
11
+ import { createCheckoutTool } from "../workspace/checkout-tool.js";
10
12
  import type { WorkerRuntimeOptions, WorkerRuntimeTimer } from "./adapters.js";
11
13
  import { sampleCredentialFiles, WorkerLiveResources } from "./bootstrap-session.js";
12
- import { extractDockerRegistrySecretValues, redactSecrets } from "./failure-policy.js";
14
+ import {
15
+ extractDockerRegistrySecretValues,
16
+ extractSecretValuesFromPayload,
17
+ redactSecrets,
18
+ } from "./failure-policy.js";
13
19
  import {
14
20
  createInitialWorkerRuntimeState,
15
21
  reduceWorkerRuntime,
@@ -45,6 +51,12 @@ export function createWorkerRuntime(options: WorkerRuntimeOptions): WorkerRuntim
45
51
  const sampleCredentials = adapters.sampleCredentials ?? sampleCredentialFiles;
46
52
  const ipc: WorkerIpc = adapters.transport;
47
53
  const deliveredSecrets = new Set<string>();
54
+ const inspectionSecrets = new Set<string>();
55
+ const redactInspectionText = (text: string) =>
56
+ redactSecrets(
57
+ text,
58
+ [...inspectionSecrets].sort((a, b) => b.length - a.length),
59
+ );
48
60
  const redact = (text: string) =>
49
61
  redactSecrets(
50
62
  text,
@@ -80,12 +92,31 @@ export function createWorkerRuntime(options: WorkerRuntimeOptions): WorkerRuntim
80
92
  });
81
93
  const questionBridge = new WorkerQuestionBridge(reporter);
82
94
  const integrationToolBridge = new WorkerIntegrationToolBridge(reporter);
95
+ const reportInspection = (
96
+ capture: unknown,
97
+ turnRecordId: string,
98
+ selectedTurnId: string | null,
99
+ ) => {
100
+ reporter.project({
101
+ kind: "protocol",
102
+ type: "worker.event",
103
+ payload: {
104
+ eventType: "execution.inspection",
105
+ selectedTurnId,
106
+ data: { turnRecordId, capture: redactInspectionEvidence(capture, redactInspectionText) },
107
+ },
108
+ });
109
+ };
83
110
 
84
111
  let dispatch: (event: WorkerRuntimeEvent) => void;
85
112
  const piEvents = createPiEventReporter({
86
113
  reporter,
87
114
  emitExtensionEvent,
88
115
  getCurrentSelectedTurnId: () => state.session?.selectedTurnId ?? null,
116
+ getCurrentTurnRecordId: () => (state.phase.kind === "active" ? state.phase.turnRecordId : null),
117
+ reportInspection(capture, turnRecordId) {
118
+ reportInspection(capture, turnRecordId, state.session?.selectedTurnId ?? null);
119
+ },
89
120
  getSessionTainted: () => state.sessionTainted,
90
121
  onLifecycleObservation(kind) {
91
122
  dispatch({ kind });
@@ -226,10 +257,23 @@ export function createWorkerRuntime(options: WorkerRuntimeOptions): WorkerRuntim
226
257
  executeSelectedTurn({
227
258
  session: command.session,
228
259
  requestQuestions: (request) => questionBridge.request(request),
229
- integrationTools: integrationToolBridge.createTools(
230
- command.session.integrationTools,
231
- command.turnRecordId,
232
- ),
260
+ integrationTools: [
261
+ ...integrationToolBridge.createTools(
262
+ command.session.integrationTools,
263
+ command.turnRecordId,
264
+ ),
265
+ ...(command.session.resolvedWorkerProcess.runtime?.repositoryCheckout ===
266
+ "on_demand"
267
+ ? [
268
+ createCheckoutTool(
269
+ command.session.workspaceRoot,
270
+ command.session.processSnapshot.id,
271
+ command.session.projectSnapshots,
272
+ adapters.gitOps,
273
+ ),
274
+ ]
275
+ : []),
276
+ ],
233
277
  piHandle: resources.piHandle,
234
278
  turnRecordId: command.turnRecordId,
235
279
  targetedInputs: command.targetedInputs,
@@ -237,7 +281,13 @@ export function createWorkerRuntime(options: WorkerRuntimeOptions): WorkerRuntim
237
281
  resultImageTools: adapters.resultImageTools,
238
282
  signal,
239
283
  emit(emission) {
240
- if (emission.kind === "session_tainted") {
284
+ if (emission.kind === "inspection") {
285
+ reportInspection(
286
+ emission.capture,
287
+ emission.turnRecordId,
288
+ command.session.selectedTurnId,
289
+ );
290
+ } else if (emission.kind === "session_tainted") {
241
291
  complete({ kind: "session_tainted", reason: emission.reason });
242
292
  } else if (emission.kind === "trace") {
243
293
  reporter.workerTrace(emission.payload, command.session.selectedTurnId);
@@ -288,13 +338,15 @@ export function createWorkerRuntime(options: WorkerRuntimeOptions): WorkerRuntim
288
338
  return;
289
339
  case "sample_credentials":
290
340
  void sampleCredentials(command.descriptor)
291
- .then((sample) =>
341
+ .then((sample) => {
342
+ for (const value of Object.values(sample.values))
343
+ if (value) inspectionSecrets.add(value);
292
344
  complete({
293
345
  kind: "credential_sampled",
294
346
  providerId: command.descriptor.providerId,
295
347
  ...sample,
296
- }),
297
- )
348
+ });
349
+ })
298
350
  .catch((error) =>
299
351
  complete({
300
352
  kind: "credential_sample_failed",
@@ -374,9 +426,12 @@ export function createWorkerRuntime(options: WorkerRuntimeOptions): WorkerRuntim
374
426
  };
375
427
 
376
428
  const receive = (message: ServerToWorkerMessage): void => {
377
- if (message.type === "worker.start")
429
+ if (message.type === "worker.start") {
430
+ for (const secret of extractSecretValuesFromPayload(message.payload))
431
+ inspectionSecrets.add(secret);
378
432
  for (const secret of extractDockerRegistrySecretValues(message.payload))
379
433
  deliveredSecrets.add(secret);
434
+ }
380
435
  if (message.type === "worker.integration_tool_result") {
381
436
  integrationToolBridge.handle(message);
382
437
  return;
@@ -113,6 +113,8 @@ export interface LlmTurnExecutorCallbacks {
113
113
  ): void;
114
114
  emit?: WorkerOperationEmitter;
115
115
  integrationTools?: readonly import("@leitwerk-dev/process-sdk").PiCustomTool[];
116
+ callIntegrationTool?: (name: string, args: Record<string, unknown>) => Promise<unknown>;
117
+ reportProgress?: import("@leitwerk-dev/process-sdk").LlmTurnPreparationContext["reportProgress"];
116
118
  }
117
119
 
118
120
  /** Pi writes these on new sessions before any conversational content exists. */
@@ -334,6 +336,31 @@ export async function executeLlmTurn<TOutcome extends string>(input: {
334
336
  turnId,
335
337
  turnRecordId,
336
338
  turnDef: input.turnDef,
339
+ questionsEnabled: input.turnDef.resolveAskQuestions?.({
340
+ ...input.ctx,
341
+ prepared: input.prepared,
342
+ }),
343
+ ...(input.turnDef.validateOutcome
344
+ ? {
345
+ validateOutcome: async (outcome: {
346
+ outcome: TOutcome;
347
+ params: Record<string, unknown>;
348
+ }) =>
349
+ input.turnDef.validateOutcome!(
350
+ {
351
+ ...input.ctx,
352
+ prepared: input.prepared,
353
+ callIntegrationTool:
354
+ input.callbacks.callIntegrationTool ??
355
+ (async () => {
356
+ throw new Error("Integration tools unavailable");
357
+ }),
358
+ reportProgress: input.callbacks.reportProgress ?? (() => {}),
359
+ },
360
+ outcome,
361
+ ),
362
+ }
363
+ : {}),
337
364
  requestQuestions: input.callbacks.requestQuestions,
338
365
  integrationTools: input.callbacks.integrationTools,
339
366
  resultImageTool: input.resultImageTools.create({
@@ -651,7 +678,7 @@ export async function executeLlmTurn<TOutcome extends string>(input: {
651
678
  const { recoveryContext, description } = recoveryResult.failure;
652
679
  return reportFailedTurn(
653
680
  "protocol_error",
654
- `Turn '${turnId}' completed without the required tool calls after ${MAX_MISSING_TOOL_CALL_RECOVERY_ATTEMPTS} automatic recovery attempts: ${description}`,
681
+ `Turn '${turnId}' did not complete within the recovery budget of ${MAX_MISSING_TOOL_CALL_RECOVERY_ATTEMPTS} attempts: ${description}`,
655
682
  finalPromptResult.resultEntryId,
656
683
  {
657
684
  recoveryContext,
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import type { TurnProgressReport } from "@leitwerk-dev/domain";
2
3
  import type {
3
4
  LlmTurnDefinition,
@@ -6,7 +7,11 @@ import type {
6
7
  WorkerProcessContext,
7
8
  WorkerRunHandle,
8
9
  } from "@leitwerk-dev/process-sdk";
9
- import { assertValidLlmTurnDefinition } from "@leitwerk-dev/process-sdk";
10
+ import {
11
+ applyOutcomeContract,
12
+ assertValidLlmTurnDefinition,
13
+ resolveOutcomeContract,
14
+ } from "@leitwerk-dev/process-sdk";
10
15
  import { createAutomaticTurnExecutor } from "../automatic-turn-executor.js";
11
16
  import type { WorkerOperationEmitter } from "../diagnostics.js";
12
17
  import type { PiTreeHandle } from "../pi-adapter.js";
@@ -96,6 +101,46 @@ export async function executeSelectedTurn(
96
101
  }
97
102
  const handler = resolvedWorkerProcess.definition.turns.get(currentTurnId);
98
103
  if (!handler) throw new Error(`Validated turn handler '${currentTurnId}' is unavailable`);
104
+ const supplyId = randomUUID();
105
+ input.emit({
106
+ kind: "inspection",
107
+ turnRecordId: input.turnRecordId,
108
+ capture: {
109
+ id: supplyId,
110
+ version: 1,
111
+ timestamp: input.scheduler.now().toISOString(),
112
+ fact: {
113
+ kind: "supplied_context",
114
+ origin: input.session.kind === "llm" ? input.session.preparedTurnStart : null,
115
+ products: input.session.inspectionProducts ?? [],
116
+ },
117
+ },
118
+ });
119
+ const products = input.session.turnResultMarkdownByProduct;
120
+ const observedProducts = products
121
+ ? Object.fromEntries(Object.keys(products).map((name) => [name, products[name]]))
122
+ : undefined;
123
+ const consumedProducts = new Set<string>();
124
+ for (const name of Object.keys(observedProducts ?? {})) {
125
+ Object.defineProperty(observedProducts, name, {
126
+ enumerable: true,
127
+ get() {
128
+ if (consumedProducts.has(name)) return products?.[name];
129
+ consumedProducts.add(name);
130
+ input.emit({
131
+ kind: "inspection",
132
+ turnRecordId: input.turnRecordId,
133
+ capture: {
134
+ id: `${supplyId}:product:${name}`,
135
+ version: 1,
136
+ timestamp: input.scheduler.now().toISOString(),
137
+ fact: { kind: "product_consumed", supplyId, name },
138
+ },
139
+ });
140
+ return products?.[name];
141
+ },
142
+ });
143
+ }
99
144
  let automaticIntegrationCallIndex = 0;
100
145
  let latestProgressReport: TurnProgressReport | null = null;
101
146
  const reportProgress = (report: TurnProgressReport) => {
@@ -118,12 +163,24 @@ export async function executeSelectedTurn(
118
163
  };
119
164
 
120
165
  const ctx = {
166
+ reportDiagnostic(report) {
167
+ input.emit({
168
+ kind: "trace",
169
+ payload: {
170
+ ...report,
171
+ turnRecordId: input.turnRecordId,
172
+ turnId: currentTurnId,
173
+ timestamp: input.scheduler.now().toISOString(),
174
+ },
175
+ });
176
+ },
177
+ scopedSettings: input.session.scopedSettings,
121
178
  process: processSnapshot,
122
179
  projects: projectSnapshots,
123
180
  params: resolvedWorkerProcess.params,
124
181
  state: resolvedWorkerProcess.state,
125
182
  turnResultMarkdownBySemanticRef: input.session.turnResultMarkdownBySemanticRef,
126
- turnResultMarkdownByProduct: input.session.turnResultMarkdownByProduct,
183
+ turnResultMarkdownByProduct: observedProducts,
127
184
  workspaceRoot: input.session.workspaceRoot,
128
185
  ...(input.session.iteration ? { iteration: input.session.iteration } : {}),
129
186
  ...(selectedTurnType === "automatic"
@@ -161,6 +218,15 @@ export async function executeSelectedTurn(
161
218
  `Selected turn '${currentTurnId}' of type '${selectedTurnType}' cannot call run.turn()`,
162
219
  );
163
220
  }
221
+ turnDef = applyOutcomeContract(
222
+ turnDef,
223
+ input.session.outcomeContract ??
224
+ resolveOutcomeContract(
225
+ turnDef,
226
+ { params: ctx.params, state: ctx.state },
227
+ input.session.iteration,
228
+ ),
229
+ );
164
230
  assertValidLlmTurnDefinition(currentTurnId, turnDef);
165
231
  if (!piHandle) {
166
232
  throw new TurnExecutionError(
@@ -216,6 +282,8 @@ export async function executeSelectedTurn(
216
282
  callbacks: {
217
283
  requestQuestions: input.requestQuestions,
218
284
  integrationTools: input.integrationTools,
285
+ callIntegrationTool,
286
+ reportProgress,
219
287
  onPreTurnTargetedInputApplied(inputId, sequence, meta) {
220
288
  appliedTargetedInputs.push({ inputId, sequence, ...(meta ? { meta } : {}) });
221
289
  },
@@ -94,6 +94,8 @@ export function createWorkerSessionSnapshotExchange(input: {
94
94
  },
95
95
  body: content,
96
96
  signal: AbortSignal.timeout(timeoutMs),
97
+ }).catch((cause: unknown) => {
98
+ throw new Error("Session snapshot transport failed", { cause });
97
99
  });
98
100
  if (!response.ok) {
99
101
  throw new Error(`Session snapshot upload failed with HTTP ${response.status}`);