@springbrand/agent-runtime 0.3.0-alpha.1 → 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.
Files changed (107) hide show
  1. package/package.json +6 -6
  2. package/src/adapter/cloudflare/agent.ts +157 -14
  3. package/src/adapter/cloudflare/define-agent.ts +12 -7
  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 +15 -0
  8. package/src/adapter/cloudflare/subagent/definition.ts +4 -4
  9. package/src/adapter/cloudflare/subagent/runner.ts +1 -1
  10. package/src/adapter/cloudflare/subagent/tools.ts +2 -2
  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/agent-context.ts +1 -1
  15. package/src/config/assembler.ts +29 -31
  16. package/src/config/assembly-snapshot.ts +1 -1
  17. package/src/config/definition.ts +1 -1
  18. package/src/config/harness-runtime.ts +9 -1
  19. package/src/config/model-guidance.ts +21 -0
  20. package/src/config/pinning.ts +22 -3
  21. package/src/config/ports.ts +27 -7
  22. package/src/config/public-contracts.ts +2 -2
  23. package/src/context/assembly.ts +1 -1
  24. package/src/context/extension/assembly.ts +2 -2
  25. package/src/context/memory/budget/gate.ts +19 -3
  26. package/src/conversation/harness-stream.ts +2 -1
  27. package/src/conversation/message/projection.ts +38 -21
  28. package/src/conversation/state.ts +23 -2
  29. package/src/harness/session-harness.ts +86 -5
  30. package/src/index.ts +7 -7
  31. package/src/lib/artifacts.ts +18 -0
  32. package/src/lib/execution-level.ts +13 -0
  33. package/src/lib/prompt.ts +7 -6
  34. package/src/lib/token-estimate.ts +8 -0
  35. package/src/models/index.ts +1 -0
  36. package/src/session/cloudflare/migration.ts +70 -6
  37. package/src/skills/springbrand-worker-website/index.ts +1 -1
  38. package/src/submission/admission.ts +12 -1
  39. package/src/submission/contracts.ts +42 -2
  40. package/src/submission/delivery.ts +1 -1
  41. package/src/submission/finalization.ts +1 -1
  42. package/src/submission/repository.ts +64 -4
  43. package/src/submission/unattended.ts +40 -0
  44. package/src/telemetry/coordinator.ts +1 -1
  45. package/src/telemetry/subagent-lifecycle.ts +1 -1
  46. package/src/telemetry/turn-events.ts +1 -1
  47. package/src/tools/README.md +44 -0
  48. package/src/tools/{ai-adapter.ts → adapters/ai-to-pi.ts} +6 -9
  49. package/src/tools/{declared.ts → adapters/declared.ts} +6 -2
  50. package/src/tools/{nested-tools.ts → adapters/pi-to-ai.ts} +2 -2
  51. package/src/tools/assistant/ask-user.ts +317 -0
  52. package/src/tools/assistant/candidate.ts +15 -0
  53. package/src/tools/assistant/followups.ts +34 -0
  54. package/src/tools/assistant/index.ts +19 -0
  55. package/src/tools/assistant/memory.ts +73 -0
  56. package/src/tools/assistant/plan.ts +98 -0
  57. package/src/tools/{time.ts → assistant/time.ts} +1 -1
  58. package/src/tools/{core-host.ts → codemode/adapter.ts} +50 -49
  59. package/src/tools/{core.ts → codemode/index.ts} +36 -92
  60. package/src/tools/codemode/workspace-connector.ts +198 -0
  61. package/src/tools/extension/index.ts +42 -0
  62. package/src/tools/index.ts +28 -26
  63. package/src/tools/{gateway.ts → mcp/gateway.ts} +19 -19
  64. package/src/tools/{mcp.ts → mcp/index.ts} +5 -5
  65. package/src/tools/{approval → runtime/approval}/repository.ts +13 -12
  66. package/src/tools/{compiler.ts → runtime/compiler.ts} +84 -147
  67. package/src/tools/runtime/contracts.ts +117 -0
  68. package/src/tools/{decision-gate.ts → runtime/decision-gate.ts} +147 -37
  69. package/src/tools/{human-decisions.ts → runtime/human-decisions.ts} +4 -4
  70. package/src/tools/{interaction → runtime/interaction}/repository.ts +1 -7
  71. package/src/tools/runtime/result.ts +22 -0
  72. package/src/tools/runtime/unattended-error.ts +4 -0
  73. package/src/tools/sandbox/index.ts +228 -0
  74. package/src/tools/schedule/index.ts +301 -0
  75. package/src/tools/skill/contracts.ts +20 -0
  76. package/src/tools/skill/index.ts +99 -0
  77. package/src/tools/skill/resources.ts +322 -0
  78. package/src/tools/skill/scripts.ts +168 -0
  79. package/src/tools/{subagent-authority.ts → subagent/authority.ts} +31 -31
  80. package/src/tools/{subagent.ts → subagent/index.ts} +34 -37
  81. package/src/tools/{subagent-run-repository.ts → subagent/repository.ts} +1 -1
  82. package/src/tools/{subagent-runtime.ts → subagent/runtime.ts} +1 -1
  83. package/src/tools/{temporary-agent → subagent/temporary}/approvals.ts +4 -7
  84. package/src/tools/{temporary-agent → subagent/temporary}/core.ts +1 -1
  85. package/src/tools/{temporary-agent → subagent/temporary}/runner.ts +1 -1
  86. package/src/tools/{temporary-agent → subagent/temporary}/workspace.ts +1 -4
  87. package/src/tools/{web-fetch.ts → web/fetch.ts} +4 -13
  88. package/src/tools/web/index.ts +2 -0
  89. package/src/tools/web/search/api.ts +1320 -0
  90. package/src/tools/web/search/index.ts +2 -0
  91. package/src/tools/{web-search/web-search.ts → web/search/search.ts} +5 -7
  92. package/src/tools/{workspace-sandbox.ts → workspace/index.ts} +12 -272
  93. package/src/tools/{workspace-revision.ts → workspace/revision.ts} +3 -3
  94. package/src/tools/base.ts +0 -534
  95. package/src/tools/schedule.ts +0 -261
  96. package/src/tools/skill.ts +0 -565
  97. package/src/tools/web-search/api.ts +0 -1318
  98. package/src/tools/web-search/index.ts +0 -2
  99. package/src/tools/workspace-state-connector.ts +0 -146
  100. package/src/tools/{approval → runtime/approval}/index.ts +0 -0
  101. package/src/tools/{interaction → runtime/interaction}/index.ts +0 -0
  102. package/src/tools/{temporary-agent → subagent/temporary}/coordinator.ts +0 -0
  103. package/src/tools/{subagent-types → subagent/types}/contract.ts +0 -0
  104. package/src/tools/{subagent-types → subagent/types}/extract/index.ts +0 -0
  105. package/src/tools/{subagent-types → subagent/types}/fanout/index.ts +0 -0
  106. package/src/tools/{subagent-types → subagent/types}/registry.ts +1 -1
  107. /package/src/tools/{workspace-versioning.ts → workspace/versioning.ts} +0 -0
@@ -1,6 +1,6 @@
1
- import type { RuntimeGatewaySession } from "../config/ports";
2
- import type { PiToolCandidate } from "./compiler";
3
- import { createPiMcpToolCandidate } from "./mcp";
1
+ import type { RuntimeGatewaySession } from "../../config/ports";
2
+ import type { PiToolCandidate } from "../runtime/contracts";
3
+ import { createPiMcpToolCandidate } from "./index";
4
4
 
5
5
  const GATEWAY_TOOLS = [
6
6
  "search_capabilities",
@@ -31,22 +31,22 @@ export function createPiGatewayToolCandidates(
31
31
  requiredExecutionLevel: execute ? "high" : "safe",
32
32
  ...(execute
33
33
  ? {
34
- requiredExecutionLevelForInput: async (input: unknown) => {
35
- const reference = input && typeof input === "object" &&
36
- !Array.isArray(input)
37
- ? (input as Record<string, unknown>).name
38
- : undefined;
39
- if (typeof reference !== "string" || !reference) {
40
- throw new Error(
41
- "Gateway Capability Reference is not verified",
42
- );
43
- }
44
- return (await session.resolveCapabilityRisk(reference)) ===
45
- "none"
46
- ? "safe" as const
47
- : "high" as const;
48
- },
49
- }
34
+ requiredExecutionLevelForInput: async (input: unknown) => {
35
+ const reference = input && typeof input === "object" &&
36
+ !Array.isArray(input)
37
+ ? (input as Record<string, unknown>).name
38
+ : undefined;
39
+ if (typeof reference !== "string" || !reference) {
40
+ throw new Error(
41
+ "Gateway Capability Reference is not verified",
42
+ );
43
+ }
44
+ return (await session.resolveCapabilityRisk(reference)) ===
45
+ "none"
46
+ ? "safe" as const
47
+ : "high" as const;
48
+ },
49
+ }
50
50
  : {}),
51
51
  },
52
52
  );
@@ -1,6 +1,6 @@
1
- import type { RuntimeMcpServer } from "../config/profile";
2
- import type { PiToolCandidate } from "./compiler";
3
- import { createPiDeclaredToolCandidate } from "./declared";
1
+ import type { RuntimeMcpServer } from "../../config/profile";
2
+ import { createPiDeclaredToolCandidate } from "../adapters/declared";
3
+ import type { PiToolCandidate } from "../runtime/contracts";
4
4
 
5
5
  interface McpCallResult {
6
6
  content: unknown[];
@@ -34,7 +34,7 @@ interface PiMcpCandidatePolicy {
34
34
  * 单个 Server 的客户端,Server 是对外提供工具的服务。连接持久化、OAuth 和
35
35
  * 恢复仍由 Agents SDK 的 MCP Client 管理,本接口只读取和调用。
36
36
  *
37
- * `Host` 与 `Pi` 等项目核心术语见 `../../index.ts`。
37
+ * `Host` 与 `Pi` 等项目核心术语见 `src/index.ts`。
38
38
  */
39
39
  export interface PiMcpHost {
40
40
  /**
@@ -284,7 +284,7 @@ export function createPiMcpToolCandidate(
284
284
  * 远端 Server 提供的 annotations 只是提示,不是本地审批边界,所以所有动态
285
285
  * MCP 工具继续标为高风险,不能据此绕过审批。
286
286
  *
287
- * `Host`、`Pi`、`Runtime Snapshot` 与“候选工具”见 `../../index.ts`。
287
+ * `Host`、`Pi`、`Runtime Snapshot` 与“候选工具”见 `src/index.ts`。
288
288
  */
289
289
  export async function createPiMcpToolCandidates(
290
290
  host: PiMcpHost,
@@ -1,8 +1,7 @@
1
1
  import type { SqlTaggedTemplate } from "agents/chat";
2
- import type { ExecutionLevel } from "../../lib/execution-level";
2
+ import type { ExecutionLevel } from "../../../lib/execution-level";
3
3
 
4
4
  // Approval 的统一定义见 ./index.ts。
5
- // #region 状态与行类型
6
5
  export type ApprovalStatus = "pending" | "approved" | "rejected";
7
6
 
8
7
  export interface StoredApproval {
@@ -16,6 +15,7 @@ export interface StoredApproval {
16
15
  executionLevel: ExecutionLevel;
17
16
  requiredExecutionLevel: ExecutionLevel;
18
17
  inputJson: string;
18
+ confirmationJson?: string | null;
19
19
  status: ApprovalStatus;
20
20
  createdAt: number;
21
21
  decidedAt: number | null;
@@ -33,6 +33,7 @@ export interface NewApproval {
33
33
  executionLevel: ExecutionLevel;
34
34
  requiredExecutionLevel: ExecutionLevel;
35
35
  inputJson: string;
36
+ confirmationJson?: string | null;
36
37
  status: ApprovalStatus;
37
38
  createdAt: number;
38
39
  }
@@ -46,6 +47,7 @@ export interface PendingApprovalSummary {
46
47
  executionLevel: ExecutionLevel;
47
48
  requiredExecutionLevel: ExecutionLevel;
48
49
  inputJson: string;
50
+ confirmationJson?: string | null;
49
51
  requestId: string;
50
52
  }
51
53
 
@@ -66,14 +68,13 @@ type ApprovalRow = {
66
68
  execution_level: string;
67
69
  required_level: string;
68
70
  input_json: string;
71
+ confirmation_json: string | null;
69
72
  status: string;
70
73
  created_at: number;
71
74
  decided_at: number | null;
72
75
  reason: string | null;
73
76
  };
74
77
 
75
- // #endregion
76
- // #region 行映射
77
78
  // 把 SQLite 的 Approval 行转成 Runtime 对象。
78
79
  // find 查到记录后调用,上层因而不需要理解 snake_case 列名。
79
80
  // 状态由表内字符串转成联合类型;新增列或状态时必须同步核对类型、SELECT 和映射。
@@ -89,6 +90,7 @@ function mapRow(row: ApprovalRow): StoredApproval {
89
90
  executionLevel: row.execution_level as ExecutionLevel,
90
91
  requiredExecutionLevel: row.required_level as ExecutionLevel,
91
92
  inputJson: row.input_json,
93
+ confirmationJson: row.confirmation_json,
92
94
  status: row.status as ApprovalStatus,
93
95
  createdAt: row.created_at,
94
96
  decidedAt: row.decided_at,
@@ -96,13 +98,11 @@ function mapRow(row: ApprovalRow): StoredApproval {
96
98
  };
97
99
  }
98
100
 
99
- // #endregion
100
- // #region Repository
101
101
  export class ApprovalRepository {
102
102
  // 保存当前 Agent SQLite 的查询入口。
103
103
  // RuntimeDatabase 构造时调用,HarnessDecisionGate 和 Transcript 随后共享这个 Repository。
104
104
  // Approval 必须与所属 Submission 在同一 Agent 存储中查询,不能跨 Durable Object 拼接状态。
105
- constructor(private readonly sql: SqlTaggedTemplate) {}
105
+ constructor(private readonly sql: SqlTaggedTemplate) { }
106
106
 
107
107
  // 按 executionId 读取一条完整 Approval,不存在时返回 null。
108
108
  // HarnessDecisionGate 在请求去重、决策、继续和拒绝时调用,调用方必须处理 null。
@@ -111,7 +111,7 @@ export class ApprovalRepository {
111
111
  const row = this.sql<ApprovalRow>`
112
112
  SELECT execution_id, submission_id, request_id, source,
113
113
  tool_call_id, tool_name, summary,
114
- execution_level, required_level, input_json,
114
+ execution_level, required_level, input_json, confirmation_json,
115
115
  status, created_at, decided_at, reason
116
116
  FROM pi_approvals
117
117
  WHERE execution_id = ${executionId}
@@ -128,7 +128,7 @@ export class ApprovalRepository {
128
128
  INSERT INTO pi_approvals (
129
129
  execution_id, submission_id, request_id, source,
130
130
  tool_call_id, tool_name, summary,
131
- execution_level, required_level, input_json,
131
+ execution_level, required_level, input_json, confirmation_json,
132
132
  status, created_at
133
133
  ) VALUES (
134
134
  ${approval.executionId},
@@ -141,6 +141,7 @@ export class ApprovalRepository {
141
141
  ${approval.executionLevel},
142
142
  ${approval.requiredExecutionLevel},
143
143
  ${approval.inputJson},
144
+ ${approval.confirmationJson ?? null},
144
145
  ${approval.status},
145
146
  ${approval.createdAt}
146
147
  )
@@ -192,12 +193,13 @@ export class ApprovalRepository {
192
193
  execution_level: string;
193
194
  required_level: string;
194
195
  input_json: string;
196
+ confirmation_json: string | null;
195
197
  request_id: string;
196
198
  }>`
197
199
  SELECT approval.execution_id, approval.tool_call_id, approval.source,
198
200
  approval.tool_name, approval.summary,
199
201
  approval.execution_level, approval.required_level,
200
- approval.input_json, approval.request_id
202
+ approval.input_json, approval.confirmation_json, approval.request_id
201
203
  FROM pi_approvals approval
202
204
  JOIN pi_submissions submission
203
205
  ON submission.submission_id = approval.submission_id
@@ -212,7 +214,7 @@ export class ApprovalRepository {
212
214
  summary: row.summary,
213
215
  executionLevel: row.execution_level as ExecutionLevel,
214
216
  requiredExecutionLevel: row.required_level as ExecutionLevel,
215
- inputJson: row.input_json,
217
+ inputJson: row.confirmation_json ?? row.input_json,
216
218
  requestId: row.request_id,
217
219
  }));
218
220
  }
@@ -271,4 +273,3 @@ export class ApprovalRepository {
271
273
  }));
272
274
  }
273
275
  }
274
- // #endregion
@@ -1,121 +1,16 @@
1
- import type {
2
- AgentHarnessTool,
3
- AgentTool,
4
- AgentToolResult,
5
- } from "@earendil-works/pi-agent-core";
6
- import type { ApprovalReceipt } from "../submission/contracts";
7
- import {
8
- boundDurableToolOutput,
9
- type BudgetPolicy,
10
- spillDurableToolOutput,
11
- } from "../context/memory/budget/gate";
12
- import {
13
- type ArtifactRef,
14
- serializeOutput,
15
- type SpillWorkspace,
16
- } from "../lib/artifacts";
17
- import {
18
- type ExecutionLevel,
19
- } from "../lib/execution-level";
20
-
21
- // 本文件沿用 `../../index.ts` 入口定义的 Tool Candidate 和 Tool Settlement 术语。
22
-
23
- // #region Public contracts
24
-
25
- /**
26
- * 声明一个 Tool 的结果由客户端投递,而不是由 `execute()` 产出。
27
- *
28
- * 带这个字段的 Tool 会在执行链里 park 住,等宿主经 `respondToolInteraction` 把响应送进来,
29
- * 再用 `settle` 把响应映射成这次 `toolCallId` 的权威 ToolResult。它的 `execute` 不会被调用。
30
- *
31
- * 这是 AI SDK 里「没有 execute 的 user-interaction tool」的等价物;差别是我们 park 住整个 Turn,
32
- * 而不是让 tool part 悬空到下一次请求 —— 我们的 transcript 是服务端权威的,悬空的 tool_use
33
- * 会让下一次模型调用非法。
34
- */
35
- export interface PiToolInteractionSpec {
36
- /** 结合 Tool 输入校验客户端响应体;不通过则拒绝投递,park 保持不变。 */
37
- readonly validateResponse: (input: unknown, response: unknown) => boolean;
38
- /** 把通过校验的响应映射成 ToolResult;缺省是原样回传。 */
39
- readonly settle?: (
40
- input: unknown,
41
- response: unknown,
42
- ) => Omit<AgentToolResult<unknown>, "terminate">;
43
- }
44
-
45
- /** 描述一个尚未进入最终 Tool Surface 和结算包装的 Pi 工具。 */
46
- export type ToolExposureMode = "direct" | "codemode" | "both";
47
-
48
- export interface PiToolCandidate {
49
- readonly owner: string;
50
- readonly tool: AgentTool<any, any>;
51
- /** @internal Send the complete schema but hide it until provider Tool Search finds it. */
52
- readonly deferLoading?: true;
53
- /** Omitted means visible both directly and through Code Mode. */
54
- readonly exposureMode?: ToolExposureMode;
55
- /** Conservative maximum used in the stable Runtime descriptor. */
56
- readonly requiredExecutionLevel: ExecutionLevel;
57
- /** Trusted parameter-level policy, evaluated before approval or dispatch. */
58
- readonly requiredExecutionLevelForInput?: (
59
- input: unknown,
60
- ) => ExecutionLevel | Promise<ExecutionLevel>;
61
- /**
62
- * 无条件需要人来决定:不看执行档位矩阵,每次调用都 park 出审批。
63
- *
64
- * 档位差是「够不够格自己跑」,不是「该不该问人」。花用户钱、改变账户
65
- * 状态这类工具,一旦 Agent 档位被 `allow_level` 永久拉高就会静默执行,
66
- * 那是失效不是降级。`deny` 仍然优先,被 deny 的工具根本不会注入。
67
- */
68
- readonly alwaysRequiresApproval?: boolean;
69
- /** Recovery may replay this Tool Call only when the candidate guarantees convergence. Omitted means non-idempotent. */
70
- readonly retry?: "idempotent" | "non-idempotent";
71
- readonly summary?: string;
72
- readonly source?: ApprovalReceipt["source"];
73
- readonly interaction?: PiToolInteractionSpec;
74
- /** Large payloads spill by default; protocol-shaped results opt into structure. */
75
- readonly outputBudget?: BudgetPolicy;
76
- }
77
-
78
- export interface CompileHarnessToolsOptions {
79
- readonly workspace?: SpillWorkspace;
80
- /** Recheck live authorization at the effect boundary, including safe replay. */
81
- readonly authorize?: (
82
- candidate: PiToolCandidate,
83
- args: unknown,
84
- invocation: { readonly toolCallId: string; readonly signal: AbortSignal },
85
- ) => void | Promise<void>;
86
- /** Return an already decided interaction result without invoking the handler. */
87
- readonly resolveReplay?: (
88
- candidate: PiToolCandidate,
89
- toolCallId: string,
90
- args: unknown,
91
- ) => AgentToolResult<unknown> | undefined | Promise<AgentToolResult<unknown> | undefined>;
92
- /** Optional business projection; Pi remains the authoritative Tool result. */
93
- readonly onSettlement?: (
94
- call: SettledPiToolCall,
95
- ) => void | Promise<void>;
96
- }
97
-
98
- /** 描述一次已进入持久化结算边界的 Pi 工具调用。 */
99
- export interface SettledPiToolCall {
100
- readonly toolCallId: string;
101
- readonly toolName: string;
102
- readonly args: unknown;
103
- readonly result: AgentToolResult<unknown>;
104
- readonly isError: boolean;
105
- /** Diagnostic-only original error; callers must not persist or expose it. */
106
- readonly cause?: unknown;
107
- readonly summary?: string;
108
- readonly source?: ApprovalReceipt["source"];
109
- }
1
+ import type { AgentHarnessTool, AgentToolResult } from "@earendil-works/pi-agent-core";
2
+ import { boundDurableToolOutput, spillDurableToolOutput } from "../../context/memory/budget/gate";
3
+ import { artifactId, serializeOutput, sha256Hex, type ArtifactRef, type SpillWorkspace } from "../../lib/artifacts";
4
+ import type { CompileHarnessToolsOptions, PiToolCandidate } from "./contracts";
5
+ import { UnattendedExecutionError } from "./unattended-error";
110
6
 
111
7
  // DO SQLite rows also contain arguments and transcript/recovery envelopes.
112
8
  // Keep each serialized result below half the 2 MiB row limit.
113
9
  const DURABLE_TOOL_RESULT_MAX_BYTES = 1024 * 1024;
10
+
114
11
  const MEDIA_CAPTION_MAX_CHARS = 4 * 1024;
115
12
 
116
- // #endregion
117
13
 
118
- // #region Governance helpers
119
14
 
120
15
  // 把任意失败值收敛为可安全显示的简短消息。
121
16
  // 受治理工具在工具执行或结算抛错时调用它。
@@ -154,11 +49,11 @@ function artifactResult(
154
49
  let captionRemaining = MEDIA_CAPTION_MAX_CHARS;
155
50
  const mediaContent = result.content.some((part) => part.type !== "text")
156
51
  ? result.content.flatMap((part): AgentToolResult<unknown>["content"] => {
157
- if (part.type !== "text") return [part];
158
- const text = part.text.slice(0, captionRemaining);
159
- captionRemaining -= text.length;
160
- return text ? [{ ...part, text }] : [];
161
- })
52
+ if (part.type !== "text") return [part];
53
+ const text = part.text.slice(0, captionRemaining);
54
+ captionRemaining -= text.length;
55
+ return text ? [{ ...part, text }] : [];
56
+ })
162
57
  : [];
163
58
  return {
164
59
  ...result,
@@ -175,15 +70,54 @@ function artifactResult(
175
70
  };
176
71
  }
177
72
 
73
+ async function unavailableArtifactResult(
74
+ result: AgentToolResult<unknown>,
75
+ ): Promise<AgentToolResult<unknown>> {
76
+ const { text, ext } = serializeOutput(spillPayload(result));
77
+ const hash = await sha256Hex(text);
78
+ const ref: ArtifactRef = {
79
+ kind: "artifact_ref",
80
+ artifactId: artifactId(hash),
81
+ path: `/scratch/tool-output/${hash.slice(0, 24)}.${ext}`,
82
+ bytes: new TextEncoder().encode(text).byteLength,
83
+ hash,
84
+ workspaceRevision: "unavailable",
85
+ availability: "unavailable",
86
+ preview: text.slice(0, 600),
87
+ note:
88
+ "The Tool output was too large to keep inline, and the Workspace artifact " +
89
+ "could not be verified. The evidence is unavailable; do not treat the preview as complete.",
90
+ };
91
+ return {
92
+ ...result,
93
+ content: [{
94
+ type: "text",
95
+ text: [
96
+ ref.note,
97
+ `Artifact ID: ${ref.artifactId}`,
98
+ `Path: ${ref.path}`,
99
+ `Bytes: ${ref.bytes}`,
100
+ `Hash: ${ref.hash}`,
101
+ `Preview:\n${ref.preview}`,
102
+ ].join("\n"),
103
+ }],
104
+ details: ref,
105
+ };
106
+ }
107
+
178
108
  async function durableResult(
179
109
  result: AgentToolResult<unknown>,
180
110
  candidate: PiToolCandidate,
181
111
  workspace: SpillWorkspace | undefined,
182
112
  ): Promise<AgentToolResult<unknown>> {
183
113
  const spill = (candidate.outputBudget ?? { kind: "spill" }).kind === "spill";
114
+ const serialized = serializeOutput(spillPayload(result));
184
115
  let ref = spill
185
116
  ? await spillDurableToolOutput(spillPayload(result), { workspace })
186
117
  : null;
118
+ if (spill && serialized.text.length > 32 * 1024 && !ref) {
119
+ return unavailableArtifactResult(result);
120
+ }
187
121
  const bounded = ref
188
122
  ? artifactResult(result, ref)
189
123
  : boundDurableToolOutput(result) as AgentToolResult<unknown>;
@@ -221,9 +155,7 @@ async function untilAborted<T>(
221
155
  }
222
156
  }
223
157
 
224
- // #endregion
225
158
 
226
- // #region Governance and compilation
227
159
 
228
160
  /**
229
161
  * Convert the configured candidate surface once at the AgentHarness boundary.
@@ -239,19 +171,19 @@ export function compileHarnessTools(
239
171
  const tool = source.constrainedSampling === false
240
172
  ? source
241
173
  : {
242
- ...source,
243
- constrainedSampling: source.constrainedSampling ?? {
244
- type: "json_schema" as const,
245
- strict: "prefer" as const,
246
- },
247
- };
174
+ ...source,
175
+ constrainedSampling: source.constrainedSampling ?? {
176
+ type: "json_schema" as const,
177
+ strict: "prefer" as const,
178
+ },
179
+ };
248
180
  return {
249
181
  ...tool,
250
182
  replay: candidate.retry === "idempotent" &&
251
- candidate.requiredExecutionLevel === "safe" &&
252
- !candidate.alwaysRequiresApproval &&
253
- !candidate.requiredExecutionLevelForInput &&
254
- !candidate.interaction
183
+ candidate.requiredExecutionLevel === "safe" &&
184
+ !candidate.alwaysRequiresApproval &&
185
+ !candidate.requiredExecutionLevelForInput &&
186
+ !candidate.interaction
255
187
  ? "safe" as const
256
188
  : "never" as const,
257
189
  ...(candidate.deferLoading ? { deferLoading: true as const } : {}),
@@ -264,27 +196,28 @@ export function compileHarnessTools(
264
196
  context,
265
197
  ) {
266
198
  const signal = context.abortSignal ?? new AbortController().signal;
267
- await options.authorize?.(candidate, args, {
268
- toolCallId,
269
- signal,
270
- });
271
- const replay = await options.resolveReplay?.(
272
- candidate,
273
- toolCallId,
274
- args,
275
- );
276
- if (replay) return durableResult(replay, candidate, options.workspace);
277
199
  let result: AgentToolResult<unknown>;
278
200
  try {
201
+ await options.authorize?.(candidate, args, {
202
+ toolCallId,
203
+ signal,
204
+ });
205
+ const replay = await options.resolveReplay?.(
206
+ candidate,
207
+ toolCallId,
208
+ args,
209
+ );
210
+ if (replay) return durableResult(replay, candidate, options.workspace);
279
211
  result = await untilAborted(
280
212
  signal,
281
213
  async () => durableResult(
282
- await source.execute(
283
- toolCallId,
284
- args,
285
- signal,
286
- (update) => onUpdate(update),
287
- ),
214
+ await (candidate.confirmation
215
+ ? (() => {
216
+ const confirmed = options.resolveConfirmation?.(candidate, toolCallId, args);
217
+ if (!confirmed) throw new Error("User confirmation is required");
218
+ return candidate.confirmation.execute(confirmed.prepared, { intentId: confirmed.intentId, signal });
219
+ })()
220
+ : source.execute(toolCallId, args, signal, (update) => onUpdate(update))),
288
221
  candidate,
289
222
  options.workspace,
290
223
  ),
@@ -305,6 +238,9 @@ export function compileHarnessTools(
305
238
  summary: candidate.summary,
306
239
  source: candidate.source,
307
240
  });
241
+ if (cause instanceof UnattendedExecutionError) {
242
+ return { ...failed, terminate: true };
243
+ }
308
244
  throw cause instanceof Error && cause.message === message
309
245
  ? cause
310
246
  : new Error(message, { cause });
@@ -314,7 +250,10 @@ export function compileHarnessTools(
314
250
  toolName: source.name,
315
251
  args,
316
252
  result,
317
- isError: false,
253
+ isError: result.details !== null &&
254
+ typeof result.details === "object" &&
255
+ (result.details as { availability?: unknown }).availability ===
256
+ "unavailable",
318
257
  summary: candidate.summary,
319
258
  source: candidate.source,
320
259
  });
@@ -323,5 +262,3 @@ export function compileHarnessTools(
323
262
  } satisfies AgentHarnessTool<object | undefined>;
324
263
  });
325
264
  }
326
-
327
- // #endregion
@@ -0,0 +1,117 @@
1
+ import type { AgentTool, AgentToolResult } from "@earendil-works/pi-agent-core";
2
+ import type { ApprovalReceipt } from "../../submission/contracts";
3
+ import { type BudgetPolicy } from "../../context/memory/budget/gate";
4
+ import { type SpillWorkspace } from "../../lib/artifacts";
5
+ import { type ExecutionLevel } from "../../lib/execution-level";
6
+
7
+ // 本文件沿用 `src/index.ts` 入口定义的 Tool Candidate 和 Tool Settlement 术语。
8
+
9
+
10
+ /**
11
+ * 声明一个 Tool 的结果由客户端投递,而不是由 `execute()` 产出。
12
+ *
13
+ * 带这个字段的 Tool 会在执行链里 park 住,等宿主经 `respondToolInteraction` 把响应送进来,
14
+ * 再用 `settle` 把响应映射成这次 `toolCallId` 的权威 ToolResult。它的 `execute` 不会被调用。
15
+ *
16
+ * 这是 AI SDK 里「没有 execute 的 user-interaction tool」的等价物;差别是我们 park 住整个 Turn,
17
+ * 而不是让 tool part 悬空到下一次请求 —— 我们的 transcript 是服务端权威的,悬空的 tool_use
18
+ * 会让下一次模型调用非法。
19
+ */
20
+ export interface PiToolInteractionSpec {
21
+ /** 结合 Tool 输入校验客户端响应体;不通过则拒绝投递,park 保持不变。 */
22
+ readonly validateResponse: (input: unknown, response: unknown) => boolean;
23
+ /** 把通过校验的响应映射成 ToolResult;缺省是原样回传。 */
24
+ readonly settle?: (
25
+ input: unknown,
26
+ response: unknown,
27
+ ) => Omit<AgentToolResult<unknown>, "terminate">;
28
+ }
29
+
30
+ /** Trusted Tool metadata used to evaluate a scheduled task grant. */
31
+ export interface PiToolUnattendedExecutionSpec {
32
+ readonly capability: string;
33
+ readonly operation: string;
34
+ readonly objectForInput?: (
35
+ input: unknown,
36
+ ) => unknown | Promise<unknown>;
37
+ }
38
+
39
+ /** 描述一个尚未进入最终 Tool Surface 和结算包装的 Pi 工具。 */
40
+ export type ToolExposureMode = "direct" | "codemode" | "both";
41
+
42
+ /** Host-prepared confirmation travels through the existing durable approval. */
43
+ export interface PiToolConfirmationSpec {
44
+ prepare(input: unknown, context: { intentId: string }): Promise<unknown>;
45
+ execute(prepared: unknown, context: { intentId: string; signal: AbortSignal }): Promise<AgentToolResult<unknown>>;
46
+ }
47
+
48
+ export interface PiToolCandidate {
49
+ /** Presentation only, resolved at the model boundary; never changes approved execution inputs. */
50
+ readonly modelGuidance?: () => Promise<{ description: string; systemPrompt?: string }>;
51
+ readonly confirmation?: PiToolConfirmationSpec;
52
+ readonly owner: string;
53
+ readonly tool: AgentTool<any, any>;
54
+ /** @internal Send the complete schema but hide it until provider Tool Search finds it. */
55
+ readonly deferLoading?: true;
56
+ /** Omitted means visible both directly and through Code Mode. */
57
+ readonly exposureMode?: ToolExposureMode;
58
+ /** Conservative maximum used in the stable Runtime descriptor. */
59
+ readonly requiredExecutionLevel: ExecutionLevel;
60
+ /** Trusted parameter-level policy, evaluated before approval or dispatch. */
61
+ readonly requiredExecutionLevelForInput?: (
62
+ input: unknown,
63
+ ) => ExecutionLevel | Promise<ExecutionLevel>;
64
+ /**
65
+ * 无条件需要人来决定:不看执行档位矩阵,每次调用都 park 出审批。
66
+ *
67
+ * 档位差是「够不够格自己跑」,不是「该不该问人」。花用户钱、改变账户
68
+ * 状态这类工具,一旦 Agent 档位被 `allow_level` 永久拉高就会静默执行,
69
+ * 那是失效不是降级。`deny` 仍然优先,被 deny 的工具根本不会注入。
70
+ */
71
+ readonly alwaysRequiresApproval?: boolean;
72
+ /** Declares the concrete grant identity derived from actual Tool input. */
73
+ readonly unattendedExecution?: PiToolUnattendedExecutionSpec;
74
+ /** Explicitly forbids this Tool from unattended Scheduled Runs. */
75
+ readonly unattendedMode?: "forbidden";
76
+ /** Recovery may replay this Tool Call only when the candidate guarantees convergence. Omitted means non-idempotent. */
77
+ readonly retry?: "idempotent" | "non-idempotent";
78
+ readonly summary?: string;
79
+ readonly source?: ApprovalReceipt["source"];
80
+ readonly interaction?: PiToolInteractionSpec;
81
+ /** Large payloads spill by default; protocol-shaped results opt into structure. */
82
+ readonly outputBudget?: BudgetPolicy;
83
+ }
84
+
85
+ export interface CompileHarnessToolsOptions {
86
+ readonly workspace?: SpillWorkspace;
87
+ readonly resolveConfirmation?: (candidate: PiToolCandidate, toolCallId: string, args: unknown) => { prepared: unknown; intentId: string };
88
+ /** Recheck live authorization at the effect boundary, including safe replay. */
89
+ readonly authorize?: (
90
+ candidate: PiToolCandidate,
91
+ args: unknown,
92
+ invocation: { readonly toolCallId: string; readonly signal: AbortSignal },
93
+ ) => void | Promise<void>;
94
+ /** Return an already decided interaction result without invoking the handler. */
95
+ readonly resolveReplay?: (
96
+ candidate: PiToolCandidate,
97
+ toolCallId: string,
98
+ args: unknown,
99
+ ) => AgentToolResult<unknown> | undefined | Promise<AgentToolResult<unknown> | undefined>;
100
+ /** Optional business projection; Pi remains the authoritative Tool result. */
101
+ readonly onSettlement?: (
102
+ call: SettledPiToolCall,
103
+ ) => void | Promise<void>;
104
+ }
105
+
106
+ /** 描述一次已进入持久化结算边界的 Pi 工具调用。 */
107
+ export interface SettledPiToolCall {
108
+ readonly toolCallId: string;
109
+ readonly toolName: string;
110
+ readonly args: unknown;
111
+ readonly result: AgentToolResult<unknown>;
112
+ readonly isError: boolean;
113
+ /** Diagnostic-only original error; callers must not persist or expose it. */
114
+ readonly cause?: unknown;
115
+ readonly summary?: string;
116
+ readonly source?: ApprovalReceipt["source"];
117
+ }