@leitwerk-dev/worker 0.1.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/LICENSE +13 -0
- package/dist/automatic-turn-executor.d.ts +28 -0
- package/dist/automatic-turn-executor.d.ts.map +1 -0
- package/dist/automatic-turn-executor.js +58 -0
- package/dist/automatic-turn-executor.js.map +1 -0
- package/dist/chunk-N5HLJDWA.js +8124 -0
- package/dist/chunk-N5HLJDWA.js.map +1 -0
- package/dist/diagnostics.d.ts +23 -0
- package/dist/diagnostics.d.ts.map +1 -0
- package/dist/diagnostics.js +51 -0
- package/dist/diagnostics.js.map +1 -0
- package/dist/entry-runtime.d.ts +24 -0
- package/dist/entry-runtime.d.ts.map +1 -0
- package/dist/entry-runtime.js +160 -0
- package/dist/entry-runtime.js.map +1 -0
- package/dist/event-translator.d.ts +8 -0
- package/dist/event-translator.d.ts.map +1 -0
- package/dist/event-translator.js +12 -0
- package/dist/event-translator.js.map +1 -0
- package/dist/extension-entry-roots.d.ts +7 -0
- package/dist/extension-entry-roots.d.ts.map +1 -0
- package/dist/extension-entry-roots.js +41 -0
- package/dist/extension-entry-roots.js.map +1 -0
- package/dist/identified-pi-entry.d.ts +56 -0
- package/dist/identified-pi-entry.d.ts.map +1 -0
- package/dist/identified-pi-entry.js +125 -0
- package/dist/identified-pi-entry.js.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -0
- package/dist/input-consumer.d.ts +24 -0
- package/dist/input-consumer.d.ts.map +1 -0
- package/dist/input-consumer.js +34 -0
- package/dist/input-consumer.js.map +1 -0
- package/dist/ipc.d.ts +22 -0
- package/dist/ipc.d.ts.map +1 -0
- package/dist/ipc.js +192 -0
- package/dist/ipc.js.map +1 -0
- package/dist/logical-prompt-runner.d.ts +49 -0
- package/dist/logical-prompt-runner.d.ts.map +1 -0
- package/dist/logical-prompt-runner.js +225 -0
- package/dist/logical-prompt-runner.js.map +1 -0
- package/dist/managed-pi-agent-dir.d.ts +13 -0
- package/dist/managed-pi-agent-dir.d.ts.map +1 -0
- package/dist/managed-pi-agent-dir.js +66 -0
- package/dist/managed-pi-agent-dir.js.map +1 -0
- package/dist/managed-pi-bootstrap.d.ts +24 -0
- package/dist/managed-pi-bootstrap.d.ts.map +1 -0
- package/dist/managed-pi-bootstrap.js +135 -0
- package/dist/managed-pi-bootstrap.js.map +1 -0
- package/dist/missing-tool-recovery-runner.d.ts +23 -0
- package/dist/missing-tool-recovery-runner.d.ts.map +1 -0
- package/dist/missing-tool-recovery-runner.js +73 -0
- package/dist/missing-tool-recovery-runner.js.map +1 -0
- package/dist/pi-adapter.d.ts +134 -0
- package/dist/pi-adapter.d.ts.map +1 -0
- package/dist/pi-adapter.js +1648 -0
- package/dist/pi-adapter.js.map +1 -0
- package/dist/pi-branch-guard.d.ts +39 -0
- package/dist/pi-branch-guard.d.ts.map +1 -0
- package/dist/pi-branch-guard.js +75 -0
- package/dist/pi-branch-guard.js.map +1 -0
- package/dist/pi-event-reporter.d.ts +15 -0
- package/dist/pi-event-reporter.d.ts.map +1 -0
- package/dist/pi-event-reporter.js +136 -0
- package/dist/pi-event-reporter.js.map +1 -0
- package/dist/pi-resource-bundle.d.ts +12 -0
- package/dist/pi-resource-bundle.d.ts.map +1 -0
- package/dist/pi-resource-bundle.js +58 -0
- package/dist/pi-resource-bundle.js.map +1 -0
- package/dist/pre-turn-targeted-inputs.d.ts +44 -0
- package/dist/pre-turn-targeted-inputs.d.ts.map +1 -0
- package/dist/pre-turn-targeted-inputs.js +101 -0
- package/dist/pre-turn-targeted-inputs.js.map +1 -0
- package/dist/prompt-guards.d.ts +52 -0
- package/dist/prompt-guards.d.ts.map +1 -0
- package/dist/prompt-guards.js +318 -0
- package/dist/prompt-guards.js.map +1 -0
- package/dist/question-bridge.d.ts +16 -0
- package/dist/question-bridge.d.ts.map +1 -0
- package/dist/question-bridge.js +55 -0
- package/dist/question-bridge.js.map +1 -0
- package/dist/question-tool.d.ts +14 -0
- package/dist/question-tool.d.ts.map +1 -0
- package/dist/question-tool.js +54 -0
- package/dist/question-tool.js.map +1 -0
- package/dist/resource-loader-factory.d.ts +11 -0
- package/dist/resource-loader-factory.d.ts.map +1 -0
- package/dist/resource-loader-factory.js +87 -0
- package/dist/resource-loader-factory.js.map +1 -0
- package/dist/result-image-upload.d.ts +14 -0
- package/dist/result-image-upload.d.ts.map +1 -0
- package/dist/result-image-upload.js +183 -0
- package/dist/result-image-upload.js.map +1 -0
- package/dist/runtime/adapters.d.ts +48 -0
- package/dist/runtime/adapters.d.ts.map +1 -0
- package/dist/runtime/adapters.js +15 -0
- package/dist/runtime/adapters.js.map +1 -0
- package/dist/runtime/bootstrap-session.d.ts +95 -0
- package/dist/runtime/bootstrap-session.d.ts.map +1 -0
- package/dist/runtime/bootstrap-session.js +198 -0
- package/dist/runtime/bootstrap-session.js.map +1 -0
- package/dist/runtime/bootstrap.d.ts +81 -0
- package/dist/runtime/bootstrap.d.ts.map +1 -0
- package/dist/runtime/bootstrap.js +440 -0
- package/dist/runtime/bootstrap.js.map +1 -0
- package/dist/runtime/failure-policy.d.ts +79 -0
- package/dist/runtime/failure-policy.d.ts.map +1 -0
- package/dist/runtime/failure-policy.js +182 -0
- package/dist/runtime/failure-policy.js.map +1 -0
- package/dist/runtime/index.d.ts +9 -0
- package/dist/runtime/index.d.ts.map +1 -0
- package/dist/runtime/index.js +326 -0
- package/dist/runtime/index.js.map +1 -0
- package/dist/runtime/lifecycle-reducer.d.ts +328 -0
- package/dist/runtime/lifecycle-reducer.d.ts.map +1 -0
- package/dist/runtime/lifecycle-reducer.js +1100 -0
- package/dist/runtime/lifecycle-reducer.js.map +1 -0
- package/dist/runtime/llm-turn-execution.d.ts +42 -0
- package/dist/runtime/llm-turn-execution.d.ts.map +1 -0
- package/dist/runtime/llm-turn-execution.js +472 -0
- package/dist/runtime/llm-turn-execution.js.map +1 -0
- package/dist/runtime/settings.d.ts +11 -0
- package/dist/runtime/settings.d.ts.map +1 -0
- package/dist/runtime/settings.js +23 -0
- package/dist/runtime/settings.js.map +1 -0
- package/dist/runtime/snapshot-policy.d.ts +11 -0
- package/dist/runtime/snapshot-policy.d.ts.map +1 -0
- package/dist/runtime/snapshot-policy.js +16 -0
- package/dist/runtime/snapshot-policy.js.map +1 -0
- package/dist/runtime/turn-execution.d.ts +49 -0
- package/dist/runtime/turn-execution.d.ts.map +1 -0
- package/dist/runtime/turn-execution.js +120 -0
- package/dist/runtime/turn-execution.js.map +1 -0
- package/dist/session-snapshot-exchange.d.ts +39 -0
- package/dist/session-snapshot-exchange.d.ts.map +1 -0
- package/dist/session-snapshot-exchange.js +102 -0
- package/dist/session-snapshot-exchange.js.map +1 -0
- package/dist/test-helpers/fake-websocket.d.ts +16 -0
- package/dist/test-helpers/fake-websocket.d.ts.map +1 -0
- package/dist/test-helpers/fake-websocket.js +40 -0
- package/dist/test-helpers/fake-websocket.js.map +1 -0
- package/dist/test-helpers/ipc-harness.d.ts +11 -0
- package/dist/test-helpers/ipc-harness.d.ts.map +1 -0
- package/dist/test-helpers/ipc-harness.js +17 -0
- package/dist/test-helpers/ipc-harness.js.map +1 -0
- package/dist/test-helpers/worker-message-builders.d.ts +21 -0
- package/dist/test-helpers/worker-message-builders.d.ts.map +1 -0
- package/dist/test-helpers/worker-message-builders.js +62 -0
- package/dist/test-helpers/worker-message-builders.js.map +1 -0
- package/dist/turn-continuation.d.ts +28 -0
- package/dist/turn-continuation.d.ts.map +1 -0
- package/dist/turn-continuation.js +80 -0
- package/dist/turn-continuation.js.map +1 -0
- package/dist/turn-execution-error.d.ts +39 -0
- package/dist/turn-execution-error.d.ts.map +1 -0
- package/dist/turn-execution-error.js +64 -0
- package/dist/turn-execution-error.js.map +1 -0
- package/dist/turn-execution-result.d.ts +35 -0
- package/dist/turn-execution-result.d.ts.map +1 -0
- package/dist/turn-execution-result.js +21 -0
- package/dist/turn-execution-result.js.map +1 -0
- package/dist/turn-outcome-tool-session.d.ts +50 -0
- package/dist/turn-outcome-tool-session.d.ts.map +1 -0
- package/dist/turn-outcome-tool-session.js +209 -0
- package/dist/turn-outcome-tool-session.js.map +1 -0
- package/dist/turn-record-id.d.ts +3 -0
- package/dist/turn-record-id.d.ts.map +1 -0
- package/dist/turn-record-id.js +10 -0
- package/dist/turn-record-id.js.map +1 -0
- package/dist/turn-result-markdown.d.ts +74 -0
- package/dist/turn-result-markdown.d.ts.map +1 -0
- package/dist/turn-result-markdown.js +263 -0
- package/dist/turn-result-markdown.js.map +1 -0
- package/dist/turn-tree-strategy.d.ts +29 -0
- package/dist/turn-tree-strategy.d.ts.map +1 -0
- package/dist/turn-tree-strategy.js +80 -0
- package/dist/turn-tree-strategy.js.map +1 -0
- package/dist/worker-entry.d.ts +2 -0
- package/dist/worker-entry.d.ts.map +1 -0
- package/dist/worker-entry.js +7 -0
- package/dist/worker-entry.js.map +1 -0
- package/dist/worker-http.d.ts +2 -0
- package/dist/worker-http.d.ts.map +1 -0
- package/dist/worker-http.js +9 -0
- package/dist/worker-http.js.map +1 -0
- package/dist/worker-ipc-reporter.d.ts +29 -0
- package/dist/worker-ipc-reporter.d.ts.map +1 -0
- package/dist/worker-ipc-reporter.js +58 -0
- package/dist/worker-ipc-reporter.js.map +1 -0
- package/dist/worker-payloads.d.ts +10 -0
- package/dist/worker-payloads.d.ts.map +1 -0
- package/dist/worker-payloads.js +66 -0
- package/dist/worker-payloads.js.map +1 -0
- package/dist/worker-start-payload.d.ts +7 -0
- package/dist/worker-start-payload.d.ts.map +1 -0
- package/dist/worker-start-payload.js +5 -0
- package/dist/worker-start-payload.js.map +1 -0
- package/dist/workspace/manifest.d.ts +35 -0
- package/dist/workspace/manifest.d.ts.map +1 -0
- package/dist/workspace/manifest.js +79 -0
- package/dist/workspace/manifest.js.map +1 -0
- package/dist/workspace/node-run-root-git-ops.d.ts +17 -0
- package/dist/workspace/node-run-root-git-ops.d.ts.map +1 -0
- package/dist/workspace/node-run-root-git-ops.js +96 -0
- package/dist/workspace/node-run-root-git-ops.js.map +1 -0
- package/dist/workspace/resource-aggregator.d.ts +15 -0
- package/dist/workspace/resource-aggregator.d.ts.map +1 -0
- package/dist/workspace/resource-aggregator.js +39 -0
- package/dist/workspace/resource-aggregator.js.map +1 -0
- package/dist/workspace/run-root.d.ts +52 -0
- package/dist/workspace/run-root.d.ts.map +1 -0
- package/dist/workspace/run-root.js +209 -0
- package/dist/workspace/run-root.js.map +1 -0
- package/package.json +55 -0
- package/src/automatic-turn-executor.ts +106 -0
- package/src/diagnostics.ts +82 -0
- package/src/entry-runtime.ts +235 -0
- package/src/event-translator.ts +22 -0
- package/src/extension-entry-roots.ts +43 -0
- package/src/identified-pi-entry.ts +188 -0
- package/src/index.ts +54 -0
- package/src/input-consumer.ts +71 -0
- package/src/ipc.ts +250 -0
- package/src/logical-prompt-runner.ts +320 -0
- package/src/managed-pi-agent-dir.ts +86 -0
- package/src/managed-pi-bootstrap.ts +208 -0
- package/src/missing-tool-recovery-runner.ts +112 -0
- package/src/pi-adapter.ts +2197 -0
- package/src/pi-branch-guard.ts +104 -0
- package/src/pi-event-reporter.ts +164 -0
- package/src/pi-resource-bundle.ts +90 -0
- package/src/pre-turn-targeted-inputs.ts +167 -0
- package/src/prompt-guards.ts +385 -0
- package/src/question-bridge.ts +69 -0
- package/src/question-tool.ts +65 -0
- package/src/resource-loader-factory.ts +115 -0
- package/src/result-image-upload.ts +256 -0
- package/src/runtime/adapters.ts +67 -0
- package/src/runtime/bootstrap-session.ts +294 -0
- package/src/runtime/bootstrap.ts +621 -0
- package/src/runtime/failure-policy.ts +274 -0
- package/src/runtime/index.ts +362 -0
- package/src/runtime/lifecycle-reducer.ts +1537 -0
- package/src/runtime/llm-turn-execution.ts +696 -0
- package/src/runtime/settings.ts +41 -0
- package/src/runtime/snapshot-policy.ts +28 -0
- package/src/runtime/turn-execution.ts +203 -0
- package/src/session-snapshot-exchange.ts +155 -0
- package/src/test-helpers/fake-websocket.ts +46 -0
- package/src/test-helpers/ipc-harness.ts +19 -0
- package/src/test-helpers/worker-message-builders.ts +92 -0
- package/src/turn-continuation.ts +147 -0
- package/src/turn-execution-error.ts +102 -0
- package/src/turn-execution-result.ts +48 -0
- package/src/turn-outcome-tool-session.ts +311 -0
- package/src/turn-record-id.ts +17 -0
- package/src/turn-result-markdown.ts +355 -0
- package/src/turn-tree-strategy.ts +141 -0
- package/src/worker-entry.ts +8 -0
- package/src/worker-http.ts +6 -0
- package/src/worker-ipc-reporter.ts +100 -0
- package/src/worker-payloads.ts +94 -0
- package/src/worker-start-payload.ts +10 -0
- package/src/workspace/manifest.ts +126 -0
- package/src/workspace/node-run-root-git-ops.ts +137 -0
- package/src/workspace/resource-aggregator.ts +43 -0
- package/src/workspace/run-root.ts +361 -0
|
@@ -0,0 +1,696 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createGenericFailedTurnRecoveryContext,
|
|
3
|
+
DEFAULT_CONTINUE_PROMPT,
|
|
4
|
+
type PreparedTurnStart,
|
|
5
|
+
type ProcessTurnRecordPathType,
|
|
6
|
+
type ProcessTurnType,
|
|
7
|
+
type WorkerErrorClass,
|
|
8
|
+
} from "@leitwerk-dev/domain";
|
|
9
|
+
import type { ResolvedWorkerProcess } from "@leitwerk-dev/extension-runtime";
|
|
10
|
+
import type { LlmTurnDefinition, WorkerProcessContext } from "@leitwerk-dev/process-sdk";
|
|
11
|
+
import { resolveLlmTurnRestorePrimaryLeafAfterTurn } from "@leitwerk-dev/process-sdk";
|
|
12
|
+
import type { ConfigSnapshot } from "@leitwerk-dev/protocol";
|
|
13
|
+
import type { WorkerDiagnosticPayload, WorkerOperationEmitter } from "../diagnostics.js";
|
|
14
|
+
import {
|
|
15
|
+
ensureIdentifiedCompaction,
|
|
16
|
+
findIdentifiedPrompt,
|
|
17
|
+
validateIdentifiedPrompt,
|
|
18
|
+
} from "../identified-pi-entry.js";
|
|
19
|
+
import {
|
|
20
|
+
type LogicalTurnPromptPlan,
|
|
21
|
+
executeLogicalPromptPlan as runLogicalPromptPlan,
|
|
22
|
+
} from "../logical-prompt-runner.js";
|
|
23
|
+
import {
|
|
24
|
+
MAX_MISSING_TOOL_CALL_RECOVERY_ATTEMPTS,
|
|
25
|
+
runMissingToolRecovery,
|
|
26
|
+
} from "../missing-tool-recovery-runner.js";
|
|
27
|
+
import type { PiTreeHandle } from "../pi-adapter.js";
|
|
28
|
+
import {
|
|
29
|
+
applyPreTurnTargetedInputs,
|
|
30
|
+
type PreTurnTargetedInput,
|
|
31
|
+
resolvePreTurnTargetStartSelection,
|
|
32
|
+
validatePreTurnTargetedInputs,
|
|
33
|
+
} from "../pre-turn-targeted-inputs.js";
|
|
34
|
+
import type { WorkerQuestionRequest } from "../question-tool.js";
|
|
35
|
+
import {
|
|
36
|
+
resolvePromptlessTurnResumeReason,
|
|
37
|
+
resolveTurnContinuationState,
|
|
38
|
+
} from "../turn-continuation.js";
|
|
39
|
+
import {
|
|
40
|
+
buildTurnFailureReport,
|
|
41
|
+
TurnExecutionError,
|
|
42
|
+
type TurnFailureReportOptions,
|
|
43
|
+
toErrorMessage,
|
|
44
|
+
} from "../turn-execution-error.js";
|
|
45
|
+
import { type LlmTurnExecutionSuccess, TurnExecutionFailure } from "../turn-execution-result.js";
|
|
46
|
+
import {
|
|
47
|
+
createTurnOutcomeToolSession,
|
|
48
|
+
type ToolCompletionSnapshot,
|
|
49
|
+
} from "../turn-outcome-tool-session.js";
|
|
50
|
+
import { resolveTurnRecordIdForExecution } from "../turn-record-id.js";
|
|
51
|
+
import {
|
|
52
|
+
planTurnTreeExecution,
|
|
53
|
+
positionHandleForTurn,
|
|
54
|
+
resolveRootEntryIdFromHandle,
|
|
55
|
+
restoreHandleAfterTurn,
|
|
56
|
+
type TurnTreePlan,
|
|
57
|
+
} from "../turn-tree-strategy.js";
|
|
58
|
+
import { readProcessProductRefs, readProcessSemanticEntryRefs } from "../worker-payloads.js";
|
|
59
|
+
import type { ResultImageToolFactory, WorkerRuntimeScheduler } from "./adapters.js";
|
|
60
|
+
|
|
61
|
+
export {
|
|
62
|
+
shouldAutoContinueAfterCompactionError,
|
|
63
|
+
shouldAutoContinueAfterPromptReturn,
|
|
64
|
+
} from "../logical-prompt-runner.js";
|
|
65
|
+
|
|
66
|
+
function buildPromptlessTargetedFollowUpGuidance(input: {
|
|
67
|
+
turnId: string;
|
|
68
|
+
activeToolNames: readonly string[];
|
|
69
|
+
promptSuffix: string;
|
|
70
|
+
}): string {
|
|
71
|
+
const activeTools = input.activeToolNames.length > 0 ? input.activeToolNames.join(", ") : "none";
|
|
72
|
+
return [
|
|
73
|
+
[
|
|
74
|
+
"Active-turn handoff:",
|
|
75
|
+
`- This queued follow-up is now running turn '${input.turnId}'. The task and tool availability may differ from the prior branch context.`,
|
|
76
|
+
`- Active built-in tools for this turn: ${activeTools}. Use only these built-in tools, plus any custom/outcome tools exposed for this turn.`,
|
|
77
|
+
"- Treat these active-turn instructions and tool availability as authoritative where they conflict with earlier branch instructions.",
|
|
78
|
+
].join("\n"),
|
|
79
|
+
input.promptSuffix.trim(),
|
|
80
|
+
]
|
|
81
|
+
.filter((section) => section !== "")
|
|
82
|
+
.join("\n\n");
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function appendGuidanceToLastTargetedInput(
|
|
86
|
+
inputs: readonly PreTurnTargetedInput[],
|
|
87
|
+
guidance: string | null,
|
|
88
|
+
): readonly PreTurnTargetedInput[] {
|
|
89
|
+
if (!guidance || inputs.length === 0) {
|
|
90
|
+
return inputs;
|
|
91
|
+
}
|
|
92
|
+
return inputs.map((targetedInput, index) =>
|
|
93
|
+
index === inputs.length - 1
|
|
94
|
+
? {
|
|
95
|
+
...targetedInput,
|
|
96
|
+
bodyMarkdown: `${targetedInput.bodyMarkdown.trimEnd()}\n\n${guidance}`,
|
|
97
|
+
}
|
|
98
|
+
: targetedInput,
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export interface LlmTurnExecutorCallbacks {
|
|
103
|
+
requestQuestions?: (request: WorkerQuestionRequest) => Promise<string[]>;
|
|
104
|
+
onPreTurnTargetedInputApplied?(
|
|
105
|
+
inputId: string,
|
|
106
|
+
sequence: number,
|
|
107
|
+
meta?: {
|
|
108
|
+
currentPrimaryPathLeafId?: string | null;
|
|
109
|
+
rootEntryId?: string | null;
|
|
110
|
+
targetSemanticRef?: import("@leitwerk-dev/domain").ProcessSemanticEntryRefKey | null;
|
|
111
|
+
targetProductName?: string | null;
|
|
112
|
+
targetEntryId?: string | null;
|
|
113
|
+
},
|
|
114
|
+
): void;
|
|
115
|
+
emit?: WorkerOperationEmitter;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Convert the bootstrap receipt into the executor plan without consulting the
|
|
120
|
+
* current process state. The receipt is the pre-acceptance decision; runtime
|
|
121
|
+
* may only verify that the retained tree still supports it.
|
|
122
|
+
*/
|
|
123
|
+
function treePlanFromPreparedStart(input: {
|
|
124
|
+
preparedStart: PreparedTurnStart;
|
|
125
|
+
turnDef: LlmTurnDefinition<string, unknown, unknown>;
|
|
126
|
+
piHandle: PiTreeHandle;
|
|
127
|
+
allowRetainedExecution?: boolean;
|
|
128
|
+
}): TurnTreePlan {
|
|
129
|
+
const { preparedStart, turnDef, piHandle } = input;
|
|
130
|
+
if (preparedStart.pathType !== turnDef.branchType) {
|
|
131
|
+
throw new Error("Accepted tree plan path type no longer matches the selected turn");
|
|
132
|
+
}
|
|
133
|
+
if (preparedStart.contextMode !== turnDef.context) {
|
|
134
|
+
throw new Error("Accepted tree plan context mode no longer matches the selected turn");
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
switch (preparedStart.startTarget.kind) {
|
|
138
|
+
case "current_leaf":
|
|
139
|
+
if (preparedStart.forkPiEntryId === null) {
|
|
140
|
+
if (
|
|
141
|
+
!input.allowRetainedExecution &&
|
|
142
|
+
(piHandle.getLeafId() !== null || piHandle.getTree().length !== 0)
|
|
143
|
+
) {
|
|
144
|
+
throw new Error("Accepted empty-tree plan no longer has an empty Pi tree");
|
|
145
|
+
}
|
|
146
|
+
} else if (
|
|
147
|
+
!piHandle
|
|
148
|
+
.getBranch(piHandle.getLeafId() ?? undefined)
|
|
149
|
+
.some((entry) => entry.id === preparedStart.forkPiEntryId)
|
|
150
|
+
) {
|
|
151
|
+
throw new Error("Pi tree leaf no longer matches the accepted tree plan");
|
|
152
|
+
}
|
|
153
|
+
break;
|
|
154
|
+
case "entry":
|
|
155
|
+
if (
|
|
156
|
+
preparedStart.forkPiEntryId !== preparedStart.startTarget.entryId ||
|
|
157
|
+
!piHandle.getEntry(preparedStart.startTarget.entryId)
|
|
158
|
+
) {
|
|
159
|
+
throw new Error("Pi tree entry no longer matches the accepted tree plan");
|
|
160
|
+
}
|
|
161
|
+
break;
|
|
162
|
+
case "root":
|
|
163
|
+
if (preparedStart.forkPiEntryId !== null) {
|
|
164
|
+
throw new Error("Accepted root tree plan must not retain a fork entry");
|
|
165
|
+
}
|
|
166
|
+
break;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
return {
|
|
170
|
+
pathType: preparedStart.pathType,
|
|
171
|
+
forkPiEntryId: preparedStart.forkPiEntryId,
|
|
172
|
+
savedPrimaryLeafId: piHandle.getLeafId(),
|
|
173
|
+
restorePrimaryLeafAfterTurn: resolveLlmTurnRestorePrimaryLeafAfterTurn(turnDef),
|
|
174
|
+
startTarget: preparedStart.startTarget,
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export async function executeLlmTurn<TOutcome extends string>(input: {
|
|
179
|
+
resolvedWorkerProcess: ResolvedWorkerProcess;
|
|
180
|
+
ctx: WorkerProcessContext;
|
|
181
|
+
piHandle: PiTreeHandle;
|
|
182
|
+
turnDef: LlmTurnDefinition<TOutcome, unknown, unknown>;
|
|
183
|
+
turnId: string;
|
|
184
|
+
acceptedTurnRecordId: string | null;
|
|
185
|
+
turnStartRecordId?: string | null;
|
|
186
|
+
preparedTurnStart?: PreparedTurnStart | null;
|
|
187
|
+
configSnapshot?: ConfigSnapshot;
|
|
188
|
+
preTurnTargetedInputs?: readonly PreTurnTargetedInput[];
|
|
189
|
+
scheduler: WorkerRuntimeScheduler;
|
|
190
|
+
resultImageTools: ResultImageToolFactory;
|
|
191
|
+
turnMaxDurationMs?: number;
|
|
192
|
+
turnInactivityTimeoutMs?: number;
|
|
193
|
+
turnAbortGracePeriodMs?: number;
|
|
194
|
+
operatorAbortSignal?: AbortSignal;
|
|
195
|
+
callbacks: LlmTurnExecutorCallbacks;
|
|
196
|
+
}): Promise<LlmTurnExecutionSuccess<TOutcome>> {
|
|
197
|
+
const turnId = input.turnId;
|
|
198
|
+
const trace = (payload: WorkerDiagnosticPayload) =>
|
|
199
|
+
input.callbacks.emit?.({ kind: "trace", payload });
|
|
200
|
+
const reportError = (payload: WorkerDiagnosticPayload) =>
|
|
201
|
+
input.callbacks.emit?.({ kind: "error", payload });
|
|
202
|
+
const taint = (reason: string) => input.callbacks.emit?.({ kind: "session_tainted", reason });
|
|
203
|
+
const activePiHandle = input.piHandle;
|
|
204
|
+
const turnType: ProcessTurnType = "llm";
|
|
205
|
+
const rootEntryId = resolveRootEntryIdFromHandle(activePiHandle);
|
|
206
|
+
const pathType: ProcessTurnRecordPathType = input.turnDef.branchType;
|
|
207
|
+
const turnRecordId = resolveTurnRecordIdForExecution(
|
|
208
|
+
input.ctx.process,
|
|
209
|
+
turnId,
|
|
210
|
+
input.acceptedTurnRecordId,
|
|
211
|
+
);
|
|
212
|
+
const turnStartRecordId = input.turnStartRecordId;
|
|
213
|
+
const preTurnTargetedInputs = input.preTurnTargetedInputs ?? [];
|
|
214
|
+
const continuationState = resolveTurnContinuationState({
|
|
215
|
+
process: input.ctx.process,
|
|
216
|
+
turnId,
|
|
217
|
+
state: input.ctx.state,
|
|
218
|
+
});
|
|
219
|
+
const currentLeafIdBeforePlan = activePiHandle.getLeafId();
|
|
220
|
+
const acceptedStartKickoff = turnStartRecordId
|
|
221
|
+
? findIdentifiedPrompt(activePiHandle, {
|
|
222
|
+
kind: "turn_prompt",
|
|
223
|
+
startRecordId: turnStartRecordId,
|
|
224
|
+
purpose: "kickoff",
|
|
225
|
+
})
|
|
226
|
+
: null;
|
|
227
|
+
const hasActiveTurnResume =
|
|
228
|
+
!continuationState &&
|
|
229
|
+
acceptedStartKickoff !== null &&
|
|
230
|
+
activePiHandle.isResumed &&
|
|
231
|
+
currentLeafIdBeforePlan !== null &&
|
|
232
|
+
input.ctx.process.selectedTurnId === turnId &&
|
|
233
|
+
typeof input.acceptedTurnRecordId === "string" &&
|
|
234
|
+
input.acceptedTurnRecordId.trim() !== "";
|
|
235
|
+
const semanticEntryRefs = readProcessSemanticEntryRefs(input.ctx.state);
|
|
236
|
+
const preTurnStartSelection = resolvePreTurnTargetStartSelection(preTurnTargetedInputs);
|
|
237
|
+
if (
|
|
238
|
+
input.acceptedTurnRecordId !== null &&
|
|
239
|
+
input.acceptedTurnRecordId !== undefined &&
|
|
240
|
+
turnStartRecordId &&
|
|
241
|
+
!input.preparedTurnStart
|
|
242
|
+
) {
|
|
243
|
+
throw new TurnExecutionError(
|
|
244
|
+
turnId,
|
|
245
|
+
"infrastructure",
|
|
246
|
+
`Accepted LLM turn '${turnId}' lacks its prepared tree start`,
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
const preparedTreePlan = input.preparedTurnStart
|
|
250
|
+
? treePlanFromPreparedStart({
|
|
251
|
+
preparedStart: input.preparedTurnStart,
|
|
252
|
+
turnDef: input.turnDef,
|
|
253
|
+
piHandle: activePiHandle,
|
|
254
|
+
allowRetainedExecution: hasActiveTurnResume,
|
|
255
|
+
})
|
|
256
|
+
: null;
|
|
257
|
+
let treePlan: TurnTreePlan;
|
|
258
|
+
if (hasActiveTurnResume) {
|
|
259
|
+
const persistedPrimaryLeafId = semanticEntryRefs?.currentPrimaryPathLeaf?.entryId ?? null;
|
|
260
|
+
treePlan = {
|
|
261
|
+
// A replacement continues the already identified accepted kickoff. It
|
|
262
|
+
// must not reposition to the original pre-kickoff target.
|
|
263
|
+
pathType: input.turnDef.branchType,
|
|
264
|
+
// Preserve the acceptance receipt's provenance in all lifecycle callbacks.
|
|
265
|
+
// Only positioning changes for an in-flight replacement.
|
|
266
|
+
forkPiEntryId: preparedTreePlan?.forkPiEntryId ?? currentLeafIdBeforePlan,
|
|
267
|
+
savedPrimaryLeafId:
|
|
268
|
+
input.turnDef.branchType === "primary"
|
|
269
|
+
? null
|
|
270
|
+
: persistedPrimaryLeafId && activePiHandle.getEntry(persistedPrimaryLeafId)
|
|
271
|
+
? persistedPrimaryLeafId
|
|
272
|
+
: currentLeafIdBeforePlan,
|
|
273
|
+
restorePrimaryLeafAfterTurn: resolveLlmTurnRestorePrimaryLeafAfterTurn(input.turnDef),
|
|
274
|
+
startTarget: { kind: "current_leaf" },
|
|
275
|
+
};
|
|
276
|
+
} else if (preparedTreePlan) {
|
|
277
|
+
treePlan = {
|
|
278
|
+
...preparedTreePlan,
|
|
279
|
+
// Failed-turn continuation owns restoration of the pre-failure primary
|
|
280
|
+
// path; receipt preparation remains authoritative for the start target.
|
|
281
|
+
savedPrimaryLeafId:
|
|
282
|
+
continuationState && input.turnDef.branchType !== "primary"
|
|
283
|
+
? continuationState.savedPrimaryLeafId
|
|
284
|
+
: preparedTreePlan.savedPrimaryLeafId,
|
|
285
|
+
};
|
|
286
|
+
} else if (continuationState) {
|
|
287
|
+
treePlan = {
|
|
288
|
+
pathType: input.turnDef.branchType,
|
|
289
|
+
forkPiEntryId: continuationState.continueFromPiEntryId,
|
|
290
|
+
savedPrimaryLeafId:
|
|
291
|
+
input.turnDef.branchType === "primary" ? null : continuationState.savedPrimaryLeafId,
|
|
292
|
+
restorePrimaryLeafAfterTurn: resolveLlmTurnRestorePrimaryLeafAfterTurn(input.turnDef),
|
|
293
|
+
startTarget: {
|
|
294
|
+
kind: "entry",
|
|
295
|
+
entryId: continuationState.continueFromPiEntryId,
|
|
296
|
+
},
|
|
297
|
+
};
|
|
298
|
+
} else {
|
|
299
|
+
treePlan = planTurnTreeExecution({
|
|
300
|
+
turnDef: input.turnDef,
|
|
301
|
+
currentLeafId: currentLeafIdBeforePlan,
|
|
302
|
+
rootEntryId,
|
|
303
|
+
semanticEntryRefs,
|
|
304
|
+
productRefs: readProcessProductRefs(input.ctx.state),
|
|
305
|
+
entryExists: (entryId) => activePiHandle.getEntry(entryId) !== undefined,
|
|
306
|
+
preTurnStartSelection,
|
|
307
|
+
hasPreTurnTargetedInputs: preTurnTargetedInputs.length > 0,
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
const initialPromptlessTurnResumeReason = resolvePromptlessTurnResumeReason({
|
|
311
|
+
process: input.ctx.process,
|
|
312
|
+
acceptedTurnRecordId: input.acceptedTurnRecordId,
|
|
313
|
+
turnId,
|
|
314
|
+
hasFailedTurnContinuation: continuationState !== null,
|
|
315
|
+
preTurnTargetedInputs,
|
|
316
|
+
piHandleIsResumed: hasActiveTurnResume,
|
|
317
|
+
hasCurrentLeaf: activePiHandle.getLeafId() !== null,
|
|
318
|
+
});
|
|
319
|
+
const toolSession = createTurnOutcomeToolSession({
|
|
320
|
+
turnId,
|
|
321
|
+
turnRecordId,
|
|
322
|
+
turnDef: input.turnDef,
|
|
323
|
+
requestQuestions: input.callbacks.requestQuestions,
|
|
324
|
+
resultImageTool: input.resultImageTools.create({
|
|
325
|
+
workspaceRoot: input.ctx.workspaceRoot,
|
|
326
|
+
instanceId: input.ctx.process.id,
|
|
327
|
+
turnRecordId,
|
|
328
|
+
}),
|
|
329
|
+
});
|
|
330
|
+
const promptlessTargetedFollowUpGuidance =
|
|
331
|
+
initialPromptlessTurnResumeReason === "targeted_follow_up"
|
|
332
|
+
? buildPromptlessTargetedFollowUpGuidance({
|
|
333
|
+
turnId,
|
|
334
|
+
activeToolNames: toolSession.activeTools,
|
|
335
|
+
promptSuffix: toolSession.addPromptSuffix(""),
|
|
336
|
+
})
|
|
337
|
+
: null;
|
|
338
|
+
const preTurnTargetedInputsToApply = appendGuidanceToLastTargetedInput(
|
|
339
|
+
preTurnTargetedInputs,
|
|
340
|
+
promptlessTargetedFollowUpGuidance,
|
|
341
|
+
);
|
|
342
|
+
const reportFailedTurn = async (
|
|
343
|
+
errorClass: WorkerErrorClass,
|
|
344
|
+
message: string,
|
|
345
|
+
resultPiEntryId: string | null,
|
|
346
|
+
options: TurnFailureReportOptions = {},
|
|
347
|
+
): Promise<never> => {
|
|
348
|
+
const recoveryContext =
|
|
349
|
+
options.recoveryContext !== undefined
|
|
350
|
+
? options.recoveryContext
|
|
351
|
+
: createGenericFailedTurnRecoveryContext();
|
|
352
|
+
let failure = new TurnExecutionError(turnId, errorClass, message, {
|
|
353
|
+
recoveryContext,
|
|
354
|
+
failureCode: options.failureCode,
|
|
355
|
+
failureDetails: options.failureDetails,
|
|
356
|
+
});
|
|
357
|
+
if (options.restorePrimaryLeaf ?? true) {
|
|
358
|
+
try {
|
|
359
|
+
await restoreHandleAfterTurn(activePiHandle, treePlan);
|
|
360
|
+
} catch (restoreError: unknown) {
|
|
361
|
+
reportError({
|
|
362
|
+
level: "error",
|
|
363
|
+
code: "turn.primary_leaf_restore_failed",
|
|
364
|
+
message: `Failed to restore the primary path leaf after turn '${turnId}': ${toErrorMessage(restoreError)}`,
|
|
365
|
+
turnRecordId,
|
|
366
|
+
turnId,
|
|
367
|
+
errorClass: "infrastructure",
|
|
368
|
+
});
|
|
369
|
+
failure = new TurnExecutionError(
|
|
370
|
+
turnId,
|
|
371
|
+
"infrastructure",
|
|
372
|
+
`${message}. Failed to restore the primary path leaf: ${toErrorMessage(restoreError)}`,
|
|
373
|
+
{ recoveryContext: null },
|
|
374
|
+
);
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
throw new TurnExecutionFailure({
|
|
378
|
+
turnRecordId,
|
|
379
|
+
turnId,
|
|
380
|
+
turnType,
|
|
381
|
+
pathType,
|
|
382
|
+
failure,
|
|
383
|
+
forkPiEntryId: treePlan.forkPiEntryId,
|
|
384
|
+
resultPiEntryId,
|
|
385
|
+
});
|
|
386
|
+
};
|
|
387
|
+
|
|
388
|
+
const failWithWorkerError = (
|
|
389
|
+
code: string,
|
|
390
|
+
errorClass: WorkerErrorClass,
|
|
391
|
+
message: string,
|
|
392
|
+
resultPiEntryId: string | null,
|
|
393
|
+
options: TurnFailureReportOptions = {},
|
|
394
|
+
details?: Record<string, unknown>,
|
|
395
|
+
): Promise<never> => {
|
|
396
|
+
reportError({
|
|
397
|
+
level: "error",
|
|
398
|
+
code,
|
|
399
|
+
message,
|
|
400
|
+
turnRecordId,
|
|
401
|
+
turnId,
|
|
402
|
+
errorClass,
|
|
403
|
+
...(details ? { details } : {}),
|
|
404
|
+
});
|
|
405
|
+
return reportFailedTurn(errorClass, message, resultPiEntryId, options);
|
|
406
|
+
};
|
|
407
|
+
|
|
408
|
+
const failFromCaughtError = (
|
|
409
|
+
code: string,
|
|
410
|
+
error: unknown,
|
|
411
|
+
currentLeafId: string | null,
|
|
412
|
+
messagePrefix: string,
|
|
413
|
+
options: { restorePrimaryLeaf?: boolean } = {},
|
|
414
|
+
): Promise<never> => {
|
|
415
|
+
const failure = buildTurnFailureReport(error, { turnId, currentLeafId, messagePrefix });
|
|
416
|
+
if (failure.taintReason) {
|
|
417
|
+
taint(failure.taintReason);
|
|
418
|
+
}
|
|
419
|
+
return failWithWorkerError(
|
|
420
|
+
code,
|
|
421
|
+
failure.errorClass,
|
|
422
|
+
failure.message,
|
|
423
|
+
failure.resultPiEntryId,
|
|
424
|
+
options.restorePrimaryLeaf === undefined
|
|
425
|
+
? (failure.options ?? {})
|
|
426
|
+
: { ...(failure.options ?? {}), restorePrimaryLeaf: options.restorePrimaryLeaf },
|
|
427
|
+
failure.details,
|
|
428
|
+
);
|
|
429
|
+
};
|
|
430
|
+
|
|
431
|
+
let promptText: string | null = null;
|
|
432
|
+
if (
|
|
433
|
+
initialPromptlessTurnResumeReason === null ||
|
|
434
|
+
initialPromptlessTurnResumeReason === "active_turn_resume"
|
|
435
|
+
) {
|
|
436
|
+
try {
|
|
437
|
+
promptText = await input.turnDef.prompt(input.ctx);
|
|
438
|
+
} catch (error: unknown) {
|
|
439
|
+
return failWithWorkerError(
|
|
440
|
+
"turn.prompt_preparation_failed",
|
|
441
|
+
"infrastructure",
|
|
442
|
+
`Turn '${turnId}' prompt preparation failed: ${toErrorMessage(error)}`,
|
|
443
|
+
null,
|
|
444
|
+
{ restorePrimaryLeaf: false },
|
|
445
|
+
);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
const prePositionLeafId = activePiHandle.getLeafId();
|
|
450
|
+
try {
|
|
451
|
+
await positionHandleForTurn(activePiHandle, treePlan);
|
|
452
|
+
} catch (error: unknown) {
|
|
453
|
+
return failFromCaughtError(
|
|
454
|
+
"turn.position_failed",
|
|
455
|
+
error,
|
|
456
|
+
prePositionLeafId,
|
|
457
|
+
`Turn '${turnId}' failed to position the instance tree`,
|
|
458
|
+
);
|
|
459
|
+
}
|
|
460
|
+
if (!continuationState && input.turnDef.context === "compacted") {
|
|
461
|
+
if (!turnStartRecordId) {
|
|
462
|
+
return reportFailedTurn(
|
|
463
|
+
"infrastructure",
|
|
464
|
+
`Turn '${turnId}' requested compacted context without an accepted start identity`,
|
|
465
|
+
activePiHandle.getLeafId(),
|
|
466
|
+
{ restorePrimaryLeaf: false },
|
|
467
|
+
);
|
|
468
|
+
}
|
|
469
|
+
try {
|
|
470
|
+
const expectedParentId = hasActiveTurnResume
|
|
471
|
+
? (preparedTreePlan?.forkPiEntryId ?? null)
|
|
472
|
+
: activePiHandle.getLeafId();
|
|
473
|
+
await ensureIdentifiedCompaction({
|
|
474
|
+
piHandle: activePiHandle,
|
|
475
|
+
identity: { kind: "turn_compaction", startRecordId: turnStartRecordId },
|
|
476
|
+
expectedParentId,
|
|
477
|
+
allowDescendantParent:
|
|
478
|
+
hasActiveTurnResume && preparedTreePlan?.startTarget.kind === "current_leaf",
|
|
479
|
+
requireOnCurrentBranch: hasActiveTurnResume,
|
|
480
|
+
reuseWithoutBranching: hasActiveTurnResume,
|
|
481
|
+
});
|
|
482
|
+
trace({
|
|
483
|
+
level: "info",
|
|
484
|
+
code: "turn.context_compacted",
|
|
485
|
+
message: `Turn '${turnId}' compacted the selected Pi context before prompting`,
|
|
486
|
+
turnRecordId,
|
|
487
|
+
turnId,
|
|
488
|
+
details: { resultPiEntryId: activePiHandle.getLeafId() },
|
|
489
|
+
});
|
|
490
|
+
} catch (error: unknown) {
|
|
491
|
+
return failFromCaughtError(
|
|
492
|
+
"turn.context_compaction_failed",
|
|
493
|
+
error,
|
|
494
|
+
activePiHandle.getLeafId(),
|
|
495
|
+
`Turn '${turnId}' failed to compact the selected Pi context`,
|
|
496
|
+
);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
if (preTurnTargetedInputs.length > 0) {
|
|
500
|
+
const semanticEntryRefs = readProcessSemanticEntryRefs(input.ctx.state);
|
|
501
|
+
const productRefs = readProcessProductRefs(input.ctx.state);
|
|
502
|
+
const targetValidationError = validatePreTurnTargetedInputs({
|
|
503
|
+
turnId,
|
|
504
|
+
inputs: preTurnTargetedInputs,
|
|
505
|
+
treePlan: hasActiveTurnResume ? (preparedTreePlan ?? treePlan) : treePlan,
|
|
506
|
+
semanticEntryRefs,
|
|
507
|
+
productRefs,
|
|
508
|
+
currentLeafId: prePositionLeafId,
|
|
509
|
+
rootEntryId,
|
|
510
|
+
entryExists: (entryId) => activePiHandle.getEntry(entryId) !== undefined,
|
|
511
|
+
});
|
|
512
|
+
if (targetValidationError) {
|
|
513
|
+
return reportFailedTurn("infrastructure", targetValidationError, activePiHandle.getLeafId());
|
|
514
|
+
}
|
|
515
|
+
try {
|
|
516
|
+
await applyPreTurnTargetedInputs({
|
|
517
|
+
piHandle: activePiHandle,
|
|
518
|
+
inputs: preTurnTargetedInputsToApply,
|
|
519
|
+
pathType,
|
|
520
|
+
...(hasActiveTurnResume
|
|
521
|
+
? {
|
|
522
|
+
recoveryBaseEntryId: preparedTreePlan?.forkPiEntryId ?? null,
|
|
523
|
+
reuseExistingWithoutBranching: true,
|
|
524
|
+
requireExisting: true,
|
|
525
|
+
}
|
|
526
|
+
: {}),
|
|
527
|
+
onApplied: input.callbacks.onPreTurnTargetedInputApplied,
|
|
528
|
+
});
|
|
529
|
+
} catch (error: unknown) {
|
|
530
|
+
return failFromCaughtError(
|
|
531
|
+
"turn.targeted_input_apply_failed",
|
|
532
|
+
error,
|
|
533
|
+
activePiHandle.getLeafId(),
|
|
534
|
+
`Turn '${turnId}' failed to apply a queued targeted input`,
|
|
535
|
+
);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
if (
|
|
539
|
+
(initialPromptlessTurnResumeReason === null ||
|
|
540
|
+
initialPromptlessTurnResumeReason === "active_turn_resume") &&
|
|
541
|
+
promptText !== null
|
|
542
|
+
) {
|
|
543
|
+
promptText = toolSession.addPromptSuffix(promptText);
|
|
544
|
+
}
|
|
545
|
+
if (
|
|
546
|
+
initialPromptlessTurnResumeReason === "active_turn_resume" &&
|
|
547
|
+
turnStartRecordId &&
|
|
548
|
+
promptText !== null
|
|
549
|
+
) {
|
|
550
|
+
validateIdentifiedPrompt({
|
|
551
|
+
piHandle: activePiHandle,
|
|
552
|
+
identity: {
|
|
553
|
+
kind: "turn_prompt",
|
|
554
|
+
startRecordId: turnStartRecordId,
|
|
555
|
+
purpose: "kickoff",
|
|
556
|
+
},
|
|
557
|
+
content: promptText,
|
|
558
|
+
expectedParentId:
|
|
559
|
+
input.turnDef.context === "compacted"
|
|
560
|
+
? (findIdentifiedPrompt(activePiHandle, {
|
|
561
|
+
kind: "turn_compaction",
|
|
562
|
+
startRecordId: turnStartRecordId,
|
|
563
|
+
})?.id ?? null)
|
|
564
|
+
: (preparedTreePlan?.forkPiEntryId ?? null),
|
|
565
|
+
allowDescendantParent: hasActiveTurnResume,
|
|
566
|
+
requireOnCurrentBranch: true,
|
|
567
|
+
});
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
const executeLogicalPromptPlan = (
|
|
571
|
+
plan: LogicalTurnPromptPlan,
|
|
572
|
+
options: { baseState?: ToolCompletionSnapshot<TOutcome> } = {},
|
|
573
|
+
) =>
|
|
574
|
+
runLogicalPromptPlan({
|
|
575
|
+
plan,
|
|
576
|
+
baseState: options.baseState,
|
|
577
|
+
turnId,
|
|
578
|
+
turnRecordId,
|
|
579
|
+
piHandle: activePiHandle,
|
|
580
|
+
turnDef: input.turnDef,
|
|
581
|
+
toolSession,
|
|
582
|
+
scheduler: input.scheduler,
|
|
583
|
+
turnMaxDurationMs: input.turnMaxDurationMs,
|
|
584
|
+
turnInactivityTimeoutMs: input.turnInactivityTimeoutMs,
|
|
585
|
+
turnAbortGracePeriodMs: input.turnAbortGracePeriodMs,
|
|
586
|
+
operatorAbortSignal: input.operatorAbortSignal,
|
|
587
|
+
emit: input.callbacks.emit,
|
|
588
|
+
reportFailedTurn,
|
|
589
|
+
});
|
|
590
|
+
|
|
591
|
+
const initialPromptPlan: LogicalTurnPromptPlan =
|
|
592
|
+
initialPromptlessTurnResumeReason === null
|
|
593
|
+
? turnStartRecordId
|
|
594
|
+
? {
|
|
595
|
+
kind: "continue",
|
|
596
|
+
continueUserPrompt: promptText ?? "",
|
|
597
|
+
identifiedPrompt: {
|
|
598
|
+
kind: "turn_prompt",
|
|
599
|
+
startRecordId: turnStartRecordId,
|
|
600
|
+
purpose: "kickoff",
|
|
601
|
+
},
|
|
602
|
+
}
|
|
603
|
+
: { kind: "prompt", promptText: promptText ?? "" }
|
|
604
|
+
: {
|
|
605
|
+
kind: "continue",
|
|
606
|
+
continueUserPrompt:
|
|
607
|
+
initialPromptlessTurnResumeReason === "targeted_follow_up"
|
|
608
|
+
? null
|
|
609
|
+
: initialPromptlessTurnResumeReason === "failed_turn_continue"
|
|
610
|
+
? (continuationState?.continuePrompt ?? DEFAULT_CONTINUE_PROMPT)
|
|
611
|
+
: DEFAULT_CONTINUE_PROMPT,
|
|
612
|
+
...(turnStartRecordId && initialPromptlessTurnResumeReason === "failed_turn_continue"
|
|
613
|
+
? {
|
|
614
|
+
identifiedPrompt: {
|
|
615
|
+
kind: "turn_prompt" as const,
|
|
616
|
+
startRecordId: turnStartRecordId,
|
|
617
|
+
purpose: "continue" as const,
|
|
618
|
+
},
|
|
619
|
+
}
|
|
620
|
+
: {}),
|
|
621
|
+
};
|
|
622
|
+
const initialAttempt = await executeLogicalPromptPlan(initialPromptPlan);
|
|
623
|
+
const recoveryResult = await runMissingToolRecovery({
|
|
624
|
+
turnId,
|
|
625
|
+
turnRecordId,
|
|
626
|
+
piHandle: activePiHandle,
|
|
627
|
+
initialAttempt,
|
|
628
|
+
toolSession,
|
|
629
|
+
emit: input.callbacks.emit,
|
|
630
|
+
executeLogicalPromptPlan,
|
|
631
|
+
});
|
|
632
|
+
const finalCompletionState = recoveryResult.finalAttempt.completionState;
|
|
633
|
+
const finalPromptResult = recoveryResult.finalAttempt.promptResult;
|
|
634
|
+
const finalResolvedOutcome = recoveryResult.finalAttempt.resolvedOutcome;
|
|
635
|
+
if (!recoveryResult.recovered) {
|
|
636
|
+
return reportFailedTurn(
|
|
637
|
+
"protocol_error",
|
|
638
|
+
`Turn '${turnId}' completed without the required tool calls after ${MAX_MISSING_TOOL_CALL_RECOVERY_ATTEMPTS} automatic recovery attempts: ${recoveryResult.baseMissingToolRecoveryDescription}`,
|
|
639
|
+
finalPromptResult.resultEntryId,
|
|
640
|
+
{
|
|
641
|
+
recoveryContext: recoveryResult.recoveryContext,
|
|
642
|
+
restorePrimaryLeaf:
|
|
643
|
+
recoveryResult.recoveryContext?.failureCode !== "missing_markdown_result",
|
|
644
|
+
},
|
|
645
|
+
);
|
|
646
|
+
}
|
|
647
|
+
if (finalResolvedOutcome === null) {
|
|
648
|
+
return failWithWorkerError(
|
|
649
|
+
"turn.outcome_missing",
|
|
650
|
+
"protocol_error",
|
|
651
|
+
toolSession.usesOutcomeTools
|
|
652
|
+
? `Turn '${turnId}' completed without calling an outcome tool`
|
|
653
|
+
: `Turn '${turnId}' completed without a turnEnd`,
|
|
654
|
+
finalPromptResult.resultEntryId,
|
|
655
|
+
);
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
const finalizedTurnResultMarkdown = toolSession.finalizeMarkdown(
|
|
659
|
+
finalCompletionState,
|
|
660
|
+
finalPromptResult.assistantMarkdown,
|
|
661
|
+
);
|
|
662
|
+
if (finalizedTurnResultMarkdown.errorMessage) {
|
|
663
|
+
return failWithWorkerError(
|
|
664
|
+
"turn.result_markdown_missing",
|
|
665
|
+
"protocol_error",
|
|
666
|
+
`Turn '${turnId}' completed without publishing a valid markdown result: ${finalizedTurnResultMarkdown.errorMessage}`,
|
|
667
|
+
finalPromptResult.resultEntryId,
|
|
668
|
+
{ restorePrimaryLeaf: false },
|
|
669
|
+
);
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
try {
|
|
673
|
+
await restoreHandleAfterTurn(activePiHandle, treePlan);
|
|
674
|
+
} catch (error: unknown) {
|
|
675
|
+
return failFromCaughtError(
|
|
676
|
+
"turn.primary_leaf_restore_failed",
|
|
677
|
+
error,
|
|
678
|
+
finalPromptResult.resultEntryId,
|
|
679
|
+
`Turn '${turnId}' completed but failed to restore the primary path leaf`,
|
|
680
|
+
{ restorePrimaryLeaf: false },
|
|
681
|
+
);
|
|
682
|
+
}
|
|
683
|
+
const rootEntryIdAfterTurn = resolveRootEntryIdFromHandle(activePiHandle);
|
|
684
|
+
return {
|
|
685
|
+
turnResult: finalResolvedOutcome,
|
|
686
|
+
meta: {
|
|
687
|
+
turnRecordId,
|
|
688
|
+
turnType,
|
|
689
|
+
pathType,
|
|
690
|
+
forkPiEntryId: treePlan.forkPiEntryId,
|
|
691
|
+
resultPiEntryId: finalPromptResult.resultEntryId,
|
|
692
|
+
turnResultMarkdown: finalizedTurnResultMarkdown.markdown,
|
|
693
|
+
rootEntryId: rootEntryIdAfterTurn,
|
|
694
|
+
},
|
|
695
|
+
};
|
|
696
|
+
}
|