@cotal-ai/connector-core 0.167.0 → 0.168.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/dist/agent-inbox.d.ts +531 -0
- package/dist/agent-inbox.d.ts.map +1 -0
- package/dist/agent-inbox.js +1455 -0
- package/dist/agent-inbox.js.map +1 -0
- package/dist/agent.d.ts +4 -271
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +56 -1191
- package/dist/agent.js.map +1 -1
- package/dist/docs-bundle.bin +0 -0
- package/dist/docs-bundle.generated.d.ts +1 -1
- package/dist/docs-bundle.generated.js +7 -7
- package/dist/docs-bundle.generated.js.map +1 -1
- package/dist/docs-index.bin +0 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/prompt-desk.d.ts +167 -0
- package/dist/prompt-desk.d.ts.map +1 -0
- package/dist/prompt-desk.js +696 -0
- package/dist/prompt-desk.js.map +1 -0
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.js +1 -1
- package/package.json +3 -3
|
@@ -0,0 +1,696 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The prompt desk (SPEC 13.22): the agent's own server for the questions its harness stops to ask,
|
|
3
|
+
* such as "Allow this command?", a multiple-choice question, a plan or a form. It holds the open
|
|
4
|
+
* prompts, runs their state table, keeps the expiry and settle timers, and serves the `agent`
|
|
5
|
+
* endpoint's `prompts`, `prompt` and `prompt-answer` commands on the principal route (SPEC 13.21)
|
|
6
|
+
* through `CotalEndpoint.servePrincipal`. Nothing per prompt is stored on the broker: presence
|
|
7
|
+
* carries a count and a counter, and the rest lives in this process.
|
|
8
|
+
*
|
|
9
|
+
* It knows no harness. An adapter opens a prompt for a native dialog, hands the one accepted answer
|
|
10
|
+
* to its harness in `deliver`, reports what the harness was then seen to do with `settle`, and frees
|
|
11
|
+
* what it holds in `end`, which comes exactly once per prompt.
|
|
12
|
+
*
|
|
13
|
+
* One rule orders everything. The desk is synchronous: every event is applied in one uninterrupted
|
|
14
|
+
* step, in the order it reaches the desk, and no step waits for anything. An event that reaches the
|
|
15
|
+
* desk while a step runs, such as an adapter report made from inside `check`, `deliver` or `end`, is
|
|
16
|
+
* applied after that step. The first event applied wins, and each later one meets the state the
|
|
17
|
+
* first one left. Opening a prompt is not such an event: `open` called from inside a hook takes
|
|
18
|
+
* effect at once.
|
|
19
|
+
*/
|
|
20
|
+
import { randomBytes } from "node:crypto";
|
|
21
|
+
import { AGENT_CLUSTER, AGENT_CONTRACTS, AGENT_ENDPOINT, AGENT_PROMPT_CONTENT_MAX_BYTES, AGENT_PROMPT_DIGEST_DETAIL, AGENT_PROMPT_LIST_MAX, AGENT_PROMPT_SIZE_DETAIL, AGENT_PROMPT_STATE_DETAIL, EpEnvelopeError, agentPromptDigest, canonicalJson, compileContractSchema, contractDigest, processRuntime, } from "@cotal-ai/core";
|
|
22
|
+
/** The desk serves only on a connection whose `max_payload` is at least this many bytes, which covers
|
|
23
|
+
* the largest `prompts` and `prompt` replies with their envelopes. */
|
|
24
|
+
export const PROMPT_DESK_MIN_MAX_PAYLOAD = 524288;
|
|
25
|
+
/** A summary's JSON encoding is at most this many bytes of UTF-8, in every state its prompt can reach. */
|
|
26
|
+
export const PROMPT_SUMMARY_MAX_BYTES = 4096;
|
|
27
|
+
/** A `prompt-answer` reply waits at most this long for the delivery result of the answer it accepted. */
|
|
28
|
+
export const PROMPT_ANSWER_REPLY_MS = 10_000;
|
|
29
|
+
/** The range of {@link PromptSpec.openMs}: 1 s to 7 days. */
|
|
30
|
+
export const PROMPT_OPEN_MS = Object.freeze({ min: 1000, max: 7 * 24 * 60 * 60 * 1000 });
|
|
31
|
+
/** The range of {@link PromptSpec.settleMs}: 1 s to 24 h. */
|
|
32
|
+
export const PROMPT_SETTLE_MS = Object.freeze({ min: 1000, max: 24 * 60 * 60 * 1000 });
|
|
33
|
+
/** Why {@link PromptDesk.open} refused a prompt: 32 are `open` or `sent` (`full`), the content or a
|
|
34
|
+
* summary is over its limit (`too-large`), the spec or its content breaks a rule (`invalid`), or the
|
|
35
|
+
* desk has closed (`closed`). */
|
|
36
|
+
export class PromptRefused extends Error {
|
|
37
|
+
reason;
|
|
38
|
+
constructor(reason, message) {
|
|
39
|
+
super(message);
|
|
40
|
+
this.reason = reason;
|
|
41
|
+
this.name = "PromptRefused";
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const NONE = { tie: "none" };
|
|
45
|
+
/** The state table, as a pure function: the step `event` takes from `state`, at `at`. */
|
|
46
|
+
export function stepPrompt(state, event, at) {
|
|
47
|
+
const close = (outcome, attempted) => ({ kind: "move", next: { kind: "closed", at, outcome }, end: { attempted } });
|
|
48
|
+
if (state.kind === "open") {
|
|
49
|
+
switch (event.kind) {
|
|
50
|
+
case "accept":
|
|
51
|
+
return { kind: "move", next: { kind: "sent", answer: event.answer, delivery: "unconfirmed" }, deliver: true };
|
|
52
|
+
case "settle": {
|
|
53
|
+
const e = event.evidence;
|
|
54
|
+
if (e.kind === "local")
|
|
55
|
+
return close({ kind: "local", seen: e.seen }, false);
|
|
56
|
+
// An `open` prompt had no remote answer, so what the harness did with it, it did on its own.
|
|
57
|
+
// A sighting tied only to the subject says nothing about this prompt.
|
|
58
|
+
if (e.kind === "observed")
|
|
59
|
+
return close(e.seen.tie === "prompt" ? { kind: "local", seen: e.seen } : { kind: "withdrawn", seen: e.seen }, false);
|
|
60
|
+
if (e.kind === "withdrawn")
|
|
61
|
+
return close({ kind: "withdrawn", seen: NONE }, false);
|
|
62
|
+
return { kind: "stay", warn: "a confirmation came for a prompt with no accepted answer" };
|
|
63
|
+
}
|
|
64
|
+
case "expiry":
|
|
65
|
+
return close({ kind: "expired" }, false);
|
|
66
|
+
case "close":
|
|
67
|
+
return close({ kind: "withdrawn", seen: NONE }, false);
|
|
68
|
+
case "delivery":
|
|
69
|
+
return { kind: "stay", warn: "a delivery result came for a prompt with no deliver call" };
|
|
70
|
+
case "settle-time":
|
|
71
|
+
return { kind: "cannot-happen", why: "the settle time starts at the accepted answer" };
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
if (state.kind === "sent") {
|
|
75
|
+
const answer = state.answer;
|
|
76
|
+
switch (event.kind) {
|
|
77
|
+
case "accept":
|
|
78
|
+
return { kind: "never-reached", why: "an answer to a sent prompt meets check 3 or 4" };
|
|
79
|
+
case "delivery":
|
|
80
|
+
if (state.delivery === "delivered")
|
|
81
|
+
return { kind: "cannot-happen", why: "deliver has one result" };
|
|
82
|
+
if (event.result === "delivered")
|
|
83
|
+
return { kind: "move", next: { kind: "sent", answer, delivery: "delivered" } };
|
|
84
|
+
if (event.result === "confirmed")
|
|
85
|
+
return close({ kind: "answered", answer }, true);
|
|
86
|
+
if (event.result === "gone")
|
|
87
|
+
return close({ kind: "undelivered", answer }, true);
|
|
88
|
+
return { kind: "stay", warn: "deliver failed, which proves nothing about the hand-over" };
|
|
89
|
+
case "settle": {
|
|
90
|
+
const e = event.evidence;
|
|
91
|
+
if (e.kind === "confirmed")
|
|
92
|
+
return close({ kind: "answered", answer }, true);
|
|
93
|
+
if (e.kind === "local")
|
|
94
|
+
return close({ kind: "local", seen: e.seen, late: answer }, true);
|
|
95
|
+
if (e.kind === "observed")
|
|
96
|
+
return close({ kind: "unconfirmed", answer, seen: e.seen }, true);
|
|
97
|
+
return close({ kind: "unconfirmed", answer, seen: NONE }, true);
|
|
98
|
+
}
|
|
99
|
+
case "expiry":
|
|
100
|
+
return { kind: "stay" }; // the answer is already with the adapter
|
|
101
|
+
case "settle-time":
|
|
102
|
+
case "close":
|
|
103
|
+
return close({ kind: "unconfirmed", answer, seen: NONE }, true);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
if (event.kind === "accept")
|
|
107
|
+
return { kind: "never-reached", why: "an answer to a closed prompt meets check 3 or 4" };
|
|
108
|
+
if (event.kind === "settle")
|
|
109
|
+
return { kind: "stay", warn: "a report came for a closed prompt", report: true };
|
|
110
|
+
return { kind: "stay" };
|
|
111
|
+
}
|
|
112
|
+
const iso = (ms) => new Date(ms).toISOString();
|
|
113
|
+
/** Text for any value, such as one a hook gave back. Never throws: `JSON.stringify` throws on `1n`,
|
|
114
|
+
* and `String` on an object with no primitive form. */
|
|
115
|
+
function describe(v) {
|
|
116
|
+
try {
|
|
117
|
+
if (v instanceof Error)
|
|
118
|
+
return v.message;
|
|
119
|
+
const json = JSON.stringify(v);
|
|
120
|
+
if (json !== undefined)
|
|
121
|
+
return json.length > 200 ? `${json.slice(0, 200)}...` : json;
|
|
122
|
+
}
|
|
123
|
+
catch { /* not JSON */ }
|
|
124
|
+
try {
|
|
125
|
+
return typeof v === "bigint" ? `${v}n` : String(v);
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
return `a ${typeof v} with no text form`;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
/** A hook that returns a thenable where it returns a plain value broke its contract, and a rejection
|
|
132
|
+
* of that thenable must not go unhandled: Node exits on one. Attaches a no-op rejection handler and
|
|
133
|
+
* says whether `v` was a thenable. */
|
|
134
|
+
function ignoreRejection(v) {
|
|
135
|
+
try {
|
|
136
|
+
const then = v?.then;
|
|
137
|
+
if (typeof then !== "function")
|
|
138
|
+
return false;
|
|
139
|
+
then.call(v, undefined, () => { });
|
|
140
|
+
}
|
|
141
|
+
catch { /* a `then` that throws has nothing to attach to */ }
|
|
142
|
+
return true;
|
|
143
|
+
}
|
|
144
|
+
/** `d.kind`, or undefined when reading it throws. */
|
|
145
|
+
function deliveryKind(d) {
|
|
146
|
+
try {
|
|
147
|
+
return d?.kind;
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
return undefined;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
const B32 = "abcdefghijklmnopqrstuvwxyz234567";
|
|
154
|
+
const EFFECTS = new Set(["proceed", "refuse", "cancel"]);
|
|
155
|
+
function deepFreeze(value) {
|
|
156
|
+
if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
|
|
157
|
+
for (const child of Object.values(value))
|
|
158
|
+
deepFreeze(child);
|
|
159
|
+
Object.freeze(value);
|
|
160
|
+
}
|
|
161
|
+
return value;
|
|
162
|
+
}
|
|
163
|
+
function timer(ms, fn) {
|
|
164
|
+
const t = setTimeout(fn, ms);
|
|
165
|
+
t.unref();
|
|
166
|
+
return t;
|
|
167
|
+
}
|
|
168
|
+
function refused(code, message, details) {
|
|
169
|
+
return new EpEnvelopeError(code, message, details, "not-executed");
|
|
170
|
+
}
|
|
171
|
+
function parseSeen(s) {
|
|
172
|
+
const o = s;
|
|
173
|
+
if (o && typeof o === "object" && !Array.isArray(o)) {
|
|
174
|
+
const keys = Object.keys(o).length;
|
|
175
|
+
if (o.tie === "none" && keys === 1)
|
|
176
|
+
return { tie: "none" };
|
|
177
|
+
if ((o.tie === "prompt" || o.tie === "subject") && keys === 2 && EFFECTS.has(o.effect))
|
|
178
|
+
return { tie: o.tie, effect: o.effect };
|
|
179
|
+
}
|
|
180
|
+
throw new TypeError(`settle: ${describe(s)} is not a sighting ({ tie: "prompt" | "subject", effect } or { tie: "none" })`);
|
|
181
|
+
}
|
|
182
|
+
function parseEvidence(e) {
|
|
183
|
+
const o = e;
|
|
184
|
+
if (o && typeof o === "object" && !Array.isArray(o)) {
|
|
185
|
+
const keys = Object.keys(o).length;
|
|
186
|
+
if ((o.kind === "confirmed" || o.kind === "withdrawn") && keys === 1)
|
|
187
|
+
return { kind: o.kind };
|
|
188
|
+
if ((o.kind === "local" || o.kind === "observed") && keys === 2)
|
|
189
|
+
return { kind: o.kind, seen: parseSeen(o.seen) };
|
|
190
|
+
}
|
|
191
|
+
throw new TypeError(`settle: ${describe(e)} is not an Evidence`);
|
|
192
|
+
}
|
|
193
|
+
/** The longest legal answerer: owner and actor at 64 characters, a 32-character lifecycle UID, and
|
|
194
|
+
* an authority word (both are five characters). */
|
|
195
|
+
const LONGEST_BY = Object.freeze({ id: `${"w".repeat(64)}.${"w".repeat(64)}`, uid: "w".repeat(32), authority: "owner" });
|
|
196
|
+
/** Every timestamp has one 24-byte form. */
|
|
197
|
+
const ANY_AT = "2000-01-01T00:00:00.000Z";
|
|
198
|
+
/** The longest sighting: the longer tie word and the longest effect. */
|
|
199
|
+
const LONGEST_SEEN = Object.freeze({ tie: "subject", effect: "proceed" });
|
|
200
|
+
/** The largest encoded summary over every state the prompt can reach, with every variable field at
|
|
201
|
+
* its longest legal value. */
|
|
202
|
+
function largestSummaryBytes(base, options) {
|
|
203
|
+
let max = 0;
|
|
204
|
+
const measure = (state) => { max = Math.max(max, Buffer.byteLength(JSON.stringify({ ...base, state }))); };
|
|
205
|
+
const closed = (outcome) => ({ kind: "closed", at: ANY_AT, outcome });
|
|
206
|
+
measure({ kind: "open" });
|
|
207
|
+
measure(closed({ kind: "expired" }));
|
|
208
|
+
measure(closed({ kind: "withdrawn", seen: LONGEST_SEEN }));
|
|
209
|
+
measure(closed({ kind: "local", seen: LONGEST_SEEN }));
|
|
210
|
+
for (const o of options) {
|
|
211
|
+
const answer = { by: LONGEST_BY, option: o.id, effect: o.effect, at: ANY_AT };
|
|
212
|
+
measure({ kind: "sent", answer, delivery: "unconfirmed" });
|
|
213
|
+
measure({ kind: "sent", answer, delivery: "delivered" });
|
|
214
|
+
measure(closed({ kind: "answered", answer }));
|
|
215
|
+
measure(closed({ kind: "unconfirmed", answer, seen: LONGEST_SEEN }));
|
|
216
|
+
measure(closed({ kind: "undelivered", answer }));
|
|
217
|
+
measure(closed({ kind: "local", seen: LONGEST_SEEN, late: answer }));
|
|
218
|
+
}
|
|
219
|
+
return max;
|
|
220
|
+
}
|
|
221
|
+
class Desk {
|
|
222
|
+
ep;
|
|
223
|
+
/** Every prompt in memory, in the order it opened. */
|
|
224
|
+
held = new Map();
|
|
225
|
+
/** The closed prompts in memory, in the order they closed. */
|
|
226
|
+
closedOrder = [];
|
|
227
|
+
live = 0;
|
|
228
|
+
/** Taken from the endpoint, which keeps the highest for this process's runtime id, so a desk opened
|
|
229
|
+
* again in the process goes on counting: a reader orders lists by `seq` within one `runtime.id`. */
|
|
230
|
+
seq = 0;
|
|
231
|
+
stepping = false;
|
|
232
|
+
later = [];
|
|
233
|
+
presenceOwed = false;
|
|
234
|
+
closed = false;
|
|
235
|
+
closing;
|
|
236
|
+
serve;
|
|
237
|
+
/** The adapter's logger. A logger that throws stops no step and no close. */
|
|
238
|
+
warn;
|
|
239
|
+
constructor(ep, warn) {
|
|
240
|
+
this.ep = ep;
|
|
241
|
+
this.warn = (msg) => {
|
|
242
|
+
try {
|
|
243
|
+
warn(msg);
|
|
244
|
+
}
|
|
245
|
+
catch { /* the desk goes on without the line */ }
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
get waiting() {
|
|
249
|
+
return this.live;
|
|
250
|
+
}
|
|
251
|
+
/** Serve the `agent` endpoint, and close on a refused subscription or a smaller payload limit. */
|
|
252
|
+
start() {
|
|
253
|
+
const handlers = [
|
|
254
|
+
{ command: "prompts", contract: AGENT_CONTRACTS.prompts, handler: (ctx) => this.list(ctx) },
|
|
255
|
+
{ command: "prompt", contract: AGENT_CONTRACTS.prompt, handler: (ctx) => this.read(ctx) },
|
|
256
|
+
{ command: "prompt-answer", contract: AGENT_CONTRACTS["prompt-answer"], handler: (ctx) => this.answer(ctx) },
|
|
257
|
+
];
|
|
258
|
+
const serve = this.ep.servePrincipal({ endpoint: AGENT_ENDPOINT, cluster: AGENT_CLUSTER, handlers });
|
|
259
|
+
this.seq = this.ep.nextPromptsSeq();
|
|
260
|
+
this.serve = serve;
|
|
261
|
+
this.ep.on("transport", this.onTransport);
|
|
262
|
+
void serve.failed.then((err) => {
|
|
263
|
+
if (this.closed)
|
|
264
|
+
return;
|
|
265
|
+
this.warn(`the prompt desk closed: ${err.message}`);
|
|
266
|
+
void this.close();
|
|
267
|
+
});
|
|
268
|
+
return serve;
|
|
269
|
+
}
|
|
270
|
+
/** The broker accepted the subscription: show this desk's counter. */
|
|
271
|
+
announce() {
|
|
272
|
+
this.presenceOwed = true;
|
|
273
|
+
this.flushPresence();
|
|
274
|
+
}
|
|
275
|
+
/** Every replaced connection runs the payload check again. */
|
|
276
|
+
onTransport = (t) => {
|
|
277
|
+
if (!t.connected || this.closed)
|
|
278
|
+
return;
|
|
279
|
+
let max;
|
|
280
|
+
try {
|
|
281
|
+
max = this.ep.maxPayload;
|
|
282
|
+
}
|
|
283
|
+
catch {
|
|
284
|
+
return; // not live after all; the next connection runs the check
|
|
285
|
+
}
|
|
286
|
+
if (max >= PROMPT_DESK_MIN_MAX_PAYLOAD)
|
|
287
|
+
return;
|
|
288
|
+
this.warn(`the prompt desk closed: the connection's max_payload is ${max} bytes, under the ${PROMPT_DESK_MIN_MAX_PAYLOAD} its largest replies need`);
|
|
289
|
+
void this.close();
|
|
290
|
+
};
|
|
291
|
+
close() {
|
|
292
|
+
if (this.closing)
|
|
293
|
+
return this.closing;
|
|
294
|
+
this.closed = true;
|
|
295
|
+
this.ep.off("transport", this.onTransport);
|
|
296
|
+
this.defer(() => {
|
|
297
|
+
for (const h of [...this.held.values()])
|
|
298
|
+
if (h.state.kind !== "closed")
|
|
299
|
+
this.apply(h, { kind: "close" });
|
|
300
|
+
});
|
|
301
|
+
this.closing = this.serve ? this.serve.stop() : Promise.resolve();
|
|
302
|
+
return this.closing;
|
|
303
|
+
}
|
|
304
|
+
open(spec, hooks) {
|
|
305
|
+
if (this.closed)
|
|
306
|
+
throw new PromptRefused("closed", "the prompt desk has closed; the harness answers this dialog");
|
|
307
|
+
const invalid = (why) => new PromptRefused("invalid", why);
|
|
308
|
+
if (!spec || typeof spec !== "object")
|
|
309
|
+
throw invalid("a prompt spec is an object");
|
|
310
|
+
if (!hooks || typeof hooks.deliver !== "function" || typeof hooks.end !== "function" || (hooks.check !== undefined && typeof hooks.check !== "function"))
|
|
311
|
+
throw invalid("hooks need deliver and end, and check when given, as functions");
|
|
312
|
+
for (const [name, value, range] of [["openMs", spec.openMs, PROMPT_OPEN_MS], ["settleMs", spec.settleMs, PROMPT_SETTLE_MS]])
|
|
313
|
+
if (!Number.isSafeInteger(value) || value < range.min || value > range.max)
|
|
314
|
+
throw invalid(`${name} must be an integer from ${range.min} to ${range.max} ms, not ${String(value)}`);
|
|
315
|
+
let canonical;
|
|
316
|
+
try {
|
|
317
|
+
canonical = canonicalJson(spec.content);
|
|
318
|
+
}
|
|
319
|
+
catch (e) {
|
|
320
|
+
throw invalid(`the content is not interchangeable JSON: ${describe(e)}`);
|
|
321
|
+
}
|
|
322
|
+
const contentBytes = Buffer.byteLength(canonical);
|
|
323
|
+
if (contentBytes > AGENT_PROMPT_CONTENT_MAX_BYTES)
|
|
324
|
+
throw new PromptRefused("too-large", `the canonical content is ${contentBytes} bytes, over ${AGENT_PROMPT_CONTENT_MAX_BYTES}`);
|
|
325
|
+
// The served content is exactly the bytes the digest covers, and nothing the adapter keeps can change it.
|
|
326
|
+
const content = deepFreeze(JSON.parse(canonical));
|
|
327
|
+
let id;
|
|
328
|
+
do
|
|
329
|
+
id = Array.from(randomBytes(26), (b) => B32[b & 31]).join("");
|
|
330
|
+
while (this.held.has(id));
|
|
331
|
+
const digest = agentPromptDigest(content);
|
|
332
|
+
const now = Date.now();
|
|
333
|
+
const openedAt = iso(now), expiresAtMs = now + spec.openMs, expiresAt = iso(expiresAtMs);
|
|
334
|
+
const validate = AGENT_CONTRACTS.prompt.output.validate;
|
|
335
|
+
if (!validate({ prompt: { id, digest, openedAt, expiresAt, state: { kind: "open" }, content } })) {
|
|
336
|
+
const first = validate.errors?.[0];
|
|
337
|
+
throw invalid(`the content does not match the prompt schema: ${first ? `${first.instancePath || "/"} ${first.message}` : "invalid"}`);
|
|
338
|
+
}
|
|
339
|
+
const options = new Map();
|
|
340
|
+
for (const o of content.options) {
|
|
341
|
+
if (options.has(o.id))
|
|
342
|
+
throw invalid(`option id "${o.id}" is used twice`);
|
|
343
|
+
options.set(o.id, o);
|
|
344
|
+
if (o.form === "required" && content.form === undefined)
|
|
345
|
+
throw invalid(`option "${o.id}" submits a form, and the content has none`);
|
|
346
|
+
}
|
|
347
|
+
if (content.form !== undefined && !content.options.some((o) => o.form === "required"))
|
|
348
|
+
throw invalid("the content has a form, and no option submits it");
|
|
349
|
+
const input = content.subject?.type === "tool" ? content.subject.input : undefined;
|
|
350
|
+
if (input?.kind === "omitted" && content.options.some((o) => o.effect === "proceed"))
|
|
351
|
+
throw invalid("a tool input that is omitted can be refused remotely, never approved: no option may proceed");
|
|
352
|
+
let form;
|
|
353
|
+
if (content.form !== undefined) {
|
|
354
|
+
const schema = content.form.schema;
|
|
355
|
+
for (const name of schema.required ?? [])
|
|
356
|
+
if (!Object.hasOwn(schema.properties, name))
|
|
357
|
+
throw invalid(`form.schema.required names "${name}", which is not a property`);
|
|
358
|
+
try {
|
|
359
|
+
// Values carry the declared properties and nothing else.
|
|
360
|
+
form = compileContractSchema({ root: { ...schema, additionalProperties: false } });
|
|
361
|
+
}
|
|
362
|
+
catch (e) {
|
|
363
|
+
throw invalid(`form.schema does not compile: ${describe(e)}`);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
const base = {
|
|
367
|
+
id, digest, openedAt, expiresAt, kind: content.kind, title: content.title, contentBytes,
|
|
368
|
+
...(content.source !== undefined ? { source: content.source } : {}),
|
|
369
|
+
};
|
|
370
|
+
const largest = largestSummaryBytes(base, content.options);
|
|
371
|
+
if (largest > PROMPT_SUMMARY_MAX_BYTES)
|
|
372
|
+
throw new PromptRefused("too-large", `the summary encodes to ${largest} bytes in its largest state, over ${PROMPT_SUMMARY_MAX_BYTES}`);
|
|
373
|
+
if (this.live >= AGENT_PROMPT_LIST_MAX)
|
|
374
|
+
throw new PromptRefused("full", `${AGENT_PROMPT_LIST_MAX} prompts are open or sent`);
|
|
375
|
+
const h = {
|
|
376
|
+
id, hooks, settleMs: spec.settleMs, expiresAtMs, base: deepFreeze(base), live: { content, options, ...(form ? { form } : {}) },
|
|
377
|
+
state: deepFreeze({ kind: "open" }), reports: 0, ended: false, waiters: new Set(),
|
|
378
|
+
};
|
|
379
|
+
this.held.set(id, h);
|
|
380
|
+
this.live++;
|
|
381
|
+
this.bump();
|
|
382
|
+
// Validation, the form and the summary bound ran since `expiresAt` was fixed.
|
|
383
|
+
h.expiry = timer(Math.max(0, expiresAtMs - Date.now()), () => this.expire(h));
|
|
384
|
+
if (!this.stepping)
|
|
385
|
+
this.flushPresence();
|
|
386
|
+
return Object.freeze({
|
|
387
|
+
id,
|
|
388
|
+
settle: (evidence) => {
|
|
389
|
+
const e = parseEvidence(evidence);
|
|
390
|
+
this.defer(() => this.apply(h, { kind: "settle", evidence: e }));
|
|
391
|
+
},
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
/** X fires at `expiresAt`. A timer that runs early arms itself again for what is left. */
|
|
395
|
+
expire(h) {
|
|
396
|
+
const left = h.expiresAtMs - Date.now();
|
|
397
|
+
if (left > 0) {
|
|
398
|
+
h.expiry = timer(left, () => this.expire(h));
|
|
399
|
+
return;
|
|
400
|
+
}
|
|
401
|
+
this.defer(() => this.apply(h, { kind: "expiry" }));
|
|
402
|
+
}
|
|
403
|
+
/** T fires at the settle time. A timer that runs early arms itself again for what is left. */
|
|
404
|
+
settleTime(h) {
|
|
405
|
+
const left = h.settleAtMs - Date.now();
|
|
406
|
+
if (left > 0) {
|
|
407
|
+
h.settle = timer(left, () => this.settleTime(h));
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
this.defer(() => this.apply(h, { kind: "settle-time" }));
|
|
411
|
+
}
|
|
412
|
+
// ---- steps ----
|
|
413
|
+
/** Run `fn` as one step. Events that reach the desk during it are applied after it, in order. */
|
|
414
|
+
run(fn) {
|
|
415
|
+
if (this.stepping)
|
|
416
|
+
throw new Error("prompt desk: a step started inside another step");
|
|
417
|
+
this.stepping = true;
|
|
418
|
+
try {
|
|
419
|
+
return fn();
|
|
420
|
+
}
|
|
421
|
+
finally {
|
|
422
|
+
try {
|
|
423
|
+
for (let next = this.later.shift(); next; next = this.later.shift())
|
|
424
|
+
next();
|
|
425
|
+
}
|
|
426
|
+
finally {
|
|
427
|
+
this.stepping = false;
|
|
428
|
+
this.flushPresence();
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
defer(fn) {
|
|
433
|
+
if (this.stepping)
|
|
434
|
+
this.later.push(fn);
|
|
435
|
+
else
|
|
436
|
+
this.run(fn);
|
|
437
|
+
}
|
|
438
|
+
/** Apply one event to one prompt: the table's row, then the waiting replies, then `end`. */
|
|
439
|
+
apply(h, event, why) {
|
|
440
|
+
const step = stepPrompt(h.state, event, iso(Date.now()));
|
|
441
|
+
if (step.kind === "cannot-happen" || step.kind === "never-reached") {
|
|
442
|
+
this.warn(`prompt desk bug: event ${event.kind} met prompt ${h.id} in state ${h.state.kind}, a row that ${step.kind === "cannot-happen" ? "cannot happen" : "is never reached"}: ${step.why}`);
|
|
443
|
+
return;
|
|
444
|
+
}
|
|
445
|
+
if (step.kind === "stay") {
|
|
446
|
+
if (step.report)
|
|
447
|
+
this.warn(`prompt ${h.id} is closed, so a "${event.evidence.kind}" report is ignored (${++h.reports} so far)`);
|
|
448
|
+
else if (step.warn)
|
|
449
|
+
this.warn(`prompt ${h.id}: ${step.warn}${why ? `: ${why}` : ""}`);
|
|
450
|
+
// A failed call ends the reply's wait: the state it reads is still `sent`, `unconfirmed`.
|
|
451
|
+
if (event.kind === "delivery" && event.result === "failed")
|
|
452
|
+
this.answerWaiters(h);
|
|
453
|
+
return;
|
|
454
|
+
}
|
|
455
|
+
h.state = deepFreeze(step.next);
|
|
456
|
+
this.bump();
|
|
457
|
+
if (h.state.kind === "closed")
|
|
458
|
+
this.retire(h);
|
|
459
|
+
if (!(h.state.kind === "sent" && h.state.delivery === "unconfirmed"))
|
|
460
|
+
this.answerWaiters(h);
|
|
461
|
+
if (step.end)
|
|
462
|
+
this.end(h, step.end.attempted);
|
|
463
|
+
}
|
|
464
|
+
/** Reply to every `prompt-answer` waiting on `h`, each with the state read now. */
|
|
465
|
+
answerWaiters(h) {
|
|
466
|
+
for (const w of h.waiters) {
|
|
467
|
+
clearTimeout(w.timer);
|
|
468
|
+
w.resolve(h.state);
|
|
469
|
+
}
|
|
470
|
+
h.waiters.clear();
|
|
471
|
+
}
|
|
472
|
+
/** A prompt closed: stop its timers, free its content, and keep it in the closed memory. */
|
|
473
|
+
retire(h) {
|
|
474
|
+
clearTimeout(h.expiry);
|
|
475
|
+
clearTimeout(h.settle);
|
|
476
|
+
h.live = undefined;
|
|
477
|
+
this.live--;
|
|
478
|
+
this.closedOrder.push(h.id);
|
|
479
|
+
while (this.closedOrder.length > AGENT_PROMPT_LIST_MAX)
|
|
480
|
+
this.held.delete(this.closedOrder.shift());
|
|
481
|
+
}
|
|
482
|
+
end(h, attempted) {
|
|
483
|
+
if (h.ended) {
|
|
484
|
+
this.warn(`prompt desk bug: prompt ${h.id} ended twice`);
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
487
|
+
h.ended = true;
|
|
488
|
+
const hooks = h.hooks;
|
|
489
|
+
h.hooks = undefined;
|
|
490
|
+
try {
|
|
491
|
+
ignoreRejection(hooks.end({ attempted }));
|
|
492
|
+
}
|
|
493
|
+
catch (e) {
|
|
494
|
+
this.warn(`prompt ${h.id}: the adapter's end threw: ${describe(e)}`);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
bump() {
|
|
498
|
+
this.seq = this.ep.nextPromptsSeq();
|
|
499
|
+
this.presenceOwed = true;
|
|
500
|
+
}
|
|
501
|
+
flushPresence() {
|
|
502
|
+
if (!this.presenceOwed || this.closed || !this.serve)
|
|
503
|
+
return;
|
|
504
|
+
this.presenceOwed = false;
|
|
505
|
+
this.ep.setPromptsPresence({ open: this.live, seq: this.seq }).catch((e) => {
|
|
506
|
+
if (!this.closed)
|
|
507
|
+
this.warn(`the prompts presence field was not written: ${describe(e)}`);
|
|
508
|
+
});
|
|
509
|
+
}
|
|
510
|
+
// ---- the commands ----
|
|
511
|
+
/** Fit a reply to the connection's `max_payload`, or refuse it with its size. */
|
|
512
|
+
fit(ctx, data) {
|
|
513
|
+
if (ctx.replyFits(data, Number.MAX_SAFE_INTEGER))
|
|
514
|
+
return data;
|
|
515
|
+
const bytes = Buffer.byteLength(JSON.stringify({ v: 1, id: ctx.request.id, ok: true, data }));
|
|
516
|
+
const limit = this.ep.maxPayload;
|
|
517
|
+
throw refused("resource-exhausted", `the reply is ${bytes} bytes, over this connection's max_payload of ${limit}`, [{ kind: AGENT_PROMPT_SIZE_DETAIL, bytes, limit }]);
|
|
518
|
+
}
|
|
519
|
+
summary(h) {
|
|
520
|
+
return { ...h.base, state: h.state };
|
|
521
|
+
}
|
|
522
|
+
list(ctx) {
|
|
523
|
+
const open = [];
|
|
524
|
+
for (const h of this.held.values())
|
|
525
|
+
if (h.state.kind !== "closed")
|
|
526
|
+
open.push(this.summary(h));
|
|
527
|
+
const closed = this.closedOrder.map((id) => this.summary(this.held.get(id)));
|
|
528
|
+
const runtime = { id: ctx.principal.runtimeId, startedAt: processRuntime(ctx.principal.uid).startedAt };
|
|
529
|
+
return this.fit(ctx, { runtime, seq: this.seq, open, closed });
|
|
530
|
+
}
|
|
531
|
+
read(ctx) {
|
|
532
|
+
const { id } = ctx.request.args;
|
|
533
|
+
const h = this.held.get(id);
|
|
534
|
+
if (h === undefined)
|
|
535
|
+
throw refused("not-found", `prompt ${id} is not known to this runtime`);
|
|
536
|
+
if (h.live === undefined)
|
|
537
|
+
throw refused("failed-precondition", `prompt ${id} is closed`, [{ kind: AGENT_PROMPT_STATE_DETAIL, state: h.state }]);
|
|
538
|
+
const { digest, openedAt, expiresAt } = h.base;
|
|
539
|
+
return this.fit(ctx, { prompt: { id, digest, openedAt, expiresAt, state: h.state, content: h.live.content } });
|
|
540
|
+
}
|
|
541
|
+
answer(ctx) {
|
|
542
|
+
const got = this.run(() => this.decide(ctx));
|
|
543
|
+
return got instanceof Promise ? got.then((state) => ({ state })) : { state: got };
|
|
544
|
+
}
|
|
545
|
+
/** The `prompt-answer` checks, in order, and the accept, as one step. Returns the state for a reply
|
|
546
|
+
* sent at once, or the wait of an accepted answer. Throws the refusal. */
|
|
547
|
+
decide(ctx) {
|
|
548
|
+
const a = ctx.request.args;
|
|
549
|
+
try {
|
|
550
|
+
canonicalJson(a);
|
|
551
|
+
}
|
|
552
|
+
catch (e) {
|
|
553
|
+
throw refused("bad-request", `the answer is not interchangeable JSON: ${describe(e)}`);
|
|
554
|
+
}
|
|
555
|
+
// 1. An agent never answers its own prompt, whatever its row.
|
|
556
|
+
if (ctx.caller.owner === ctx.principal.owner && ctx.caller.actor === ctx.principal.actor)
|
|
557
|
+
throw refused("permission-denied", "an agent never answers its own prompt");
|
|
558
|
+
// 2.
|
|
559
|
+
const h = this.held.get(a.id);
|
|
560
|
+
if (h === undefined)
|
|
561
|
+
throw refused("not-found", `prompt ${a.id} is not known to this runtime`);
|
|
562
|
+
// 3. The same answer again gets the state it has now, and nothing is handed over twice.
|
|
563
|
+
const fingerprint = answerFingerprint(a, ctx.caller);
|
|
564
|
+
if (h.fingerprint === fingerprint)
|
|
565
|
+
return h.state;
|
|
566
|
+
// 4.
|
|
567
|
+
if (h.state.kind !== "open" || h.live === undefined)
|
|
568
|
+
throw refused("conflict", `prompt ${a.id} is not open`, [{ kind: AGENT_PROMPT_STATE_DETAIL, state: h.state }]);
|
|
569
|
+
// 5.
|
|
570
|
+
if (a.digest !== h.base.digest)
|
|
571
|
+
throw refused("failed-precondition", `the digest is not prompt ${a.id}'s`, [{ kind: AGENT_PROMPT_DIGEST_DETAIL, digest: h.base.digest }]);
|
|
572
|
+
// 6.
|
|
573
|
+
const option = h.live.options.get(a.option);
|
|
574
|
+
if (option === undefined)
|
|
575
|
+
throw refused("bad-request", `option "${a.option}" is not one of the prompt's`);
|
|
576
|
+
// 7.
|
|
577
|
+
if (option.note === "required" && (a.note === undefined || a.note === ""))
|
|
578
|
+
throw refused("bad-request", `option "${option.id}" needs a note`);
|
|
579
|
+
if (option.note === undefined && a.note !== undefined)
|
|
580
|
+
throw refused("bad-request", `option "${option.id}" takes no note`);
|
|
581
|
+
if (option.form === "required" && a.values === undefined)
|
|
582
|
+
throw refused("bad-request", `option "${option.id}" submits the form and needs values`);
|
|
583
|
+
if (option.form === undefined && a.values !== undefined)
|
|
584
|
+
throw refused("bad-request", `option "${option.id}" takes no values`);
|
|
585
|
+
// 8.
|
|
586
|
+
if (a.values !== undefined && !h.live.form(a.values)) {
|
|
587
|
+
const first = h.live.form.errors?.[0];
|
|
588
|
+
throw refused("bad-request", `the values do not match the form: ${first ? `${first.instancePath || "/"} ${first.message}` : "invalid"}`);
|
|
589
|
+
}
|
|
590
|
+
const by = { id: `${ctx.caller.owner}.${ctx.caller.actor}`, uid: ctx.caller.uid, authority: ctx.authority };
|
|
591
|
+
const verdict = deepFreeze({
|
|
592
|
+
option: option.id,
|
|
593
|
+
...(a.note !== undefined ? { note: a.note } : {}),
|
|
594
|
+
...(a.values !== undefined ? { values: structuredClone(a.values) } : {}),
|
|
595
|
+
by,
|
|
596
|
+
});
|
|
597
|
+
// 9. The adapter's own rules.
|
|
598
|
+
let refusal;
|
|
599
|
+
try {
|
|
600
|
+
refusal = h.hooks.check?.(verdict);
|
|
601
|
+
}
|
|
602
|
+
catch (e) {
|
|
603
|
+
this.warn(`prompt ${h.id}: the adapter's check threw: ${describe(e)}`);
|
|
604
|
+
throw refused("internal", `the agent could not check this answer: ${describe(e)}`);
|
|
605
|
+
}
|
|
606
|
+
if (refusal !== undefined) {
|
|
607
|
+
if (typeof refusal !== "string") {
|
|
608
|
+
this.warn(`prompt ${h.id}: the adapter's check returned ${ignoreRejection(refusal) ? "a promise, and check is synchronous" : `${typeof refusal}, not a message or undefined`}`);
|
|
609
|
+
throw refused("internal", "the agent could not check this answer");
|
|
610
|
+
}
|
|
611
|
+
throw refused("bad-request", refusal || "the agent refused this answer");
|
|
612
|
+
}
|
|
613
|
+
// 10.
|
|
614
|
+
if (Date.now() >= h.expiresAtMs)
|
|
615
|
+
throw refused("expired", `prompt ${h.id} expired at ${h.base.expiresAt}`);
|
|
616
|
+
// 11. Accept: event A. The state, the fingerprint, the settle time and the `deliver` call are one step.
|
|
617
|
+
const acceptedAt = Date.now();
|
|
618
|
+
const answer = { by, option: option.id, effect: option.effect, at: iso(acceptedAt) };
|
|
619
|
+
const step = stepPrompt(h.state, { kind: "accept", answer }, answer.at);
|
|
620
|
+
if (step.kind !== "move" || !step.deliver)
|
|
621
|
+
throw refused("internal", "prompt desk bug: an open prompt did not accept");
|
|
622
|
+
h.state = deepFreeze(step.next);
|
|
623
|
+
h.fingerprint = fingerprint;
|
|
624
|
+
this.bump();
|
|
625
|
+
h.settleAtMs = acceptedAt + h.settleMs;
|
|
626
|
+
h.settle = timer(h.settleMs, () => this.settleTime(h));
|
|
627
|
+
const wait = new Promise((resolve) => {
|
|
628
|
+
const w = {
|
|
629
|
+
resolve,
|
|
630
|
+
timer: timer(PROMPT_ANSWER_REPLY_MS, () => this.defer(() => {
|
|
631
|
+
if (h.waiters.delete(w))
|
|
632
|
+
resolve(h.state);
|
|
633
|
+
})),
|
|
634
|
+
};
|
|
635
|
+
h.waiters.add(w);
|
|
636
|
+
});
|
|
637
|
+
this.deliver(h, verdict);
|
|
638
|
+
return wait;
|
|
639
|
+
}
|
|
640
|
+
/** Call `deliver` once, and apply its one result as event D when it ends: anything that is not a
|
|
641
|
+
* Delivery is one `failed` event, and nothing it holds escapes as an unhandled rejection. */
|
|
642
|
+
deliver(h, verdict) {
|
|
643
|
+
let result;
|
|
644
|
+
try {
|
|
645
|
+
result = Promise.resolve(h.hooks.deliver(verdict));
|
|
646
|
+
}
|
|
647
|
+
catch (e) {
|
|
648
|
+
result = Promise.reject(e);
|
|
649
|
+
}
|
|
650
|
+
const failed = (why) => this.defer(() => this.apply(h, { kind: "delivery", result: "failed" }, why));
|
|
651
|
+
result.then((d) => {
|
|
652
|
+
const kind = deliveryKind(d);
|
|
653
|
+
if (kind === "confirmed" || kind === "delivered" || kind === "gone")
|
|
654
|
+
this.defer(() => this.apply(h, { kind: "delivery", result: kind }));
|
|
655
|
+
else
|
|
656
|
+
failed(`deliver resolved with ${describe(d)}, which is not a Delivery`);
|
|
657
|
+
}, (e) => failed(describe(e))).catch((e) => this.warn(`prompt desk bug: applying prompt ${h.id}'s delivery result threw: ${describe(e)}`));
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
/** The identity of an answer: SHA-256 over the RFC 8785 form of what it says and who said it. */
|
|
661
|
+
function answerFingerprint(a, caller) {
|
|
662
|
+
return contractDigest({
|
|
663
|
+
id: a.id, digest: a.digest, option: a.option, note: a.note ?? null, values: a.values ?? null,
|
|
664
|
+
caller: `${caller.owner}.${caller.actor}.${caller.uid}`,
|
|
665
|
+
});
|
|
666
|
+
}
|
|
667
|
+
/**
|
|
668
|
+
* Open this process's prompt desk on `ep`: serve the `agent` endpoint on the principal route and show
|
|
669
|
+
* the `prompts` presence field. Resolves once the broker accepted the subscription.
|
|
670
|
+
*
|
|
671
|
+
* Rejects on an open mesh, under a static credential and without a lifecycle UID, when the broker
|
|
672
|
+
* refuses the subscription (a credential minted before the rows existed), and when the connection's
|
|
673
|
+
* `max_payload` is under {@link PROMPT_DESK_MIN_MAX_PAYLOAD}. Then the connector leaves every dialog to
|
|
674
|
+
* the harness, and presence shows no `prompts` field. The same checks run on every replaced
|
|
675
|
+
* connection, and a failure there closes the desk and warns. Stopping `ep` ends the serve and not the
|
|
676
|
+
* prompts, so call `close()` first: it ends every prompt and gives each open dialog back.
|
|
677
|
+
*/
|
|
678
|
+
export async function openPromptDesk(ep, opts) {
|
|
679
|
+
if (typeof opts?.warn !== "function")
|
|
680
|
+
throw new TypeError("openPromptDesk needs opts.warn");
|
|
681
|
+
const max = ep.maxPayload;
|
|
682
|
+
if (max < PROMPT_DESK_MIN_MAX_PAYLOAD)
|
|
683
|
+
throw new Error(`the prompt desk needs a connection whose max_payload is at least ${PROMPT_DESK_MIN_MAX_PAYLOAD} bytes, and this one is ${max}`);
|
|
684
|
+
const desk = new Desk(ep, opts.warn);
|
|
685
|
+
const serve = desk.start();
|
|
686
|
+
try {
|
|
687
|
+
await serve.ready;
|
|
688
|
+
}
|
|
689
|
+
catch (e) {
|
|
690
|
+
void desk.close();
|
|
691
|
+
throw e;
|
|
692
|
+
}
|
|
693
|
+
desk.announce();
|
|
694
|
+
return desk;
|
|
695
|
+
}
|
|
696
|
+
//# sourceMappingURL=prompt-desk.js.map
|