@springbrand/agent-runtime 0.2.0-alpha.72 → 0.3.0-alpha.10
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/package.json +7 -7
- package/src/{agent-tool-runtime.ts → adapter/cloudflare/agent-tool.ts} +1 -1
- package/src/adapter/cloudflare/agent.ts +1682 -0
- package/src/{db/index.ts → adapter/cloudflare/database.ts} +18 -55
- package/src/{runtime-agent.ts → adapter/cloudflare/define-agent.ts} +37 -42
- package/src/adapter/cloudflare/dynamic-worker-observability.ts +1 -1
- package/src/adapter/cloudflare/index.ts +18 -0
- package/src/adapter/cloudflare/resources/runtime-resources.ts +4 -4
- package/src/adapter/cloudflare/sandbox/adapter.ts +1 -1
- package/src/adapter/cloudflare/scheduling/schedule-rule.ts +322 -0
- package/src/adapter/cloudflare/scheduling/zoned-cron.ts +11 -6
- package/src/{db → adapter/cloudflare}/schema.ts +28 -80
- package/src/adapter/cloudflare/subagent/definition.ts +63 -33
- package/src/adapter/cloudflare/subagent/runner.ts +174 -120
- package/src/adapter/cloudflare/subagent/tools.ts +13 -14
- package/src/adapter/cloudflare/universal-agent/preparation.ts +7 -7
- package/src/adapter/cloudflare/universal-agent/tools.ts +10 -12
- package/src/adapter/cloudflare/workspace/git-fs.ts +1 -1
- package/src/adapter/cloudflare/workspace/scoped-workspace.ts +1 -1
- package/src/adapter/cloudflare/workspace/version-control.ts +2 -2
- package/src/config/activation.ts +140 -0
- package/src/{runtime-agent-context.ts → config/agent-context.ts} +3 -3
- package/src/{runtime-assembler.ts → config/assembler.ts} +45 -46
- package/src/{kernel/runtime-assembly.ts → config/assembly-projection.ts} +4 -4
- package/src/{pi/assembly/snapshot.ts → config/assembly-snapshot.ts} +6 -6
- package/src/{runtime-definition.ts → config/definition.ts} +13 -13
- package/src/config/harness-runtime.ts +190 -0
- package/src/config/index.ts +14 -0
- package/src/config/model-guidance.ts +21 -0
- package/src/{pi/runtime-adapter/assembly.ts → config/pinning.ts} +60 -19
- package/src/{kernel/bindings.ts → config/ports.ts} +32 -16
- package/src/{kernel → config}/profile.ts +7 -0
- package/src/{kernel → config}/public-contracts.ts +6 -6
- package/src/{kernel → config}/runtime-load.ts +1 -1
- package/src/{pi/assembly/context.ts → context/assembly.ts} +5 -207
- package/src/{pi/assembly/extensions.ts → context/extension/assembly.ts} +5 -5
- package/src/context/extension/index.ts +3 -0
- package/src/context/index.ts +6 -0
- package/src/{layers/context → context/memory}/budget/gate.ts +21 -5
- package/src/conversation/harness-resume.ts +288 -0
- package/src/conversation/harness-stream.ts +99 -0
- package/src/{pi/runtime-adapter/transcript.ts → conversation/history.ts} +206 -233
- package/src/conversation/index.ts +6 -0
- package/src/{pi → conversation}/message/contract.ts +3 -0
- package/src/{pi → conversation}/message/conversion.ts +75 -0
- package/src/{pi → conversation}/message/index.ts +1 -0
- package/src/{pi → conversation}/message/model-input.ts +1 -1
- package/src/{pi → conversation}/message/projection.ts +113 -30
- package/src/{db/message-ui.repo.ts → conversation/repository.ts} +4 -0
- package/src/conversation/state.ts +196 -0
- package/src/harness/index.ts +7 -0
- package/src/harness/session-harness.ts +562 -0
- package/src/harness/submission-operation.ts +49 -0
- package/src/index.ts +38 -43
- package/src/lib/artifacts.ts +18 -0
- package/src/lib/execution-level.ts +13 -0
- package/src/lib/mcp.ts +1 -1
- package/src/lib/prompt.ts +7 -6
- package/src/lib/token-estimate.ts +8 -0
- package/src/{pi/runtime-adapter/models.ts → models/index.ts} +64 -17
- package/src/{pi/turn/tool-recovery.ts → session/cloudflare/legacy-tool-recovery.ts} +33 -525
- package/src/{pi/session → session/cloudflare}/migration.ts +404 -14
- package/src/{pi/session → session/cloudflare}/storage.ts +8 -36
- package/src/session/index.ts +39 -0
- package/src/skills/springbrand-worker-website/index.ts +1 -1
- package/src/submission/admission.ts +286 -0
- package/src/{kernel/receipts.ts → submission/contracts.ts} +56 -2
- package/src/submission/delivery.ts +212 -0
- package/src/submission/finalization.ts +111 -0
- package/src/submission/index.ts +9 -0
- package/src/{kernel/submission-lifecycle.ts → submission/lifecycle.ts} +41 -28
- package/src/{db/submission.repo.ts → submission/repository.ts} +117 -114
- package/src/submission/steer-delivery.ts +167 -0
- package/src/{db/steer.repo.ts → submission/steer-repository.ts} +27 -5
- package/src/submission/unattended.ts +40 -0
- package/src/telemetry/contract.ts +12 -0
- package/src/telemetry/coordinator.ts +65 -0
- package/src/telemetry/delivery.ts +2 -2
- package/src/telemetry/index.ts +5 -0
- package/src/{model-usage.ts → telemetry/model-usage.ts} +1 -1
- package/src/telemetry/recorder.ts +1 -1
- package/src/telemetry/runtime-telemetry.ts +12 -0
- package/src/{kernel/durable-lifecycle.ts → telemetry/subagent-lifecycle.ts} +1 -1
- package/src/telemetry/turn-events.ts +279 -0
- package/src/tools/README.md +44 -0
- package/src/{pi/tool/ai-adapter.ts → tools/adapters/ai-to-pi.ts} +6 -9
- package/src/{pi/tool → tools/adapters}/declared.ts +6 -2
- package/src/{pi/tool/nested-tools.ts → tools/adapters/pi-to-ai.ts} +2 -2
- package/src/tools/assistant/ask-user.ts +317 -0
- package/src/tools/assistant/candidate.ts +15 -0
- package/src/tools/assistant/followups.ts +34 -0
- package/src/tools/assistant/index.ts +19 -0
- package/src/tools/assistant/memory.ts +73 -0
- package/src/tools/assistant/plan.ts +98 -0
- package/src/{pi/tool → tools/assistant}/time.ts +1 -1
- package/src/{pi/tool/core-host.ts → tools/codemode/adapter.ts} +50 -49
- package/src/{pi/tool/core.ts → tools/codemode/index.ts} +35 -91
- package/src/tools/codemode/workspace-connector.ts +198 -0
- package/src/tools/extension/index.ts +42 -0
- package/src/tools/index.ts +32 -0
- package/src/{pi/tool → tools/mcp}/gateway.ts +19 -19
- package/src/{pi/tool/mcp.ts → tools/mcp/index.ts} +5 -5
- package/src/tools/runtime/approval/index.ts +1 -0
- package/src/{db/approval.repo.ts → tools/runtime/approval/repository.ts} +22 -41
- package/src/tools/runtime/compiler.ts +264 -0
- package/src/tools/runtime/contracts.ts +117 -0
- package/src/tools/runtime/decision-gate.ts +337 -0
- package/src/tools/runtime/human-decisions.ts +127 -0
- package/src/tools/runtime/interaction/index.ts +1 -0
- package/src/{db/interaction.repo.ts → tools/runtime/interaction/repository.ts} +1 -7
- package/src/tools/runtime/result.ts +22 -0
- package/src/tools/runtime/unattended-error.ts +4 -0
- package/src/tools/sandbox/index.ts +228 -0
- package/src/tools/schedule/index.ts +301 -0
- package/src/tools/skill/contracts.ts +20 -0
- package/src/tools/skill/index.ts +99 -0
- package/src/tools/skill/resources.ts +322 -0
- package/src/tools/skill/scripts.ts +168 -0
- package/src/{kernel/submission-authority.ts → tools/subagent/authority.ts} +31 -31
- package/src/{pi/tool/subagent.ts → tools/subagent/index.ts} +33 -36
- package/src/{db/agent-tool.repo.ts → tools/subagent/repository.ts} +1 -1
- package/src/{kernel/subagent-runtime.ts → tools/subagent/runtime.ts} +1 -1
- package/src/tools/subagent/temporary/approvals.ts +123 -0
- package/src/{layers/orchestration/temporary-agent/core.ts → tools/subagent/temporary/coordinator.ts} +41 -49
- package/src/tools/subagent/temporary/core.ts +53 -0
- package/src/{layers/orchestration/temporary-agent → tools/subagent/temporary}/runner.ts +1 -1
- package/src/{layers/orchestration/temporary-agent → tools/subagent/temporary}/workspace.ts +1 -4
- package/src/{pi/tool/web-fetch.ts → tools/web/fetch.ts} +4 -13
- package/src/tools/web/index.ts +2 -0
- package/src/tools/web/search/api.ts +1320 -0
- package/src/tools/web/search/index.ts +2 -0
- package/src/{pi/tool/web-search/web-search.ts → tools/web/search/search.ts} +5 -7
- package/src/{pi/tool/workspace-sandbox.ts → tools/workspace/index.ts} +12 -272
- package/src/{pi/tool/workspace-revision.ts → tools/workspace/revision.ts} +2 -2
- package/src/db/milestone.repo.ts +0 -104
- package/src/db/settlement.repo.ts +0 -104
- package/src/kernel/approval-lifecycle.ts +0 -638
- package/src/kernel/interaction-lifecycle.ts +0 -433
- package/src/kernel/recoverable-chat-agent.ts +0 -1020
- package/src/kernel/state.ts +0 -91
- package/src/pi/assembly/index.ts +0 -19
- package/src/pi/runtime-adapter/execution.ts +0 -1163
- package/src/pi/runtime-adapter/index.ts +0 -293
- package/src/pi/runtime-adapter/recovery.ts +0 -982
- package/src/pi/session/index.ts +0 -24
- package/src/pi/tool/base.ts +0 -550
- package/src/pi/tool/compiler.ts +0 -483
- package/src/pi/tool/index.ts +0 -38
- package/src/pi/tool/schedule.ts +0 -261
- package/src/pi/tool/skill.ts +0 -565
- package/src/pi/tool/web-search/api.ts +0 -1318
- package/src/pi/tool/web-search/index.ts +0 -2
- package/src/pi/tool/workspace-state-connector.ts +0 -146
- package/src/pi/turn/approval.ts +0 -181
- package/src/pi/turn/index.ts +0 -82
- package/src/pi/turn/interaction.ts +0 -181
- package/src/runtime.ts +0 -4760
- package/src/{kernel/runtime-assembly-view.ts → config/assembly-view.ts} +0 -0
- package/src/{kernel → config}/degradation.ts +0 -0
- package/src/{kernel → config}/runtime-config.ts +0 -0
- package/src/{kernel/extensions.ts → context/extension/contracts.ts} +0 -0
- package/src/{db/ext-context.repo.ts → context/extension/repository.ts} +0 -0
- package/src/{pi/runtime-adapter/openrouter-messages.ts → models/openrouter/messages.ts} +0 -0
- package/src/{pi/runtime-adapter → models/openrouter}/test-fixtures/openrouter-tool-search.sse +0 -0
- package/src/{db/submission-admission.repo.ts → submission/admission-repository.ts} +0 -0
- package/src/{db/telemetry-outbox.repo.ts → telemetry/repository.ts} +0 -0
- package/src/{db/runtime-event-outbox.repo.ts → telemetry/runtime-event-repository.ts} +0 -0
- package/src/{layers/orchestration/subagents/agent-types → tools/subagent/types}/contract.ts +0 -0
- package/src/{layers/orchestration/subagents/agent-types → tools/subagent/types}/extract/index.ts +0 -0
- package/src/{layers/orchestration/subagents/agent-types → tools/subagent/types}/fanout/index.ts +0 -0
- package/src/{layers/orchestration/subagents/agent-types → tools/subagent/types}/registry.ts +1 -1
- /package/src/{workspace-versioning.ts → tools/workspace/versioning.ts} +0 -0
|
@@ -0,0 +1,562 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AgentHarness,
|
|
3
|
+
type AgentMessage,
|
|
4
|
+
type AgentHarness as PiAgentHarness,
|
|
5
|
+
type AgentHarnessOptions,
|
|
6
|
+
type AgentLane,
|
|
7
|
+
type DriveOutcome,
|
|
8
|
+
type DriveOptions,
|
|
9
|
+
type OpenOperation,
|
|
10
|
+
type OperationRequest,
|
|
11
|
+
} from "@earendil-works/pi-agent-core";
|
|
12
|
+
import type { Context } from "@earendil-works/pi-agent-core/harness/context";
|
|
13
|
+
import type { Entry, SettledAssistantMessage } from "@earendil-works/pi-agent-core/harness/session";
|
|
14
|
+
import {
|
|
15
|
+
isModelStreamStallMessage,
|
|
16
|
+
isOpenRouterServerToolTimeout,
|
|
17
|
+
isRecoverableAssistantError,
|
|
18
|
+
} from "../models";
|
|
19
|
+
import { projectToolOutputForModel } from "../context/memory/budget/gate";
|
|
20
|
+
import type { ArtifactRef } from "../lib/artifacts";
|
|
21
|
+
|
|
22
|
+
export interface SessionHarnessLimits {
|
|
23
|
+
/** Complete model turns committed before one Worker instance releases. */
|
|
24
|
+
modelTurnsPerSlice?: number;
|
|
25
|
+
/** Complete working turns allowed before the no-tool final response. */
|
|
26
|
+
maxModelTurns?: number;
|
|
27
|
+
/** Maximum text turns allowed after the working or Tool failure budget. */
|
|
28
|
+
maxWrapUpModelTurns?: number;
|
|
29
|
+
wrapUpInstruction?: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface SessionHarnessOptions<TContext extends object | undefined>
|
|
33
|
+
extends AgentHarnessOptions<TContext> {
|
|
34
|
+
limits?: SessionHarnessLimits;
|
|
35
|
+
modelToolResultExemptions?: readonly string[];
|
|
36
|
+
/** Base provider Session identity, retained except after a server Tool timeout. */
|
|
37
|
+
modelSessionId?: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export type SessionHarnessRunResult = DriveOutcome | {
|
|
41
|
+
kind: "released";
|
|
42
|
+
operationId: string;
|
|
43
|
+
reason: "slice" | "budget" | "tool-failure" | "approval" | "interaction";
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const DEFAULT_MODEL_TURNS_PER_SLICE = 30;
|
|
47
|
+
const DEFAULT_MAX_MODEL_TURNS = 300;
|
|
48
|
+
const DEFAULT_MAX_WRAP_UP_MODEL_TURNS = 2;
|
|
49
|
+
const RECOVERY_MAX_FAILURES = 5;
|
|
50
|
+
const STALL_MAX_FAILURES = 3;
|
|
51
|
+
const SERVER_TOOL_TIMEOUT_MAX_FAILURES = 2;
|
|
52
|
+
const DEFAULT_WRAP_UP_INSTRUCTION =
|
|
53
|
+
"Finish this request now without using tools. Summarize the completed work and any remaining limitation.";
|
|
54
|
+
const TOOL_FAILURE_WRAP_UP_INSTRUCTION =
|
|
55
|
+
"This turn reached its tool failure limit. Stop calling tools now. Reply with a final message that explains what failed and the exact next step the user should take. Do not start new work.";
|
|
56
|
+
const MAX_TOOL_RETRIES = 3;
|
|
57
|
+
const TURN_FAILURE_CEILING = 8;
|
|
58
|
+
const ARTIFACT_MANIFEST_MAX_CHARS = 12 * 1024;
|
|
59
|
+
|
|
60
|
+
function canonicalJson(value: unknown): string {
|
|
61
|
+
if (Array.isArray(value)) {
|
|
62
|
+
return `[${value.map(canonicalJson).join(",")}]`;
|
|
63
|
+
}
|
|
64
|
+
if (value !== null && typeof value === "object") {
|
|
65
|
+
return `{${Object.entries(value)
|
|
66
|
+
.filter(([, item]) => item !== undefined)
|
|
67
|
+
.sort(([left], [right]) => left.localeCompare(right))
|
|
68
|
+
.map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`)
|
|
69
|
+
.join(",")}}`;
|
|
70
|
+
}
|
|
71
|
+
return JSON.stringify(value) ?? "null";
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function toolCallKey(toolName: string, args: unknown): string {
|
|
75
|
+
return `${toolName}\0${canonicalJson(args)}`;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function projectToolResultsForModel(
|
|
79
|
+
messages: readonly AgentMessage[],
|
|
80
|
+
exemptions: ReadonlySet<string>,
|
|
81
|
+
): AgentMessage[] {
|
|
82
|
+
let changed = false;
|
|
83
|
+
const projected = messages.map((message) => {
|
|
84
|
+
if (
|
|
85
|
+
message.role !== "toolResult" ||
|
|
86
|
+
exemptions.has(message.toolName)
|
|
87
|
+
) return message;
|
|
88
|
+
const payload = { content: message.content, details: message.details };
|
|
89
|
+
const next = projectToolOutputForModel(payload) as typeof payload;
|
|
90
|
+
if (next === payload) return message;
|
|
91
|
+
changed = true;
|
|
92
|
+
return { ...message, content: next.content, details: next.details };
|
|
93
|
+
});
|
|
94
|
+
return changed ? projected : [...messages];
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function artifactRefFromMessage(message: AgentMessage): ArtifactRef | undefined {
|
|
98
|
+
if (message.role !== "toolResult" || message.details === null ||
|
|
99
|
+
typeof message.details !== "object" ||
|
|
100
|
+
(message.details as { kind?: unknown }).kind !== "artifact_ref") {
|
|
101
|
+
return undefined;
|
|
102
|
+
}
|
|
103
|
+
const ref = message.details as Partial<ArtifactRef>;
|
|
104
|
+
if (typeof ref.path !== "string" || typeof ref.hash !== "string" ||
|
|
105
|
+
typeof ref.bytes !== "number" || typeof ref.preview !== "string" ||
|
|
106
|
+
typeof ref.note !== "string") return undefined;
|
|
107
|
+
return {
|
|
108
|
+
kind: "artifact_ref",
|
|
109
|
+
artifactId: typeof ref.artifactId === "string"
|
|
110
|
+
? ref.artifactId
|
|
111
|
+
: `artifact_${ref.hash.slice(0, 24)}`,
|
|
112
|
+
path: ref.path,
|
|
113
|
+
bytes: ref.bytes,
|
|
114
|
+
hash: ref.hash,
|
|
115
|
+
workspaceRevision: typeof ref.workspaceRevision === "string"
|
|
116
|
+
? ref.workspaceRevision
|
|
117
|
+
: "unknown",
|
|
118
|
+
availability: ref.availability === "unavailable"
|
|
119
|
+
? "unavailable"
|
|
120
|
+
: "available",
|
|
121
|
+
preview: ref.preview,
|
|
122
|
+
note: ref.note,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function artifactManifestMessage(
|
|
127
|
+
refs: ReadonlyMap<string, ArtifactRef>,
|
|
128
|
+
): AgentMessage | undefined {
|
|
129
|
+
if (refs.size === 0) return undefined;
|
|
130
|
+
const lines = [
|
|
131
|
+
"<workspace_artifact_manifest>",
|
|
132
|
+
"These are lightweight references to prior Tool output. Do not treat previews as complete. Read an available artifact with the Workspace readFile/readFilePage tool only when the current request needs its evidence.",
|
|
133
|
+
];
|
|
134
|
+
let omitted = 0;
|
|
135
|
+
for (const ref of refs.values()) {
|
|
136
|
+
const preview = ref.preview.replace(/[\r\n]+/g, " ").slice(0, 240);
|
|
137
|
+
const line = [
|
|
138
|
+
`artifactId=${ref.artifactId}`,
|
|
139
|
+
`path=${ref.path}`,
|
|
140
|
+
`hash=${ref.hash}`,
|
|
141
|
+
`bytes=${ref.bytes}`,
|
|
142
|
+
`workspaceRevision=${ref.workspaceRevision}`,
|
|
143
|
+
`availability=${ref.availability}`,
|
|
144
|
+
`preview=${preview}`,
|
|
145
|
+
].join(" ");
|
|
146
|
+
if ([...lines, line, "</workspace_artifact_manifest>"].join("\n").length > ARTIFACT_MANIFEST_MAX_CHARS) {
|
|
147
|
+
omitted += 1;
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
lines.push(line);
|
|
151
|
+
}
|
|
152
|
+
if (omitted > 0) lines.push(`omitted=${omitted} older artifact references due to manifest budget`);
|
|
153
|
+
lines.push("</workspace_artifact_manifest>");
|
|
154
|
+
return {
|
|
155
|
+
role: "user",
|
|
156
|
+
content: lines.join("\n"),
|
|
157
|
+
timestamp: 1,
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function deferred<T>(): {
|
|
162
|
+
promise: Promise<T>;
|
|
163
|
+
resolve(value: T): void;
|
|
164
|
+
} {
|
|
165
|
+
let resolve!: (value: T) => void;
|
|
166
|
+
const promise = new Promise<T>((done) => {
|
|
167
|
+
resolve = done;
|
|
168
|
+
});
|
|
169
|
+
return { promise, resolve };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function positiveInteger(value: number | undefined, fallback: number): number {
|
|
173
|
+
const resolved = value ?? fallback;
|
|
174
|
+
if (!Number.isInteger(resolved) || resolved <= 0) {
|
|
175
|
+
throw new Error("Harness model turn limits must be positive integers");
|
|
176
|
+
}
|
|
177
|
+
return resolved;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* The only adapter that owns a live Pi AgentHarness for a Session.
|
|
182
|
+
*
|
|
183
|
+
* Submission and Cloudflare lifecycle code may accept, drive, abort, watch, or
|
|
184
|
+
* close through this object. It deliberately does not know how Host config or
|
|
185
|
+
* business repositories are loaded.
|
|
186
|
+
*/
|
|
187
|
+
export class SessionHarness<TContext extends object | undefined> {
|
|
188
|
+
private _openOperation: OpenOperation | null;
|
|
189
|
+
private readonly modelTurnsPerSlice: number;
|
|
190
|
+
private readonly maxModelTurns: number;
|
|
191
|
+
private readonly maxWrapUpModelTurns: number;
|
|
192
|
+
private readonly modelSessionId: string | undefined;
|
|
193
|
+
private readonly wrapUpInstruction: string;
|
|
194
|
+
private readonly configuredToolNames: string[];
|
|
195
|
+
private readonly modelToolResultExemptions: ReadonlySet<string>;
|
|
196
|
+
private readonly toolFailures = new Map<string, number>();
|
|
197
|
+
private totalToolFailures = 0;
|
|
198
|
+
private toolFailureWrapUp = false;
|
|
199
|
+
private toolFailureWrapUpAt: number | undefined;
|
|
200
|
+
private operationStartTip: string | null = null;
|
|
201
|
+
private turnsAtOpen = 0;
|
|
202
|
+
private wrappingUp = false;
|
|
203
|
+
private releaseReason:
|
|
204
|
+
| "slice"
|
|
205
|
+
| "budget"
|
|
206
|
+
| "tool-failure"
|
|
207
|
+
| "approval"
|
|
208
|
+
| "interaction"
|
|
209
|
+
| undefined;
|
|
210
|
+
private readonly releaseRequest = deferred<"approval" | "interaction">();
|
|
211
|
+
private readonly activeTools = new Set<string>();
|
|
212
|
+
private readonly toolsIdle = new Set<() => void>();
|
|
213
|
+
private readonly artifactRefs = new Map<string, ArtifactRef>();
|
|
214
|
+
|
|
215
|
+
private constructor(
|
|
216
|
+
readonly harness: PiAgentHarness<TContext>,
|
|
217
|
+
readonly lane: AgentLane,
|
|
218
|
+
openOperation: OpenOperation | null,
|
|
219
|
+
options: SessionHarnessOptions<TContext>,
|
|
220
|
+
) {
|
|
221
|
+
this._openOperation = openOperation;
|
|
222
|
+
this.modelTurnsPerSlice = positiveInteger(
|
|
223
|
+
options.limits?.modelTurnsPerSlice,
|
|
224
|
+
DEFAULT_MODEL_TURNS_PER_SLICE,
|
|
225
|
+
);
|
|
226
|
+
this.maxModelTurns = positiveInteger(
|
|
227
|
+
options.limits?.maxModelTurns,
|
|
228
|
+
DEFAULT_MAX_MODEL_TURNS,
|
|
229
|
+
);
|
|
230
|
+
this.maxWrapUpModelTurns = positiveInteger(
|
|
231
|
+
options.limits?.maxWrapUpModelTurns,
|
|
232
|
+
DEFAULT_MAX_WRAP_UP_MODEL_TURNS,
|
|
233
|
+
);
|
|
234
|
+
this.modelSessionId = options.modelSessionId;
|
|
235
|
+
this.wrapUpInstruction = options.limits?.wrapUpInstruction ??
|
|
236
|
+
DEFAULT_WRAP_UP_INSTRUCTION;
|
|
237
|
+
this.configuredToolNames = options.activeToolNames ??
|
|
238
|
+
(options.tools ?? []).map(({ name }) => name);
|
|
239
|
+
this.modelToolResultExemptions = new Set(
|
|
240
|
+
options.modelToolResultExemptions ?? [],
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
private async operationEntries(context: Context): Promise<Entry[]> {
|
|
245
|
+
// Stop boundaries follow traversal order; walk back from the current tip.
|
|
246
|
+
const entries = await this.lane.findEntries({
|
|
247
|
+
...(this.operationStartTip === null ? {} : { stopAtId: this.operationStartTip }),
|
|
248
|
+
type: "message",
|
|
249
|
+
order: "newestFirst",
|
|
250
|
+
}, context);
|
|
251
|
+
return entries.filter(({ id }) => id !== this.operationStartTip).reverse();
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
private async restoreToolGovernance(context: Context): Promise<void> {
|
|
255
|
+
this.toolFailures.clear();
|
|
256
|
+
this.totalToolFailures = 0;
|
|
257
|
+
this.toolFailureWrapUp = false;
|
|
258
|
+
this.toolFailureWrapUpAt = undefined;
|
|
259
|
+
let turns = 0;
|
|
260
|
+
for (const entry of await this.operationEntries(context)) {
|
|
261
|
+
if (entry.type !== "message") continue;
|
|
262
|
+
const message = entry.message;
|
|
263
|
+
if (message.role === "assistant") {
|
|
264
|
+
turns += 1;
|
|
265
|
+
continue;
|
|
266
|
+
}
|
|
267
|
+
this.recordCanonicalToolOutcome(entry);
|
|
268
|
+
if (this.toolFailureWrapUp) this.toolFailureWrapUpAt ??= turns;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
private recordCanonicalToolOutcome(entry: Entry): void {
|
|
273
|
+
if (entry.type !== "message" || entry.message.role !== "toolResult") return;
|
|
274
|
+
const message = entry.message;
|
|
275
|
+
if (entry.toolExecution?.status === "executed") {
|
|
276
|
+
this.recordToolOutcome(message.toolName, entry.toolExecution.args, message.isError);
|
|
277
|
+
} else if (entry.toolExecution?.status === "blocked" && entry.toolExecution.args !== undefined) {
|
|
278
|
+
const key = toolCallKey(message.toolName, entry.toolExecution.args);
|
|
279
|
+
if ((this.toolFailures.get(key) ?? 0) >= MAX_TOOL_RETRIES) this.toolFailureWrapUp = true;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
private recordToolOutcome(toolName: string, args: unknown, isError: boolean): void {
|
|
284
|
+
const key = toolCallKey(toolName, args);
|
|
285
|
+
if (!isError) {
|
|
286
|
+
this.toolFailures.delete(key);
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
this.toolFailures.set(key, (this.toolFailures.get(key) ?? 0) + 1);
|
|
290
|
+
this.totalToolFailures += 1;
|
|
291
|
+
if (this.totalToolFailures >= TURN_FAILURE_CEILING) this.toolFailureWrapUp = true;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
private async shouldRetry(
|
|
295
|
+
message: SettledAssistantMessage,
|
|
296
|
+
context: Context,
|
|
297
|
+
recovery: boolean,
|
|
298
|
+
): Promise<boolean> {
|
|
299
|
+
const stalled = isModelStreamStallMessage(message.errorMessage);
|
|
300
|
+
const serverToolTimeout = isOpenRouterServerToolTimeout(message);
|
|
301
|
+
if (!recovery && !stalled && !serverToolTimeout && !isRecoverableAssistantError(message)) return false;
|
|
302
|
+
const failures = 1 + (await this.operationEntries(context)).filter((entry) =>
|
|
303
|
+
entry.type === "message" && entry.message.role === "assistant" && entry.message.stopReason === "error"
|
|
304
|
+
).length;
|
|
305
|
+
return failures < (stalled ? STALL_MAX_FAILURES
|
|
306
|
+
: serverToolTimeout ? SERVER_TOOL_TIMEOUT_MAX_FAILURES : RECOVERY_MAX_FAILURES);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
private async shouldFinishRun(context: Context): Promise<boolean> {
|
|
310
|
+
const wrapUpAt = Math.min(this.maxModelTurns, this.toolFailureWrapUpAt ?? Infinity);
|
|
311
|
+
return await this.completedModelTurns(context) >= wrapUpAt + this.maxWrapUpModelTurns;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
get openOperation(): OpenOperation | null {
|
|
315
|
+
return this._openOperation;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
static async open<TContext extends object | undefined>(
|
|
319
|
+
options: SessionHarnessOptions<TContext>,
|
|
320
|
+
context: Context,
|
|
321
|
+
): Promise<SessionHarness<TContext>> {
|
|
322
|
+
const {
|
|
323
|
+
limits: _limits,
|
|
324
|
+
modelToolResultExemptions: _modelToolResultExemptions,
|
|
325
|
+
modelSessionId: _modelSessionId,
|
|
326
|
+
...harnessOptions
|
|
327
|
+
} = options;
|
|
328
|
+
let runtime!: SessionHarness<TContext>;
|
|
329
|
+
const { harness, open } = await AgentHarness.create({
|
|
330
|
+
...harnessOptions,
|
|
331
|
+
retry: options.retry ?? { enabled: true, maxRetries: RECOVERY_MAX_FAILURES - 1, baseDelayMs: 1_000 },
|
|
332
|
+
recoveryPolicy: async (event, policyContext) =>
|
|
333
|
+
await runtime.shouldRetry(event.message, policyContext, event.recovery) &&
|
|
334
|
+
(options.recoveryPolicy === undefined || await options.recoveryPolicy(event, policyContext)),
|
|
335
|
+
shouldFinishRun: async (event, policyContext) =>
|
|
336
|
+
await runtime.shouldFinishRun(policyContext) ||
|
|
337
|
+
(options.shouldFinishRun !== undefined && await options.shouldFinishRun(event, policyContext)),
|
|
338
|
+
}, context);
|
|
339
|
+
const foreign = open.find((operation) => operation.lane !== "main");
|
|
340
|
+
if (foreign) {
|
|
341
|
+
await harness.close(context);
|
|
342
|
+
throw new Error(`Unexpected open Harness lane: ${foreign.lane}`);
|
|
343
|
+
}
|
|
344
|
+
if (open.length > 1) {
|
|
345
|
+
await harness.close(context);
|
|
346
|
+
throw new Error("Session has multiple open operations on the main lane");
|
|
347
|
+
}
|
|
348
|
+
runtime = new SessionHarness(
|
|
349
|
+
harness,
|
|
350
|
+
await harness.lane("main", context),
|
|
351
|
+
open[0] ?? null,
|
|
352
|
+
options,
|
|
353
|
+
);
|
|
354
|
+
await runtime.install(context);
|
|
355
|
+
return runtime;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
private async install(context: Context): Promise<void> {
|
|
359
|
+
for (const entry of await this.lane.findEntries({ type: "message", order: "oldestFirst" }, context)) {
|
|
360
|
+
if (entry.type === "message") {
|
|
361
|
+
const ref = artifactRefFromMessage(entry.message);
|
|
362
|
+
if (ref) this.artifactRefs.set(ref.artifactId, ref);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
if (this._openOperation) {
|
|
366
|
+
const watch = await this.lane.watch(context);
|
|
367
|
+
this.operationStartTip = watch.snapshot.operation?.fromTipId ?? null;
|
|
368
|
+
watch.unsubscribe();
|
|
369
|
+
await this.restoreToolGovernance(context);
|
|
370
|
+
this.turnsAtOpen = await this.completedModelTurns(context);
|
|
371
|
+
if (this.turnsAtOpen >= this.maxModelTurns) {
|
|
372
|
+
this.wrappingUp = true;
|
|
373
|
+
}
|
|
374
|
+
if (this.wrappingUp || this.toolFailureWrapUp) {
|
|
375
|
+
await this.lane.setActiveTools([], context);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
this.harness.hooks.on("before_request", async (event, requestContext) => {
|
|
379
|
+
if (event.step !== "assistant") return;
|
|
380
|
+
const resets = (await this.operationEntries(requestContext)).filter((entry) =>
|
|
381
|
+
entry.type === "message" && entry.message.role === "assistant" && isOpenRouterServerToolTimeout(entry.message)
|
|
382
|
+
).length;
|
|
383
|
+
if (resets > 0) {
|
|
384
|
+
return { streamOptions: { sessionId: `${this.modelSessionId ?? event.runId}:server-tool-recovery:${resets}` } };
|
|
385
|
+
}
|
|
386
|
+
if (this.modelSessionId !== undefined) return { streamOptions: { sessionId: this.modelSessionId } };
|
|
387
|
+
});
|
|
388
|
+
this.harness.hooks.on("transform_context", (event) => {
|
|
389
|
+
const messages = projectToolResultsForModel(
|
|
390
|
+
event.messages,
|
|
391
|
+
this.modelToolResultExemptions,
|
|
392
|
+
);
|
|
393
|
+
const manifest = artifactManifestMessage(this.artifactRefs);
|
|
394
|
+
const instruction = this.toolFailureWrapUp
|
|
395
|
+
? TOOL_FAILURE_WRAP_UP_INSTRUCTION
|
|
396
|
+
: this.wrappingUp
|
|
397
|
+
? this.wrapUpInstruction
|
|
398
|
+
: undefined;
|
|
399
|
+
const contextMessages = manifest ? [...messages, manifest] : messages;
|
|
400
|
+
return {
|
|
401
|
+
messages: instruction
|
|
402
|
+
? [...contextMessages, {
|
|
403
|
+
role: "user" as const,
|
|
404
|
+
content: instruction,
|
|
405
|
+
timestamp: 1,
|
|
406
|
+
}]
|
|
407
|
+
: contextMessages,
|
|
408
|
+
};
|
|
409
|
+
});
|
|
410
|
+
this.harness.hooks.on("before_tool", (event) => {
|
|
411
|
+
if (this.toolFailureWrapUp) {
|
|
412
|
+
return {
|
|
413
|
+
block: {
|
|
414
|
+
reason: "This turn reached its tool failure limit. Stop calling tools now.",
|
|
415
|
+
terminate: true,
|
|
416
|
+
},
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
if (
|
|
420
|
+
(this.toolFailures.get(toolCallKey(event.toolName, event.args)) ?? 0) <
|
|
421
|
+
MAX_TOOL_RETRIES
|
|
422
|
+
) return;
|
|
423
|
+
this.toolFailureWrapUp = true;
|
|
424
|
+
return {
|
|
425
|
+
block: {
|
|
426
|
+
reason:
|
|
427
|
+
`This exact ${event.toolName} call has already failed ${MAX_TOOL_RETRIES} times — change the input or approach instead of retrying it verbatim.`,
|
|
428
|
+
},
|
|
429
|
+
};
|
|
430
|
+
});
|
|
431
|
+
this.harness.events.on("entry_added", (event) => {
|
|
432
|
+
if (event.lane !== this.lane.name) return;
|
|
433
|
+
this.recordCanonicalToolOutcome(event.entry);
|
|
434
|
+
if (event.entry.type === "message") {
|
|
435
|
+
const ref = artifactRefFromMessage(event.entry.message);
|
|
436
|
+
if (ref) this.artifactRefs.set(ref.artifactId, ref);
|
|
437
|
+
}
|
|
438
|
+
});
|
|
439
|
+
this.harness.events.on("turn_end", async (_event, eventContext) => {
|
|
440
|
+
const total = await this.completedModelTurns(eventContext);
|
|
441
|
+
if (this.toolFailureWrapUp && this.toolFailureWrapUpAt === undefined) {
|
|
442
|
+
this.toolFailureWrapUpAt = total;
|
|
443
|
+
this.releaseReason = "tool-failure";
|
|
444
|
+
} else if (this.wrappingUp || this.toolFailureWrapUp) {
|
|
445
|
+
return;
|
|
446
|
+
} else if (total >= this.maxModelTurns) {
|
|
447
|
+
this.releaseReason = "budget";
|
|
448
|
+
} else if (total - this.turnsAtOpen >= this.modelTurnsPerSlice) {
|
|
449
|
+
this.releaseReason = "slice";
|
|
450
|
+
} else {
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
await this.harness.close(eventContext);
|
|
454
|
+
});
|
|
455
|
+
this.harness.events.on("tool_start", (event) => {
|
|
456
|
+
this.activeTools.add(event.toolCallId);
|
|
457
|
+
});
|
|
458
|
+
this.harness.events.on("tool_end", (event) => {
|
|
459
|
+
this.activeTools.delete(event.toolCallId);
|
|
460
|
+
if (this.activeTools.size === 0) {
|
|
461
|
+
for (const resolve of this.toolsIdle) resolve();
|
|
462
|
+
this.toolsIdle.clear();
|
|
463
|
+
}
|
|
464
|
+
});
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/** Ask the active drive to detach after already-started parallel Tools settle. */
|
|
468
|
+
requestHumanRelease(reason: "approval" | "interaction"): void {
|
|
469
|
+
this.releaseRequest.resolve(reason);
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
private async waitForToolsToSettle(): Promise<void> {
|
|
473
|
+
if (this.activeTools.size === 0) return;
|
|
474
|
+
await new Promise<void>((resolve) => this.toolsIdle.add(resolve));
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
private async completedModelTurns(context: Context): Promise<number> {
|
|
478
|
+
return (await this.operationEntries(context)).filter((entry) =>
|
|
479
|
+
entry.type === "message" && entry.message.role === "assistant"
|
|
480
|
+
).length;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
async run(
|
|
484
|
+
request: OperationRequest | undefined,
|
|
485
|
+
context: Context,
|
|
486
|
+
driveOptions: Omit<DriveOptions, "operationId"> = {},
|
|
487
|
+
): Promise<SessionHarnessRunResult> {
|
|
488
|
+
let operationId = this.openOperation?.operationId;
|
|
489
|
+
if (request) {
|
|
490
|
+
if (operationId) {
|
|
491
|
+
throw new Error(`Harness operation ${operationId} is already open`);
|
|
492
|
+
}
|
|
493
|
+
this.operationStartTip = await this.lane.getTipId(context);
|
|
494
|
+
this.turnsAtOpen = 0;
|
|
495
|
+
this.wrappingUp = false;
|
|
496
|
+
this.toolFailures.clear();
|
|
497
|
+
this.totalToolFailures = 0;
|
|
498
|
+
this.toolFailureWrapUp = false;
|
|
499
|
+
this.toolFailureWrapUpAt = undefined;
|
|
500
|
+
this.releaseReason = undefined;
|
|
501
|
+
await this.lane.setActiveTools(this.configuredToolNames, context);
|
|
502
|
+
const admission = await this.lane.accept(request, context);
|
|
503
|
+
if (!admission.ok) throw admission.error;
|
|
504
|
+
operationId = admission.value.operationId;
|
|
505
|
+
this._openOperation = {
|
|
506
|
+
lane: "main",
|
|
507
|
+
operationId,
|
|
508
|
+
kind: admission.value.kind,
|
|
509
|
+
startedAt: admission.value.startedAt,
|
|
510
|
+
};
|
|
511
|
+
}
|
|
512
|
+
if (!operationId) throw new Error("No Harness operation to drive");
|
|
513
|
+
try {
|
|
514
|
+
const driving = this.lane.drive({ ...driveOptions, operationId }, context);
|
|
515
|
+
const winner = await Promise.race([
|
|
516
|
+
driving.then((result) => ({ kind: "drive" as const, result })),
|
|
517
|
+
this.releaseRequest.promise.then((reason) => ({
|
|
518
|
+
kind: "release" as const,
|
|
519
|
+
reason,
|
|
520
|
+
})),
|
|
521
|
+
]);
|
|
522
|
+
if (winner.kind === "release") {
|
|
523
|
+
this.releaseReason = winner.reason;
|
|
524
|
+
await this.waitForToolsToSettle();
|
|
525
|
+
await this.harness.close(context);
|
|
526
|
+
await driving.catch(() => undefined);
|
|
527
|
+
return { kind: "released", operationId, reason: winner.reason };
|
|
528
|
+
}
|
|
529
|
+
const result = winner.result;
|
|
530
|
+
if (!result.ok) throw result.error;
|
|
531
|
+
if (result.value.kind === "settled") {
|
|
532
|
+
this._openOperation = null;
|
|
533
|
+
}
|
|
534
|
+
return result.value;
|
|
535
|
+
} catch (error) {
|
|
536
|
+
if (
|
|
537
|
+
this.releaseReason && error instanceof Error &&
|
|
538
|
+
error.name === "HarnessClosed"
|
|
539
|
+
) {
|
|
540
|
+
return { kind: "released", operationId, reason: this.releaseReason };
|
|
541
|
+
}
|
|
542
|
+
throw error;
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
async requestAbort(operationId: string, context: Context): Promise<boolean> {
|
|
547
|
+
const result = await this.lane.requestAbort(operationId, context);
|
|
548
|
+
if (!result.ok) throw result.error;
|
|
549
|
+
return result.value.newlyRequested;
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
close(context: Context): Promise<void> {
|
|
553
|
+
return this.harness.close(context);
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
export function openSessionHarness<TContext extends object | undefined>(
|
|
558
|
+
options: SessionHarnessOptions<TContext>,
|
|
559
|
+
context: Context,
|
|
560
|
+
): Promise<SessionHarness<TContext>> {
|
|
561
|
+
return SessionHarness.open(options, context);
|
|
562
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { OperationRequest, OperationResultRecord } from "@earendil-works/pi-agent-core";
|
|
2
|
+
import type { Context } from "@earendil-works/pi-agent-core/harness/context";
|
|
3
|
+
import type { PiCanonicalUserInput } from "../conversation/message/contract";
|
|
4
|
+
import type { StoredSubmission } from "../submission/repository";
|
|
5
|
+
import type { SessionHarness } from "./session-harness";
|
|
6
|
+
|
|
7
|
+
/** Recover the stable operation before accepting new input or navigating its branch. */
|
|
8
|
+
export async function prepareSubmissionOperation(
|
|
9
|
+
runtime: SessionHarness<object | undefined>,
|
|
10
|
+
submission: Pick<StoredSubmission, "submissionId" | "queuedInputJson" | "regenerateMessageId">,
|
|
11
|
+
regenerationTarget: (messageId: string) => string | null,
|
|
12
|
+
context: Context,
|
|
13
|
+
): Promise<{ kind: "run"; request?: OperationRequest } | { kind: "settled"; outcome: OperationResultRecord }> {
|
|
14
|
+
const id = submission.submissionId;
|
|
15
|
+
const navigationId = `${id}:regenerate`;
|
|
16
|
+
if (runtime.openOperation?.operationId === navigationId) {
|
|
17
|
+
const navigation = await runtime.run(undefined, context);
|
|
18
|
+
if (navigation.kind !== "settled" || navigation.outcome.status !== "completed") {
|
|
19
|
+
throw new Error("Could not recover the regeneration branch navigation");
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
if (runtime.openOperation) {
|
|
23
|
+
if (runtime.openOperation.operationId !== id) {
|
|
24
|
+
throw new Error(`Submission ${id} does not own the open Harness operation`);
|
|
25
|
+
}
|
|
26
|
+
return { kind: "run" };
|
|
27
|
+
}
|
|
28
|
+
const watch = await runtime.lane.watch(context);
|
|
29
|
+
const previous = watch.snapshot.lastResult;
|
|
30
|
+
watch.unsubscribe();
|
|
31
|
+
if (previous?.operationId === id) return { kind: "settled", outcome: previous };
|
|
32
|
+
if (!submission.queuedInputJson) {
|
|
33
|
+
throw new Error(`Submission ${id} has no open Harness operation or queued input`);
|
|
34
|
+
}
|
|
35
|
+
const prompt = JSON.parse(submission.queuedInputJson) as PiCanonicalUserInput;
|
|
36
|
+
if (prompt.role !== "user") throw new Error("Queued SpringBrand user message is invalid");
|
|
37
|
+
if (submission.regenerateMessageId && previous?.operationId !== navigationId) {
|
|
38
|
+
const navigation = await runtime.run({
|
|
39
|
+
kind: "navigation",
|
|
40
|
+
operationId: navigationId,
|
|
41
|
+
targetId: regenerationTarget(submission.regenerateMessageId),
|
|
42
|
+
options: { summarize: false },
|
|
43
|
+
}, context);
|
|
44
|
+
if (navigation.kind !== "settled" || navigation.outcome.status !== "completed") {
|
|
45
|
+
throw new Error("Could not navigate to the regeneration branch");
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return { kind: "run", request: { kind: "prompt", operationId: id, prompt } };
|
|
49
|
+
}
|