@wheatley-ai/cli 0.0.0-stage → 0.1.0

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 (210) hide show
  1. package/LICENSE +15 -0
  2. package/bin/wheatley.js +2 -0
  3. package/dist/approvals/gate.js +278 -0
  4. package/dist/approvals/module.js +21 -0
  5. package/dist/approvals/policy.js +30 -0
  6. package/dist/approvals/preview.js +17 -0
  7. package/dist/approvals/prompt.js +98 -0
  8. package/dist/approvals/rpc.js +16 -0
  9. package/dist/approvals/store.js +159 -0
  10. package/dist/cli/ask.js +94 -0
  11. package/dist/cli/chat.js +178 -0
  12. package/dist/cli/client.js +104 -0
  13. package/dist/cli/daemon.js +35 -0
  14. package/dist/cli/init.js +72 -0
  15. package/dist/cli/io.js +45 -0
  16. package/dist/cli/main.js +206 -0
  17. package/dist/cli/session.js +86 -0
  18. package/dist/cli/status.js +46 -0
  19. package/dist/contracts/approval-gate.js +1 -0
  20. package/dist/contracts/config-store.js +1 -0
  21. package/dist/contracts/delivery-outbox.js +1 -0
  22. package/dist/contracts/errors.js +28 -0
  23. package/dist/contracts/extension-catalog.js +1 -0
  24. package/dist/contracts/maintenance-runner.js +1 -0
  25. package/dist/contracts/memory-store.js +1 -0
  26. package/dist/contracts/module.js +7 -0
  27. package/dist/contracts/tool-names.js +43 -0
  28. package/dist/contracts/trigger-runtime.js +1 -0
  29. package/dist/contracts/webhook-ingress.js +2 -0
  30. package/dist/core/agent/agent-store.js +300 -0
  31. package/dist/core/agent/agent.js +1033 -0
  32. package/dist/core/agent/gated-models.js +89 -0
  33. package/dist/core/agent/pi-adapter.js +401 -0
  34. package/dist/core/agent/policy-gate.js +44 -0
  35. package/dist/core/builtin-catalog.js +20 -0
  36. package/dist/core/concurrency-gate.js +87 -0
  37. package/dist/core/config/atomic-file.js +72 -0
  38. package/dist/core/config/config-store.js +138 -0
  39. package/dist/core/config/pending-restart.js +53 -0
  40. package/dist/core/config/secret-references.js +69 -0
  41. package/dist/core/config/secret-store.js +147 -0
  42. package/dist/core/config/validate.js +55 -0
  43. package/dist/core/config/yaml-patch.js +57 -0
  44. package/dist/core/daemon-socket.js +96 -0
  45. package/dist/core/daemon.js +97 -0
  46. package/dist/core/deployment.js +379 -0
  47. package/dist/core/error-message.js +4 -0
  48. package/dist/core/events.js +25 -0
  49. package/dist/core/logger.js +81 -0
  50. package/dist/core/models.js +27 -0
  51. package/dist/core/module.js +42 -0
  52. package/dist/core/rpc/agent-handlers.js +82 -0
  53. package/dist/core/rpc/deployment-handlers.js +63 -0
  54. package/dist/core/rpc/router.js +96 -0
  55. package/dist/core/server/connection.js +170 -0
  56. package/dist/core/server/control-server.js +152 -0
  57. package/dist/core/server/static-files.js +79 -0
  58. package/dist/core/supervisor.js +215 -0
  59. package/dist/core/tool-routing.js +41 -0
  60. package/dist/dashboard/assets/index-C9Rul5vE.css +2 -0
  61. package/dist/dashboard/assets/index-DXzGGAxQ.js +11 -0
  62. package/dist/dashboard/assets/sheet-presentation-DMljN0LW.js +1 -0
  63. package/dist/dashboard/index.html +18 -0
  64. package/dist/db/database.js +16 -0
  65. package/dist/db/migrations.js +184 -0
  66. package/dist/frontends/discord/approvals.js +199 -0
  67. package/dist/frontends/discord/attachments.js +115 -0
  68. package/dist/frontends/discord/binding.js +489 -0
  69. package/dist/frontends/discord/config.js +107 -0
  70. package/dist/frontends/discord/discord-runtime.js +52 -0
  71. package/dist/frontends/discord/errors.js +61 -0
  72. package/dist/frontends/discord/live-runs.js +189 -0
  73. package/dist/frontends/discord/module.js +39 -0
  74. package/dist/frontends/discord/recent-ids.js +20 -0
  75. package/dist/frontends/slack/approval-blocks.js +98 -0
  76. package/dist/frontends/slack/attachments.js +102 -0
  77. package/dist/frontends/slack/background-tasks.js +20 -0
  78. package/dist/frontends/slack/binding.js +405 -0
  79. package/dist/frontends/slack/bounded.js +9 -0
  80. package/dist/frontends/slack/chat-id.js +17 -0
  81. package/dist/frontends/slack/config.js +80 -0
  82. package/dist/frontends/slack/delivery-errors.js +81 -0
  83. package/dist/frontends/slack/inbound.js +76 -0
  84. package/dist/frontends/slack/live-progress.js +190 -0
  85. package/dist/frontends/slack/manifest.js +66 -0
  86. package/dist/frontends/slack/outbound.js +160 -0
  87. package/dist/frontends/slack/schemas.js +99 -0
  88. package/dist/frontends/slack/signature.js +30 -0
  89. package/dist/frontends/slack/slack-client.js +60 -0
  90. package/dist/frontends/slack/slack-frontend.js +38 -0
  91. package/dist/frontends/slack/state-store.js +112 -0
  92. package/dist/frontends/telegram/approvals.js +134 -0
  93. package/dist/frontends/telegram/attachments.js +126 -0
  94. package/dist/frontends/telegram/binding.js +144 -0
  95. package/dist/frontends/telegram/chat-key.js +43 -0
  96. package/dist/frontends/telegram/client.js +88 -0
  97. package/dist/frontends/telegram/config.js +93 -0
  98. package/dist/frontends/telegram/delivery.js +215 -0
  99. package/dist/frontends/telegram/frontend.js +42 -0
  100. package/dist/frontends/telegram/grammy-client.js +122 -0
  101. package/dist/frontends/telegram/http-status.js +6 -0
  102. package/dist/frontends/telegram/inbound.js +149 -0
  103. package/dist/frontends/telegram/live.js +182 -0
  104. package/dist/frontends/telegram/markdown.js +103 -0
  105. package/dist/frontends/telegram/recent-set.js +18 -0
  106. package/dist/frontends/telegram/serial-queue.js +23 -0
  107. package/dist/index.js +7 -0
  108. package/dist/mcp/content.js +61 -0
  109. package/dist/mcp/mcp-module.js +35 -0
  110. package/dist/mcp/mcp-tool-provider.js +93 -0
  111. package/dist/mcp/server-connection.js +297 -0
  112. package/dist/memory/consolidation.js +260 -0
  113. package/dist/memory/format.js +5 -0
  114. package/dist/memory/migrations.js +76 -0
  115. package/dist/memory/module.js +69 -0
  116. package/dist/memory/names.js +20 -0
  117. package/dist/memory/rows.js +22 -0
  118. package/dist/memory/rpc.js +49 -0
  119. package/dist/memory/snapshots.js +12 -0
  120. package/dist/memory/store.js +281 -0
  121. package/dist/memory/tools.js +158 -0
  122. package/dist/node_modules/@wheatley-ai/protocol/dist/config.d.ts +262 -0
  123. package/dist/node_modules/@wheatley-ai/protocol/dist/config.js +120 -0
  124. package/dist/node_modules/@wheatley-ai/protocol/dist/domain.d.ts +512 -0
  125. package/dist/node_modules/@wheatley-ai/protocol/dist/domain.js +441 -0
  126. package/dist/node_modules/@wheatley-ai/protocol/dist/duration.d.ts +8 -0
  127. package/dist/node_modules/@wheatley-ai/protocol/dist/duration.js +28 -0
  128. package/dist/node_modules/@wheatley-ai/protocol/dist/events.d.ts +234 -0
  129. package/dist/node_modules/@wheatley-ai/protocol/dist/events.js +124 -0
  130. package/dist/node_modules/@wheatley-ai/protocol/dist/index.d.ts +11 -0
  131. package/dist/node_modules/@wheatley-ai/protocol/dist/index.js +11 -0
  132. package/dist/node_modules/@wheatley-ai/protocol/dist/json-rpc.d.ts +81 -0
  133. package/dist/node_modules/@wheatley-ai/protocol/dist/json-rpc.js +157 -0
  134. package/dist/node_modules/@wheatley-ai/protocol/dist/json.d.ts +14 -0
  135. package/dist/node_modules/@wheatley-ai/protocol/dist/json.js +23 -0
  136. package/dist/node_modules/@wheatley-ai/protocol/dist/limits.d.ts +17 -0
  137. package/dist/node_modules/@wheatley-ai/protocol/dist/limits.js +17 -0
  138. package/dist/node_modules/@wheatley-ai/protocol/dist/methods.d.ts +1107 -0
  139. package/dist/node_modules/@wheatley-ai/protocol/dist/methods.js +201 -0
  140. package/dist/node_modules/@wheatley-ai/protocol/dist/rpc-error.d.ts +45 -0
  141. package/dist/node_modules/@wheatley-ai/protocol/dist/rpc-error.js +44 -0
  142. package/dist/node_modules/@wheatley-ai/protocol/dist/validation.d.ts +20 -0
  143. package/dist/node_modules/@wheatley-ai/protocol/dist/validation.js +11 -0
  144. package/dist/node_modules/@wheatley-ai/protocol/package.json +14 -0
  145. package/dist/node_modules/@wheatley-ai/sdk/dist/chunk.d.ts +11 -0
  146. package/dist/node_modules/@wheatley-ai/sdk/dist/chunk.js +162 -0
  147. package/dist/node_modules/@wheatley-ai/sdk/dist/commands.d.ts +48 -0
  148. package/dist/node_modules/@wheatley-ai/sdk/dist/commands.js +39 -0
  149. package/dist/node_modules/@wheatley-ai/sdk/dist/delivery-error.d.ts +29 -0
  150. package/dist/node_modules/@wheatley-ai/sdk/dist/delivery-error.js +27 -0
  151. package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.d.ts +236 -0
  152. package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.js +2 -0
  153. package/dist/node_modules/@wheatley-ai/sdk/dist/index.d.ts +10 -0
  154. package/dist/node_modules/@wheatley-ai/sdk/dist/index.js +7 -0
  155. package/dist/node_modules/@wheatley-ai/sdk/dist/json.d.ts +9 -0
  156. package/dist/node_modules/@wheatley-ai/sdk/dist/json.js +2 -0
  157. package/dist/node_modules/@wheatley-ai/sdk/dist/logger.d.ts +18 -0
  158. package/dist/node_modules/@wheatley-ai/sdk/dist/logger.js +2 -0
  159. package/dist/node_modules/@wheatley-ai/sdk/dist/plugin.d.ts +48 -0
  160. package/dist/node_modules/@wheatley-ai/sdk/dist/plugin.js +5 -0
  161. package/dist/node_modules/@wheatley-ai/sdk/dist/schema.d.ts +69 -0
  162. package/dist/node_modules/@wheatley-ai/sdk/dist/schema.js +3 -0
  163. package/dist/node_modules/@wheatley-ai/sdk/dist/tool.d.ts +69 -0
  164. package/dist/node_modules/@wheatley-ai/sdk/dist/tool.js +3 -0
  165. package/dist/node_modules/@wheatley-ai/sdk/package.json +11 -0
  166. package/dist/ops/backup.js +185 -0
  167. package/dist/ops/cli.js +194 -0
  168. package/dist/ops/command-runner.js +34 -0
  169. package/dist/ops/dashboard-assets.js +37 -0
  170. package/dist/ops/migrate.js +63 -0
  171. package/dist/ops/module.js +47 -0
  172. package/dist/ops/paths.js +55 -0
  173. package/dist/ops/service.js +376 -0
  174. package/dist/ops/update.js +145 -0
  175. package/dist/plugins/contributions.js +89 -0
  176. package/dist/plugins/guards.js +111 -0
  177. package/dist/plugins/load.js +76 -0
  178. package/dist/plugins/module.js +31 -0
  179. package/dist/plugins/provider.js +349 -0
  180. package/dist/plugins/schema.js +69 -0
  181. package/dist/skills/disclosure.js +142 -0
  182. package/dist/skills/discovery.js +120 -0
  183. package/dist/skills/fs-errors.js +8 -0
  184. package/dist/skills/read-skill-tool.js +3 -0
  185. package/dist/skills/skill-file.js +90 -0
  186. package/dist/skills/skills.js +140 -0
  187. package/dist/tools/builtin-tools.js +61 -0
  188. package/dist/tools/input.js +45 -0
  189. package/dist/tools/paths.js +6 -0
  190. package/dist/tools/read-file.js +65 -0
  191. package/dist/tools/shell.js +156 -0
  192. package/dist/tools/write-file.js +58 -0
  193. package/dist/triggers/delivery-codec.js +99 -0
  194. package/dist/triggers/delivery-outbox.js +313 -0
  195. package/dist/triggers/due-timer.js +14 -0
  196. package/dist/triggers/errors.js +2 -0
  197. package/dist/triggers/migrations.js +91 -0
  198. package/dist/triggers/module.js +106 -0
  199. package/dist/triggers/rpc.js +35 -0
  200. package/dist/triggers/schedule.js +52 -0
  201. package/dist/triggers/sql-row.js +59 -0
  202. package/dist/triggers/trigger-runtime.js +445 -0
  203. package/dist/triggers/trigger-tools.js +210 -0
  204. package/dist/triggers/webhook-ingress.js +212 -0
  205. package/dist/wiring/agent-services.js +151 -0
  206. package/dist/wiring/catalog.js +81 -0
  207. package/dist/wiring/daemon.js +83 -0
  208. package/dist/wiring/frontend-host.js +268 -0
  209. package/package.json +50 -3
  210. package/README.md +0 -3
@@ -0,0 +1,89 @@
1
+ import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";
2
+ import { errorMessage } from "../error-message.js";
3
+ /** An error response for a request whose provider stream could not start. */
4
+ const failedResponse = (model, message) => ({
5
+ api: model.api,
6
+ content: [],
7
+ errorMessage: message,
8
+ model: model.id,
9
+ provider: model.provider,
10
+ role: "assistant",
11
+ stopReason: "error",
12
+ timestamp: Date.now(),
13
+ usage: {
14
+ cacheRead: 0,
15
+ cacheWrite: 0,
16
+ cost: { cacheRead: 0, cacheWrite: 0, input: 0, output: 0, total: 0 },
17
+ input: 0,
18
+ output: 0,
19
+ totalTokens: 0,
20
+ },
21
+ });
22
+ /** Forwards `source` into `target` after the gate grants a slot of `key`, and frees the slot when the response ends. */
23
+ const pipeWithSlot = async (gate, model, signal, open, target) => {
24
+ let lease;
25
+ try {
26
+ lease = await gate.acquire(model.provider, signal);
27
+ }
28
+ catch {
29
+ // The request was aborted while it waited. The provider sees the aborted signal and ends the stream itself.
30
+ }
31
+ try {
32
+ const source = open();
33
+ for await (const event of source) {
34
+ target.push(event);
35
+ }
36
+ target.end(await source.result());
37
+ }
38
+ catch (error) {
39
+ const response = failedResponse(model, errorMessage(error));
40
+ target.push({ error: response, reason: "error", type: "error" });
41
+ target.end(response);
42
+ }
43
+ finally {
44
+ lease?.release();
45
+ }
46
+ };
47
+ /** Applies the `baseUrl` of the provider's `config.yaml` entry, if it has one. */
48
+ const withBaseUrl = (model, baseUrlOf) => {
49
+ const baseUrl = baseUrlOf(model.provider);
50
+ return baseUrl === undefined ? model : { ...model, baseUrl };
51
+ };
52
+ /**
53
+ * Wraps pi-ai `Models` so that each model request first takes a Concurrency Gate slot of its provider. A parked Tool
54
+ * call makes no request, so it holds no slot (ADR 0011). Requests also use the provider's configured `baseUrl`.
55
+ */
56
+ export const gatedModels = (inner, gate, baseUrlOf) => ({
57
+ cancelDeferred: inner.cancelDeferred.bind(inner),
58
+ checkAuth: inner.checkAuth.bind(inner),
59
+ classify: inner.classify.bind(inner),
60
+ complete: inner.complete.bind(inner),
61
+ completeSimple: inner.completeSimple.bind(inner),
62
+ fetchDeferred: inner.fetchDeferred.bind(inner),
63
+ generateImages: inner.generateImages.bind(inner),
64
+ getAllAvailable: inner.getAllAvailable.bind(inner),
65
+ getAllModels: inner.getAllModels.bind(inner),
66
+ getAuth: inner.getAuth.bind(inner),
67
+ getAvailable: inner.getAvailable.bind(inner),
68
+ getAvailableOfType: inner.getAvailableOfType.bind(inner),
69
+ getModel: inner.getModel.bind(inner),
70
+ getModelOfType: inner.getModelOfType.bind(inner),
71
+ getModels: inner.getModels.bind(inner),
72
+ getModelsOfType: inner.getModelsOfType.bind(inner),
73
+ getProvider: inner.getProvider.bind(inner),
74
+ getProviders: inner.getProviders.bind(inner),
75
+ login: inner.login.bind(inner),
76
+ logout: inner.logout.bind(inner),
77
+ refresh: inner.refresh.bind(inner),
78
+ stream: (model, context, options) => {
79
+ const target = createAssistantMessageEventStream();
80
+ void pipeWithSlot(gate, model, options?.signal, () => inner.stream(withBaseUrl(model, baseUrlOf), context, options), target);
81
+ return target;
82
+ },
83
+ streamDeferred: inner.streamDeferred.bind(inner),
84
+ streamSimple: (model, context, options) => {
85
+ const target = createAssistantMessageEventStream();
86
+ void pipeWithSlot(gate, model, options?.signal, () => inner.streamSimple(withBaseUrl(model, baseUrlOf), context, options), target);
87
+ return target;
88
+ },
89
+ });
@@ -0,0 +1,401 @@
1
+ // The only module of Wheatley that imports @earendil-works/pi-durable (ADR 0003). Everything outside it sees
2
+ // Wheatley's own types: string IDs, `ToolResult`, and `PiRunOutcome`.
3
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
4
+ import { CompactionTask, createRegistry, defineExtension, defineSignal, defineTool, Harness, hook, LiveDoc, ToolTask, } from "@earendil-works/pi-durable";
5
+ import { openNodeSqliteStorage } from "@earendil-works/pi-durable/storage/sqlite/node";
6
+ import { bool, obj } from "@earendil-works/pi-schema";
7
+ import { isJsonValue } from "@wheatley-ai/protocol";
8
+ import { errorMessage } from "../error-message.js";
9
+ const context = BACKGROUND_CONTEXT;
10
+ /** The longest run of entries that `wait` reads to sum a Run's usage. */
11
+ const RUN_ENTRY_PAGE = 500;
12
+ /** The memo of a compaction task that holds the ID of its flush fork, so a rerun after a crash reuses the fork. */
13
+ const FLUSH_FORK_MEMO = "wheatley.flush.fork";
14
+ /** The transcript entry of text that Wheatley adds to a Conversation's context without a Run. */
15
+ const CONTEXT_ENTRY_KIND = "wheatley.context";
16
+ /** Wakes a Tool call that waits for an Approval. The value carries nothing: the gate reads the decision itself. */
17
+ const ApprovalWake = defineSignal({
18
+ name: "wheatley.approval.wake",
19
+ schema: obj({ decided: bool() }),
20
+ version: 1,
21
+ });
22
+ const isConversationId = (value) => Number.isSafeInteger(value) && value >= 0;
23
+ const isTaskId = (value) => Number.isSafeInteger(value) && value >= 0;
24
+ const isSubmissionId = (value) => Number.isSafeInteger(value) && value >= 0;
25
+ const conversationIdOf = (id) => {
26
+ const value = Number(id);
27
+ if (!isConversationId(value)) {
28
+ throw new Error(`Invalid Conversation ID: ${id}`);
29
+ }
30
+ return value;
31
+ };
32
+ const PROVIDER_SAFE = /[^A-Za-z0-9_-]/gu;
33
+ const MAX_PROVIDER_TOOL_NAME = 64;
34
+ /**
35
+ * Maps canonical Tool names, such as `notes:add` or `mcp:github:create_issue`, to names that model providers accept
36
+ * (`^[A-Za-z0-9_-]{1,64}$`), and back. Built-in names stay the same.
37
+ */
38
+ const providerToolNames = (names) => {
39
+ const byProviderName = new Map();
40
+ for (const name of names) {
41
+ const base = name
42
+ .replaceAll(":", "__")
43
+ .replaceAll(PROVIDER_SAFE, "_")
44
+ .slice(0, MAX_PROVIDER_TOOL_NAME);
45
+ let candidate = base;
46
+ let suffix = 2;
47
+ while (byProviderName.has(candidate)) {
48
+ const tail = `_${suffix}`;
49
+ candidate = `${base.slice(0, MAX_PROVIDER_TOOL_NAME - tail.length)}${tail}`;
50
+ suffix += 1;
51
+ }
52
+ byProviderName.set(candidate, name);
53
+ }
54
+ return byProviderName;
55
+ };
56
+ const toolOutput = (result) => result.content.map((block) => block.type === "text"
57
+ ? { text: block.text, type: "text" }
58
+ : { data: block.data, mimeType: block.mimeType, type: "image" });
59
+ const assistantText = (message) => message?.role === "assistant"
60
+ ? message.content
61
+ .flatMap((block) => (block.type === "text" ? [block.text] : []))
62
+ .join("")
63
+ : undefined;
64
+ const sumUsage = (entries) => {
65
+ let inputTokens = 0;
66
+ let outputTokens = 0;
67
+ let costUsd = 0;
68
+ for (const entry of entries) {
69
+ for (const message of entry.model ?? []) {
70
+ if (message.role === "assistant") {
71
+ inputTokens +=
72
+ message.usage.input +
73
+ message.usage.cacheRead +
74
+ message.usage.cacheWrite;
75
+ outputTokens += message.usage.output;
76
+ costUsd += message.usage.cost.total;
77
+ }
78
+ }
79
+ }
80
+ return { costUsd, inputTokens, outputTokens };
81
+ };
82
+ /** The text of the partial response in `pi.live`, or `undefined` while no response streams. */
83
+ const partialText = (live) => {
84
+ const message = live.generation?.message;
85
+ if (message === undefined) {
86
+ return undefined;
87
+ }
88
+ return message.content
89
+ .flatMap((block) => (block.type === "text" ? [block.text] : []))
90
+ .join("");
91
+ };
92
+ const agentChange = (options) => ({
93
+ cwd: options.cwd,
94
+ instructions: options.instructions ?? null,
95
+ model: { modelId: options.model.id, provider: options.model.provider },
96
+ thinkingLevel: options.model.thinking ?? null,
97
+ });
98
+ /**
99
+ * Opens the Harness of one Agent over `harness.sqlite` and starts its scheduler, so work that an earlier process left
100
+ * unfinished continues.
101
+ *
102
+ * Every Tool call passes `hooks.checkTool` from a `beforeTool` hook before it runs. A `wait` verdict parks the call in a
103
+ * durable signal sleep on the verdict's `signalKey`; `wake` ends the sleep, and the hook asks again.
104
+ */
105
+ export const openPiAdapter = async (options) => {
106
+ const { hooks, log } = options;
107
+ const clock = options.now ?? Date.now;
108
+ const toolNames = providerToolNames(options.tools.map((tool) => tool.name));
109
+ const specs = new Map(options.tools.map((tool) => [tool.name, tool]));
110
+ const canonical = (providerName) => toolNames.get(providerName) ?? providerName;
111
+ const tools = [...toolNames.entries()].flatMap(([providerName, name]) => {
112
+ const spec = specs.get(name);
113
+ return spec === undefined
114
+ ? []
115
+ : [
116
+ defineTool({
117
+ description: spec.description,
118
+ execute: async (args, api, callContext) => {
119
+ const input = isJsonValue(args) ? args : null;
120
+ const result = await hooks.executeTool({
121
+ callKey: String(api.taskId),
122
+ conversationId: String(api.conversationId),
123
+ input,
124
+ toolCallId: api.callId,
125
+ toolName: name,
126
+ }, callContext.abortSignal ?? new AbortController().signal);
127
+ return {
128
+ isError: result.isError === true,
129
+ output: toolOutput(result),
130
+ };
131
+ },
132
+ name: providerName,
133
+ parameters: spec.inputSchema,
134
+ }),
135
+ ];
136
+ });
137
+ // The compaction hook runs after `Harness.open`, so it reaches the Harness through this holder.
138
+ const opened = { harness: undefined };
139
+ /**
140
+ * Runs the flush prompt as one turn in a fork of the compacting Conversation at `at`, the newest entry that the
141
+ * summary replaces. The fork sees what the summary replaces, and has the same Tools, so the model can save facts to
142
+ * Memory. The fork never compacts by itself, and its answer goes nowhere.
143
+ */
144
+ const flush = async (api, at, prompt, hookContext) => {
145
+ const { harness } = opened;
146
+ if (harness === undefined) {
147
+ return;
148
+ }
149
+ let forkId = await api.memo(FLUSH_FORK_MEMO, hookContext);
150
+ if (forkId === undefined) {
151
+ const parent = await harness.conversation(api.conversationId, hookContext);
152
+ if (parent === undefined) {
153
+ return;
154
+ }
155
+ const fork = await parent.fork(at, {
156
+ agent: { compaction: { enabled: false } },
157
+ ownership: { kind: "ownerless" },
158
+ }, hookContext);
159
+ forkId = await api.memo(FLUSH_FORK_MEMO, fork.id, hookContext);
160
+ }
161
+ const handle = isConversationId(forkId)
162
+ ? await harness.conversation(forkId, hookContext)
163
+ : undefined;
164
+ if (handle === undefined) {
165
+ return;
166
+ }
167
+ const submission = await handle.submit({ content: prompt, requestId: `flush:${api.taskId}`, type: "input" }, hookContext);
168
+ await submission.wait(hookContext);
169
+ };
170
+ const extension = defineExtension({
171
+ hooks: [
172
+ hook(CompactionTask, {
173
+ beforeCompact: async (compaction, api, hookContext) => {
174
+ const last = compaction.entries.at(-1);
175
+ const prompt = compaction.reason === "manual" ? undefined : hooks.flushPrompt();
176
+ if (prompt !== undefined && last !== undefined) {
177
+ try {
178
+ await flush(api, last.id, prompt, hookContext);
179
+ }
180
+ catch (error) {
181
+ // A failed flush must not block the compaction: without it, the next model request can overflow.
182
+ log.warn("The Memory flush before a compaction failed", {
183
+ conversationId: String(api.conversationId),
184
+ error: errorMessage(error),
185
+ });
186
+ }
187
+ }
188
+ },
189
+ }),
190
+ hook(ToolTask, {
191
+ beforeTool: async (call, api) => {
192
+ const verdict = await hooks.checkTool({
193
+ callKey: String(api.taskId),
194
+ conversationId: String(api.conversationId),
195
+ input: isJsonValue(call.arguments) ? call.arguments : null,
196
+ toolCallId: call.id,
197
+ toolName: canonical(call.name),
198
+ });
199
+ if (verdict.kind === "allow") {
200
+ return {};
201
+ }
202
+ if (verdict.kind === "deny") {
203
+ return { block: verdict.message };
204
+ }
205
+ return {
206
+ sleep: {
207
+ signals: [ApprovalWake.key(verdict.signalKey)],
208
+ until: verdict.expiresAt ?? undefined,
209
+ },
210
+ };
211
+ },
212
+ }),
213
+ ],
214
+ name: "wheatley",
215
+ tools,
216
+ });
217
+ const registry = createRegistry();
218
+ registry.install(extension);
219
+ const storage = await openNodeSqliteStorage(options.harnessPath);
220
+ const harness = await Harness.open(storage, {
221
+ models: options.models,
222
+ now: options.now,
223
+ onReport: (report) => {
224
+ log.warn("pi-durable report", {
225
+ kind: report.kind,
226
+ message: errorMessage(report.error),
227
+ });
228
+ },
229
+ registry,
230
+ }, context);
231
+ const watchClosed = async () => {
232
+ const end = await harness.closed;
233
+ if (end.kind === "failed") {
234
+ hooks.onFailed(end.error instanceof Error ? end.error : new Error(String(end.error)));
235
+ }
236
+ };
237
+ opened.harness = harness;
238
+ void watchClosed();
239
+ harness.resume();
240
+ const conversation = async (id) => {
241
+ const found = await harness.conversation(conversationIdOf(id), context);
242
+ if (found === undefined) {
243
+ throw new Error(`Unknown Conversation: ${id}`);
244
+ }
245
+ return found;
246
+ };
247
+ const outcomeOf = async (settled) => {
248
+ if (settled.type !== "input") {
249
+ return { status: "completed", text: "" };
250
+ }
251
+ if (settled.status === "unanswered") {
252
+ const detail = settled.detail === undefined
253
+ ? ""
254
+ : `: ${JSON.stringify(settled.detail)}`;
255
+ return settled.reason === "aborted"
256
+ ? { status: "stopped", text: "" }
257
+ : { error: `${settled.reason}${detail}`, status: "failed", text: "" };
258
+ }
259
+ if (settled.answer === undefined) {
260
+ return { status: "completed", text: "" };
261
+ }
262
+ const handle = await conversation(String(settled.conversationId));
263
+ const page = await handle.entries({
264
+ maxEntryId: settled.answer,
265
+ minEntryId: settled.entry,
266
+ order: "ascending",
267
+ }, RUN_ENTRY_PAGE, undefined, context);
268
+ const answer = page.items.find((entry) => entry.id === settled.answer);
269
+ return {
270
+ status: "completed",
271
+ text: assistantText(answer?.model?.[0]) ?? "",
272
+ usage: sumUsage(page.items),
273
+ };
274
+ };
275
+ return {
276
+ addContext: async (conversationId, text, requestId) => {
277
+ const handle = await conversation(conversationId);
278
+ await handle.submit({
279
+ entry: {
280
+ data: { text },
281
+ kind: CONTEXT_ENTRY_KIND,
282
+ model: [{ content: text, role: "user", timestamp: clock() }],
283
+ },
284
+ requestId,
285
+ type: "write",
286
+ }, context);
287
+ },
288
+ close: async () => {
289
+ await harness.close(context);
290
+ },
291
+ compact: async (conversationId) => {
292
+ const handle = await conversation(conversationId);
293
+ const taskId = await handle.compact(undefined, context);
294
+ await harness.waitForTask(taskId, context);
295
+ },
296
+ createConversation: async (conversationOptions) => {
297
+ const created = await harness.createConversation({
298
+ agent: agentChange(conversationOptions),
299
+ ownership: { kind: "ownerless" },
300
+ }, context);
301
+ return String(created.id);
302
+ },
303
+ modelOf: async (conversationId) => {
304
+ const found = await harness.conversation(conversationIdOf(conversationId), context);
305
+ const agent = found === undefined ? undefined : await found.agent(context);
306
+ const model = agent?.model;
307
+ return model === undefined
308
+ ? undefined
309
+ : `${model.provider}/${model.modelId}`;
310
+ },
311
+ setInstructions: async (conversationId, instructions) => {
312
+ const handle = await conversation(conversationId);
313
+ await handle.configure({ instructions: instructions ?? null }, context);
314
+ },
315
+ setModel: async (conversationId, model) => {
316
+ const handle = await conversation(conversationId);
317
+ await handle.configure({
318
+ model: { modelId: model.id, provider: model.provider },
319
+ thinkingLevel: model.thinking ?? null,
320
+ }, context);
321
+ },
322
+ stop: async (conversationId) => {
323
+ const handle = await conversation(conversationId);
324
+ await handle.abort(context);
325
+ },
326
+ submit: async (conversationId, text, requestId) => {
327
+ const handle = await conversation(conversationId);
328
+ const submission = await handle.submit({ content: text, requestId, type: "input" }, context);
329
+ return String(submission.id);
330
+ },
331
+ wait: async (submissionId) => {
332
+ const id = Number(submissionId);
333
+ if (!isSubmissionId(id)) {
334
+ throw new Error(`Invalid submission ID: ${submissionId}`);
335
+ }
336
+ const submission = await harness.submission(id, context);
337
+ if (submission === undefined) {
338
+ return {
339
+ error: "The submission no longer exists",
340
+ status: "failed",
341
+ text: "",
342
+ };
343
+ }
344
+ return await outcomeOf(await submission.wait(context));
345
+ },
346
+ watchText: async (conversationId, onText) => {
347
+ let sent = "";
348
+ const forward = (live) => {
349
+ const text = partialText(live);
350
+ if (text === undefined) {
351
+ sent = "";
352
+ return;
353
+ }
354
+ // A shorter or different text belongs to a new response.
355
+ const start = text.startsWith(sent) ? sent.length : 0;
356
+ const piece = text.slice(start);
357
+ sent = text;
358
+ if (piece !== "") {
359
+ // The observer must not call back into the Harness or throw, so the listener runs after it returns.
360
+ queueMicrotask(() => {
361
+ onText(piece);
362
+ });
363
+ }
364
+ };
365
+ const observation = await harness.observeDoc(LiveDoc, conversationIdOf(conversationId), {
366
+ advance: (call) => {
367
+ if (call.kind === "value") {
368
+ forward(call.value);
369
+ }
370
+ },
371
+ end: () => {
372
+ // The Harness closed; the Run ends with it.
373
+ },
374
+ }, context);
375
+ if (observation === undefined) {
376
+ return () => {
377
+ // The Conversation has no live document to watch.
378
+ };
379
+ }
380
+ forward(observation.value);
381
+ return () => {
382
+ observation.detach();
383
+ };
384
+ },
385
+ wake: async (calls) => {
386
+ await Promise.all(calls.map(async (call) => {
387
+ const taskId = Number(call.callKey);
388
+ if (!isTaskId(taskId)) {
389
+ return;
390
+ }
391
+ const result = await harness.signal(taskId, ApprovalWake, call.signalKey, { decided: true }, context);
392
+ if (result !== "delivered" && result !== "duplicate") {
393
+ log.debug("An Approval wake found no parked call", {
394
+ callKey: call.callKey,
395
+ result,
396
+ });
397
+ }
398
+ }));
399
+ },
400
+ };
401
+ };
@@ -0,0 +1,44 @@
1
+ import { matchesToolPattern } from "../../contracts/tool-names.js";
2
+ /** The action of the first matching rule, else the Tool's default action, else `ask` (ADR 0011). */
3
+ export const evaluatePolicy = (policy, toolName, defaultAction) => policy.find((rule) => matchesToolPattern(rule.tool, toolName))?.action ??
4
+ defaultAction ??
5
+ "ask";
6
+ /**
7
+ * The gate of an Agent that runs without the Approvals module. It applies the Permission Policy and denies every `ask`
8
+ * Tool, because nobody can answer an Approval. It stores nothing, so `decide` and `cancelRun` find no Approvals.
9
+ */
10
+ export const createPolicyOnlyGate = (host) => ({
11
+ cancelRun: async () => {
12
+ await Promise.resolve();
13
+ return 0;
14
+ },
15
+ check: async (call) => {
16
+ await Promise.resolve();
17
+ const action = evaluatePolicy(host.policy, call.toolName, host.defaultAction(call.toolName));
18
+ if (action === "allow") {
19
+ return { kind: "allow" };
20
+ }
21
+ return action === "deny"
22
+ ? {
23
+ kind: "deny",
24
+ message: `The Permission Policy denies ${call.toolName}`,
25
+ reason: "policy",
26
+ }
27
+ : {
28
+ kind: "deny",
29
+ message: `${call.toolName} needs an Approval, and this Agent has no Approval gate`,
30
+ reason: "non_interactive",
31
+ };
32
+ },
33
+ clearConversationGrants: async () => {
34
+ await Promise.resolve();
35
+ },
36
+ decide: async () => {
37
+ await Promise.resolve();
38
+ return false;
39
+ },
40
+ listPending: async () => {
41
+ await Promise.resolve();
42
+ return [];
43
+ },
44
+ });
@@ -0,0 +1,20 @@
1
+ import { createBuiltinToolProvider } from "../tools/builtin-tools.js";
2
+ /**
3
+ * The extension catalog of a Deployment without the Plugins, MCP, and Skills modules: each Agent gets its own built-in
4
+ * Tools and nothing else. The Wave 2 catalog replaces it and adds the other providers after the built-in Tools.
5
+ */
6
+ export const builtinOnlyCatalog = {
7
+ createAgentExtensions: async () => {
8
+ await Promise.resolve();
9
+ const builtin = createBuiltinToolProvider();
10
+ return {
11
+ close: builtin.close,
12
+ executeTool: builtin.execute,
13
+ frontends: () => new Map(),
14
+ health: () => ({ mcpServers: [], plugins: [], skillWarnings: [] }),
15
+ skillCatalogPrompt: () => "",
16
+ skills: () => [],
17
+ tools: builtin.tools,
18
+ };
19
+ },
20
+ };
@@ -0,0 +1,87 @@
1
+ /** The slot limit of a provider credential without `maxConcurrent` in `config.yaml`. */
2
+ export const DEFAULT_PROVIDER_CONCURRENCY = 4;
3
+ /**
4
+ * Limits concurrent model requests per provider credential across every Agent of the Deployment (ADR 0001). Each key
5
+ * is one provider entry of `config.yaml`. Waiters get slots in FIFO order.
6
+ *
7
+ * Invariant: `inUse` never exceeds the key's limit at the moment a slot is granted. A lower limit applies as slots free
8
+ * up; it never revokes a held slot.
9
+ */
10
+ export class ConcurrencyGate {
11
+ #limitOf;
12
+ #keys = new Map();
13
+ /** `limitOf` returns the current limit of a key. The gate reads it on every grant, so config changes apply live. */
14
+ constructor(limitOf) {
15
+ this.#limitOf = limitOf;
16
+ }
17
+ /**
18
+ * Resolves with a lease once a slot of `key` is free. Waiters are served in call order.
19
+ *
20
+ * Errors: rejects with the abort reason if `signal` aborts first. The waiter then leaves the queue and takes no slot.
21
+ */
22
+ acquire = async (key, signal) => {
23
+ signal?.throwIfAborted();
24
+ const state = this.#state(key);
25
+ if (state.waiting.length === 0 && state.inUse < this.#limit(key)) {
26
+ return this.#grant(key, state);
27
+ }
28
+ const { promise, resolve, reject } = Promise.withResolvers();
29
+ const waiter = { grant: resolve, refuse: reject };
30
+ const onAbort = () => {
31
+ const index = state.waiting.indexOf(waiter);
32
+ if (index !== -1) {
33
+ state.waiting.splice(index, 1);
34
+ reject(signal?.reason instanceof Error
35
+ ? signal.reason
36
+ : new Error("The wait for a model slot was aborted"));
37
+ }
38
+ };
39
+ signal?.addEventListener("abort", onAbort, { once: true });
40
+ state.waiting.push(waiter);
41
+ try {
42
+ return await promise;
43
+ }
44
+ finally {
45
+ signal?.removeEventListener("abort", onAbort);
46
+ }
47
+ };
48
+ /** The use of every key that has held or waited for a slot, sorted by key. */
49
+ pressure = () => [...this.#keys.entries()]
50
+ .toSorted(([left], [right]) => left.localeCompare(right))
51
+ .map(([credential, state]) => ({
52
+ credential,
53
+ inUse: state.inUse,
54
+ limit: this.#limit(credential),
55
+ waiting: state.waiting.length,
56
+ }));
57
+ #limit = (key) => Math.max(1, Math.floor(this.#limitOf(key)));
58
+ #state = (key) => {
59
+ const existing = this.#keys.get(key);
60
+ if (existing !== undefined) {
61
+ return existing;
62
+ }
63
+ const created = { inUse: 0, waiting: [] };
64
+ this.#keys.set(key, created);
65
+ return created;
66
+ };
67
+ #grant = (key, state) => {
68
+ state.inUse += 1;
69
+ let released = false;
70
+ return {
71
+ release: () => {
72
+ if (released) {
73
+ return;
74
+ }
75
+ released = true;
76
+ state.inUse -= 1;
77
+ this.#drain(key, state);
78
+ },
79
+ };
80
+ };
81
+ #drain = (key, state) => {
82
+ while (state.waiting.length > 0 && state.inUse < this.#limit(key)) {
83
+ const next = state.waiting.shift();
84
+ next?.grant(this.#grant(key, state));
85
+ }
86
+ };
87
+ }