@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,279 @@
|
|
|
1
|
+
import type { AgentHarness, Entry } from "@earendil-works/pi-agent-core";
|
|
2
|
+
import type {
|
|
3
|
+
RuntimeLifecycleFact,
|
|
4
|
+
RuntimeModelUsageEvent,
|
|
5
|
+
RuntimeSubagentUsageEvent,
|
|
6
|
+
RuntimeToolSettlementEvent,
|
|
7
|
+
RuntimeTurnEventsPort,
|
|
8
|
+
} from "../config/ports";
|
|
9
|
+
import type { StoredSubmission } from "../submission/repository";
|
|
10
|
+
import { decodeSubagentCompletion, isZeroSubagentUsage, subagentTerminalStatus, type RuntimeSubagentRunMetadata } from "../tools/subagent/runtime";
|
|
11
|
+
import type { RuntimeTelemetryCoordinator } from "./coordinator";
|
|
12
|
+
import { summarizeModelUsage } from "./model-usage";
|
|
13
|
+
import type { RuntimeEventOutboxRepository } from "./runtime-event-repository";
|
|
14
|
+
import { RuntimeSubagentLifecycleRecorder } from "./subagent-lifecycle";
|
|
15
|
+
|
|
16
|
+
const RETRY_SECONDS = 10;
|
|
17
|
+
const MAX_ATTEMPTS = 5;
|
|
18
|
+
|
|
19
|
+
type Payload =
|
|
20
|
+
| { readonly type: "model-usage"; readonly event: RuntimeModelUsageEvent }
|
|
21
|
+
| { readonly type: "tool-settlement"; readonly event: RuntimeToolSettlementEvent }
|
|
22
|
+
| { readonly type: "subagent-usage"; readonly event: RuntimeSubagentUsageEvent }
|
|
23
|
+
| { readonly type: "lifecycle"; readonly event: RuntimeLifecycleFact };
|
|
24
|
+
|
|
25
|
+
type RequestedModel = Parameters<typeof summarizeModelUsage>[0];
|
|
26
|
+
type SubagentRun = {
|
|
27
|
+
readonly runId: string;
|
|
28
|
+
readonly agentType: string;
|
|
29
|
+
readonly parentToolCallId?: string;
|
|
30
|
+
readonly startedAt: number;
|
|
31
|
+
readonly completedAt?: number;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/** Canonical Pi facts become durable Host events; delivery never drives Pi. */
|
|
35
|
+
export class RuntimeTurnEvents {
|
|
36
|
+
private drainTail?: Promise<void>;
|
|
37
|
+
|
|
38
|
+
constructor(private readonly options: {
|
|
39
|
+
readonly outbox: RuntimeEventOutboxRepository;
|
|
40
|
+
readonly transaction: <T>(run: () => T) => T;
|
|
41
|
+
readonly port: () => RuntimeTurnEventsPort | undefined;
|
|
42
|
+
readonly telemetry: Pick<RuntimeTelemetryCoordinator, "capture">;
|
|
43
|
+
readonly waitUntil: (promise: Promise<void>) => void;
|
|
44
|
+
readonly scheduleRetry: (delaySeconds: number, idempotent: boolean) => Promise<void>;
|
|
45
|
+
}) {}
|
|
46
|
+
|
|
47
|
+
private save(payload: Payload, createdAt: number): void {
|
|
48
|
+
this.options.transaction(() => this.options.outbox.insert({
|
|
49
|
+
eventId: payload.event.eventId,
|
|
50
|
+
body: JSON.stringify(payload),
|
|
51
|
+
createdAt,
|
|
52
|
+
}));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
submissionAdmitted(
|
|
56
|
+
submission: Pick<StoredSubmission, "submissionId" | "requestId" | "createdAt"> & { idempotencyKey?: string | null },
|
|
57
|
+
hostAccepted: boolean,
|
|
58
|
+
): void {
|
|
59
|
+
if (hostAccepted) this.save({ type: "lifecycle", event: {
|
|
60
|
+
kind: "submission-admitted",
|
|
61
|
+
eventId: `${submission.submissionId}:admitted`,
|
|
62
|
+
submissionId: submission.submissionId,
|
|
63
|
+
runId: submission.submissionId,
|
|
64
|
+
} }, submission.createdAt);
|
|
65
|
+
this.options.telemetry.capture("turnAdmitted", {
|
|
66
|
+
submissionId: submission.submissionId,
|
|
67
|
+
requestId: submission.requestId,
|
|
68
|
+
...(submission.idempotencyKey ? { idempotencyKey: submission.idempotencyKey } : {}),
|
|
69
|
+
occurredAt: submission.createdAt,
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
submissionTerminal(
|
|
74
|
+
submission: Pick<StoredSubmission, "submissionId" | "runId" | "status"> & { completedAt?: number | null },
|
|
75
|
+
): void {
|
|
76
|
+
if (submission.status === "pending" || submission.status === "running") {
|
|
77
|
+
throw new Error("Submission terminal fact requires a terminal status");
|
|
78
|
+
}
|
|
79
|
+
this.save({ type: "lifecycle", event: {
|
|
80
|
+
kind: "submission-terminal",
|
|
81
|
+
eventId: `${submission.submissionId}:terminal`,
|
|
82
|
+
submissionId: submission.submissionId,
|
|
83
|
+
runId: submission.runId ?? submission.submissionId,
|
|
84
|
+
status: submission.status,
|
|
85
|
+
childRegistrationClosed: true,
|
|
86
|
+
zeroUsage: !this.options.outbox.hasNonZeroModelUsage(submission.submissionId),
|
|
87
|
+
} }, submission.completedAt ?? Date.now());
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
private recordEntry(submissionId: string, entry: Entry, model: RequestedModel): void {
|
|
91
|
+
if (entry.type === "message" && entry.message.role === "assistant") {
|
|
92
|
+
this.save({ type: "model-usage", event: {
|
|
93
|
+
eventId: `${submissionId}:model:${entry.id}`,
|
|
94
|
+
submissionId,
|
|
95
|
+
runId: submissionId,
|
|
96
|
+
kind: "assistant",
|
|
97
|
+
...summarizeModelUsage(model, [entry.message]),
|
|
98
|
+
} }, entry.message.timestamp);
|
|
99
|
+
} else if (entry.type === "message" && entry.message.role === "toolResult") {
|
|
100
|
+
this.save({ type: "tool-settlement", event: {
|
|
101
|
+
eventId: `${submissionId}:tool:${entry.message.toolCallId}`,
|
|
102
|
+
submissionId,
|
|
103
|
+
toolCallId: entry.message.toolCallId,
|
|
104
|
+
toolName: entry.message.toolName,
|
|
105
|
+
status: entry.message.isError ? "error" : "success",
|
|
106
|
+
} }, entry.message.timestamp);
|
|
107
|
+
} else if (entry.type === "compaction" || entry.type === "branch_summary") {
|
|
108
|
+
if (entry.usage) {
|
|
109
|
+
this.save({ type: "model-usage", event: {
|
|
110
|
+
eventId: `${submissionId}:compaction:${entry.id}`,
|
|
111
|
+
submissionId,
|
|
112
|
+
runId: submissionId,
|
|
113
|
+
kind: "compaction",
|
|
114
|
+
api: model.api,
|
|
115
|
+
provider: model.provider,
|
|
116
|
+
model: model.id,
|
|
117
|
+
usage: entry.usage,
|
|
118
|
+
} }, entry.timestamp);
|
|
119
|
+
}
|
|
120
|
+
this.options.telemetry.capture("contextCompacted", {
|
|
121
|
+
submissionId,
|
|
122
|
+
compactionId: entry.id,
|
|
123
|
+
...(entry.usage ? {
|
|
124
|
+
inputTokens: entry.usage.input,
|
|
125
|
+
outputTokens: entry.usage.output,
|
|
126
|
+
} : {}),
|
|
127
|
+
summary: entry.summary,
|
|
128
|
+
occurredAt: entry.timestamp,
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Live observation and recovery use exactly the same committed-entry projection. */
|
|
134
|
+
observe(harness: Pick<AgentHarness, "events">, submissionId: string, model: RequestedModel): void {
|
|
135
|
+
harness.events.on("entry_added", ({ entry }) => {
|
|
136
|
+
this.recordEntry(submissionId, entry, model);
|
|
137
|
+
this.options.waitUntil(this.drain());
|
|
138
|
+
});
|
|
139
|
+
harness.events.on("tool_start", (event) => {
|
|
140
|
+
this.options.telemetry.capture("toolStarted", {
|
|
141
|
+
submissionId,
|
|
142
|
+
toolCallId: event.toolCallId,
|
|
143
|
+
toolName: event.toolName,
|
|
144
|
+
input: event.args,
|
|
145
|
+
});
|
|
146
|
+
});
|
|
147
|
+
harness.events.on("tool_end", (event) => {
|
|
148
|
+
this.options.telemetry.capture("toolFinished", {
|
|
149
|
+
submissionId,
|
|
150
|
+
toolCallId: event.toolCallId,
|
|
151
|
+
toolName: event.toolName,
|
|
152
|
+
outcome: event.isError ? "failed" : "completed",
|
|
153
|
+
output: event.result,
|
|
154
|
+
outputBytes: JSON.stringify(event.result).length,
|
|
155
|
+
});
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
backfill(
|
|
160
|
+
submissionId: string,
|
|
161
|
+
model: RequestedModel,
|
|
162
|
+
entries: readonly { readonly entry: Entry; readonly submissionId: string | null }[],
|
|
163
|
+
): void {
|
|
164
|
+
for (const stored of entries) {
|
|
165
|
+
if (stored.submissionId === submissionId) this.recordEntry(submissionId, stored.entry, model);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
private subagentLifecycle(input: { submissionId: string; parentRunId: string }): RuntimeSubagentLifecycleRecorder {
|
|
170
|
+
return new RuntimeSubagentLifecycleRecorder(input, {
|
|
171
|
+
save: async (event) => {
|
|
172
|
+
this.save(event.kind === "subagent"
|
|
173
|
+
? { type: "subagent-usage", event }
|
|
174
|
+
: { type: "lifecycle", event }, Date.now());
|
|
175
|
+
await this.drain();
|
|
176
|
+
},
|
|
177
|
+
has: (eventId) => this.options.outbox.has(eventId),
|
|
178
|
+
hasSubagentUsage: (submissionId, subagentRunId) =>
|
|
179
|
+
this.options.outbox.hasSubagentUsage(submissionId, subagentRunId),
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
async subagentStarted(metadata: RuntimeSubagentRunMetadata, run: SubagentRun): Promise<void> {
|
|
184
|
+
await this.subagentLifecycle(metadata).register(run.runId);
|
|
185
|
+
this.options.telemetry.capture("subagentStarted", {
|
|
186
|
+
submissionId: metadata.submissionId,
|
|
187
|
+
...(run.parentToolCallId ? { toolCallId: run.parentToolCallId } : {}),
|
|
188
|
+
subagentId: run.runId,
|
|
189
|
+
agentType: run.agentType,
|
|
190
|
+
occurredAt: run.startedAt,
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
async subagentFinished(metadata: RuntimeSubagentRunMetadata, run: SubagentRun, result: {
|
|
195
|
+
readonly status: string;
|
|
196
|
+
readonly summary?: string;
|
|
197
|
+
readonly error?: string;
|
|
198
|
+
readonly childStillRunning?: boolean;
|
|
199
|
+
}): Promise<void> {
|
|
200
|
+
const lifecycle = this.subagentLifecycle(metadata);
|
|
201
|
+
await lifecycle.register(run.runId);
|
|
202
|
+
if (result.status === "interrupted" && result.childStillRunning) return;
|
|
203
|
+
const completion = decodeSubagentCompletion(result.summary);
|
|
204
|
+
const hasUsage = completion && !isZeroSubagentUsage(completion.usage);
|
|
205
|
+
const status = subagentTerminalStatus(result.status);
|
|
206
|
+
if (completion && hasUsage) await lifecycle.usage({
|
|
207
|
+
eventId: `${run.runId}:usage`,
|
|
208
|
+
submissionId: metadata.submissionId,
|
|
209
|
+
runId: run.runId,
|
|
210
|
+
subagentRunId: run.runId,
|
|
211
|
+
parentRunId: metadata.parentRunId,
|
|
212
|
+
kind: "subagent",
|
|
213
|
+
status,
|
|
214
|
+
usage: completion.usage,
|
|
215
|
+
});
|
|
216
|
+
await lifecycle.terminal({ subagentRunId: run.runId, status, zeroUsage: !hasUsage });
|
|
217
|
+
const occurredAt = run.completedAt ?? Date.now();
|
|
218
|
+
this.options.telemetry.capture("subagentFinished", {
|
|
219
|
+
submissionId: metadata.submissionId,
|
|
220
|
+
...(run.parentToolCallId ? { toolCallId: run.parentToolCallId } : {}),
|
|
221
|
+
subagentId: run.runId,
|
|
222
|
+
outcome: status === "completed" ? "completed"
|
|
223
|
+
: status === "aborted" || status === "skipped" ? "cancelled" : "failed",
|
|
224
|
+
durationMs: Math.max(0, occurredAt - run.startedAt),
|
|
225
|
+
...(completion ? { output: completion.output } : {}),
|
|
226
|
+
...(result.error ? { error: result.error } : {}),
|
|
227
|
+
occurredAt,
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
drain(idempotentRetry = true): Promise<void> {
|
|
232
|
+
const drain = (this.drainTail ?? Promise.resolve())
|
|
233
|
+
.catch(() => undefined)
|
|
234
|
+
.then(() => this.deliver(idempotentRetry));
|
|
235
|
+
this.drainTail = drain;
|
|
236
|
+
return drain.finally(() => {
|
|
237
|
+
if (this.drainTail === drain) this.drainTail = undefined;
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
private async deliver(idempotentRetry: boolean): Promise<void> {
|
|
242
|
+
const port = this.options.port();
|
|
243
|
+
if (!port) return;
|
|
244
|
+
for (const row of this.options.outbox.listPending()) {
|
|
245
|
+
try {
|
|
246
|
+
const payload = JSON.parse(row.body) as Payload;
|
|
247
|
+
if (payload.type === "model-usage") {
|
|
248
|
+
await port.onModelUsage?.(payload.event);
|
|
249
|
+
} else if (payload.type === "tool-settlement") {
|
|
250
|
+
await port.onToolSettled?.(payload.event);
|
|
251
|
+
} else if (payload.type === "subagent-usage") {
|
|
252
|
+
if (port.onSubagentUsage && (await port.onSubagentUsage(payload.event))?.confirmed !== true) {
|
|
253
|
+
throw new Error("Runtime event was not confirmed");
|
|
254
|
+
}
|
|
255
|
+
} else if (port.onLifecycleFact && (await port.onLifecycleFact(payload.event))?.confirmed !== true) {
|
|
256
|
+
throw new Error("Runtime event was not confirmed");
|
|
257
|
+
}
|
|
258
|
+
this.options.transaction(() => this.options.outbox.markDelivered(row.eventId, Date.now()));
|
|
259
|
+
} catch (error) {
|
|
260
|
+
const failure = error instanceof Error ? error.message : String(error);
|
|
261
|
+
const attemptCount = this.options.transaction(() => {
|
|
262
|
+
const count = this.options.outbox.markFailed(row.eventId, failure);
|
|
263
|
+
if (count >= MAX_ATTEMPTS) this.options.outbox.quarantine(row.eventId, Date.now(), failure);
|
|
264
|
+
return count;
|
|
265
|
+
});
|
|
266
|
+
console.warn(attemptCount >= MAX_ATTEMPTS
|
|
267
|
+
? "[runtime-turn-event:quarantined]"
|
|
268
|
+
: "[runtime-turn-event:degraded]", JSON.stringify({ eventId: row.eventId, attemptCount, error: failure }));
|
|
269
|
+
if (attemptCount >= MAX_ATTEMPTS) continue;
|
|
270
|
+
try {
|
|
271
|
+
await this.options.scheduleRetry(RETRY_SECONDS, idempotentRetry);
|
|
272
|
+
} catch (error) {
|
|
273
|
+
console.warn("[runtime-turn-event-retry:degraded]", String(error));
|
|
274
|
+
}
|
|
275
|
+
break;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# Runtime Tools
|
|
2
|
+
|
|
3
|
+
工具按功能归组。根 `index.ts` 只维护包内统一导出;功能目录的 `index.ts` 定义或组合该功能的 Pi Tool。
|
|
4
|
+
|
|
5
|
+
| 目录 | 职责 |
|
|
6
|
+
| --- | --- |
|
|
7
|
+
| `runtime/` | 公共工具契约、Harness 编译、执行决策、审批与客户端交互结算 |
|
|
8
|
+
| `adapters/` | AI SDK ↔ Pi 转换,以及外部工具声明到 Pi Candidate 的适配 |
|
|
9
|
+
| `codemode/` | `execute` 和 `browser_execute` 的 Pi Tool 定义、Cloudflare 执行适配、Workspace Connector |
|
|
10
|
+
| `assistant/` | 用户问答、计划、后续建议、记忆与时间工具 |
|
|
11
|
+
| `workspace/` | 持久 Workspace 文件操作、写入串行化与版本操作工具 |
|
|
12
|
+
| `sandbox/` | 临时 Linux Sandbox 的命令、进程和显式文件发布工具 |
|
|
13
|
+
| `skill/` | Skill 工具组合、资源读取与复制、脚本运行与输出投影 |
|
|
14
|
+
| `subagent/` | 子 Agent 工具、权限、运行记录、类型和临时 Agent 协调 |
|
|
15
|
+
| `schedule/` | 定时任务的 Pi Tool 定义 |
|
|
16
|
+
| `web/` | 网页获取与 Provider-native 搜索 |
|
|
17
|
+
| `mcp/` | MCP Tool 接入及使用 MCP Session 的 Connector Gateway |
|
|
18
|
+
| `extension/` | 已加载 Extension 的发现工具;Extension 装载仍归 `context/extension/` |
|
|
19
|
+
|
|
20
|
+
## Code Mode
|
|
21
|
+
|
|
22
|
+
```text
|
|
23
|
+
codemode/index.ts Pi Tool 定义、执行级别与调用截止
|
|
24
|
+
|
|
|
25
|
+
v
|
|
26
|
+
RuntimeCodeExecutionPort 内部执行接口
|
|
27
|
+
|
|
|
28
|
+
v
|
|
29
|
+
codemode/adapter.ts Cloudflare 执行器组装、描述与结果适配
|
|
30
|
+
|
|
|
31
|
+
+-- workspace-connector.ts state.* 方法、发现与校验
|
|
32
|
+
+-- ../adapters/pi-to-ai.ts 现有 Pi 工具到 Cloudflare ToolSet 的转换
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
`pi-to-ai.ts` 也被 Skill 脚本执行使用,因此放在共用 `adapters/` 中。工具声明仍以 Pi 为唯一事实源。
|
|
36
|
+
|
|
37
|
+
## 修改位置
|
|
38
|
+
|
|
39
|
+
- 修改某个工具:进入对应功能目录,测试与实现放在一起。
|
|
40
|
+
- 修改所有工具共用的执行策略:进入 `runtime/`,不要复制到每个工具。
|
|
41
|
+
- 修改外部协议转换:进入 `adapters/`,不新增另一份工具定义。
|
|
42
|
+
- 小功能可以只有 `index.ts`,不强制拆分 Adapter、Service 或 Repository。
|
|
43
|
+
- `runtime/result.ts` 只共享结果包装与进度报告;`assistant/candidate.ts` 只共享助手工具已有的元数据默认值。
|
|
44
|
+
- 包的公共导出名及 `@springbrand/agent-runtime/declared-tool` 子路径保持不变。内部路径变更需要同步 Vitest 测试池配置。
|
|
@@ -1,11 +1,8 @@
|
|
|
1
1
|
// 本文件把 ai-sdk Tool 转成 Pi AgentTool。
|
|
2
2
|
// `@cloudflare/think`、Agents Skills 和 Workspace 等上游工厂生成 ai-sdk Tool 时调用这个边界。
|
|
3
|
-
// 转换只保留在这里,才能让后续治理和结算始终看到同一种 AgentTool 结果;核心术语见
|
|
3
|
+
// 转换只保留在这里,才能让后续治理和结算始终看到同一种 AgentTool 结果;核心术语见 `src/index.ts` 入口说明。
|
|
4
4
|
|
|
5
|
-
import type {
|
|
6
|
-
AgentTool,
|
|
7
|
-
AgentToolResult,
|
|
8
|
-
} from "@earendil-works/pi-agent-core";
|
|
5
|
+
import type { AgentTool, AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
9
6
|
import { asSchema, type Tool as AiTool } from "ai";
|
|
10
7
|
import { serializeOutput } from "../../lib/artifacts";
|
|
11
8
|
|
|
@@ -87,7 +84,7 @@ function modelContent(
|
|
|
87
84
|
/**
|
|
88
85
|
* 把一个可执行的 ai-sdk Tool 转成 Pi AgentTool。
|
|
89
86
|
*
|
|
90
|
-
* Workspace、Skill 和其他 ai-sdk 工具工厂在把候选项交给 `
|
|
87
|
+
* Workspace、Skill 和其他 ai-sdk 工具工厂在把候选项交给 `compileHarnessTools()` 前调用。
|
|
91
88
|
*
|
|
92
89
|
* 实现必须在一处同时对齐 schema、execute 参数和结果形状,否则 Pi 的校验、取消信号和 artifact 处理会绕过统一工具边界。
|
|
93
90
|
*
|
|
@@ -141,9 +138,9 @@ export function aiToolToPi(
|
|
|
141
138
|
.toModelOutput;
|
|
142
139
|
const content = typeof toModelOutput === "function"
|
|
143
140
|
? modelContent(await (toModelOutput as (input: {
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
141
|
+
input: unknown;
|
|
142
|
+
output: unknown;
|
|
143
|
+
}) => unknown)({ input: params, output: raw }))
|
|
147
144
|
: null;
|
|
148
145
|
return {
|
|
149
146
|
content: content ?? [{
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { AgentTool, AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
2
|
-
import type { PiToolCandidate } from "
|
|
2
|
+
import type { PiToolCandidate } from "../runtime/contracts";
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* 一个由 Runtime 之外声明、由 Runtime 之外执行的工具。
|
|
@@ -15,7 +15,7 @@ import type { PiToolCandidate } from "./compiler";
|
|
|
15
15
|
* 本模块只引入类型,因此可经 `@springbrand/agent-runtime/declared-tool` 单独导入:
|
|
16
16
|
* 声明方在 Node 下也能装配自己的工具,不必为此加载 Workers 运行时。
|
|
17
17
|
*
|
|
18
|
-
* `Pi`、`Tool Candidate` 与 `Runtime` 等核心术语见
|
|
18
|
+
* `Pi`、`Tool Candidate` 与 `Runtime` 等核心术语见 `src/index.ts`。
|
|
19
19
|
*/
|
|
20
20
|
export interface PiDeclaredTool {
|
|
21
21
|
/** 声明方自己的工具名,用于结果详情与诊断,不一定是模型看到的名字。 */
|
|
@@ -49,6 +49,7 @@ export interface PiDeclaredToolPolicy<Reply = unknown> {
|
|
|
49
49
|
readonly modelName: string;
|
|
50
50
|
readonly requiredExecutionLevel: PiToolCandidate["requiredExecutionLevel"];
|
|
51
51
|
readonly requiredExecutionLevelForInput?: PiToolCandidate["requiredExecutionLevelForInput"];
|
|
52
|
+
readonly unattendedExecution?: PiToolCandidate["unattendedExecution"];
|
|
52
53
|
readonly exposureMode?: PiToolCandidate["exposureMode"];
|
|
53
54
|
readonly retry?: PiToolCandidate["retry"];
|
|
54
55
|
readonly source?: PiToolCandidate["source"];
|
|
@@ -117,6 +118,9 @@ export function createPiDeclaredToolCandidate<Reply = unknown>(
|
|
|
117
118
|
...(policy.requiredExecutionLevelForInput
|
|
118
119
|
? { requiredExecutionLevelForInput: policy.requiredExecutionLevelForInput }
|
|
119
120
|
: {}),
|
|
121
|
+
...(policy.unattendedExecution
|
|
122
|
+
? { unattendedExecution: policy.unattendedExecution }
|
|
123
|
+
: {}),
|
|
120
124
|
...(policy.exposureMode ? { exposureMode: policy.exposureMode } : {}),
|
|
121
125
|
...(policy.retry ? { retry: policy.retry } : {}),
|
|
122
126
|
...(policy.source ? { source: policy.source } : {}),
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
2
2
|
import { validateToolArguments } from "@earendil-works/pi-ai";
|
|
3
|
-
import {
|
|
4
|
-
import type { PiToolCandidate } from "
|
|
3
|
+
import { tool as aiTool, jsonSchema, type ToolSet } from "ai";
|
|
4
|
+
import type { PiToolCandidate } from "../runtime/contracts";
|
|
5
5
|
|
|
6
6
|
interface NestedToolOptions {
|
|
7
7
|
readonly fallbackToolCallId?: (name: string) => string;
|