@wheatley-ai/cli 0.0.0-stage → 0.0.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.
- package/LICENSE +15 -0
- package/bin/wheatley.js +2 -0
- package/dist/approvals/gate.js +278 -0
- package/dist/approvals/module.js +21 -0
- package/dist/approvals/policy.js +30 -0
- package/dist/approvals/preview.js +17 -0
- package/dist/approvals/prompt.js +98 -0
- package/dist/approvals/rpc.js +16 -0
- package/dist/approvals/store.js +159 -0
- package/dist/cli/ask.js +94 -0
- package/dist/cli/chat.js +180 -0
- package/dist/cli/client.js +104 -0
- package/dist/cli/daemon.js +35 -0
- package/dist/cli/init.js +72 -0
- package/dist/cli/io.js +45 -0
- package/dist/cli/main.js +204 -0
- package/dist/cli/session.js +87 -0
- package/dist/cli/status.js +46 -0
- package/dist/contracts/approval-gate.js +1 -0
- package/dist/contracts/config-store.js +1 -0
- package/dist/contracts/delivery-outbox.js +1 -0
- package/dist/contracts/errors.js +28 -0
- package/dist/contracts/extension-catalog.js +1 -0
- package/dist/contracts/maintenance-runner.js +1 -0
- package/dist/contracts/memory-store.js +1 -0
- package/dist/contracts/module.js +7 -0
- package/dist/contracts/tool-names.js +43 -0
- package/dist/contracts/trigger-runtime.js +1 -0
- package/dist/contracts/webhook-ingress.js +2 -0
- package/dist/core/agent/agent-store.js +300 -0
- package/dist/core/agent/agent.js +1020 -0
- package/dist/core/agent/gated-models.js +89 -0
- package/dist/core/agent/pi-adapter.js +401 -0
- package/dist/core/agent/policy-gate.js +44 -0
- package/dist/core/builtin-catalog.js +20 -0
- package/dist/core/concurrency-gate.js +87 -0
- package/dist/core/config/atomic-file.js +61 -0
- package/dist/core/config/config-store.js +138 -0
- package/dist/core/config/pending-restart.js +53 -0
- package/dist/core/config/secret-references.js +69 -0
- package/dist/core/config/secret-store.js +147 -0
- package/dist/core/config/validate.js +55 -0
- package/dist/core/config/yaml-patch.js +57 -0
- package/dist/core/daemon.js +88 -0
- package/dist/core/deployment.js +347 -0
- package/dist/core/error-message.js +4 -0
- package/dist/core/events.js +25 -0
- package/dist/core/logger.js +81 -0
- package/dist/core/models.js +27 -0
- package/dist/core/module.js +42 -0
- package/dist/core/rpc/agent-handlers.js +82 -0
- package/dist/core/rpc/deployment-handlers.js +63 -0
- package/dist/core/rpc/router.js +95 -0
- package/dist/core/server/connection.js +170 -0
- package/dist/core/server/control-server.js +152 -0
- package/dist/core/server/static-files.js +79 -0
- package/dist/core/supervisor.js +206 -0
- package/dist/core/tool-routing.js +41 -0
- package/dist/dashboard/assets/index-3COz_MZq.css +2 -0
- package/dist/dashboard/assets/index-RnxedkKh.js +11 -0
- package/dist/dashboard/assets/sheet-presentation-U1UUymXc.js +1 -0
- package/dist/dashboard/index.html +13 -0
- package/dist/db/database.js +16 -0
- package/dist/db/migrations.js +184 -0
- package/dist/frontends/discord/approvals.js +199 -0
- package/dist/frontends/discord/attachments.js +115 -0
- package/dist/frontends/discord/binding.js +489 -0
- package/dist/frontends/discord/config.js +107 -0
- package/dist/frontends/discord/discord-runtime.js +52 -0
- package/dist/frontends/discord/errors.js +61 -0
- package/dist/frontends/discord/live-runs.js +189 -0
- package/dist/frontends/discord/module.js +39 -0
- package/dist/frontends/discord/recent-ids.js +20 -0
- package/dist/frontends/slack/approval-blocks.js +98 -0
- package/dist/frontends/slack/attachments.js +102 -0
- package/dist/frontends/slack/background-tasks.js +20 -0
- package/dist/frontends/slack/binding.js +405 -0
- package/dist/frontends/slack/bounded.js +9 -0
- package/dist/frontends/slack/chat-id.js +17 -0
- package/dist/frontends/slack/config.js +80 -0
- package/dist/frontends/slack/delivery-errors.js +81 -0
- package/dist/frontends/slack/inbound.js +76 -0
- package/dist/frontends/slack/live-progress.js +190 -0
- package/dist/frontends/slack/manifest.js +66 -0
- package/dist/frontends/slack/outbound.js +160 -0
- package/dist/frontends/slack/schemas.js +99 -0
- package/dist/frontends/slack/signature.js +30 -0
- package/dist/frontends/slack/slack-client.js +60 -0
- package/dist/frontends/slack/slack-frontend.js +38 -0
- package/dist/frontends/slack/state-store.js +112 -0
- package/dist/frontends/telegram/approvals.js +134 -0
- package/dist/frontends/telegram/attachments.js +126 -0
- package/dist/frontends/telegram/binding.js +144 -0
- package/dist/frontends/telegram/chat-key.js +43 -0
- package/dist/frontends/telegram/client.js +88 -0
- package/dist/frontends/telegram/config.js +93 -0
- package/dist/frontends/telegram/delivery.js +215 -0
- package/dist/frontends/telegram/frontend.js +42 -0
- package/dist/frontends/telegram/grammy-client.js +122 -0
- package/dist/frontends/telegram/http-status.js +6 -0
- package/dist/frontends/telegram/inbound.js +149 -0
- package/dist/frontends/telegram/live.js +182 -0
- package/dist/frontends/telegram/markdown.js +103 -0
- package/dist/frontends/telegram/recent-set.js +18 -0
- package/dist/frontends/telegram/serial-queue.js +23 -0
- package/dist/index.js +7 -0
- package/dist/mcp/content.js +61 -0
- package/dist/mcp/mcp-module.js +35 -0
- package/dist/mcp/mcp-tool-provider.js +93 -0
- package/dist/mcp/server-connection.js +297 -0
- package/dist/memory/consolidation.js +260 -0
- package/dist/memory/format.js +5 -0
- package/dist/memory/migrations.js +76 -0
- package/dist/memory/module.js +69 -0
- package/dist/memory/names.js +20 -0
- package/dist/memory/rows.js +22 -0
- package/dist/memory/rpc.js +49 -0
- package/dist/memory/snapshots.js +12 -0
- package/dist/memory/store.js +281 -0
- package/dist/memory/tools.js +158 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/config.d.ts +252 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/config.js +110 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/domain.d.ts +512 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/domain.js +441 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/duration.d.ts +8 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/duration.js +28 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/events.d.ts +234 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/events.js +124 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/index.d.ts +11 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/index.js +11 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json-rpc.d.ts +81 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json-rpc.js +157 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json.d.ts +14 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json.js +23 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/limits.d.ts +17 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/limits.js +17 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/methods.d.ts +1107 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/methods.js +201 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/rpc-error.d.ts +45 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/rpc-error.js +44 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/validation.d.ts +20 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/validation.js +11 -0
- package/dist/node_modules/@wheatley-ai/protocol/package.json +14 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/chunk.d.ts +11 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/chunk.js +162 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/commands.d.ts +48 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/commands.js +39 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/delivery-error.d.ts +29 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/delivery-error.js +27 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.d.ts +236 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.js +2 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/index.d.ts +10 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/index.js +7 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/json.d.ts +9 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/json.js +2 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/logger.d.ts +18 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/logger.js +2 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/plugin.d.ts +48 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/plugin.js +5 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/schema.d.ts +69 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/schema.js +3 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/tool.d.ts +69 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/tool.js +3 -0
- package/dist/node_modules/@wheatley-ai/sdk/package.json +11 -0
- package/dist/ops/backup.js +185 -0
- package/dist/ops/cli.js +195 -0
- package/dist/ops/command-runner.js +34 -0
- package/dist/ops/dashboard-assets.js +37 -0
- package/dist/ops/migrate.js +63 -0
- package/dist/ops/module.js +47 -0
- package/dist/ops/paths.js +55 -0
- package/dist/ops/service.js +376 -0
- package/dist/ops/update.js +145 -0
- package/dist/plugins/contributions.js +89 -0
- package/dist/plugins/guards.js +111 -0
- package/dist/plugins/load.js +76 -0
- package/dist/plugins/module.js +31 -0
- package/dist/plugins/provider.js +349 -0
- package/dist/plugins/schema.js +69 -0
- package/dist/skills/disclosure.js +142 -0
- package/dist/skills/discovery.js +120 -0
- package/dist/skills/fs-errors.js +8 -0
- package/dist/skills/read-skill-tool.js +3 -0
- package/dist/skills/skill-file.js +90 -0
- package/dist/skills/skills.js +140 -0
- package/dist/tools/builtin-tools.js +61 -0
- package/dist/tools/input.js +45 -0
- package/dist/tools/paths.js +6 -0
- package/dist/tools/read-file.js +65 -0
- package/dist/tools/shell.js +156 -0
- package/dist/tools/write-file.js +58 -0
- package/dist/triggers/delivery-codec.js +99 -0
- package/dist/triggers/delivery-outbox.js +313 -0
- package/dist/triggers/due-timer.js +14 -0
- package/dist/triggers/errors.js +2 -0
- package/dist/triggers/migrations.js +91 -0
- package/dist/triggers/module.js +104 -0
- package/dist/triggers/rpc.js +35 -0
- package/dist/triggers/schedule.js +52 -0
- package/dist/triggers/sql-row.js +59 -0
- package/dist/triggers/trigger-runtime.js +445 -0
- package/dist/triggers/trigger-tools.js +207 -0
- package/dist/triggers/webhook-ingress.js +216 -0
- package/dist/wiring/agent-services.js +144 -0
- package/dist/wiring/catalog.js +81 -0
- package/dist/wiring/daemon.js +83 -0
- package/dist/wiring/frontend-host.js +268 -0
- package/package.json +50 -3
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
ISC License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Amogh Lele
|
|
4
|
+
|
|
5
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
6
|
+
purpose with or without fee is hereby granted, provided that the above
|
|
7
|
+
copyright notice and this permission notice appear in all copies.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
|
10
|
+
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
|
11
|
+
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
|
12
|
+
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
|
13
|
+
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
|
14
|
+
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
|
15
|
+
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
package/bin/wheatley.js
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { policyAction } from "./policy.js";
|
|
3
|
+
import { buildInputPreview } from "./preview.js";
|
|
4
|
+
import { createApprovalStore, toPendingApproval } from "./store.js";
|
|
5
|
+
const ALLOW_OUTCOMES = new Set([
|
|
6
|
+
"allow_once",
|
|
7
|
+
"allow_conversation",
|
|
8
|
+
"allow_always",
|
|
9
|
+
]);
|
|
10
|
+
const signalKeyOf = (callKey, approvalId) => `${callKey}:${approvalId}`;
|
|
11
|
+
const denial = (reason, message) => ({
|
|
12
|
+
kind: "deny",
|
|
13
|
+
message,
|
|
14
|
+
reason,
|
|
15
|
+
});
|
|
16
|
+
const sameRule = (left, right) => left?.action === right.action && left.tool === right.tool;
|
|
17
|
+
const isFromOriginatingChat = (origin, approval) => origin.kind === "operator" ||
|
|
18
|
+
(approval.chat !== null &&
|
|
19
|
+
origin.bindingId === approval.chat.bindingId &&
|
|
20
|
+
origin.chatId === approval.chat.chatId);
|
|
21
|
+
const stoppedMessage = (toolName) => `The Run stopped before a decision on ${toolName}`;
|
|
22
|
+
/**
|
|
23
|
+
* The verdict for a call from the outcome of its own Approval. An allow outcome returns `allow`. `deny` and `cancelled`
|
|
24
|
+
* return `deny` with that reason. Every other outcome, including `null`, returns `deny` (`timeout`).
|
|
25
|
+
*/
|
|
26
|
+
const verdictForOutcome = (approval) => {
|
|
27
|
+
const { outcome, reason, toolName } = approval;
|
|
28
|
+
if (outcome !== null && ALLOW_OUTCOMES.has(outcome)) {
|
|
29
|
+
return { kind: "allow" };
|
|
30
|
+
}
|
|
31
|
+
if (outcome === "deny") {
|
|
32
|
+
const suffix = reason === null ? "" : `: ${reason}`;
|
|
33
|
+
return denial("decision", `The Approval for ${toolName} was denied${suffix}`);
|
|
34
|
+
}
|
|
35
|
+
return outcome === "cancelled"
|
|
36
|
+
? denial("cancelled", stoppedMessage(toolName))
|
|
37
|
+
: denial("timeout", `No decision on ${toolName} before the Approval timed out`);
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* Creates the `ApprovalGate` of one Agent on `agent.sqlite` (ADR 0011). It follows the `check` order and the `decide`
|
|
41
|
+
* steps of the `ApprovalGate` contract.
|
|
42
|
+
*
|
|
43
|
+
* Invariants:
|
|
44
|
+
* - Every read and write that decides a verdict or claims an Approval runs synchronously, before the first `await`.
|
|
45
|
+
* Thus two concurrent `check` calls of one Run cannot both open an Approval, and two concurrent decisions cannot both
|
|
46
|
+
* win.
|
|
47
|
+
* - The live Permission Policy starts as `deps.policy`. An `allow_always` decision prepends an exact-tool `allow` rule
|
|
48
|
+
* to it before the first `await`, so a call that the decision wakes sees the rule.
|
|
49
|
+
* - A wake never names the call that runs `check`, because that call is not parked.
|
|
50
|
+
* - After `cancelRun`, a call that waited on a cancelled Approval gets `deny` (`cancelled`) at its next `check`. It does
|
|
51
|
+
* not open an Approval of its own.
|
|
52
|
+
*
|
|
53
|
+
* Errors:
|
|
54
|
+
* - If `outbox.enqueue` fails, the gate logs the error and continues with the event and the wake.
|
|
55
|
+
* - If `config.prependPermissionRule` fails, the gate keeps the rule in the live policy, completes the event and the
|
|
56
|
+
* wake, and then rejects `decide`. The rule ends when the Agent restarts.
|
|
57
|
+
* - A failed `deps.wake` rejects the gate method. The decision stays stored, and the parked call sees it at its next
|
|
58
|
+
* `check`.
|
|
59
|
+
*/
|
|
60
|
+
export const createApprovalGate = (ctx, deps) => {
|
|
61
|
+
const { agentName, clock, events, log } = ctx;
|
|
62
|
+
const store = createApprovalStore(ctx.db);
|
|
63
|
+
const rules = [...deps.policy];
|
|
64
|
+
const isExpired = (approval) => approval.expiresAt !== null && clock.now() >= approval.expiresAt;
|
|
65
|
+
/** Claims a pending Approval. Returns the claim to announce, or `undefined` if another caller resolved it first. */
|
|
66
|
+
const claim = (approval, outcome, resolution) => {
|
|
67
|
+
const stored = {
|
|
68
|
+
outcome,
|
|
69
|
+
reason: resolution?.reason,
|
|
70
|
+
resolvedAt: clock.now(),
|
|
71
|
+
resolvedBy: resolution?.resolvedBy,
|
|
72
|
+
};
|
|
73
|
+
return store.resolve(approval.approvalId, stored)
|
|
74
|
+
? { approval, resolution: stored }
|
|
75
|
+
: undefined;
|
|
76
|
+
};
|
|
77
|
+
/** Claims each Approval with `outcome` and returns the claims that this gate won. */
|
|
78
|
+
const claimEach = (approvals, outcome) => approvals.flatMap((approval) => claim(approval, outcome) ?? []);
|
|
79
|
+
/** Enqueues a delivery for the Chat of the Approval. If the enqueue fails, the gate logs the error and continues. */
|
|
80
|
+
const enqueueFor = async ({ approvalId, chat }, delivery) => {
|
|
81
|
+
if (chat === null) {
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
try {
|
|
85
|
+
await deps.outbox.enqueue({ ...chat, delivery });
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
log.error(`Could not enqueue ${delivery.kind}`, {
|
|
89
|
+
approvalId,
|
|
90
|
+
error: String(error),
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
/** Enqueues `approval_resolved`, emits `approval.resolved`, and wakes every parked call except `runningCallKey`. */
|
|
95
|
+
const announce = async ({ approval, resolution }, runningCallKey) => {
|
|
96
|
+
const { approvalId } = approval;
|
|
97
|
+
const { outcome, reason, resolvedBy } = resolution;
|
|
98
|
+
await enqueueFor(approval, {
|
|
99
|
+
approvalId,
|
|
100
|
+
decision: outcome,
|
|
101
|
+
kind: "approval_resolved",
|
|
102
|
+
reason,
|
|
103
|
+
resolvedBy,
|
|
104
|
+
});
|
|
105
|
+
events.emit("approval.resolved", {
|
|
106
|
+
agent: agentName,
|
|
107
|
+
approvalId,
|
|
108
|
+
decision: outcome,
|
|
109
|
+
reason,
|
|
110
|
+
resolvedBy,
|
|
111
|
+
});
|
|
112
|
+
const parked = store
|
|
113
|
+
.waiters(approvalId)
|
|
114
|
+
.filter(({ callKey }) => callKey !== runningCallKey);
|
|
115
|
+
if (parked.length > 0) {
|
|
116
|
+
await deps.wake(parked);
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
const announceAll = async (claims, runningCallKey) => {
|
|
120
|
+
for (const item of claims) {
|
|
121
|
+
// oxlint-disable-next-line no-await-in-loop -- Resolutions reach each Chat in the order the gate stored them.
|
|
122
|
+
await announce(item, runningCallKey);
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
const park = (approval, callKey) => {
|
|
126
|
+
const signalKey = signalKeyOf(callKey, approval.approvalId);
|
|
127
|
+
store.addWaiter(approval.approvalId, { callKey, signalKey });
|
|
128
|
+
return {
|
|
129
|
+
approvalId: approval.approvalId,
|
|
130
|
+
expiresAt: approval.expiresAt,
|
|
131
|
+
kind: "wait",
|
|
132
|
+
signalKey,
|
|
133
|
+
};
|
|
134
|
+
};
|
|
135
|
+
/** Times out every expired pending Approval in `pending` and returns the claims. */
|
|
136
|
+
const expire = (pending) => claimEach(pending.filter(isExpired), "timeout");
|
|
137
|
+
/** Stores a new Approval for `call` and parks the call on it. */
|
|
138
|
+
const open = (call) => {
|
|
139
|
+
const now = clock.now();
|
|
140
|
+
const approval = {
|
|
141
|
+
approvalId: randomUUID(),
|
|
142
|
+
callKey: call.callKey,
|
|
143
|
+
chat: call.chat,
|
|
144
|
+
conversationId: call.conversationId,
|
|
145
|
+
createdAt: now,
|
|
146
|
+
expiresAt: deps.timeoutMs === null ? null : now + deps.timeoutMs,
|
|
147
|
+
inputPreview: buildInputPreview(call.input, deps.secrets),
|
|
148
|
+
outcome: null,
|
|
149
|
+
reason: null,
|
|
150
|
+
resolvedBy: null,
|
|
151
|
+
runId: call.runId,
|
|
152
|
+
toolName: call.toolName,
|
|
153
|
+
};
|
|
154
|
+
store.insert(approval);
|
|
155
|
+
return { approval, verdict: park(approval, call.callKey) };
|
|
156
|
+
};
|
|
157
|
+
/** Enqueues `approval_requested` and emits `approval.requested`. */
|
|
158
|
+
const request = async (approval) => {
|
|
159
|
+
await enqueueFor(approval, {
|
|
160
|
+
approvalId: approval.approvalId,
|
|
161
|
+
expiresAt: approval.expiresAt,
|
|
162
|
+
inputPreview: approval.inputPreview,
|
|
163
|
+
kind: "approval_requested",
|
|
164
|
+
runId: approval.runId,
|
|
165
|
+
toolName: approval.toolName,
|
|
166
|
+
});
|
|
167
|
+
events.emit("approval.requested", { agent: agentName, approval });
|
|
168
|
+
};
|
|
169
|
+
/** Steps 5 and 6: the call already has its own Approval. */
|
|
170
|
+
const checkOwn = async (own, callKey) => {
|
|
171
|
+
if (own.outcome !== null) {
|
|
172
|
+
return verdictForOutcome(own);
|
|
173
|
+
}
|
|
174
|
+
if (!isExpired(own)) {
|
|
175
|
+
return park(own, callKey);
|
|
176
|
+
}
|
|
177
|
+
const claims = claimEach([own], "timeout");
|
|
178
|
+
const current = store.byId(own.approvalId) ?? own;
|
|
179
|
+
await announceAll(claims, callKey);
|
|
180
|
+
return verdictForOutcome(current);
|
|
181
|
+
};
|
|
182
|
+
/** Steps 7 and 8: wait on the Run's pending Approval, or open the call's own Approval. */
|
|
183
|
+
const checkRun = async (call) => {
|
|
184
|
+
const expired = expire(store.pending(call.runId));
|
|
185
|
+
const blocking = store.oldestPendingInRun(call.runId);
|
|
186
|
+
if (blocking !== undefined) {
|
|
187
|
+
const verdict = park(blocking, call.callKey);
|
|
188
|
+
await announceAll(expired, call.callKey);
|
|
189
|
+
return verdict;
|
|
190
|
+
}
|
|
191
|
+
const { approval, verdict } = open(call);
|
|
192
|
+
await announceAll(expired, call.callKey);
|
|
193
|
+
await request(toPendingApproval(agentName, approval));
|
|
194
|
+
return verdict;
|
|
195
|
+
};
|
|
196
|
+
const check = async (call) => {
|
|
197
|
+
const action = policyAction(rules, call.toolName, deps.defaultAction);
|
|
198
|
+
if (action === "deny") {
|
|
199
|
+
return denial("policy", `The Permission Policy denies ${call.toolName}`);
|
|
200
|
+
}
|
|
201
|
+
if (action === "allow" ||
|
|
202
|
+
store.hasGrant(call.conversationId, call.toolName)) {
|
|
203
|
+
return { kind: "allow" };
|
|
204
|
+
}
|
|
205
|
+
if (!call.interactive) {
|
|
206
|
+
return denial("non_interactive", `${call.toolName} needs an Approval, and this Run cannot ask for one`);
|
|
207
|
+
}
|
|
208
|
+
const own = store.byCallKey(call.callKey);
|
|
209
|
+
if (own !== undefined) {
|
|
210
|
+
return await checkOwn(own, call.callKey);
|
|
211
|
+
}
|
|
212
|
+
if (store.waitedOnCancelled(call.callKey)) {
|
|
213
|
+
return denial("cancelled", stoppedMessage(call.toolName));
|
|
214
|
+
}
|
|
215
|
+
return await checkRun(call);
|
|
216
|
+
};
|
|
217
|
+
/**
|
|
218
|
+
* Prepends an exact-tool `allow` rule to the live policy, then saves it to `config.yaml`. Resolves with an `Error` if
|
|
219
|
+
* the save fails, so that `decide` can complete the wake before it rejects.
|
|
220
|
+
*/
|
|
221
|
+
const applyAllowAlways = async (toolName) => {
|
|
222
|
+
const rule = { action: "allow", tool: toolName };
|
|
223
|
+
if (!sameRule(rules[0], rule)) {
|
|
224
|
+
rules.unshift(rule);
|
|
225
|
+
}
|
|
226
|
+
try {
|
|
227
|
+
await deps.config.prependPermissionRule(agentName, rule);
|
|
228
|
+
return undefined;
|
|
229
|
+
}
|
|
230
|
+
catch (error) {
|
|
231
|
+
return new Error(`config.yaml did not save the allow_always rule for ${toolName}. The rule applies until the Agent restarts.`, { cause: error });
|
|
232
|
+
}
|
|
233
|
+
};
|
|
234
|
+
const decide = async (approvalId, resolution, origin) => {
|
|
235
|
+
const approval = store.byId(approvalId);
|
|
236
|
+
if (approval === undefined ||
|
|
237
|
+
approval.outcome !== null ||
|
|
238
|
+
!isFromOriginatingChat(origin, approval)) {
|
|
239
|
+
return false;
|
|
240
|
+
}
|
|
241
|
+
if (isExpired(approval)) {
|
|
242
|
+
await announceAll(expire([approval]));
|
|
243
|
+
return false;
|
|
244
|
+
}
|
|
245
|
+
const claimed = claim(approval, resolution.decision, resolution);
|
|
246
|
+
if (claimed === undefined) {
|
|
247
|
+
return false;
|
|
248
|
+
}
|
|
249
|
+
if (resolution.decision === "allow_conversation") {
|
|
250
|
+
store.addGrant(approval.conversationId, approval.toolName, claimed.resolution.resolvedAt);
|
|
251
|
+
}
|
|
252
|
+
const saveError = resolution.decision === "allow_always"
|
|
253
|
+
? await applyAllowAlways(approval.toolName)
|
|
254
|
+
: undefined;
|
|
255
|
+
await announce(claimed);
|
|
256
|
+
if (saveError !== undefined) {
|
|
257
|
+
throw saveError;
|
|
258
|
+
}
|
|
259
|
+
return true;
|
|
260
|
+
};
|
|
261
|
+
const cancelRun = async (runId) => {
|
|
262
|
+
const cancelled = claimEach(store.pending(runId), "cancelled");
|
|
263
|
+
await announceAll(cancelled);
|
|
264
|
+
return cancelled.length;
|
|
265
|
+
};
|
|
266
|
+
const clearConversationGrants = async (conversationId) => {
|
|
267
|
+
store.clearGrants(conversationId);
|
|
268
|
+
// The seam is async, but node:sqlite writes synchronously. Lint requires both `async` and an `await` here.
|
|
269
|
+
await Promise.resolve();
|
|
270
|
+
};
|
|
271
|
+
const listPending = async () => {
|
|
272
|
+
await announceAll(expire(store.pending()));
|
|
273
|
+
return store
|
|
274
|
+
.pending()
|
|
275
|
+
.map((approval) => toPendingApproval(agentName, approval));
|
|
276
|
+
};
|
|
277
|
+
return { cancelRun, check, clearConversationGrants, decide, listPending };
|
|
278
|
+
};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { createApprovalGate } from "./gate.js";
|
|
2
|
+
import { createApprovalsRpc } from "./rpc.js";
|
|
3
|
+
import { approvalsMigrations } from "./store.js";
|
|
4
|
+
export { createApprovalsRpc } from "./rpc.js";
|
|
5
|
+
export { approvalsMigrations } from "./store.js";
|
|
6
|
+
/**
|
|
7
|
+
* The `approvals` Agent module (ADR 0011). Its API is the Agent's `ApprovalGate`. Its migration namespace is
|
|
8
|
+
* `approvals`, and it handles `approvals.list` and `approvals.decide`.
|
|
9
|
+
*
|
|
10
|
+
* Build `deps.timeoutMs` with `approvalTimeoutMs(agentConfig.approvalTimeout)` and `GatedToolCall.interactive` with
|
|
11
|
+
* `isInteractiveRun`, both from `policy.ts`. The CLI renders Approval prompts with `promptForApproval` from `prompt.ts`.
|
|
12
|
+
*/
|
|
13
|
+
export const approvalsModule = {
|
|
14
|
+
create: (ctx, deps) => {
|
|
15
|
+
const gate = createApprovalGate(ctx, deps);
|
|
16
|
+
return { api: gate, rpc: createApprovalsRpc(gate) };
|
|
17
|
+
},
|
|
18
|
+
migrations: approvalsMigrations,
|
|
19
|
+
name: "approvals",
|
|
20
|
+
scope: "agent",
|
|
21
|
+
};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { parseDuration } from "@wheatley-ai/protocol";
|
|
2
|
+
import { matchesToolPattern } from "../contracts/tool-names.js";
|
|
3
|
+
/** The Approval timeout when the Agent config has no `approvalTimeout` (ADR 0011). */
|
|
4
|
+
export const DEFAULT_APPROVAL_TIMEOUT = "15m";
|
|
5
|
+
/**
|
|
6
|
+
* Returns the action of the Permission Policy for a canonical Tool name.
|
|
7
|
+
*
|
|
8
|
+
* Order: the first rule whose `tool` pattern matches (only `*` is a wildcard), else the Tool's default action, else
|
|
9
|
+
* `ask`. Plugin and MCP Tools have no default action, so they fall back to `ask`.
|
|
10
|
+
*/
|
|
11
|
+
export const policyAction = (rules, toolName, defaultAction) => {
|
|
12
|
+
const rule = rules.find((candidate) => matchesToolPattern(candidate.tool, toolName));
|
|
13
|
+
return rule?.action ?? defaultAction(toolName) ?? "ask";
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Converts the `approvalTimeout` value of an Agent config to `ApprovalGateDeps.timeoutMs`: `undefined` gives the
|
|
17
|
+
* `15m` default, and `null` disables the timeout. Throws a `RangeError` for an invalid duration.
|
|
18
|
+
*/
|
|
19
|
+
export const approvalTimeoutMs = (approvalTimeout) => {
|
|
20
|
+
if (approvalTimeout === null) {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
return parseDuration(approvalTimeout ?? DEFAULT_APPROVAL_TIMEOUT);
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Returns the `GatedToolCall.interactive` value of a Run (ADR 0011). Trigger and maintenance Runs are never
|
|
27
|
+
* interactive. A Chat Run is interactive, except a `wheatley ask` Run that the CLI sent with `interactive: false`
|
|
28
|
+
* because it has no TTY.
|
|
29
|
+
*/
|
|
30
|
+
export const isInteractiveRun = (origin, cliAsk) => origin.kind === "chat" && (cliAsk?.interactive ?? true);
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { TOOL_INPUT_PREVIEW_MAX_LENGTH } from "@wheatley-ai/protocol";
|
|
2
|
+
const HIGH_SURROGATE_MIN = 0xd8_00;
|
|
3
|
+
const HIGH_SURROGATE_MAX = 0xdb_ff;
|
|
4
|
+
const endsWithHighSurrogate = (text) => {
|
|
5
|
+
const code = text.codePointAt(text.length - 1) ?? 0;
|
|
6
|
+
return code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX;
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* Builds the `inputPreview` of an Approval: the JSON text of the Tool input with every secret value redacted, cut to
|
|
10
|
+
* 500 characters. The cut happens after redaction, so it cannot expose part of a secret, and it never splits a
|
|
11
|
+
* surrogate pair.
|
|
12
|
+
*/
|
|
13
|
+
export const buildInputPreview = (input, secrets) => {
|
|
14
|
+
const redacted = secrets.redact(JSON.stringify(input));
|
|
15
|
+
const cut = redacted.slice(0, TOOL_INPUT_PREVIEW_MAX_LENGTH);
|
|
16
|
+
return endsWithHighSurrogate(cut) ? cut.slice(0, -1) : cut;
|
|
17
|
+
};
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { APPROVAL_REASON_MAX_LENGTH } from "@wheatley-ai/protocol";
|
|
2
|
+
import { systemClock } from "../contracts/module.js";
|
|
3
|
+
const SECOND_MS = 1000;
|
|
4
|
+
const MINUTE_MS = 60 * SECOND_MS;
|
|
5
|
+
const HOUR_MS = 60 * MINUTE_MS;
|
|
6
|
+
const CHOICES = "[o] allow once [c] allow for this conversation [a] always allow [d] deny";
|
|
7
|
+
const RETRY_QUESTION = "Answer o, c, a, or d: ";
|
|
8
|
+
const REASON_QUESTION = "Reason for the denial (optional, press Enter to skip): ";
|
|
9
|
+
const ANSWERS = new Map([
|
|
10
|
+
["a", "allow_always"],
|
|
11
|
+
["always", "allow_always"],
|
|
12
|
+
["c", "allow_conversation"],
|
|
13
|
+
["conversation", "allow_conversation"],
|
|
14
|
+
["d", "deny"],
|
|
15
|
+
["deny", "deny"],
|
|
16
|
+
["n", "deny"],
|
|
17
|
+
["no", "deny"],
|
|
18
|
+
["o", "allow_once"],
|
|
19
|
+
["once", "allow_once"],
|
|
20
|
+
]);
|
|
21
|
+
/** Formats a remaining time, for example `1h 5m`, `14m 59s`, or `30s`. */
|
|
22
|
+
const formatRemaining = (ms) => {
|
|
23
|
+
const hours = Math.floor(ms / HOUR_MS);
|
|
24
|
+
const minutes = Math.floor((ms % HOUR_MS) / MINUTE_MS);
|
|
25
|
+
const seconds = Math.floor((ms % MINUTE_MS) / SECOND_MS);
|
|
26
|
+
if (hours > 0) {
|
|
27
|
+
return `${hours}h ${minutes}m`;
|
|
28
|
+
}
|
|
29
|
+
return minutes > 0 ? `${minutes}m ${seconds}s` : `${seconds}s`;
|
|
30
|
+
};
|
|
31
|
+
const deadlineLine = (expiresAt, now) => {
|
|
32
|
+
if (expiresAt === null) {
|
|
33
|
+
return "No timeout";
|
|
34
|
+
}
|
|
35
|
+
const remaining = Date.parse(expiresAt) - now;
|
|
36
|
+
return remaining > 0
|
|
37
|
+
? `Times out in ${formatRemaining(remaining)} (${expiresAt})`
|
|
38
|
+
: `Timed out at ${expiresAt}`;
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* Renders the CLI card of a pending Approval: the Tool, its redacted input preview, the deadline, and the four
|
|
42
|
+
* choices. `now` is epoch milliseconds.
|
|
43
|
+
*/
|
|
44
|
+
export const renderApprovalPrompt = (approval, now) => [
|
|
45
|
+
`Approval needed: ${approval.toolName}`,
|
|
46
|
+
`Input: ${approval.inputPreview}`,
|
|
47
|
+
deadlineLine(approval.expiresAt, now),
|
|
48
|
+
CHOICES,
|
|
49
|
+
].join("\n");
|
|
50
|
+
/**
|
|
51
|
+
* Parses an answer to the CLI card, case-insensitively: `o`/`once`, `c`/`conversation`, `a`/`always`, and
|
|
52
|
+
* `d`/`deny`/`n`/`no`. Returns `undefined` for any other answer.
|
|
53
|
+
*/
|
|
54
|
+
export const parseApprovalAnswer = (answer) => ANSWERS.get(answer.trim().toLowerCase());
|
|
55
|
+
/**
|
|
56
|
+
* Shows the CLI card of `approval` and asks until the answer is valid. After `deny`, it asks for an optional reason.
|
|
57
|
+
* Resolves with the resolution to send through `approvals.decide`, or `undefined` if `options.signal` aborts first.
|
|
58
|
+
*
|
|
59
|
+
* Errors: it rejects with the error of `question`, except the rejection that an aborted `signal` causes.
|
|
60
|
+
*/
|
|
61
|
+
export const promptForApproval = async (approval, options) => {
|
|
62
|
+
const signal = options.signal ?? new AbortController().signal;
|
|
63
|
+
const clock = options.clock ?? systemClock;
|
|
64
|
+
const ask = async (query) => {
|
|
65
|
+
try {
|
|
66
|
+
return await options.question(query, { signal });
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
if (signal.aborted) {
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
throw error;
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
let query = `${renderApprovalPrompt(approval, clock.now())}\n> `;
|
|
76
|
+
let decision;
|
|
77
|
+
while (decision === undefined) {
|
|
78
|
+
// oxlint-disable-next-line no-await-in-loop -- Each question waits for the answer to the previous one.
|
|
79
|
+
const answer = await ask(query);
|
|
80
|
+
if (answer === undefined) {
|
|
81
|
+
return undefined;
|
|
82
|
+
}
|
|
83
|
+
decision = parseApprovalAnswer(answer);
|
|
84
|
+
query = RETRY_QUESTION;
|
|
85
|
+
}
|
|
86
|
+
const resolvedBy = options.resolvedBy === undefined ? {} : { resolvedBy: options.resolvedBy };
|
|
87
|
+
if (decision !== "deny") {
|
|
88
|
+
return { decision, ...resolvedBy };
|
|
89
|
+
}
|
|
90
|
+
const answer = await ask(REASON_QUESTION);
|
|
91
|
+
if (answer === undefined) {
|
|
92
|
+
return undefined;
|
|
93
|
+
}
|
|
94
|
+
const reason = answer.trim().slice(0, APPROVAL_REASON_MAX_LENGTH);
|
|
95
|
+
return reason === ""
|
|
96
|
+
? { decision, ...resolvedBy }
|
|
97
|
+
: { decision, reason, ...resolvedBy };
|
|
98
|
+
};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The JSON-RPC handlers of the `approvals` module: `approvals.list` and `approvals.decide`. A decision through
|
|
3
|
+
* JSON-RPC comes from the CLI or the dashboard, so it has the Operator origin and can decide every Approval of the
|
|
4
|
+
* Agent (ADR 0002).
|
|
5
|
+
*
|
|
6
|
+
* Errors: `approvals.decide` rejects if `ApprovalGate.decide` rejects, for example after a failed wake or a failed
|
|
7
|
+
* `config.yaml` write. The decision stays stored in both cases.
|
|
8
|
+
*/
|
|
9
|
+
export const createApprovalsRpc = (gate) => ({
|
|
10
|
+
"approvals.decide": async ({ approvalId, resolution }) => ({
|
|
11
|
+
accepted: await gate.decide(approvalId, resolution, { kind: "operator" }),
|
|
12
|
+
}),
|
|
13
|
+
"approvals.list": async () => ({
|
|
14
|
+
approvals: [...(await gate.listPending())],
|
|
15
|
+
}),
|
|
16
|
+
});
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/** The `agent.sqlite` schema of the `approvals` namespace. */
|
|
2
|
+
export const approvalsMigrations = [
|
|
3
|
+
{
|
|
4
|
+
name: "create approvals, waiters, and grants",
|
|
5
|
+
up: (db) => {
|
|
6
|
+
db.exec(`
|
|
7
|
+
CREATE TABLE approvals_requests (
|
|
8
|
+
approval_id TEXT PRIMARY KEY,
|
|
9
|
+
call_key TEXT NOT NULL UNIQUE,
|
|
10
|
+
run_id TEXT NOT NULL,
|
|
11
|
+
conversation_id TEXT NOT NULL,
|
|
12
|
+
binding_id TEXT,
|
|
13
|
+
chat_id TEXT,
|
|
14
|
+
tool_name TEXT NOT NULL,
|
|
15
|
+
input_preview TEXT NOT NULL,
|
|
16
|
+
created_at INTEGER NOT NULL,
|
|
17
|
+
expires_at INTEGER,
|
|
18
|
+
outcome TEXT CHECK (outcome IN (
|
|
19
|
+
'allow_once', 'allow_conversation', 'allow_always', 'deny', 'timeout', 'cancelled'
|
|
20
|
+
)),
|
|
21
|
+
reason TEXT,
|
|
22
|
+
resolved_by TEXT,
|
|
23
|
+
resolved_at INTEGER,
|
|
24
|
+
CHECK ((binding_id IS NULL) = (chat_id IS NULL)),
|
|
25
|
+
CHECK ((outcome IS NULL) = (resolved_at IS NULL))
|
|
26
|
+
) STRICT;
|
|
27
|
+
CREATE INDEX approvals_requests_pending
|
|
28
|
+
ON approvals_requests (run_id, created_at) WHERE outcome IS NULL;
|
|
29
|
+
CREATE TABLE approvals_waiters (
|
|
30
|
+
approval_id TEXT NOT NULL REFERENCES approvals_requests (approval_id) ON DELETE CASCADE,
|
|
31
|
+
call_key TEXT NOT NULL,
|
|
32
|
+
signal_key TEXT NOT NULL,
|
|
33
|
+
PRIMARY KEY (approval_id, call_key)
|
|
34
|
+
) STRICT;
|
|
35
|
+
CREATE INDEX approvals_waiters_call ON approvals_waiters (call_key);
|
|
36
|
+
CREATE TABLE approvals_grants (
|
|
37
|
+
conversation_id TEXT NOT NULL,
|
|
38
|
+
tool_name TEXT NOT NULL,
|
|
39
|
+
granted_at INTEGER NOT NULL,
|
|
40
|
+
PRIMARY KEY (conversation_id, tool_name)
|
|
41
|
+
) STRICT;
|
|
42
|
+
`);
|
|
43
|
+
},
|
|
44
|
+
version: 1,
|
|
45
|
+
},
|
|
46
|
+
];
|
|
47
|
+
const OUTCOMES = [
|
|
48
|
+
"allow_once",
|
|
49
|
+
"allow_conversation",
|
|
50
|
+
"allow_always",
|
|
51
|
+
"deny",
|
|
52
|
+
"timeout",
|
|
53
|
+
"cancelled",
|
|
54
|
+
];
|
|
55
|
+
const isOutcome = (value) => OUTCOMES.some((outcome) => outcome === value);
|
|
56
|
+
const isText = (value) => typeof value === "string";
|
|
57
|
+
const isTextOrNull = (value) => value === null || isText(value);
|
|
58
|
+
const isIntegerOrNull = (value) => value === null || Number.isSafeInteger(value);
|
|
59
|
+
const isApprovalRow = (row) => isText(row.approval_id) &&
|
|
60
|
+
isText(row.call_key) &&
|
|
61
|
+
isText(row.run_id) &&
|
|
62
|
+
isText(row.conversation_id) &&
|
|
63
|
+
isTextOrNull(row.binding_id) &&
|
|
64
|
+
isTextOrNull(row.chat_id) &&
|
|
65
|
+
isText(row.tool_name) &&
|
|
66
|
+
isText(row.input_preview) &&
|
|
67
|
+
Number.isSafeInteger(row.created_at) &&
|
|
68
|
+
isIntegerOrNull(row.expires_at) &&
|
|
69
|
+
(row.outcome === null || isOutcome(row.outcome)) &&
|
|
70
|
+
isTextOrNull(row.reason) &&
|
|
71
|
+
isTextOrNull(row.resolved_by);
|
|
72
|
+
const isWaiterRow = (row) => isText(row.call_key) && isText(row.signal_key);
|
|
73
|
+
const toApproval = (row) => {
|
|
74
|
+
if (!isApprovalRow(row)) {
|
|
75
|
+
throw new TypeError(`Invalid approvals_requests row: ${String(row.approval_id)}`);
|
|
76
|
+
}
|
|
77
|
+
return {
|
|
78
|
+
approvalId: row.approval_id,
|
|
79
|
+
callKey: row.call_key,
|
|
80
|
+
chat: row.binding_id === null || row.chat_id === null
|
|
81
|
+
? null
|
|
82
|
+
: { bindingId: row.binding_id, chatId: row.chat_id },
|
|
83
|
+
conversationId: row.conversation_id,
|
|
84
|
+
createdAt: row.created_at,
|
|
85
|
+
expiresAt: row.expires_at,
|
|
86
|
+
inputPreview: row.input_preview,
|
|
87
|
+
outcome: row.outcome,
|
|
88
|
+
reason: row.reason,
|
|
89
|
+
resolvedBy: row.resolved_by,
|
|
90
|
+
runId: row.run_id,
|
|
91
|
+
toolName: row.tool_name,
|
|
92
|
+
};
|
|
93
|
+
};
|
|
94
|
+
const toParkedCall = (row) => {
|
|
95
|
+
if (!isWaiterRow(row)) {
|
|
96
|
+
throw new TypeError("Invalid approvals_waiters row");
|
|
97
|
+
}
|
|
98
|
+
return { callKey: row.call_key, signalKey: row.signal_key };
|
|
99
|
+
};
|
|
100
|
+
const toOptionalApproval = (row) => row === undefined ? undefined : toApproval(row);
|
|
101
|
+
const toIso = (epochMs) => new Date(epochMs).toISOString();
|
|
102
|
+
/** Converts a stored Approval to the protocol shape. */
|
|
103
|
+
export const toPendingApproval = (agent, approval) => ({
|
|
104
|
+
agent,
|
|
105
|
+
approvalId: approval.approvalId,
|
|
106
|
+
chat: approval.chat,
|
|
107
|
+
conversationId: approval.conversationId,
|
|
108
|
+
createdAt: toIso(approval.createdAt),
|
|
109
|
+
expiresAt: approval.expiresAt === null ? null : toIso(approval.expiresAt),
|
|
110
|
+
inputPreview: approval.inputPreview,
|
|
111
|
+
runId: approval.runId,
|
|
112
|
+
toolName: approval.toolName,
|
|
113
|
+
});
|
|
114
|
+
const COLUMNS = `approval_id, call_key, run_id, conversation_id, binding_id, chat_id, tool_name, input_preview,
|
|
115
|
+
created_at, expires_at, outcome, reason, resolved_by`;
|
|
116
|
+
/** Creates the store on an `agent.sqlite` handle with the `approvals` migrations applied. */
|
|
117
|
+
export const createApprovalStore = (db) => {
|
|
118
|
+
const selectById = db.prepare(`SELECT ${COLUMNS} FROM approvals_requests WHERE approval_id = ?`);
|
|
119
|
+
const selectByCallKey = db.prepare(`SELECT ${COLUMNS} FROM approvals_requests WHERE call_key = ?`);
|
|
120
|
+
const selectPendingInRun = db.prepare(`SELECT ${COLUMNS} FROM approvals_requests WHERE outcome IS NULL AND run_id = ? ORDER BY created_at, rowid`);
|
|
121
|
+
const selectPending = db.prepare(`SELECT ${COLUMNS} FROM approvals_requests WHERE outcome IS NULL ORDER BY created_at, rowid`);
|
|
122
|
+
const insertApproval = db.prepare(`INSERT INTO approvals_requests (
|
|
123
|
+
approval_id, call_key, run_id, conversation_id, binding_id, chat_id, tool_name, input_preview, created_at,
|
|
124
|
+
expires_at
|
|
125
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
126
|
+
const updateResolution = db.prepare(`UPDATE approvals_requests SET outcome = ?, reason = ?, resolved_by = ?, resolved_at = ?
|
|
127
|
+
WHERE approval_id = ? AND outcome IS NULL`);
|
|
128
|
+
const insertWaiter = db.prepare("INSERT OR IGNORE INTO approvals_waiters (approval_id, call_key, signal_key) VALUES (?, ?, ?)");
|
|
129
|
+
const selectWaiters = db.prepare("SELECT call_key, signal_key FROM approvals_waiters WHERE approval_id = ? ORDER BY rowid");
|
|
130
|
+
const selectCancelledWait = db.prepare(`SELECT 1 FROM approvals_waiters JOIN approvals_requests USING (approval_id)
|
|
131
|
+
WHERE approvals_waiters.call_key = ? AND outcome = 'cancelled' LIMIT 1`);
|
|
132
|
+
const selectGrant = db.prepare("SELECT 1 FROM approvals_grants WHERE conversation_id = ? AND tool_name = ?");
|
|
133
|
+
const insertGrant = db.prepare("INSERT OR IGNORE INTO approvals_grants (conversation_id, tool_name, granted_at) VALUES (?, ?, ?)");
|
|
134
|
+
const deleteGrants = db.prepare("DELETE FROM approvals_grants WHERE conversation_id = ?");
|
|
135
|
+
return {
|
|
136
|
+
addGrant: (conversationId, toolName, grantedAt) => {
|
|
137
|
+
insertGrant.run(conversationId, toolName, grantedAt);
|
|
138
|
+
},
|
|
139
|
+
addWaiter: (approvalId, call) => {
|
|
140
|
+
insertWaiter.run(approvalId, call.callKey, call.signalKey);
|
|
141
|
+
},
|
|
142
|
+
byCallKey: (callKey) => toOptionalApproval(selectByCallKey.get(callKey)),
|
|
143
|
+
byId: (approvalId) => toOptionalApproval(selectById.get(approvalId)),
|
|
144
|
+
clearGrants: (conversationId) => {
|
|
145
|
+
deleteGrants.run(conversationId);
|
|
146
|
+
},
|
|
147
|
+
hasGrant: (conversationId, toolName) => selectGrant.get(conversationId, toolName) !== undefined,
|
|
148
|
+
insert: (approval) => {
|
|
149
|
+
insertApproval.run(approval.approvalId, approval.callKey, approval.runId, approval.conversationId, approval.chat?.bindingId ?? null, approval.chat?.chatId ?? null, approval.toolName, approval.inputPreview, approval.createdAt, approval.expiresAt);
|
|
150
|
+
},
|
|
151
|
+
oldestPendingInRun: (runId) => toOptionalApproval(selectPendingInRun.get(runId)),
|
|
152
|
+
pending: (runId) => (runId === undefined
|
|
153
|
+
? selectPending.all()
|
|
154
|
+
: selectPendingInRun.all(runId)).map(toApproval),
|
|
155
|
+
resolve: (approvalId, resolution) => Number(updateResolution.run(resolution.outcome, resolution.reason ?? null, resolution.resolvedBy ?? null, resolution.resolvedAt, approvalId).changes) === 1,
|
|
156
|
+
waitedOnCancelled: (callKey) => selectCancelledWait.get(callKey) !== undefined,
|
|
157
|
+
waiters: (approvalId) => selectWaiters.all(approvalId).map(toParkedCall),
|
|
158
|
+
};
|
|
159
|
+
};
|