@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
@@ -0,0 +1,301 @@
1
+ import type { AgentTool, AgentToolResult } from "@earendil-works/pi-agent-core";
2
+ import { Type, fauxToolCall, validateToolArguments, type JsonObject, type TSchema } from "@earendil-works/pi-ai";
3
+ import {
4
+ toScheduleRuleSpec,
5
+ validateScheduleRuleSpec,
6
+ } from "../../adapter/cloudflare/scheduling/schedule-rule";
7
+ import { isValidTimeZone } from "../../adapter/cloudflare/scheduling/zoned-cron";
8
+ import type { RuntimeSchedulePort, RuntimeSchedulePreparation } from "../../config/ports";
9
+ import { serializeOutput } from "../../lib/artifacts";
10
+ import type { ScheduleSpec } from "../../submission/contracts";
11
+ import type { PiToolCandidate } from "../runtime/contracts";
12
+
13
+ const scheduleTriggerParameters = Type.Union([
14
+ Type.Object({
15
+ kind: Type.Literal("local", { description: "Interpret the rule in the explicit task timezone." }),
16
+ rule: Type.Union([
17
+ Type.Object({ kind: Type.Literal("once", { description: "Run on one local date." }), date: Type.String({ description: "Local date YYYY-MM-DD." }), time: Type.String({ description: "Local clock time HH:mm." }) }, { additionalProperties: false }),
18
+ Type.Object({ kind: Type.Literal("daily", { description: "Run each local day." }), time: Type.String({ description: "Local clock time HH:mm." }) }, { additionalProperties: false }),
19
+ Type.Object({ kind: Type.Literal("weekly", { description: "Run on the selected weekdays." }), weekdays: Type.Array(Type.Integer({ minimum: 0, maximum: 6 }), { minItems: 1, description: "Weekdays: Sunday 0 through Saturday 6." }), time: Type.String({ description: "Local clock time HH:mm." }) }, { additionalProperties: false }),
20
+ ], { description: "Once, daily or weekly local-time rule." }),
21
+ startDate: Type.Optional(Type.String({ description: "Inclusive first local date YYYY-MM-DD." })),
22
+ endDate: Type.Optional(Type.String({ description: "Inclusive last local date YYYY-MM-DD." })),
23
+ }, { additionalProperties: false }),
24
+ Type.Object({
25
+ kind: Type.Literal("once-in", { description: "Run once after a delay." }),
26
+ seconds: Type.Integer({
27
+ minimum: 1,
28
+ description: "Fire once, this many seconds from now.",
29
+ }),
30
+ }, { additionalProperties: false }),
31
+ Type.Object({
32
+ kind: Type.Literal("once-at", { description: "Run once at an absolute UTC time." }),
33
+ at: Type.String({
34
+ description:
35
+ "Fire once at this absolute UTC ISO time, e.g. 2026-07-20T09:00:00Z.",
36
+ }),
37
+ }, { additionalProperties: false }),
38
+ Type.Object({
39
+ kind: Type.Literal("cron", { description: "Repeat on a UTC cron schedule." }),
40
+ cron: Type.String({
41
+ description:
42
+ "Repeat on a standard UTC cron, e.g. '0 9 * * *' = daily 09:00 UTC.",
43
+ }),
44
+ }, { additionalProperties: false }),
45
+ Type.Object({
46
+ kind: Type.Literal("interval", { description: "Repeat at fixed intervals." }),
47
+ seconds: Type.Integer({
48
+ minimum: 1,
49
+ description: "Repeat every this many seconds.",
50
+ }),
51
+ }, { additionalProperties: false }),
52
+ ], {
53
+ description:
54
+ "When to fire. Discriminate on the `kind` field (never \"type\"). " +
55
+ 'Shapes: {"kind":"local","rule":{"kind":"once","date":"2026-09-17","time":"14:06"}} runs once at 14:06 in `timezone`; ' +
56
+ '{"kind":"local","rule":{"kind":"daily","time":"09:00"}} runs daily; ' +
57
+ '{"kind":"local","rule":{"kind":"weekly","weekdays":[1,3],"time":"09:30"}} runs on Mondays and Wednesdays; ' +
58
+ '{"kind":"once-at","at":"2026-09-17T06:06:00Z"} fires once at an absolute UTC time.',
59
+ });
60
+
61
+ const scheduleParameters = Type.Object({
62
+ prompt: Type.String({
63
+ minLength: 1, maxLength: 1000, pattern: "\\S",
64
+ description:
65
+ "The standalone instruction to run when the schedule fires. The future turn has no context from this chat, so make it self-contained.",
66
+ }),
67
+ trigger: scheduleTriggerParameters,
68
+ label: Type.Optional(Type.String({ maxLength: 50, description: "Optional task name, at most 50 Unicode characters. The Host generates a name when omitted." })),
69
+ timezone: Type.String({ minLength: 1, description: "Required IANA timezone. Use the user's explicit timezone or reliable Host/browser timezone; ask when unknown." }),
70
+ }, { additionalProperties: false });
71
+
72
+ const noParameters = Type.Object({}, { additionalProperties: false });
73
+ const scheduleIdParameters = Type.Object({
74
+ id: Type.String({
75
+ description: "The schedule id, as returned by `list_schedules`.",
76
+ }),
77
+ }, { additionalProperties: false });
78
+ const updateScheduleParameters = Type.Object({
79
+ id: Type.String({ minLength: 1, description: "The exact id returned by `list_schedules`." }),
80
+ prompt: Type.Optional(scheduleParameters.properties.prompt),
81
+ trigger: Type.Optional(scheduleTriggerParameters),
82
+ label: scheduleParameters.properties.label,
83
+ timezone: Type.Optional(scheduleParameters.properties.timezone),
84
+ }, { additionalProperties: false });
85
+ const changeScheduleAgentParameters = Type.Object({
86
+ id: Type.String({
87
+ description: "The exact schedule id returned by `list_schedules`.",
88
+ }),
89
+ userAgentId: Type.String({
90
+ description: "The exact User Agent id selected by the user.",
91
+ }),
92
+ }, { additionalProperties: false });
93
+
94
+ function result<T>(details: T): AgentToolResult<T> {
95
+ return {
96
+ content: [{ type: "text", text: serializeOutput(details).text }],
97
+ details,
98
+ };
99
+ }
100
+
101
+ function candidate<T extends TSchema>(
102
+ tool: AgentTool<T>,
103
+ options: Partial<
104
+ Pick<
105
+ PiToolCandidate,
106
+ "alwaysRequiresApproval" | "exposureMode" | "owner" | "requiredExecutionLevel" | "retry" | "summary"
107
+ >
108
+ > = {},
109
+ ): PiToolCandidate {
110
+ return {
111
+ owner: options.owner ?? "runtime-base",
112
+ exposureMode: options.exposureMode ?? "direct",
113
+ requiredExecutionLevel: options.requiredExecutionLevel ?? "safe",
114
+ source: "action",
115
+ tool,
116
+ ...(options.alwaysRequiresApproval
117
+ ? { alwaysRequiresApproval: true }
118
+ : {}),
119
+ ...(options.summary ? { summary: options.summary } : {}),
120
+ ...(options.retry ? { retry: options.retry } : {}),
121
+ };
122
+ }
123
+
124
+ export function schedulePiToolCandidates(
125
+ schedule: RuntimeSchedulePort,
126
+ ): PiToolCandidate[] {
127
+ const candidates = [
128
+ candidate(
129
+ {
130
+ name: "schedule",
131
+ label: "Schedule prompt",
132
+ description:
133
+ "Schedule a prompt to run LATER, autonomously. Required inputs: prompt (Requirement, at most 1000 Unicode characters), trigger and timezone. Prefer local once/daily/weekly rules. trigger discriminates on `kind` (never \"type\"); see the trigger parameter schema for detailed shapes. label is optional (at most 50 characters); the Host generates an omitted name. Ask for missing information. Use when the user asks to be reminded, or to run something after a delay / at a time / on a recurring basis. The user always reviews the proposed schedule before it is created. The scheduled prompt runs in its own dedicated session at each trigger with NO memory of this conversation, so phrase `prompt` as a fully standalone instruction. After scheduling, tell the user what you set.",
134
+ parameters: scheduleParameters,
135
+ async execute(_toolCallId, input, signal) {
136
+ signal?.throwIfAborted();
137
+ throw new Error("Matching user confirmation is required");
138
+ },
139
+ },
140
+ {
141
+ alwaysRequiresApproval: true,
142
+ exposureMode: "direct",
143
+ summary: "Create a scheduled task",
144
+ },
145
+ ),
146
+ candidate(
147
+ {
148
+ name: "list_schedules",
149
+ label: "List schedules",
150
+ description:
151
+ "List the user's existing scheduled tasks. Call this when the user asks what they have scheduled, or before cancelling one — you need the id, and the user will refer to a task by what it does, not by its id.",
152
+ parameters: noParameters,
153
+ async execute(_toolCallId, _input, signal) {
154
+ signal?.throwIfAborted();
155
+ return result({ schedules: await schedule.list() });
156
+ },
157
+ },
158
+ { retry: "idempotent" },
159
+ ),
160
+ candidate({
161
+ name: "update_schedule",
162
+ label: "Update schedule",
163
+ description:
164
+ "Update one scheduled task without changing its id or history. Required input: id. Optional prompt, trigger, label and timezone preserve the saved values when omitted; trigger uses the same `kind`-based shapes as `schedule`. Every edit requires user confirmation; changing Requirement requires a fresh Host authorization check. Call `list_schedules` first and use an exact id. If multiple tasks plausibly match the user's wording, ask which one instead of guessing.",
165
+ parameters: updateScheduleParameters,
166
+ async execute(_toolCallId, input, signal) {
167
+ signal?.throwIfAborted();
168
+ throw new Error("Matching user confirmation is required");
169
+ },
170
+ }),
171
+ candidate({
172
+ name: "pause_schedule",
173
+ label: "Pause schedule",
174
+ description:
175
+ "Pause one scheduled task. Call `list_schedules` first and use an exact id; ask the user if the target is ambiguous.",
176
+ parameters: scheduleIdParameters,
177
+ async execute(_toolCallId, input, signal) {
178
+ signal?.throwIfAborted();
179
+ const { ok } = await schedule.pause(input.id);
180
+ return result({ paused: ok, id: input.id });
181
+ },
182
+ }),
183
+ candidate({
184
+ name: "resume_schedule",
185
+ label: "Resume schedule",
186
+ description:
187
+ "Resume one paused scheduled task. Call `list_schedules` first and use an exact id; ask the user if the target is ambiguous.",
188
+ parameters: scheduleIdParameters,
189
+ async execute(_toolCallId, input, signal) {
190
+ signal?.throwIfAborted();
191
+ const { ok } = await schedule.resume(input.id);
192
+ return result({ resumed: ok, id: input.id });
193
+ },
194
+ }),
195
+ candidate(
196
+ {
197
+ name: "cancel_schedule",
198
+ label: "Cancel schedule",
199
+ description:
200
+ "Cancel a scheduled task by id. Call `list_schedules` first to find the id that matches what the user described. If more than one plausibly matches, ask the user which one instead of guessing — cancelling is not reversible.",
201
+ parameters: scheduleIdParameters,
202
+ async execute(_toolCallId, input, signal) {
203
+ signal?.throwIfAborted();
204
+ const { ok } = await schedule.cancel(input.id);
205
+ return result(ok
206
+ ? { cancelled: true, id: input.id }
207
+ : {
208
+ cancelled: false,
209
+ id: input.id,
210
+ reason: "no schedule with that id",
211
+ });
212
+ },
213
+ },
214
+ {
215
+ requiredExecutionLevel: "high",
216
+ summary: "Cancel a scheduled task",
217
+ },
218
+ ),
219
+ candidate(
220
+ {
221
+ name: "list_user_agents",
222
+ label: "List User Agents",
223
+ description:
224
+ "List the enabled User Agents available for scheduled tasks. " +
225
+ "Use this before changing a schedule Agent.",
226
+ parameters: noParameters,
227
+ async execute(_toolCallId, _input, signal) {
228
+ signal?.throwIfAborted();
229
+ return result({ agents: await schedule.listAgents() });
230
+ },
231
+ },
232
+ { owner: "schedule-host" },
233
+ ),
234
+ candidate(
235
+ {
236
+ name: "change_schedule_agent",
237
+ label: "Change schedule Agent",
238
+ description:
239
+ "Change which User Agent executes one scheduled task without " +
240
+ "changing its id or history. Call `list_schedules` and " +
241
+ "`list_user_agents` first and use exact ids; ask the user when " +
242
+ "the target is ambiguous.",
243
+ parameters: changeScheduleAgentParameters,
244
+ async execute(_toolCallId, input, signal) {
245
+ signal?.throwIfAborted();
246
+ const { ok } = await schedule.changeAgent(
247
+ input.id,
248
+ input.userAgentId,
249
+ );
250
+ return result({ updated: ok, id: input.id });
251
+ },
252
+ },
253
+ { owner: "schedule-host" },
254
+ ),
255
+ ];
256
+ return candidates.flatMap((toolCandidate): PiToolCandidate[] => {
257
+ const name = toolCandidate.tool.name;
258
+ if (name !== "schedule" && name !== "update_schedule") return [toolCandidate];
259
+ const confirmation = schedule.confirmation;
260
+ if (!confirmation) return [];
261
+ return [{
262
+ ...toolCandidate, alwaysRequiresApproval: true, confirmation: {
263
+ async prepare(args, { intentId }) {
264
+ const validated = validateToolArguments(toolCandidate.tool, fauxToolCall(name, args as JsonObject));
265
+ const input = validated as { id?: string; prompt?: string; trigger?: ScheduleSpec["trigger"]; label?: string; timezone?: string };
266
+ if (input.timezone !== undefined && !isValidTimeZone(input.timezone)) throw new Error("A valid IANA timezone is required");
267
+ if (input.trigger?.kind === "local" && input.timezone) {
268
+ const error = validateScheduleRuleSpec(toScheduleRuleSpec(input.trigger, input.timezone));
269
+ if (error) throw new Error(error.message);
270
+ }
271
+ const prepared = await confirmation.prepare({
272
+ intentId, ...(name === "update_schedule" ? { id: input.id } : {}),
273
+ ...(input.prompt !== undefined ? { prompt: input.prompt } : {}),
274
+ ...(input.trigger !== undefined ? { trigger: input.trigger } : {}),
275
+ ...(input.label !== undefined ? { label: input.label } : {}),
276
+ ...(input.timezone !== undefined ? { tz: input.timezone } : {}),
277
+ });
278
+ if (prepared.id !== input.id) throw new Error("Host preparation changed the target Task ID");
279
+ const fullInput = { prompt: prepared.prompt, label: prepared.label, trigger: prepared.trigger, timezone: prepared.timezone };
280
+ void validateToolArguments({ ...toolCandidate.tool, parameters: scheduleParameters }, fauxToolCall(name, fullInput));
281
+ if (!prepared.label?.trim() || !isValidTimeZone(prepared.timezone) || !prepared.candidateId?.trim() || !prepared.candidateVersion?.trim() || !prepared.authorization?.version?.trim() || !prepared.authorization.scope?.trim() || !Array.isArray(prepared.authorization.missing)) {
282
+ throw new Error("Host preparation is incomplete");
283
+ }
284
+ if (prepared.trigger.kind === "local") {
285
+ const error = validateScheduleRuleSpec(toScheduleRuleSpec(prepared.trigger, prepared.timezone));
286
+ if (error) throw new Error(error.message);
287
+ }
288
+ return prepared;
289
+ },
290
+ async execute(prepared, context) {
291
+ const preview = prepared as RuntimeSchedulePreparation;
292
+ if (preview.authorization.missing.length) throw new Error(`Missing authorization: ${preview.authorization.missing.join("; ")}`);
293
+ const { id } = await confirmation.commit(preview, context);
294
+ return result({ [name === "schedule" ? "scheduled" : "updated"]: true, id, task: { label: preview.label, prompt: preview.prompt, trigger: preview.trigger, timezone: preview.timezone } });
295
+ },
296
+ }
297
+ }];
298
+ });
299
+ }
300
+
301
+ /** 从 {@link RuntimeSchedulePort} 生成定时任务 Tool 集。 */
@@ -0,0 +1,20 @@
1
+ import { type SkillSource } from "agents/skills";
2
+ import type { RuntimeSkillScriptPolicy, WorkspacePort } from "../../config/ports";
3
+ import type { RuntimeSkillBodyTransform } from "../../config/definition";
4
+ import type { PiToolCandidate } from "../runtime/contracts";
5
+
6
+ /** A configured Skill source and its script capabilities. */
7
+ export interface PiSkillBinding {
8
+ readonly name: string;
9
+ readonly description: string;
10
+ readonly source: SkillSource;
11
+ readonly script?: RuntimeSkillScriptPolicy;
12
+ }
13
+
14
+ /** Host capabilities available while creating Skill tools. */
15
+ export interface SkillPiToolOptions {
16
+ readonly loader?: WorkerLoader;
17
+ readonly workspace?: WorkspacePort;
18
+ readonly tools?: readonly PiToolCandidate[];
19
+ readonly transformSkillBody?: RuntimeSkillBodyTransform;
20
+ }
@@ -0,0 +1,99 @@
1
+ import { SkillRegistry } from "agents/skills";
2
+ import { aiToolToPi } from "../adapters/ai-to-pi";
3
+ import type { PiToolCandidate } from "../runtime/contracts";
4
+ import type { PiSkillBinding, SkillPiToolOptions } from "./contracts";
5
+ import { catalogSkillSource, materializeSkillResourceTool, wrapSkillResourceRead } from "./resources";
6
+ import { scriptRunner, wrapSkillScript } from "./scripts";
7
+
8
+ export type { PiSkillBinding, SkillPiToolOptions } from "./contracts";
9
+ const SKILL_TOOL_LABELS: Readonly<Record<string, string>> = {
10
+ activate_skill: "Activate Skill",
11
+ read_skill_resource: "Read Skill resource",
12
+ run_skill_script: "Run Skill script",
13
+ materialize_skill_resource: "Materialize Skill resource",
14
+ };
15
+
16
+ const SKILL_TOOL_PARAMETER_DESCRIPTIONS: Readonly<Record<string, Readonly<Record<string, string>>>> = {
17
+ activate_skill: {
18
+ name: "Exact name of the available Skill to activate.",
19
+ },
20
+ read_skill_resource: {
21
+ name: "Name of the activated Skill. Omit only when path starts with the Skill name.",
22
+ path: "Bundled resource path listed by activate_skill.",
23
+ },
24
+ run_skill_script: {
25
+ name: "Name of the activated Skill that supplies the script.",
26
+ path: "Bundled script path listed by activate_skill.",
27
+ input: "JSON input expected by the Skill script. Defaults to an empty object.",
28
+ },
29
+ };
30
+
31
+ /** Create Pi candidates from the official Agents SDK SkillRegistry tools. */
32
+ export async function skillPiToolCandidates(
33
+ bindings: readonly PiSkillBinding[],
34
+ options: SkillPiToolOptions = {},
35
+ ): Promise<PiToolCandidate[]> {
36
+ if (bindings.length === 0) return [];
37
+
38
+ const availableToolNames = (options.tools ?? []).map(({ tool }) => tool.name);
39
+
40
+ const registry = new SkillRegistry(
41
+ bindings.map((binding) => catalogSkillSource(
42
+ binding,
43
+ options.transformSkillBody,
44
+ availableToolNames,
45
+ )),
46
+ scriptRunner(bindings, options),
47
+ );
48
+ await registry.load();
49
+
50
+ const tools = registry.tools();
51
+ if (options.workspace) {
52
+ tools.materialize_skill_resource = materializeSkillResourceTool(
53
+ bindings,
54
+ options.workspace,
55
+ );
56
+ }
57
+
58
+ return Object.entries(tools).map(([name, tool]) => {
59
+ const adapted = aiToolToPi(name, tool, {
60
+ label: SKILL_TOOL_LABELS[name] ?? name,
61
+ ...(name === "read_skill_resource"
62
+ ? {
63
+ description:
64
+ "Read a bundled resource listed by activate_skill. Returns structured resource metadata and content. Do not pass SKILL.md; activate_skill returns the Skill instructions.",
65
+ }
66
+ : {}),
67
+ });
68
+ const properties = (adapted.parameters as { properties?: unknown }).properties;
69
+ if (properties && typeof properties === "object" && !Array.isArray(properties)) {
70
+ for (const [parameter, description] of Object.entries(
71
+ SKILL_TOOL_PARAMETER_DESCRIPTIONS[name] ?? {},
72
+ )) {
73
+ const schema = (properties as Record<string, unknown>)[parameter];
74
+ if (schema && typeof schema === "object" && !Array.isArray(schema)) {
75
+ (schema as Record<string, unknown>).description ??= description;
76
+ }
77
+ }
78
+ }
79
+ if (name === "read_skill_resource") wrapSkillResourceRead(adapted, bindings);
80
+ if (name === "run_skill_script") wrapSkillScript(adapted, options.workspace);
81
+ return {
82
+ owner: "runtime-skill",
83
+ requiredExecutionLevel: "safe",
84
+ // activate_skill 返回的是 Skill 指令本身,是模型接下来所有动作的依据。把它外置
85
+ // 成文件,模型手里就只剩一个路径,必须再取一次才能知道该做什么 —— 而典型
86
+ // SKILL.md 正好落在会触发外置的区间。指令必须当场到手。
87
+ ...(name === "activate_skill"
88
+ ? { outputBudget: { kind: "structure" as const } }
89
+ : {}),
90
+ ...(name === "activate_skill"
91
+ ? { exposureMode: "direct" as const }
92
+ : { exposureMode: "codemode" as const }),
93
+ ...(name === "activate_skill" || name === "read_skill_resource"
94
+ ? { retry: "idempotent" as const }
95
+ : {}),
96
+ tool: adapted,
97
+ };
98
+ });
99
+ }