@springbrand/agent-runtime 0.3.0-alpha.2 → 0.3.0-alpha.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/package.json +11 -9
  2. package/src/adapter/cloudflare/agent.ts +233 -179
  3. package/src/adapter/cloudflare/define-agent.ts +252 -104
  4. package/src/adapter/cloudflare/index.ts +18 -0
  5. package/src/adapter/cloudflare/scheduling/schedule-rule.ts +322 -0
  6. package/src/adapter/cloudflare/scheduling/zoned-cron.ts +11 -6
  7. package/src/adapter/cloudflare/schema.ts +21 -2
  8. package/src/adapter/cloudflare/subagent/definition.ts +25 -13
  9. package/src/adapter/cloudflare/subagent/runner.ts +43 -50
  10. package/src/adapter/cloudflare/subagent/tools.ts +4 -4
  11. package/src/adapter/cloudflare/universal-agent/preparation.ts +3 -3
  12. package/src/adapter/cloudflare/universal-agent/tools.ts +4 -6
  13. package/src/adapter/cloudflare/workspace/version-control.ts +1 -1
  14. package/src/config/activation.ts +13 -15
  15. package/src/config/agent-context.ts +1 -1
  16. package/src/config/assembler.ts +48 -31
  17. package/src/config/assembly-snapshot.ts +1 -1
  18. package/src/config/definition.ts +1 -1
  19. package/src/config/harness-runtime.ts +77 -49
  20. package/src/config/index.ts +1 -1
  21. package/src/config/model-guidance.ts +20 -0
  22. package/src/config/ports.ts +57 -7
  23. package/src/config/{pinning.ts → prepared-runtime.ts} +59 -123
  24. package/src/config/public-contracts.ts +2 -2
  25. package/src/config/runtime-config.ts +2 -1
  26. package/src/context/assembly.ts +1 -1
  27. package/src/context/extension/assembly.ts +2 -2
  28. package/src/context/memory/budget/gate.ts +19 -3
  29. package/src/conversation/harness-resume.ts +89 -238
  30. package/src/conversation/harness-stream.ts +87 -71
  31. package/src/conversation/history.ts +154 -152
  32. package/src/conversation/message/contract.ts +28 -4
  33. package/src/conversation/message/conversion.ts +46 -5
  34. package/src/conversation/message/projection.ts +61 -21
  35. package/src/conversation/session-entry.ts +29 -0
  36. package/src/conversation/state.ts +23 -2
  37. package/src/harness/governance.ts +206 -0
  38. package/src/harness/index.ts +3 -0
  39. package/src/harness/session-harness.ts +269 -445
  40. package/src/harness/submission-operation.ts +15 -40
  41. package/src/index.ts +18 -8
  42. package/src/lib/artifacts.ts +18 -0
  43. package/src/lib/execution-level.ts +13 -0
  44. package/src/lib/prompt.ts +9 -10
  45. package/src/lib/token-estimate.ts +8 -0
  46. package/src/model-protocol/openrouter.ts +41 -0
  47. package/src/models/index.ts +200 -35
  48. package/src/models/openrouter/messages.ts +13 -8
  49. package/src/models/openrouter/openai.ts +200 -0
  50. package/src/models/openrouter/protocol-response.ts +85 -0
  51. package/src/models/provider-streams.ts +45 -0
  52. package/src/session/cloudflare/migration.ts +382 -864
  53. package/src/session/cloudflare/storage.ts +13 -536
  54. package/src/session/index.ts +22 -35
  55. package/src/skills/springbrand-worker-website/index.ts +1 -1
  56. package/src/submission/admission.ts +20 -30
  57. package/src/submission/contracts.ts +42 -2
  58. package/src/submission/delivery.ts +1 -1
  59. package/src/submission/finalization.ts +36 -15
  60. package/src/submission/lifecycle.ts +28 -15
  61. package/src/submission/repository.ts +97 -49
  62. package/src/submission/steer-delivery.ts +32 -76
  63. package/src/submission/unattended.ts +40 -0
  64. package/src/telemetry/contract.ts +0 -1
  65. package/src/telemetry/coordinator.ts +1 -1
  66. package/src/telemetry/runtime-telemetry.ts +0 -4
  67. package/src/telemetry/subagent-lifecycle.ts +1 -1
  68. package/src/telemetry/turn-events.ts +35 -25
  69. package/src/tools/README.md +44 -0
  70. package/src/tools/{ai-adapter.ts → adapters/ai-to-pi.ts} +6 -9
  71. package/src/tools/{declared.ts → adapters/declared.ts} +6 -2
  72. package/src/tools/{nested-tools.ts → adapters/pi-to-ai.ts} +4 -4
  73. package/src/tools/assistant/ask-user.ts +319 -0
  74. package/src/tools/assistant/candidate.ts +15 -0
  75. package/src/tools/assistant/followups.ts +34 -0
  76. package/src/tools/assistant/index.ts +19 -0
  77. package/src/tools/assistant/memory.ts +73 -0
  78. package/src/tools/assistant/plan.ts +98 -0
  79. package/src/tools/{time.ts → assistant/time.ts} +1 -1
  80. package/src/tools/{core-host.ts → codemode/adapter.ts} +50 -53
  81. package/src/tools/{core.ts → codemode/index.ts} +36 -92
  82. package/src/tools/codemode/workspace-connector.ts +198 -0
  83. package/src/tools/extension/index.ts +42 -0
  84. package/src/tools/index.ts +29 -26
  85. package/src/tools/{gateway.ts → mcp/gateway.ts} +19 -19
  86. package/src/tools/{mcp.ts → mcp/index.ts} +5 -5
  87. package/src/tools/runtime/activation.ts +40 -0
  88. package/src/tools/{approval → runtime/approval}/repository.ts +13 -12
  89. package/src/tools/runtime/compiler.ts +246 -0
  90. package/src/tools/runtime/contracts.ts +140 -0
  91. package/src/tools/{decision-gate.ts → runtime/decision-gate.ts} +149 -39
  92. package/src/tools/{human-decisions.ts → runtime/human-decisions.ts} +4 -4
  93. package/src/tools/{interaction → runtime/interaction}/repository.ts +1 -7
  94. package/src/tools/runtime/result.ts +22 -0
  95. package/src/tools/runtime/unattended-error.ts +4 -0
  96. package/src/tools/sandbox/index.ts +228 -0
  97. package/src/tools/schedule/index.ts +301 -0
  98. package/src/tools/skill/contracts.ts +20 -0
  99. package/src/tools/skill/index.ts +99 -0
  100. package/src/tools/skill/resources.ts +322 -0
  101. package/src/tools/skill/scripts.ts +168 -0
  102. package/src/tools/{subagent-authority.ts → subagent/authority.ts} +31 -31
  103. package/src/tools/{subagent.ts → subagent/index.ts} +34 -37
  104. package/src/tools/{subagent-run-repository.ts → subagent/repository.ts} +1 -1
  105. package/src/tools/{subagent-runtime.ts → subagent/runtime.ts} +1 -1
  106. package/src/tools/{temporary-agent → subagent/temporary}/approvals.ts +4 -7
  107. package/src/tools/{temporary-agent → subagent/temporary}/core.ts +2 -3
  108. package/src/tools/{temporary-agent → subagent/temporary}/runner.ts +1 -1
  109. package/src/tools/{temporary-agent → subagent/temporary}/workspace.ts +1 -4
  110. package/src/tools/{web-fetch.ts → web/fetch.ts} +4 -13
  111. package/src/tools/web/index.ts +2 -0
  112. package/src/tools/web/search/api.ts +1322 -0
  113. package/src/tools/web/search/index.ts +2 -0
  114. package/src/tools/{web-search/web-search.ts → web/search/search.ts} +5 -7
  115. package/src/tools/{workspace-sandbox.ts → workspace/index.ts} +12 -272
  116. package/src/tools/{workspace-revision.ts → workspace/revision.ts} +3 -3
  117. package/src/tools/base.ts +0 -534
  118. package/src/tools/compiler.ts +0 -327
  119. package/src/tools/schedule.ts +0 -261
  120. package/src/tools/skill.ts +0 -565
  121. package/src/tools/web-search/api.ts +0 -1318
  122. package/src/tools/web-search/index.ts +0 -2
  123. package/src/tools/workspace-state-connector.ts +0 -146
  124. package/src/tools/{approval → runtime/approval}/index.ts +0 -0
  125. package/src/tools/{interaction → runtime/interaction}/index.ts +0 -0
  126. package/src/tools/{temporary-agent → subagent/temporary}/coordinator.ts +0 -0
  127. package/src/tools/{subagent-types → subagent/types}/contract.ts +0 -0
  128. package/src/tools/{subagent-types → subagent/types}/extract/index.ts +0 -0
  129. package/src/tools/{subagent-types → subagent/types}/fanout/index.ts +0 -0
  130. package/src/tools/{subagent-types → subagent/types}/registry.ts +1 -1
  131. /package/src/tools/{workspace-versioning.ts → workspace/versioning.ts} +0 -0
@@ -1,21 +1,25 @@
1
- import type {
2
- AgentToolResult,
3
- HookHandler,
4
- } from "@earendil-works/pi-agent-core";
5
- import type { ExecutionLevel } from "../lib/execution-level";
1
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
2
+ import type { ExecutionLevel } from "../../lib/execution-level";
6
3
  import {
7
4
  EXECUTION_LEVELS,
5
+ minExecutionLevel,
8
6
  requiresExecutionApproval,
9
- } from "../lib/execution-level";
10
- import type { PiToolCandidate } from "./compiler";
7
+ } from "../../lib/execution-level";
8
+ import type { RuntimeTelemetryCoordinator } from "../../telemetry/coordinator";
11
9
  import type { ApprovalRepository } from "./approval";
10
+ import type { PiToolCandidate } from "./contracts";
12
11
  import type { ToolInteractionRepository } from "./interaction";
13
- import type { RuntimeTelemetryCoordinator } from "../telemetry/coordinator";
12
+ import { UnattendedExecutionError } from "./unattended-error";
14
13
 
15
14
  export interface HarnessDecisionSubmission {
16
15
  readonly submissionId: string;
17
16
  readonly requestId: string;
18
17
  readonly executionLevel: ExecutionLevel;
18
+ readonly origin?: "user" | "scheduled";
19
+ /** Maximum level allowed by the owning Schedule Definition. */
20
+ readonly scheduledMaxExecutionLevel?: ExecutionLevel;
21
+ /** @deprecated Retained for rolling upgrades; ignored by the decision gate. */
22
+ readonly unattendedExecutionGrant?: unknown;
19
23
  }
20
24
 
21
25
  export interface HarnessDecisionGateOptions {
@@ -37,6 +41,10 @@ export interface HarnessDecisionGateOptions {
37
41
  readonly requiredExecutionLevel: ExecutionLevel;
38
42
  readonly signal: AbortSignal;
39
43
  }) => void | Promise<void>;
44
+ /** @deprecated Scheduled authorization is local and never calls this hook. */
45
+ readonly authorizeUnattendedExecution?: (input: unknown) => void | Promise<void>;
46
+ readonly onUnattendedFailure?: (reason: string) => void | Promise<void>;
47
+ readonly unattendedFailure?: () => string | null | undefined;
40
48
  }
41
49
 
42
50
  function waitForRelease(signal: AbortSignal): Promise<never> {
@@ -78,36 +86,44 @@ export class HarnessDecisionGate {
78
86
  );
79
87
  }
80
88
 
81
- readonly beforeTool: HookHandler<"before_tool"> = async (event, context) => {
89
+ readonly beforeTool = async (event: { toolName: string; toolCallId: string; args: unknown }, context: import("@earendil-works/chord").Context): Promise<{ block: string } | undefined> => {
82
90
  const candidate = this.candidates.get(event.toolName);
83
91
  if (!candidate) return undefined;
84
- const requiredExecutionLevel = candidate.requiredExecutionLevelForInput
85
- ? await candidate.requiredExecutionLevelForInput(event.args)
86
- : candidate.requiredExecutionLevel;
87
- if (!EXECUTION_LEVELS.includes(requiredExecutionLevel)) {
88
- throw new Error(
89
- `SpringBrand Tool "${event.toolName}" resolved an invalid execution level`,
90
- );
92
+ let requiredExecutionLevel: ExecutionLevel;
93
+ try {
94
+ requiredExecutionLevel = await this.resolveExecutionLevel(candidate, event.args);
95
+ } catch (error) {
96
+ if (!(error instanceof UnattendedExecutionError)) throw error;
97
+ return { block: error.message };
91
98
  }
99
+ const effectiveLevel = this.effectiveExecutionLevel();
100
+ const needsApproval = candidate.alwaysRequiresApproval ||
101
+ requiresExecutionApproval(effectiveLevel, requiredExecutionLevel);
92
102
  const executionId = `${this.options.submission.submissionId}:${event.toolCallId}`;
103
+ let unattendedAuthorized = false;
104
+ try {
105
+ unattendedAuthorized = await this.authorizeUnattended(candidate, event.args, {
106
+ toolCallId: event.toolCallId,
107
+ signal: operationSignal(context.abortSignal),
108
+ }, requiredExecutionLevel);
109
+ } catch (error) {
110
+ if (!(error instanceof UnattendedExecutionError)) throw error;
111
+ return { block: error.message };
112
+ }
93
113
  const existing = this.options.approvals.find(executionId);
114
+ if (existing && (existing.requestId !== this.options.submission.requestId ||
115
+ existing.toolName !== event.toolName || existing.inputJson !== stableInput(event.args))) {
116
+ throw new Error(`Conflicting durable Tool approval: ${event.toolCallId}`);
117
+ }
94
118
  if (existing?.status === "rejected") {
95
- return { block: { reason: existing.reason ?? "Tool execution denied by user" } };
119
+ return { block: existing.reason ?? "Tool execution denied by user" };
96
120
  }
97
- const needsApproval = candidate.alwaysRequiresApproval ||
98
- requiresExecutionApproval(
99
- this.options.submission.executionLevel,
100
- requiredExecutionLevel,
101
- );
102
- if (needsApproval && existing?.status !== "approved") {
103
- if (existing && (
104
- existing.requestId !== this.options.submission.requestId ||
105
- existing.toolName !== event.toolName ||
106
- existing.inputJson !== stableInput(event.args)
107
- )) {
108
- throw new Error(`Conflicting durable Tool approval: ${event.toolCallId}`);
109
- }
121
+ if (needsApproval && !unattendedAuthorized && existing?.status !== "approved") {
110
122
  if (!existing) {
123
+ const prepared = candidate.confirmation
124
+ ? await candidate.confirmation.prepare(event.args, { intentId: executionId })
125
+ : undefined;
126
+ operationSignal(context.abortSignal).throwIfAborted();
111
127
  const createdAt = Date.now();
112
128
  this.options.transaction(() => this.options.approvals.insert({
113
129
  executionId,
@@ -120,6 +136,7 @@ export class HarnessDecisionGate {
120
136
  executionLevel: this.options.submission.executionLevel,
121
137
  requiredExecutionLevel,
122
138
  inputJson: stableInput(event.args),
139
+ confirmationJson: prepared === undefined ? null : JSON.stringify(prepared),
123
140
  status: "pending",
124
141
  createdAt,
125
142
  }));
@@ -181,16 +198,109 @@ export class HarnessDecisionGate {
181
198
  args: unknown,
182
199
  invocation: { readonly toolCallId: string; readonly signal: AbortSignal },
183
200
  ): Promise<void> {
184
- const requiredExecutionLevel = candidate.requiredExecutionLevelForInput
185
- ? await candidate.requiredExecutionLevelForInput(args)
186
- : candidate.requiredExecutionLevel;
187
- await this.options.gateTool?.({
188
- toolCallId: invocation.toolCallId,
189
- toolName: candidate.tool.name,
190
- input: args,
201
+ const requiredExecutionLevel = await this.resolveExecutionLevel(candidate, args);
202
+ await this.authorizeUnattended(
203
+ candidate,
204
+ args,
205
+ invocation,
191
206
  requiredExecutionLevel,
192
- signal: invocation.signal,
193
- });
207
+ );
208
+ try {
209
+ await this.options.gateTool?.({
210
+ toolCallId: invocation.toolCallId,
211
+ toolName: candidate.tool.name,
212
+ input: args,
213
+ requiredExecutionLevel,
214
+ signal: invocation.signal,
215
+ });
216
+ } catch (error) {
217
+ if (this.options.submission.origin !== "scheduled") throw error;
218
+ const reason = error instanceof Error ? error.message : String(error);
219
+ await this.denyUnattended(
220
+ `Unattended execution denied for ${candidate.tool.name}: ${reason}`,
221
+ );
222
+ }
223
+ this.assertUnattendedActive();
224
+ }
225
+
226
+ private assertUnattendedActive(): void {
227
+ if (this.options.submission.origin !== "scheduled") return;
228
+ const failure = this.options.unattendedFailure?.();
229
+ if (failure) throw new UnattendedExecutionError(failure);
230
+ }
231
+
232
+ private effectiveExecutionLevel(): ExecutionLevel {
233
+ const submission = this.options.submission;
234
+ const ceiling = submission.origin === "scheduled"
235
+ ? submission.scheduledMaxExecutionLevel ?? "high"
236
+ : submission.executionLevel;
237
+ return minExecutionLevel(submission.executionLevel, ceiling);
238
+ }
239
+
240
+ private async resolveExecutionLevel(candidate: PiToolCandidate, input: unknown): Promise<ExecutionLevel> {
241
+ this.assertUnattendedActive();
242
+ try {
243
+ const level = candidate.requiredExecutionLevelForInput
244
+ ? await candidate.requiredExecutionLevelForInput(input)
245
+ : candidate.requiredExecutionLevel;
246
+ if (!EXECUTION_LEVELS.includes(level)) {
247
+ throw new Error(`SpringBrand Tool "${candidate.tool.name}" resolved an invalid execution level`);
248
+ }
249
+ return level;
250
+ } catch (error) {
251
+ if (this.options.submission.origin !== "scheduled") throw error;
252
+ const reason = error instanceof Error ? error.message : String(error);
253
+ return this.denyUnattended(
254
+ `SCHEDULED_EXECUTION_RISK_CHECK_FAILED: ${candidate.tool.name}: ${reason}`,
255
+ );
256
+ }
257
+ }
258
+
259
+ private async authorizeUnattended(
260
+ candidate: PiToolCandidate,
261
+ input: unknown,
262
+ invocation: { readonly toolCallId: string; readonly signal: AbortSignal },
263
+ requiredExecutionLevel: ExecutionLevel,
264
+ ): Promise<boolean> {
265
+ if (this.options.submission.origin !== "scheduled") return false;
266
+ this.assertUnattendedActive();
267
+ if (candidate.interaction) {
268
+ return this.denyUnattended(
269
+ `SCHEDULED_EXECUTION_REQUIRES_INTERACTION: ${candidate.tool.name}`,
270
+ );
271
+ }
272
+ if (candidate.alwaysRequiresApproval) {
273
+ return this.denyUnattended(
274
+ `SCHEDULED_EXECUTION_ALWAYS_REQUIRES_APPROVAL: ${candidate.tool.name}`,
275
+ );
276
+ }
277
+ if (candidate.unattendedMode === "forbidden") {
278
+ return this.denyUnattended(
279
+ `SCHEDULED_EXECUTION_FORBIDDEN: ${candidate.tool.name}`,
280
+ );
281
+ }
282
+ const effectiveLevel = this.effectiveExecutionLevel();
283
+ if (requiresExecutionApproval(effectiveLevel, requiredExecutionLevel)) {
284
+ return this.denyUnattended(
285
+ `SCHEDULED_EXECUTION_LEVEL_EXCEEDED: ${candidate.tool.name} requires ${requiredExecutionLevel}; effective level is ${effectiveLevel}`,
286
+ );
287
+ }
288
+ return true;
289
+ }
290
+
291
+ private async denyUnattended(reason: string): Promise<never> {
292
+ await this.options.onUnattendedFailure?.(reason);
293
+ throw new UnattendedExecutionError(reason);
294
+ }
295
+
296
+ resolveConfirmation(candidate: PiToolCandidate, toolCallId: string, args: unknown): { prepared: unknown; intentId: string } {
297
+ const intentId = `${this.options.submission.submissionId}:${toolCallId}`;
298
+ const approval = this.options.approvals.find(intentId);
299
+ if (!approval || approval.status !== "approved" || !approval.confirmationJson ||
300
+ approval.toolName !== candidate.tool.name || approval.inputJson !== stableInput(args)) {
301
+ throw new Error("Matching user confirmation is required");
302
+ }
303
+ return { prepared: JSON.parse(approval.confirmationJson), intentId };
194
304
  }
195
305
 
196
306
  resolveReplay(
@@ -1,7 +1,7 @@
1
- import type { ApprovalDecision } from "../submission/contracts";
2
- import type { RuntimeTelemetryCoordinator } from "../telemetry/coordinator";
1
+ import type { ApprovalDecision } from "../../submission/contracts";
2
+ import type { RuntimeTelemetryCoordinator } from "../../telemetry/coordinator";
3
3
  import type { ApprovalRepository } from "./approval/repository";
4
- import type { PiToolInteractionSpec } from "./compiler";
4
+ import type { PiToolInteractionSpec } from "./contracts";
5
5
  import type { StoredToolInteraction, ToolInteractionRepository } from "./interaction/repository";
6
6
 
7
7
  /** Human decisions own validation and durable facts; the caller resumes Pi. */
@@ -12,7 +12,7 @@ export class HarnessHumanDecisions {
12
12
  readonly transaction: <T>(run: () => T) => T;
13
13
  readonly isSubmissionActive: (submissionId: string) => boolean;
14
14
  readonly telemetry: Pick<RuntimeTelemetryCoordinator, "capture">;
15
- }) {}
15
+ }) { }
16
16
 
17
17
  isWaitingForApproval(submissionId: string): boolean {
18
18
  return this.options.approvals.listPendingForSubmission(submissionId).length > 0;
@@ -1,7 +1,6 @@
1
1
  import type { SqlTaggedTemplate } from "agents/chat";
2
2
 
3
3
  // Tool Interaction 的统一定义见 ./index.ts。
4
- // #region 状态与行类型
5
4
  export type ToolInteractionStatus = "pending" | "responded" | "cancelled";
6
5
 
7
6
  export interface StoredToolInteraction {
@@ -41,8 +40,6 @@ type ToolInteractionRow = {
41
40
  responded_at: number | null;
42
41
  };
43
42
 
44
- // #endregion
45
- // #region 行映射
46
43
  // 把 SQLite 的 Interaction 行转成 Runtime 对象。
47
44
  // find 与 findPending* 查到记录后调用,上层因而不需要理解 snake_case 列名。
48
45
  // 状态由表内字符串转成联合类型;新增列或状态时必须同步核对类型、SELECT 和映射。
@@ -61,13 +58,11 @@ function mapRow(row: ToolInteractionRow): StoredToolInteraction {
61
58
  };
62
59
  }
63
60
 
64
- // #endregion
65
- // #region Repository
66
61
  export class ToolInteractionRepository {
67
62
  // 保存当前 Agent SQLite 的查询入口。
68
63
  // RuntimeDatabase 构造时调用,InteractionLifecycle 随后共享这个 Repository。
69
64
  // Interaction 必须与所属 Submission 在同一 Agent 存储中查询,不能跨 Durable Object 拼接状态。
70
- constructor(private readonly sql: SqlTaggedTemplate) {}
65
+ constructor(private readonly sql: SqlTaggedTemplate) { }
71
66
 
72
67
  // 按 interactionId 读取一条完整 Interaction,不存在时返回 null。
73
68
  // InteractionLifecycle 在请求去重、响应、取消和收尾时调用,调用方必须处理 null。
@@ -182,4 +177,3 @@ export class ToolInteractionRepository {
182
177
  `.map(mapRow);
183
178
  }
184
179
  }
185
- // #endregion
@@ -0,0 +1,22 @@
1
+ import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
2
+ import { serializeOutput } from "../../lib/artifacts";
3
+
4
+ export function result<T>(details: T): AgentToolResult<T> {
5
+ return {
6
+ content: [{ type: "text", text: serializeOutput(details).text }],
7
+ details,
8
+ };
9
+ }
10
+ // 作用:向 Pi 报告一次 Workspace 或 Sandbox 操作已经开始。
11
+ // 调用:可能访问存储或容器的 execute 方法在进入 Port 前调用。
12
+ // 原因:复用统一的 running 结果形状,
13
+ // 让长操作有进度反馈而不复制回调协议。
14
+ export function running(
15
+ onUpdate: AgentToolUpdateCallback<unknown> | undefined,
16
+ text: string,
17
+ ): void {
18
+ onUpdate?.({
19
+ content: [{ type: "text", text }],
20
+ details: { status: "running" },
21
+ });
22
+ }
@@ -0,0 +1,4 @@
1
+ /** A durable scheduled-run rejection, not a recoverable Tool failure. */
2
+ export class UnattendedExecutionError extends Error {
3
+ readonly name = "UnattendedExecutionError";
4
+ }
@@ -0,0 +1,228 @@
1
+ import type { AgentTool } from "@earendil-works/pi-agent-core";
2
+ import { Type } from "@earendil-works/pi-ai";
3
+ import type { RuntimeSandboxPort, WorkspacePort } from "../../config/ports";
4
+ import type { PiToolCandidate } from "../runtime/contracts";
5
+ import { result, running } from "../runtime/result";
6
+
7
+ /** 从 {@link WorkspacePort} 生成标准 workspace 文件 Tool 集(read / write / edit …)。 */
8
+
9
+
10
+
11
+ const sandboxCommandParameters = {
12
+ command: Type.String({
13
+ minLength: 1,
14
+ maxLength: 32_768,
15
+ description: "Shell command to run in the isolated Linux Sandbox.",
16
+ }),
17
+ cwd: Type.Optional(Type.String({
18
+ maxLength: 4_096,
19
+ description: "Sandbox working directory. Omit to use the Sandbox default.",
20
+ })),
21
+ stdin: Type.Optional(Type.String({
22
+ maxLength: 65_536,
23
+ description: "Optional text to pass to the command on standard input.",
24
+ })),
25
+ };
26
+
27
+ const sandboxExecParameters = Type.Object({
28
+ ...sandboxCommandParameters,
29
+ timeoutMs: Type.Optional(
30
+ Type.Integer({
31
+ minimum: 1,
32
+ maximum: 60_000,
33
+ description: "Maximum command runtime in milliseconds, from 1 to 60000.",
34
+ }),
35
+ ),
36
+ }, { additionalProperties: false });
37
+
38
+ const sandboxStartParameters = Type.Object(
39
+ sandboxCommandParameters,
40
+ { additionalProperties: false },
41
+ );
42
+
43
+ const sandboxProcessParameters = Type.Object({
44
+ id: Type.String({
45
+ minLength: 1,
46
+ maxLength: 128,
47
+ description: "Process ID returned by sandbox_start_process.",
48
+ }),
49
+ }, { additionalProperties: false });
50
+
51
+ const sandboxPublishParameters = Type.Object({
52
+ paths: Type.Array(Type.String({
53
+ minLength: 1,
54
+ maxLength: 4_096,
55
+ description: "Sandbox file path to publish.",
56
+ }), {
57
+ minItems: 1,
58
+ maxItems: 100,
59
+ description: "Files to copy from the temporary Sandbox into the persistent Workspace.",
60
+ }),
61
+ }, { additionalProperties: false });
62
+
63
+ /**
64
+ * 为现有 RuntimeSandboxPort 创建 Pi 命令、进程和文件发布工具。
65
+ *
66
+ * Worker 的 Sandbox Plugin 在容器能力和持久 Workspace 都可用时调用它。调用方
67
+ * 应传入已绑定当前会话的 Port;前台命令适合一次性执行,后台进程适合需要持续
68
+ * 运行的服务,二者不能互换结果语义。
69
+ *
70
+ * 这里的 “Sandbox” 指 Cloudflare Sandbox SDK 提供的隔离 Linux 容器;本层只
71
+ * 面向项目自己的 Port。命令限制、cwd 校验、工作区装载、超时、取消、清理和
72
+ * 冲突安全发布仍在 Port 内。容器文件不会自动写回 Workspace,只有 publish
73
+ * 工具显式选中的文件才进入持久视图;执行、启动、停止和发布继续走高风险审批。
74
+ *
75
+ * `Pi`、`Port` 与“候选工具”等项目核心术语见 `src/index.ts`。
76
+ */
77
+ export function sandboxPiToolCandidates(
78
+ sandbox: RuntimeSandboxPort,
79
+ ): PiToolCandidate[] {
80
+ const exec: AgentTool<typeof sandboxExecParameters> = {
81
+ name: "sandbox_exec",
82
+ label: "Run command",
83
+ description:
84
+ "Run a foreground command in this Chat's isolated Linux Sandbox. Files stay temporary until sandbox_publish_files is called.",
85
+ parameters: sandboxExecParameters,
86
+ // 作用:在 Sandbox 中运行一次前台命令并等待完整退出结果。
87
+ // 调用:Pi 执行构建、测试或其他会结束的命令时调用。
88
+ // 原因:输入和 AbortSignal 原样交给 Port,返回值只投影公开字段,
89
+ // 避免容器内部句柄进入对话。
90
+ async execute(_toolCallId, input, signal, onUpdate) {
91
+ signal?.throwIfAborted();
92
+ running(onUpdate, "Running the Sandbox command.");
93
+ const output = await sandbox.exec(input, signal);
94
+ return result({
95
+ success: output.success,
96
+ stdout: output.stdout,
97
+ stderr: output.stderr,
98
+ exitCode: output.exitCode,
99
+ stdoutTruncated: output.stdoutTruncated,
100
+ stderrTruncated: output.stderrTruncated,
101
+ workspacePersistence: "explicit_publish_required",
102
+ });
103
+ },
104
+ };
105
+
106
+ const startProcess: AgentTool<typeof sandboxStartParameters> = {
107
+ name: "sandbox_start_process",
108
+ label: "Start process",
109
+ description:
110
+ "Start a long-running background process in this Chat's isolated Linux Sandbox.",
111
+ parameters: sandboxStartParameters,
112
+ // 作用:在 Sandbox 中启动一个长期运行的后台进程并返回进程标识。
113
+ // 调用:Pi 启动开发服务器、监听器或其他不能等待退出的程序时调用。
114
+ // 原因:Cloudflare 官方接口把长期进程与 exec 分开;
115
+ // 这里只公开后续查日志和停止所需字段。
116
+ async execute(_toolCallId, input, signal, onUpdate) {
117
+ signal?.throwIfAborted();
118
+ running(onUpdate, "Starting the Sandbox process.");
119
+ const process = await sandbox.startProcess(input);
120
+ return result({
121
+ id: process.id,
122
+ command: process.command,
123
+ status: process.status,
124
+ ...(process.exitCode === undefined
125
+ ? {}
126
+ : { exitCode: process.exitCode }),
127
+ workspacePersistence: "explicit_publish_required",
128
+ });
129
+ },
130
+ };
131
+
132
+ const processLogs: AgentTool<typeof sandboxProcessParameters> = {
133
+ name: "sandbox_process_logs",
134
+ label: "Read process logs",
135
+ description:
136
+ "Read bounded stdout and stderr logs for one background Sandbox process.",
137
+ parameters: sandboxProcessParameters,
138
+ // 作用:读取一个 Sandbox 后台进程当前的有界日志。
139
+ // 调用:Pi 拿到 startProcess 返回的 id 后检查启动或运行状态时调用。
140
+ // 原因:日志截断由 Port 统一处理并显式回传标记,
141
+ // 避免适配层再次缓存不断增长的输出。
142
+ async execute(_toolCallId, { id }, signal, onUpdate) {
143
+ signal?.throwIfAborted();
144
+ running(onUpdate, "Reading the Sandbox process logs.");
145
+ const logs = await sandbox.getProcessLogs(id);
146
+ return result({
147
+ id: logs.id,
148
+ stdout: logs.stdout,
149
+ stderr: logs.stderr,
150
+ stdoutTruncated: logs.stdoutTruncated,
151
+ stderrTruncated: logs.stderrTruncated,
152
+ });
153
+ },
154
+ };
155
+
156
+ const stopProcess: AgentTool<typeof sandboxProcessParameters> = {
157
+ name: "sandbox_stop_process",
158
+ label: "Stop process",
159
+ description: "Stop one background Sandbox process.",
160
+ parameters: sandboxProcessParameters,
161
+ // 作用:停止一个由当前 Sandbox 管理的后台进程。
162
+ // 调用:Pi 不再需要该进程或需要清理运行环境时调用。
163
+ // 原因:只把进程 id 交给 Port,
164
+ // 进程归属检查和实际清理由 Sandbox 边界统一负责。
165
+ async execute(_toolCallId, { id }, signal, onUpdate) {
166
+ signal?.throwIfAborted();
167
+ running(onUpdate, "Stopping the Sandbox process.");
168
+ const output = await sandbox.stopProcess(id);
169
+ return result({ stopped: output.stopped });
170
+ },
171
+ };
172
+
173
+ const publishFiles: AgentTool<typeof sandboxPublishParameters> = {
174
+ name: "sandbox_publish_files",
175
+ label: "Publish files",
176
+ description:
177
+ "Publish named files from the temporary Sandbox into the scoped Workspace. Shared files remain read-only.",
178
+ parameters: sandboxPublishParameters,
179
+ // 作用:把明确列出的 Sandbox 文件发布到持久 Workspace。
180
+ // 调用:Pi 确认命令产物需要保留到会话文件区时调用。
181
+ // 原因:显式发布避免临时容器状态被误当成已持久化;
182
+ // 冲突、共享写保护和失败码继续由 Port 决定。
183
+ async execute(_toolCallId, { paths }, signal, onUpdate) {
184
+ signal?.throwIfAborted();
185
+ running(onUpdate, "Publishing Sandbox files to the Workspace.");
186
+ const output = await sandbox.publishFiles(paths);
187
+ return result({
188
+ files: output.files,
189
+ skipped: output.skipped,
190
+ failed: output.failed.map(({ path, errorCode }) => ({
191
+ path,
192
+ errorCode,
193
+ })),
194
+ bytes: output.bytes,
195
+ workspacePersistence: "published",
196
+ });
197
+ },
198
+ };
199
+
200
+ return [
201
+ {
202
+ owner: "sandbox",
203
+ requiredExecutionLevel: "high",
204
+ tool: exec,
205
+ },
206
+ {
207
+ owner: "sandbox",
208
+ requiredExecutionLevel: "high",
209
+ tool: startProcess,
210
+ },
211
+ {
212
+ owner: "sandbox",
213
+ requiredExecutionLevel: "safe",
214
+ retry: "idempotent",
215
+ tool: processLogs,
216
+ },
217
+ {
218
+ owner: "sandbox",
219
+ requiredExecutionLevel: "high",
220
+ tool: stopProcess,
221
+ },
222
+ {
223
+ owner: "sandbox",
224
+ requiredExecutionLevel: "high",
225
+ tool: publishFiles,
226
+ },
227
+ ];
228
+ }