@tnunamak/dalan 0.0.0-stage → 0.5.2
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/CHANGELOG.md +172 -0
- package/CONTRIBUTING.md +26 -0
- package/LICENSE +204 -0
- package/PROTOCOL.md +339 -0
- package/README.md +348 -2
- package/SECURITY.md +30 -0
- package/bin/dalan.mjs +38 -0
- package/bin/dot-acp-agent.mjs +377 -0
- package/bin/dot-alert.mjs +9 -0
- package/bin/dot-deadman.mjs +82 -0
- package/bin/dot-heartbeat.mjs +29 -0
- package/bin/dot-pr-reviewer.mjs +32 -0
- package/bin/dot-worker.mjs +755 -0
- package/docs/chatgpt-worker-onboarding.md +112 -0
- package/docs/claude-worker-onboarding.md +113 -0
- package/docs/connect-chatgpt.md +78 -0
- package/docs/connection-longevity.md +37 -0
- package/docs/dalan-upgrade.md +242 -0
- package/docs/deadman.md +59 -0
- package/docs/dot-pr-reviewer.config.example.json +9 -0
- package/docs/durability-audit.md +27 -0
- package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
- package/docs/keycloak-oauth-setup.md +30 -0
- package/docs/local-agent-mcp.md +39 -0
- package/docs/manual-setup.md +135 -0
- package/docs/mirror-fetch.md +98 -0
- package/docs/operations.md +751 -0
- package/docs/operator-duties.md +68 -0
- package/docs/owner-integrator.md +27 -0
- package/docs/portable-auth-profile.md +109 -0
- package/docs/pr-head-reviewer.md +54 -0
- package/docs/pr-preflight.md +26 -0
- package/docs/pull-workers.md +97 -0
- package/docs/redaction.md +27 -0
- package/docs/service-setup.md +166 -0
- package/docs/setup-reference.md +80 -0
- package/docs/t3-connector-icon.png +0 -0
- package/docs/t3-integration.md +49 -0
- package/docs/t3-result-retry-delivery.md +41 -0
- package/docs/t3-reverse-control.md +107 -0
- package/docs/usage.md +439 -0
- package/docs/worker-clients.md +285 -0
- package/integrations/t3/acp-kit/src/capability.mjs +25 -0
- package/integrations/t3/acp-kit/src/errors.mjs +13 -0
- package/integrations/t3/acp-kit/src/index.mjs +5 -0
- package/integrations/t3/acp-kit/src/lock.mjs +155 -0
- package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
- package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
- package/package.json +65 -4
- package/packages/job-core/README.md +18 -0
- package/packages/job-core/index.mjs +2 -0
- package/packages/job-core/package.json +8 -0
- package/packages/job-core/protocol/canonical.mjs +11 -0
- package/packages/job-core/protocol/v0/command.schema.json +1154 -0
- package/packages/job-core/protocol/v0/event.schema.json +77 -0
- package/packages/job-core/protocol/v0/reply.schema.json +59 -0
- package/packages/job-core/transitions.mjs +25 -0
- package/scripts/daily-selfcheck.mjs +135 -0
- package/scripts/lib/expose-tailscale.mjs +408 -0
- package/scripts/live-trial/common.mjs +272 -0
- package/scripts/monitor-targets.mjs +44 -0
- package/scripts/upgrade-drain.mjs +39 -0
- package/scripts/worker-bridge-setup.mjs +925 -0
- package/src/ack-ledger.mjs +37 -0
- package/src/acp-bridge.mjs +412 -0
- package/src/acp-context.mjs +138 -0
- package/src/admin-socket.mjs +14 -0
- package/src/alerts.mjs +147 -0
- package/src/artifact-journal.mjs +75 -0
- package/src/as-files.mjs +347 -0
- package/src/as-store.mjs +456 -0
- package/src/as.mjs +497 -0
- package/src/auth.mjs +166 -0
- package/src/builtin-http.mjs +22 -0
- package/src/check-coverage.mjs +38 -0
- package/src/check-lint.mjs +88 -0
- package/src/check-readiness.mjs +112 -0
- package/src/check-response.mjs +19 -0
- package/src/claim-command-ledger.mjs +51 -0
- package/src/cli-help.mjs +172 -0
- package/src/cli-name.mjs +16 -0
- package/src/connect-cli.mjs +126 -0
- package/src/consumers.mjs +61 -0
- package/src/deadman.mjs +329 -0
- package/src/delivery.mjs +19 -0
- package/src/demo-worker.mjs +150 -0
- package/src/destinations/index.mjs +23 -0
- package/src/destinations/none.mjs +15 -0
- package/src/destinations/t3.mjs +109 -0
- package/src/diagnostic.mjs +78 -0
- package/src/docs-url.mjs +9 -0
- package/src/drain-runner.mjs +9 -0
- package/src/drained-slot.mjs +53 -0
- package/src/drained.mjs +40 -0
- package/src/durable-waiters.mjs +236 -0
- package/src/env.mjs +19 -0
- package/src/execution.mjs +112 -0
- package/src/failure-type.mjs +28 -0
- package/src/get-summary.mjs +32 -0
- package/src/git-env.mjs +15 -0
- package/src/host-budget-receipts.mjs +154 -0
- package/src/host-budget-seccomp.py +33 -0
- package/src/host-budget-service.mjs +54 -0
- package/src/host-budget-stop.mjs +26 -0
- package/src/host-budget-storage.py +259 -0
- package/src/host-budget.mjs +149 -0
- package/src/host-cgroup.mjs +23 -0
- package/src/host-check-allowlist.mjs +42 -0
- package/src/host-execution-policy.mjs +38 -0
- package/src/host-health.mjs +34 -0
- package/src/host-stop-reverify.mjs +44 -0
- package/src/inbox.mjs +55 -0
- package/src/integrator.mjs +322 -0
- package/src/job-retention.mjs +69 -0
- package/src/legacy-names.mjs +8 -0
- package/src/lifecycle.mjs +291 -0
- package/src/limits.mjs +31 -0
- package/src/loopback.mjs +9 -0
- package/src/mcp-outcome.mjs +70 -0
- package/src/mcp-stdio.mjs +191 -0
- package/src/mirror-fetch-lock.py +164 -0
- package/src/mirror-fetch.mjs +174 -0
- package/src/notify-ledger.mjs +82 -0
- package/src/objectives.mjs +129 -0
- package/src/owner-report-artifact.mjs +66 -0
- package/src/patch-apply.mjs +84 -0
- package/src/path-syntax.mjs +16 -0
- package/src/paths.mjs +67 -0
- package/src/pr-head-reviewer.mjs +596 -0
- package/src/pr-preflight.mjs +51 -0
- package/src/prepared-node-modules.mjs +129 -0
- package/src/projects.mjs +480 -0
- package/src/protocol-artifact-commands.mjs +52 -0
- package/src/protocol-delivery-driver.mjs +167 -0
- package/src/protocol-finish.mjs +100 -0
- package/src/protocol-owner-command.mjs +35 -0
- package/src/protocol-owner-mutations.mjs +22 -0
- package/src/protocol-owner-waiters.mjs +67 -0
- package/src/protocol-retention.mjs +52 -0
- package/src/protocol-services.mjs +61 -0
- package/src/protocol-stop-observer.mjs +131 -0
- package/src/publish-plan.mjs +245 -0
- package/src/redaction.mjs +763 -0
- package/src/rejections.mjs +18 -0
- package/src/request-log.mjs +102 -0
- package/src/restore-check.mjs +90 -0
- package/src/result-binding.mjs +65 -0
- package/src/runtime-check.mjs +13 -0
- package/src/sandbox-supervisor.mjs +105 -0
- package/src/schema-subset.mjs +186 -0
- package/src/scopes.mjs +15 -0
- package/src/server.mjs +1340 -0
- package/src/shutdown-signal.mjs +12 -0
- package/src/signal-sandbox-processes.py +56 -0
- package/src/signal.mjs +119 -0
- package/src/status-evidence.mjs +47 -0
- package/src/status-summary.mjs +54 -0
- package/src/store.mjs +3057 -0
- package/src/submission-policy.mjs +623 -0
- package/src/subscription-storage.mjs +64 -0
- package/src/t3-audit.mjs +120 -0
- package/src/t3-control.mjs +102 -0
- package/src/t3-transport.mjs +158 -0
- package/src/t3.mjs +209 -0
- package/src/terminal-safe.mjs +19 -0
- package/src/tool-registry.mjs +451 -0
- package/src/try-command.mjs +11 -0
- package/src/try.mjs +589 -0
- package/src/webhooks.mjs +86 -0
- package/src/work-order.mjs +265 -0
- package/src/worker-instructions.mjs +26 -0
- package/src/worker-prompt.mjs +4 -0
- package/src/workers.mjs +622 -0
- package/src/workspace.mjs +1058 -0
- package/systemd/dot-bridge-heartbeat.service +18 -0
- package/systemd/dot-bridge-heartbeat.timer +10 -0
- package/systemd/dot-bridge-selfcheck.service +12 -0
- package/systemd/dot-bridge-selfcheck.timer +11 -0
- package/systemd/dot-bridge.service +17 -0
- package/systemd/dot-deadman.service +30 -0
- package/systemd/dot-pr-reviewer.service +11 -0
- package/systemd/dot-pr-reviewer.timer +10 -0
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// Text that a worker or a job supplied must not drive the operator's terminal. An ESC, BEL or C1 byte can retitle the
|
|
2
|
+
// window, forge earlier lines or replace the clipboard (OSC 52). This is the one place that makes such text printable.
|
|
3
|
+
const CONTROL = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u2028\u2029]/gu;
|
|
4
|
+
const escapeChar = c => {
|
|
5
|
+
const code = c.codePointAt(0);
|
|
6
|
+
return code <= 0xff ? `\\x${code.toString(16).padStart(2, '0')}` : `\\u${code.toString(16).padStart(4, '0')}`;
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
// Human output: keep \n and \t, spell every other control character as \xNN so it shows and does nothing.
|
|
10
|
+
export function terminalSafe(text) { return String(text).replace(CONTROL, escapeChar); }
|
|
11
|
+
|
|
12
|
+
// Machine JSON output: JSON.stringify already escapes C0 controls; DEL and C1 stay raw. Spell those as \uNNNN, which
|
|
13
|
+
// parses back to the same string.
|
|
14
|
+
export function jsonTerminalSafe(jsonText) {
|
|
15
|
+
return String(jsonText).replace(/[\u007f-\u009f\u2028\u2029]/gu, c => `\\u${c.codePointAt(0).toString(16).padStart(4, '0')}`);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// One-line fields (inbox rows): newline and tab are spelled out too, so a field cannot start a forged line.
|
|
19
|
+
export function terminalSafeLine(text) { return String(text).replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/gu, escapeChar); }
|
|
@@ -0,0 +1,451 @@
|
|
|
1
|
+
// Owner-managed tool registry. The owner registers tools and grants them to worker identities; a worker can only list
|
|
2
|
+
// and call what was granted to it. Registering, removing or granting never changes the MCP tools/list (this module has no
|
|
3
|
+
// MCP surface). Policy lives here, not in the model-facing dispatch tool: default deny, class match, schema-checked
|
|
4
|
+
// arguments, a closed set of handler kinds, redacted and capped results, and an audit log that never holds argument values.
|
|
5
|
+
import { createHash } from 'node:crypto';
|
|
6
|
+
import { redactOutput, redactSecrets } from './redaction.mjs';
|
|
7
|
+
import { execFile } from 'node:child_process';
|
|
8
|
+
import { compileSchema, validateValue, SchemaError } from './schema-subset.mjs';
|
|
9
|
+
|
|
10
|
+
export class RegistryError extends Error {
|
|
11
|
+
constructor(code, message) { super(message ?? code); this.name = 'RegistryError'; this.code = code; }
|
|
12
|
+
}
|
|
13
|
+
const refuse = (code, message) => { throw new RegistryError(code, message); };
|
|
14
|
+
|
|
15
|
+
const NAME = /^[a-z][a-z0-9_]{0,63}$/;
|
|
16
|
+
const WORKER = /^[a-z][a-z0-9_-]{0,31}$/;
|
|
17
|
+
const RESERVED = new Set(['list_tools', 'call_tool_read', 'call_tool_write']);
|
|
18
|
+
const FORBIDDEN_KIND = /(delete|overwrite|unlink|truncate|wipe|destroy|remove)/i;
|
|
19
|
+
const FORBIDDEN_WORD = /^(delete|overwrite|remove|unlink|truncate|wipe|destroy|rm|rmdir|erase|replace)$/i;
|
|
20
|
+
// The longest a handler may run (the t3-post command timeout), and the lease a pending reservation holds: that timeout plus
|
|
21
|
+
// a margin. A crashed call leaves a pending row; once its lease passes, a retry under the same key takes the row over.
|
|
22
|
+
export const HANDLER_TIMEOUT_MS = 15_000;
|
|
23
|
+
const LEASE_MARGIN_MS = 30_000;
|
|
24
|
+
export const LIMITS = Object.freeze({ resultBytes: 32768, callsPerMinute: 30, admissionPerMinute: 120, idempotencyKeyMax: 128, idempotencyTtlMs: 7 * 86_400_000, idempotencyLeaseMs: HANDLER_TIMEOUT_MS + LEASE_MARGIN_MS });
|
|
25
|
+
|
|
26
|
+
const canonical = value => {
|
|
27
|
+
if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
|
|
28
|
+
if (value && typeof value === 'object') return `{${Object.keys(value).sort().map(k => `${JSON.stringify(k)}:${canonical(value[k])}`).join(',')}}`;
|
|
29
|
+
return JSON.stringify(value) ?? 'null';
|
|
30
|
+
};
|
|
31
|
+
const sha256 = text => createHash('sha256').update(text).digest('hex');
|
|
32
|
+
// The definition hash recorded in the audit log. The hash a caller pins (callerHash below) also covers the caller's grants.
|
|
33
|
+
export const schemaHash = ({ name, description, input_schema, class: toolClass, handler }) => sha256(canonical({ name, description, input_schema, class: toolClass, handler: handler ?? null }));
|
|
34
|
+
|
|
35
|
+
// The lease follows the handler's real timeout: that timeout plus a margin (a handler without one gets the maximum).
|
|
36
|
+
const leaseMs = impl => (impl?.timeoutMs ?? HANDLER_TIMEOUT_MS) + LEASE_MARGIN_MS;
|
|
37
|
+
const iso = ms => new Date(ms).toISOString();
|
|
38
|
+
const workerName = worker => typeof worker === 'string' ? worker : worker?.name;
|
|
39
|
+
const configStrings = (value, out = []) => {
|
|
40
|
+
if (typeof value === 'string') out.push(value);
|
|
41
|
+
else if (Array.isArray(value)) value.forEach(v => configStrings(v, out));
|
|
42
|
+
else if (value && typeof value === 'object') for (const [k, v] of Object.entries(value)) { out.push(k); configStrings(v, out); }
|
|
43
|
+
return out;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
// `now` defaults to Date.now for the bare registry. The server passes the Store's monotonic clock, so within one running
|
|
47
|
+
// bridge process a wall-clock step cannot shorten or stretch a lease; lease expiry is not compared across processes.
|
|
48
|
+
// `hooks.afterIdempotencyLookup` is a test seam that pauses a call between its lookup and its reservation.
|
|
49
|
+
export function createToolRegistry({ store, now = Date.now, handlers = {}, audit = null, callsPerMinute = LIMITS.callsPerMinute, admissionPerMinute = LIMITS.admissionPerMinute, hooks = {} }) {
|
|
50
|
+
const db = store.db;
|
|
51
|
+
const windows = new Map();
|
|
52
|
+
const record = entry => {
|
|
53
|
+
const row = { at: iso(now()), kind: entry.kind, tool: entry.tool ?? null, worker: entry.worker ?? null,
|
|
54
|
+
args_digest: entry.args_digest ?? null, outcome: entry.outcome, schema_hash: entry.schema_hash ?? null };
|
|
55
|
+
db.prepare('INSERT INTO tool_registry_log(at,kind,tool,worker,args_digest,outcome,schema_hash) VALUES(?,?,?,?,?,?,?)')
|
|
56
|
+
.run(row.at, row.kind, row.tool, row.worker, row.args_digest, row.outcome, row.schema_hash);
|
|
57
|
+
try { audit?.(row); } catch { /* an audit sink must not break the registry */ }
|
|
58
|
+
};
|
|
59
|
+
const getTool = name => db.prepare('SELECT * FROM registered_tools WHERE name=?').get(name);
|
|
60
|
+
// The registry version moves on every register, remove, grant, revoke, enable and disable, and never goes back.
|
|
61
|
+
const registryVersion = () => db.prepare("SELECT value FROM tool_registry_meta WHERE key='version'").get()?.value ?? 0;
|
|
62
|
+
const bump = () => db.prepare("INSERT INTO tool_registry_meta(key,value) VALUES('version',1) ON CONFLICT(key) DO UPDATE SET value=value+1").run();
|
|
63
|
+
// What a caller pins: everything that decides what the call does, for this caller. It is computed from the live row,
|
|
64
|
+
// so a changed description, schema, class, handler kind or config (target thread, argv template) or grant set moves it.
|
|
65
|
+
// A handler kind that declares an effect class (impl.effectClass) fixes the class of every tool that uses it. A stored row
|
|
66
|
+
// whose class disagrees (written by an older build, or by hand) is served and enforced as the declared class.
|
|
67
|
+
const toolClass = row => handlers[JSON.parse(row.handler).kind]?.effectClass ?? row.class;
|
|
68
|
+
const callerHash = (row, worker) => sha256(canonical({
|
|
69
|
+
name: row.name, description: row.description, input_schema: JSON.parse(row.input_schema), class: toolClass(row), handler: JSON.parse(row.handler),
|
|
70
|
+
caller: worker, grants: db.prepare('SELECT tool FROM tool_grants WHERE worker=? ORDER BY tool').all(worker).map(g => g.tool),
|
|
71
|
+
}));
|
|
72
|
+
const view = (row, worker) => ({ name: row.name, description: row.description, input_schema: JSON.parse(row.input_schema), class: toolClass(row), schema_hash: callerHash(row, worker) });
|
|
73
|
+
|
|
74
|
+
// An authority change and the discarding of the messages queued under it commit together or not at all, so no crash can
|
|
75
|
+
// leave an old message that a later register, grant or enable of the same tool would deliver.
|
|
76
|
+
const atomically = fn => store.inTransaction(fn);
|
|
77
|
+
|
|
78
|
+
function register(spec) {
|
|
79
|
+
const bad = (code, message) => refuse(code, message);
|
|
80
|
+
if (!spec || typeof spec !== 'object') bad('invalid_tool', 'tool spec must be an object');
|
|
81
|
+
const { name, description, inputSchema, handler } = spec;
|
|
82
|
+
if (typeof name !== 'string' || !NAME.test(name) || RESERVED.has(name)) bad('invalid_tool', 'name must match [a-z][a-z0-9_]{0,63} and not be a dispatch tool');
|
|
83
|
+
if (typeof description !== 'string' || !description || description.length > 1000) bad('invalid_tool', 'description must be 1-1000 characters');
|
|
84
|
+
if (spec.class !== 'read' && spec.class !== 'write') bad('invalid_tool', 'class must be read or write');
|
|
85
|
+
if (!inputSchema || inputSchema.type !== 'object') bad('invalid_schema', 'inputSchema must be an object schema');
|
|
86
|
+
let normalized;
|
|
87
|
+
try { normalized = compileSchema(inputSchema); }
|
|
88
|
+
catch (error) { if (error instanceof SchemaError) bad('invalid_schema', error.message); throw error; }
|
|
89
|
+
if (!handler || typeof handler !== 'object' || typeof handler.kind !== 'string') bad('invalid_tool', 'handler.kind is required');
|
|
90
|
+
const impl = handlers[handler.kind];
|
|
91
|
+
if (!Object.hasOwn(handlers, handler.kind) || !impl) bad('unknown_handler_kind', `handler kind "${handler.kind.slice(0, 40)}" is not available`);
|
|
92
|
+
if (impl.destructive === true || FORBIDDEN_KIND.test(handler.kind)) bad('forbidden_handler', 'handlers that delete or overwrite are not allowed');
|
|
93
|
+
const { kind, ...config } = handler;
|
|
94
|
+
if (configStrings(config).some(s => FORBIDDEN_WORD.test(s.trim()))) bad('forbidden_handler', 'handlers that delete or overwrite are not allowed');
|
|
95
|
+
const allowed = new Set(impl.configKeys ?? []);
|
|
96
|
+
for (const key of Object.keys(config)) if (!allowed.has(key)) bad('invalid_tool', `handler config key "${key.slice(0, 40)}" is not allowed for ${kind}`);
|
|
97
|
+
if (impl.effectClass && spec.class !== impl.effectClass) bad('invalid_tool', `${kind} tools have side effects, so they must be registered with class "${impl.effectClass}"`);
|
|
98
|
+
impl.validateConfig?.(config, { name, inputSchema: normalized });
|
|
99
|
+
if (getTool(name)) bad('duplicate_tool', `tool "${name}" is already registered`);
|
|
100
|
+
const hash = schemaHash({ name, description, input_schema: normalized, class: spec.class, handler: { kind, ...config } });
|
|
101
|
+
// Unsent rows left under this name (by an older build or a crash) belong to no registration and are discarded here.
|
|
102
|
+
atomically(() => {
|
|
103
|
+
db.prepare('INSERT INTO registered_tools(name,description,input_schema,class,handler,schema_hash,enabled,created_at) VALUES(?,?,?,?,?,?,1,?)')
|
|
104
|
+
.run(name, description, JSON.stringify(normalized), spec.class, JSON.stringify({ kind, ...config }), hash, iso(now()));
|
|
105
|
+
dropQueued(name);
|
|
106
|
+
bump();
|
|
107
|
+
record({ kind: 'register', tool: name, outcome: 'ok', schema_hash: hash });
|
|
108
|
+
});
|
|
109
|
+
return { name, schema_hash: hash };
|
|
110
|
+
}
|
|
111
|
+
// Withdrawing a tool, or a worker's grant, discards the messages that worker queued but never delivered, so they cannot
|
|
112
|
+
// take effect later or be sent to the destination of a tool that reuses the name.
|
|
113
|
+
function dropQueued(tool, worker) {
|
|
114
|
+
if (worker === undefined) db.prepare('DELETE FROM tool_outbox WHERE tool=? AND sent_at IS NULL').run(tool);
|
|
115
|
+
else db.prepare('DELETE FROM tool_outbox WHERE tool=? AND worker=? AND sent_at IS NULL').run(tool, worker);
|
|
116
|
+
}
|
|
117
|
+
function remove(name) {
|
|
118
|
+
const row = getTool(name);
|
|
119
|
+
if (!row) refuse('unknown_tool', `tool "${String(name).slice(0, 64)}" is not registered`);
|
|
120
|
+
atomically(() => {
|
|
121
|
+
db.prepare('DELETE FROM tool_grants WHERE tool=?').run(name);
|
|
122
|
+
db.prepare('DELETE FROM registered_tools WHERE name=?').run(name);
|
|
123
|
+
dropQueued(name);
|
|
124
|
+
bump();
|
|
125
|
+
record({ kind: 'remove', tool: name, outcome: 'ok', schema_hash: row.schema_hash });
|
|
126
|
+
});
|
|
127
|
+
return { name };
|
|
128
|
+
}
|
|
129
|
+
function setEnabled(name, enabled) {
|
|
130
|
+
const row = getTool(name);
|
|
131
|
+
if (!row) refuse('unknown_tool', `tool "${String(name).slice(0, 64)}" is not registered`);
|
|
132
|
+
atomically(() => {
|
|
133
|
+
db.prepare('UPDATE registered_tools SET enabled=? WHERE name=?').run(enabled ? 1 : 0, name);
|
|
134
|
+
if (!enabled) dropQueued(name);
|
|
135
|
+
bump();
|
|
136
|
+
record({ kind: enabled ? 'enable' : 'disable', tool: name, outcome: 'ok', schema_hash: row.schema_hash });
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
function grantChange(kind, name, worker) {
|
|
140
|
+
const row = getTool(name);
|
|
141
|
+
if (!row) refuse('unknown_tool', `tool "${String(name).slice(0, 64)}" is not registered`);
|
|
142
|
+
if (typeof worker !== 'string' || !WORKER.test(worker)) refuse('invalid_tool', 'worker must be a worker name');
|
|
143
|
+
atomically(() => {
|
|
144
|
+
if (kind === 'grant') db.prepare('INSERT OR IGNORE INTO tool_grants(tool,worker,granted_at) VALUES(?,?,?)').run(name, worker, iso(now()));
|
|
145
|
+
else { db.prepare('DELETE FROM tool_grants WHERE tool=? AND worker=?').run(name, worker); dropQueued(name, worker); }
|
|
146
|
+
bump();
|
|
147
|
+
record({ kind, tool: name, worker, outcome: 'ok', schema_hash: row.schema_hash });
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
const grant = (name, worker) => grantChange('grant', name, worker);
|
|
151
|
+
const revoke = (name, worker) => grantChange('revoke', name, worker);
|
|
152
|
+
|
|
153
|
+
function list() {
|
|
154
|
+
return db.prepare('SELECT * FROM registered_tools ORDER BY name').all().map(row => ({
|
|
155
|
+
...view(row), handler: JSON.parse(row.handler), enabled: row.enabled === 1, created_at: row.created_at,
|
|
156
|
+
workers: db.prepare('SELECT worker FROM tool_grants WHERE tool=? ORDER BY worker').all(row.name).map(g => g.worker),
|
|
157
|
+
uncertain: db.prepare('SELECT count(*) n FROM tool_outbox WHERE tool=? AND sent_at IS NULL AND uncertain_at IS NOT NULL').get(row.name).n,
|
|
158
|
+
}));
|
|
159
|
+
}
|
|
160
|
+
function listTools(worker) {
|
|
161
|
+
const name = workerName(worker);
|
|
162
|
+
const tools = typeof name !== 'string' ? [] : db.prepare('SELECT t.* FROM registered_tools t JOIN tool_grants g ON g.tool=t.name WHERE g.worker=? AND t.enabled=1 ORDER BY t.name').all(name).map(row => view(row, name));
|
|
163
|
+
return { registry_version: registryVersion(), tools };
|
|
164
|
+
}
|
|
165
|
+
function lastChange() {
|
|
166
|
+
const row = db.prepare("SELECT at,kind,tool,worker,schema_hash FROM tool_registry_log WHERE kind IN ('register','remove','grant','revoke','enable','disable') ORDER BY id DESC LIMIT 1").get();
|
|
167
|
+
return row ? { ...row } : null;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function rateLimited(key) {
|
|
171
|
+
const t = now(), recent = (windows.get(key) ?? []).filter(at => t - at < 60_000);
|
|
172
|
+
if (recent.length >= callsPerMinute) { windows.set(key, recent); return true; }
|
|
173
|
+
recent.push(t); windows.set(key, recent); return false;
|
|
174
|
+
}
|
|
175
|
+
// One admission budget per verified worker, shared by every tool name and checked before anything else: lookup, refusal,
|
|
176
|
+
// replay and audit. A call past it writes no audit row; it only bumps one counter per worker in tool_registry_meta
|
|
177
|
+
// (updated in place, so it cannot grow). The window is in memory and restarts empty; the counter is durable.
|
|
178
|
+
const admissions = new Map();
|
|
179
|
+
function admit(name) {
|
|
180
|
+
const key = typeof name === 'string' ? name.slice(0, 32) : '';
|
|
181
|
+
const t = now(), recent = (admissions.get(key) ?? []).filter(at => t - at < 60_000);
|
|
182
|
+
if (recent.length >= admissionPerMinute) {
|
|
183
|
+
admissions.set(key, recent);
|
|
184
|
+
db.prepare("INSERT INTO tool_registry_meta(key,value) VALUES(?,1) ON CONFLICT(key) DO UPDATE SET value=value+1").run(`admission_refused:${key}`);
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
187
|
+
recent.push(t); admissions.set(key, recent); return true;
|
|
188
|
+
}
|
|
189
|
+
// Redact first, then cap. A result over the cap becomes {truncated:true, preview} whose serialized form fits the cap.
|
|
190
|
+
const capResult = result => {
|
|
191
|
+
const clean = redactOutput(result ?? null);
|
|
192
|
+
const text = JSON.stringify(clean) ?? 'null';
|
|
193
|
+
if (text.length <= LIMITS.resultBytes) return clean;
|
|
194
|
+
let length = LIMITS.resultBytes - 64;
|
|
195
|
+
for (;;) {
|
|
196
|
+
const capped = { truncated: true, preview: redactSecrets(text.slice(0, length)).text };
|
|
197
|
+
if (JSON.stringify(capped).length <= LIMITS.resultBytes || length < 16) return capped;
|
|
198
|
+
length = Math.floor(length * 0.9);
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
const keyProblem = (key, required) => {
|
|
203
|
+
if (key === undefined) return required ? 'idempotency_key is required for write calls' : null;
|
|
204
|
+
if (typeof key !== 'string' || !key.length || key.length > LIMITS.idempotencyKeyMax) return `idempotency_key must be 1-${LIMITS.idempotencyKeyMax} characters`;
|
|
205
|
+
return null;
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
// The one enforcement function. Order: per-worker admission budget, exact lookup, grant, class, schema hash, idempotency, arguments, rate limit,
|
|
209
|
+
// handler. Unknown, ungranted and disabled tools share one refusal (tool_unavailable) so a worker cannot enumerate
|
|
210
|
+
// tools it cannot use. The handler takes its target and config only from the registry row.
|
|
211
|
+
async function callTool({ worker, tool, class: callClass, args, schema_hash: pinnedHash, idempotency_key: key }) {
|
|
212
|
+
const name = workerName(worker);
|
|
213
|
+
if (!admit(name)) throw new RegistryError('rate_limited', 'too many calls; retry later');
|
|
214
|
+
let digest = null;
|
|
215
|
+
try { digest = sha256(canonical(args ?? null)); } catch { /* an unserializable argument has no digest */ }
|
|
216
|
+
const row = typeof tool === 'string' ? getTool(tool) : null;
|
|
217
|
+
const done = (outcome, error) => {
|
|
218
|
+
record({ kind: 'call', tool: typeof tool === 'string' ? tool.slice(0, 64) : null, worker: typeof name === 'string' ? name.slice(0, 32) : null, args_digest: digest, outcome, schema_hash: row?.schema_hash });
|
|
219
|
+
if (error) throw error;
|
|
220
|
+
};
|
|
221
|
+
const leaseLive = stored => stored.lease_expires_at != null && Date.parse(stored.lease_expires_at) > now();
|
|
222
|
+
// Retryable and machine-readable: the code is in_progress and the message names the seconds left on the lease.
|
|
223
|
+
const inProgress = stored => {
|
|
224
|
+
const seconds = Math.max(1, Math.ceil((Date.parse(stored?.lease_expires_at ?? '') - now()) / 1000) || 1);
|
|
225
|
+
done('replay_unfinished', new RegistryError('in_progress', `an earlier call with this idempotency_key is in progress; retry later with the same key in about ${seconds} s`));
|
|
226
|
+
};
|
|
227
|
+
const unavailable = outcome => done(outcome, new RegistryError('tool_unavailable', 'tool unavailable'));
|
|
228
|
+
if (!row) unavailable('unknown_tool');
|
|
229
|
+
if (typeof name !== 'string' || !db.prepare('SELECT 1 FROM tool_grants WHERE tool=? AND worker=?').get(row.name, name)) unavailable('not_granted');
|
|
230
|
+
if (row.enabled !== 1) unavailable('disabled');
|
|
231
|
+
if (callClass !== toolClass(row)) done('wrong_class', new RegistryError('wrong_class', 'wrong class for this tool; see list_tools'));
|
|
232
|
+
const stale = () => done('stale_registry', new RegistryError('stale_registry', 'call list_tools again'));
|
|
233
|
+
if (pinnedHash === undefined ? toolClass(row) === 'write' : pinnedHash !== callerHash(row, name)) stale();
|
|
234
|
+
const keyError = keyProblem(key, toolClass(row) === 'write');
|
|
235
|
+
if (keyError) done('invalid_arguments', new RegistryError('invalid_arguments', keyError));
|
|
236
|
+
if (key !== undefined) {
|
|
237
|
+
// Retention runs from completion; a row without completed_at (pending, or from an older build) uses created_at.
|
|
238
|
+
db.prepare('DELETE FROM tool_idempotency WHERE COALESCE(completed_at, created_at) < ?').run(iso(now() - LIMITS.idempotencyTtlMs));
|
|
239
|
+
for (;;) {
|
|
240
|
+
const stored = db.prepare('SELECT * FROM tool_idempotency WHERE worker=? AND tool=? AND key=?').get(name, row.name, key);
|
|
241
|
+
const paused = hooks.afterIdempotencyLookup?.(stored);
|
|
242
|
+
if (paused) await paused;
|
|
243
|
+
if (stored?.state === 'pending') {
|
|
244
|
+
// A live lease means the earlier call may still be running. An expired (or pre-lease, NULL) lease is taken over below.
|
|
245
|
+
if (leaseLive(stored)) inProgress(stored);
|
|
246
|
+
} else if (stored) {
|
|
247
|
+
const outcome = JSON.parse(stored.outcome);
|
|
248
|
+
if (outcome.ok) { done('replayed'); return { ok: true, result: outcome.result, replayed: true }; }
|
|
249
|
+
if (!outcome.retryable) done('replayed_failure', new RegistryError(outcome.code, outcome.message));
|
|
250
|
+
// Free exactly the row we read (outcome, reservation time, lease and completion time). If another caller already
|
|
251
|
+
// replaced it, this changes nothing and we read again instead of erasing theirs.
|
|
252
|
+
if (db.prepare("DELETE FROM tool_idempotency WHERE worker=? AND tool=? AND key=? AND state='done' AND outcome=? AND created_at=? AND lease_expires_at IS ? AND completed_at IS ?").run(name, row.name, key, stored.outcome, stored.created_at, stored.lease_expires_at, stored.completed_at).changes === 0) continue;
|
|
253
|
+
}
|
|
254
|
+
break;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
const schema = JSON.parse(row.input_schema);
|
|
258
|
+
const errors = validateValue(schema, args);
|
|
259
|
+
if (errors.length) done('invalid_arguments', new RegistryError('invalid_arguments', errors.slice(0, 5).join('; ')));
|
|
260
|
+
if (rateLimited(`${row.name}\0${name}`)) done('rate_limited', new RegistryError('rate_limited', 'too many calls; retry later'));
|
|
261
|
+
const config = JSON.parse(row.handler);
|
|
262
|
+
// Every write below is bound to this call's own lease, so a first attempt that wakes up after a takeover cannot
|
|
263
|
+
// overwrite or delete the taker's row.
|
|
264
|
+
const lease = iso(now() + leaseMs(handlers[config.kind]));
|
|
265
|
+
const mine = 'WHERE worker=? AND tool=? AND key=? AND state=\'pending\' AND lease_expires_at=?';
|
|
266
|
+
const settle = outcome => { if (key !== undefined) db.prepare(`UPDATE tool_idempotency SET state='done', outcome=?, completed_at=? ${mine}`).run(JSON.stringify(outcome), iso(now()), name, row.name, key, lease); };
|
|
267
|
+
// Reserve the key atomically. A fresh key is decided by the primary key. An expired pending row is taken over by a
|
|
268
|
+
// conditional UPDATE, so of two concurrent takers (even in another process) exactly one changes the row.
|
|
269
|
+
if (key !== undefined) {
|
|
270
|
+
const stamp = iso(now());
|
|
271
|
+
const taken = db.prepare("UPDATE tool_idempotency SET lease_expires_at=?, created_at=? WHERE worker=? AND tool=? AND key=? AND state='pending' AND (lease_expires_at IS NULL OR lease_expires_at <= ?)")
|
|
272
|
+
.run(lease, stamp, name, row.name, key, stamp).changes === 1;
|
|
273
|
+
if (!taken && db.prepare('INSERT INTO tool_idempotency(worker,tool,key,state,outcome,created_at,lease_expires_at) VALUES(?,?,?,\'pending\',NULL,?,?) ON CONFLICT DO NOTHING').run(name, row.name, key, stamp, lease).changes === 0) {
|
|
274
|
+
const current = db.prepare('SELECT * FROM tool_idempotency WHERE worker=? AND tool=? AND key=?').get(name, row.name, key);
|
|
275
|
+
// The winner may already have finished: replay its result rather than report it as in progress.
|
|
276
|
+
const finished = current?.state === 'done' ? JSON.parse(current.outcome) : null;
|
|
277
|
+
if (finished?.ok) { done('replayed'); return { ok: true, result: finished.result, replayed: true }; }
|
|
278
|
+
inProgress(current);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
let result;
|
|
282
|
+
try {
|
|
283
|
+
result = await handlers[config.kind].run({ tool: row.name, worker: name, args, config, now, idempotencyKey: key });
|
|
284
|
+
} catch (error) {
|
|
285
|
+
if (error instanceof RegistryError) {
|
|
286
|
+
// The handler refused before doing anything, so the key is free to use again.
|
|
287
|
+
if (key !== undefined) db.prepare(`DELETE FROM tool_idempotency ${mine}`).run(name, row.name, key, lease);
|
|
288
|
+
done(error.code, error);
|
|
289
|
+
}
|
|
290
|
+
const message = redactSecrets(error?.userMessage ?? 'handler failed; retry later').text;
|
|
291
|
+
settle({ ok: false, code: 'handler_failed', message, retryable: error?.notDelivered === true });
|
|
292
|
+
done('handler_failed', new RegistryError('handler_failed', message));
|
|
293
|
+
}
|
|
294
|
+
const capped = capResult(result);
|
|
295
|
+
settle({ ok: true, result: capped });
|
|
296
|
+
done('ok');
|
|
297
|
+
return { ok: true, result: capped };
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
return { register, remove, grant, revoke, list, listTools, registryVersion, callTool, setEnabled, lastChange };
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// ---- t3_post: the owner_message handler ----------------------------------------------------------------------------
|
|
304
|
+
const MESSAGE_KINDS = new Set(['question', 'blocker']);
|
|
305
|
+
const MESSAGE_INTERVAL_MS = 10 * 60_000;
|
|
306
|
+
const MESSAGE_BATCH_CHARS = 8000;
|
|
307
|
+
// A global budget for the whole tool, across workers. Held and retried messages count; so does a failed attempt.
|
|
308
|
+
const MESSAGE_HOURLY_CAP = 6;
|
|
309
|
+
const MESSAGE_DAILY_CAP = 30;
|
|
310
|
+
|
|
311
|
+
// Default delivery: the host `t3-post` command, which posts through T3's /mcp so the message shows as an agent chip.
|
|
312
|
+
// execFile with an argv array (no shell); the message goes on stdin, never in argv. There is no fallback to posting as
|
|
313
|
+
// the owner: exit 3 (not sent), a timeout, a spawn failure and any other failure all leave the message queued.
|
|
314
|
+
const POST_TIMEOUT_MS = HANDLER_TIMEOUT_MS;
|
|
315
|
+
const senderName = worker => (String(worker).replace(/[^A-Za-z0-9-]/g, '-').slice(0, 40) || 'worker');
|
|
316
|
+
|
|
317
|
+
// A zero, negative, non-numeric or too long timeout is refused: the lease assumes no handler outlives HANDLER_TIMEOUT_MS.
|
|
318
|
+
const checkTimeout = timeoutMs => {
|
|
319
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > HANDLER_TIMEOUT_MS) throw new RangeError(`timeoutMs must be a number from 1 to ${HANDLER_TIMEOUT_MS}`);
|
|
320
|
+
return timeoutMs;
|
|
321
|
+
};
|
|
322
|
+
|
|
323
|
+
export function createT3PostCommand({ command = 't3-post', timeoutMs = POST_TIMEOUT_MS } = {}) {
|
|
324
|
+
checkTimeout(timeoutMs);
|
|
325
|
+
return ({ threadId, label, text }) => new Promise((resolve, reject) => {
|
|
326
|
+
const args = ['--as', senderName(label), '--kind', 'script', '--mode', 'queue', '--thread', threadId];
|
|
327
|
+
const child = execFile(command, args, { timeout: timeoutMs, killSignal: 'SIGKILL', maxBuffer: 64 * 1024, windowsHide: true }, (error, _out, stderr) => {
|
|
328
|
+
if (!error) return resolve();
|
|
329
|
+
const reason = error.killed ? 'timed out' : error.code === 'ENOENT' ? 't3-post not found on PATH' : `exit ${error.code}`;
|
|
330
|
+
const detail = redactSecrets(String(stderr ?? '').trim().slice(0, 300)).text.slice(0, 300);
|
|
331
|
+
reject(Object.assign(new Error(`t3-post failed: ${reason}${detail ? `: ${detail}` : ''}`), { exitCode: error.code }));
|
|
332
|
+
});
|
|
333
|
+
child.stdin.on('error', () => {});
|
|
334
|
+
child.stdin.end(text);
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
export function createT3PostHandler({ store, post, command, timeoutMs, now = Date.now, intervalMs = MESSAGE_INTERVAL_MS, hourlyCap = MESSAGE_HOURLY_CAP, dailyCap = MESSAGE_DAILY_CAP }) {
|
|
339
|
+
if (timeoutMs !== undefined) checkTimeout(timeoutMs);
|
|
340
|
+
post ??= createT3PostCommand({ command, timeoutMs });
|
|
341
|
+
const db = store.db;
|
|
342
|
+
// The budget: every post attempt is a row in tool_post_log, whether a call or a timer retry made it.
|
|
343
|
+
const since = ms => db.prepare("SELECT count(*) n FROM tool_post_log WHERE at > ? AND outcome != 'rate_limited'").get(iso(now() - ms)).n;
|
|
344
|
+
const overBudget = () => since(3_600_000) >= hourlyCap || since(86_400_000) >= dailyCap;
|
|
345
|
+
const logPost = (outcome, tool, worker, kind) => db.prepare('INSERT INTO tool_post_log(at,tool,worker,message_kind,outcome) VALUES(?,?,?,?,?)').run(iso(now()), tool, worker, kind, outcome).lastInsertRowid;
|
|
346
|
+
const settleLog = (id, outcome) => db.prepare('UPDATE tool_post_log SET outcome=? WHERE id=?').run(outcome, id);
|
|
347
|
+
|
|
348
|
+
// One flush at a time per tool, worker and thread. A flush selects its rows only after it holds the turn, so a message
|
|
349
|
+
// another flush already sent is never selected twice. (One bridge process owns the database.)
|
|
350
|
+
const turns = new Map();
|
|
351
|
+
const inTurn = (key, fn) => {
|
|
352
|
+
const result = (turns.get(key) ?? Promise.resolve()).then(fn);
|
|
353
|
+
const tail = result.catch(() => {});
|
|
354
|
+
turns.set(key, tail);
|
|
355
|
+
tail.then(() => { if (turns.get(key) === tail) turns.delete(key); });
|
|
356
|
+
return result;
|
|
357
|
+
};
|
|
358
|
+
const lastSent = (tool, worker) => db.prepare('SELECT max(sent_at) AS at FROM tool_outbox WHERE tool=? AND worker=?').get(tool, worker).at;
|
|
359
|
+
// The shared delivery path, for calls and for the timer. Returns {held} while the 10-minute window is open; the timer
|
|
360
|
+
// path also stays inside the budget and logs its attempt. A failure that does not prove the message was undelivered
|
|
361
|
+
// (only t3-post exit 3 does) marks the rows uncertain: they are never retried automatically.
|
|
362
|
+
function flush(tool, worker, threadId, { timer = false } = {}) {
|
|
363
|
+
return inTurn(`${tool}\0${worker}\0${threadId}`, async () => {
|
|
364
|
+
const rows = db.prepare('SELECT * FROM tool_outbox WHERE tool=? AND worker=? AND thread_id=? AND sent_at IS NULL AND uncertain_at IS NULL ORDER BY id').all(tool, worker, threadId);
|
|
365
|
+
if (!rows.length) return { sent: 0, remaining: 0 };
|
|
366
|
+
const last = lastSent(tool, worker);
|
|
367
|
+
if (last && now() - Date.parse(last) < intervalMs) return { held: true, retry_after_ms: Math.max(0, intervalMs - (now() - Date.parse(last))) };
|
|
368
|
+
if (timer && overBudget()) return { held: true, retry_after_ms: 60_000 };
|
|
369
|
+
const attempt = timer ? logPost('pending', tool, worker, rows[0].kind) : null;
|
|
370
|
+
const batch = []; let chars = 0;
|
|
371
|
+
for (const row of rows) {
|
|
372
|
+
const part = `[${row.kind}] ${row.text}`;
|
|
373
|
+
if (batch.length && chars + part.length > MESSAGE_BATCH_CHARS) break;
|
|
374
|
+
batch.push({ row, part }); chars += part.length;
|
|
375
|
+
}
|
|
376
|
+
const marks = batch.map(() => '?').join(',');
|
|
377
|
+
try { await post({ threadId, label: worker, text: batch.map(b => b.part).join('\n\n') }); }
|
|
378
|
+
catch (error) {
|
|
379
|
+
if (error?.exitCode !== 3) db.prepare(`UPDATE tool_outbox SET uncertain_at=? WHERE id IN (${marks})`).run(iso(now()), ...batch.map(b => b.row.id));
|
|
380
|
+
if (attempt) settleLog(attempt, 'failed');
|
|
381
|
+
throw error;
|
|
382
|
+
}
|
|
383
|
+
db.prepare(`UPDATE tool_outbox SET sent_at=? WHERE id IN (${marks})`).run(iso(now()), ...batch.map(b => b.row.id));
|
|
384
|
+
if (attempt) settleLog(attempt, 'sent');
|
|
385
|
+
return { sent: batch.length, remaining: rows.length - batch.length };
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
// A queued message the timer can never deliver (no thread, or no enabled tool granted to its worker that still points at
|
|
389
|
+
// its thread) is discarded, so it cannot sit in the queue forever or be revived by a later grant.
|
|
390
|
+
const pruneUndeliverable = () => db.prepare(`DELETE FROM tool_outbox WHERE sent_at IS NULL AND (thread_id = '' OR NOT EXISTS (
|
|
391
|
+
SELECT 1 FROM registered_tools t JOIN tool_grants g ON g.tool=t.name
|
|
392
|
+
WHERE t.name=tool_outbox.tool AND t.enabled=1 AND g.worker=tool_outbox.worker AND json_extract(t.handler,'$.thread_id')=tool_outbox.thread_id))`).run();
|
|
393
|
+
// Timer path: retry held messages whose rate window has passed. Returns the number of messages sent.
|
|
394
|
+
async function flushDue() {
|
|
395
|
+
pruneUndeliverable();
|
|
396
|
+
const groups = db.prepare("SELECT tool, worker, thread_id FROM tool_outbox WHERE sent_at IS NULL AND uncertain_at IS NULL AND thread_id != '' GROUP BY tool, worker, thread_id").all();
|
|
397
|
+
let sent = 0;
|
|
398
|
+
for (const { tool, worker, thread_id } of groups) {
|
|
399
|
+
// Authority is checked again at delivery: the tool is still registered and enabled, the worker still holds its grant,
|
|
400
|
+
// and the tool still points at the thread the message was queued for.
|
|
401
|
+
const row = db.prepare('SELECT t.handler FROM registered_tools t JOIN tool_grants g ON g.tool=t.name WHERE t.name=? AND t.enabled=1 AND g.worker=?').get(tool, worker);
|
|
402
|
+
if (!row || JSON.parse(row.handler).thread_id !== thread_id) continue;
|
|
403
|
+
try { sent += (await flush(tool, worker, thread_id, { timer: true })).sent ?? 0; }
|
|
404
|
+
catch { /* kept queued; the next tick or call retries */ }
|
|
405
|
+
}
|
|
406
|
+
return sent;
|
|
407
|
+
}
|
|
408
|
+
const hasHeld = () => { pruneUndeliverable(); return db.prepare('SELECT 1 FROM tool_outbox WHERE sent_at IS NULL AND uncertain_at IS NULL LIMIT 1').get() !== undefined; };
|
|
409
|
+
return {
|
|
410
|
+
flushDue, hasHeld, timeoutMs: timeoutMs ?? POST_TIMEOUT_MS,
|
|
411
|
+
configKeys: ['thread_id'],
|
|
412
|
+
// Posting a message is a write effect, so a t3_post tool is always class write.
|
|
413
|
+
effectClass: 'write',
|
|
414
|
+
validateConfig(config, tool) {
|
|
415
|
+
if (typeof config.thread_id !== 'string' || !config.thread_id || config.thread_id.length > 128) refuse('invalid_tool', 't3_post needs handler.thread_id');
|
|
416
|
+
const props = tool.inputSchema.properties;
|
|
417
|
+
if (props.kind?.type !== 'string' || props.text?.type !== 'string') refuse('invalid_tool', 't3_post tools take string "kind" and "text"');
|
|
418
|
+
},
|
|
419
|
+
async run({ tool, worker, args, config, idempotencyKey }) {
|
|
420
|
+
if (!MESSAGE_KINDS.has(args.kind)) refuse('invalid_arguments', 'kind must be question or blocker');
|
|
421
|
+
if (typeof args.text !== 'string' || !args.text.trim() || args.text.length > 2000) refuse('invalid_arguments', 'text must be 1-2000 characters');
|
|
422
|
+
// Delivery is at least once. If an earlier attempt under this key already posted (its row is marked sent) but the
|
|
423
|
+
// registry never settled, return that receipt instead of posting again.
|
|
424
|
+
const digest = createHash('sha256').update(canonical([args.kind, args.text])).digest('hex');
|
|
425
|
+
const earlier = idempotencyKey ? db.prepare('SELECT args_digest, sent_at FROM tool_outbox WHERE tool=? AND worker=? AND idempotency_key=? ORDER BY id DESC LIMIT 1').get(tool, worker, idempotencyKey) : undefined;
|
|
426
|
+
// A reused key must carry the same message. Rows from an older build have no digest and keep the old behaviour.
|
|
427
|
+
if (earlier?.args_digest && earlier.args_digest !== digest) refuse('invalid_arguments', 'idempotency key reused with different content');
|
|
428
|
+
const sentRow = earlier?.sent_at != null;
|
|
429
|
+
if (sentRow) return { queued: false, sent: 1, remaining: 0, note: 'already sent; receipt reused' };
|
|
430
|
+
const stamp = iso(now());
|
|
431
|
+
// Budget first: every attempt that gets this far is logged with its kind, and counts until it ages out.
|
|
432
|
+
if (overBudget()) { logPost('rate_limited', tool, worker, args.kind); refuse('rate_limited', 'message budget reached; retry later'); }
|
|
433
|
+
const logId = logPost('pending', tool, worker, args.kind);
|
|
434
|
+
const settle = outcome => settleLog(logId, outcome);
|
|
435
|
+
// A retry under the same key reuses its queued message instead of adding a second one.
|
|
436
|
+
const queued = idempotencyKey ? db.prepare('SELECT 1 FROM tool_outbox WHERE tool=? AND worker=? AND idempotency_key=? AND sent_at IS NULL').get(tool, worker, idempotencyKey) : undefined;
|
|
437
|
+
if (!queued) db.prepare('INSERT INTO tool_outbox(tool,worker,kind,text,created_at,thread_id,idempotency_key,args_digest) VALUES(?,?,?,?,?,?,?,?)').run(tool, worker, args.kind, args.text, stamp, config.thread_id, idempotencyKey ?? null, digest);
|
|
438
|
+
try {
|
|
439
|
+
const result = await flush(tool, worker, config.thread_id);
|
|
440
|
+
if (result.held) { settle('held'); return { queued: true, retry_after_ms: result.retry_after_ms, note: 'held and merged into the next message' }; }
|
|
441
|
+
settle('sent'); return { queued: false, ...result };
|
|
442
|
+
}
|
|
443
|
+
catch (error) {
|
|
444
|
+
settle('failed');
|
|
445
|
+
// Exit code 3 and any transport failure keep the message queued. Only exit 3 proves nothing was delivered,
|
|
446
|
+
// which is the one case where the caller may retry under the same idempotency key.
|
|
447
|
+
throw Object.assign(new Error('delivery failed'), { userMessage: error?.exitCode === 3 ? 'delivery failed; the message is kept queued, retry later' : 'delivery failed and the message may have been delivered; it is not retried automatically, check the thread', cause: error, notDelivered: error?.exitCode === 3 });
|
|
448
|
+
}
|
|
449
|
+
},
|
|
450
|
+
};
|
|
451
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
|
|
3
|
+
const shellQuote = value => `'${String(value).replaceAll("'", "'\\''")}'`;
|
|
4
|
+
|
|
5
|
+
// The command that starts a trial bridge for `home`. `dalan try` alone starts the default trial home, so only another
|
|
6
|
+
// home needs --home.
|
|
7
|
+
export function tryCommand(cli, home, realHome) {
|
|
8
|
+
return path.resolve(home) === path.join(realHome, '.local/share/dalan-trial') ? `${cli} try` : `${cli} try --home ${shellQuote(home)}`;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export const stoppedTrialFix = (cli, home, realHome) => `start it in another terminal, then run this command again: ${tryCommand(cli, home, realHome)}`;
|