paseo-plugin-secure-input 0.0.0-stage → 0.2.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 +21 -0
- package/OVERVIEW.md +30 -0
- package/README.md +252 -2
- package/SECURITY.md +79 -0
- package/assets/icon.png +0 -0
- package/client/card.tsx +74 -0
- package/client/codes.ts +32 -0
- package/client/diagnostics-rows.ts +139 -0
- package/client/dialog-state.ts +59 -0
- package/client/dialog.tsx +292 -0
- package/client/envelope-cache.ts +85 -0
- package/client/fields.tsx +255 -0
- package/client/file-entry.ts +142 -0
- package/client/form-state.ts +198 -0
- package/client/globals.d.ts +19 -0
- package/client/outcome.ts +96 -0
- package/client/presentation.ts +114 -0
- package/client/sealing.ts +27 -0
- package/client/self-test.ts +96 -0
- package/client/settings.tsx +160 -0
- package/client/submit.ts +92 -0
- package/client/text.ts +47 -0
- package/client/tone.ts +36 -0
- package/client/web.ts +184 -0
- package/index.client.tsx +29 -0
- package/index.server.ts +6 -0
- package/npm-shrinkwrap.json +60 -0
- package/package.json +68 -4
- package/paseo-plugin.json +6 -0
- package/server/core/continuation.ts +151 -0
- package/server/core/entries.ts +89 -0
- package/server/core/outbox.ts +555 -0
- package/server/core/registry-store.ts +185 -0
- package/server/core/registry.ts +1031 -0
- package/server/core/selftest.ts +60 -0
- package/server/core/view.ts +38 -0
- package/server/io/atomic.ts +119 -0
- package/server/io/deadline.ts +28 -0
- package/server/io/descriptor.ts +36 -0
- package/server/io/directory.ts +40 -0
- package/server/io/drop.ts +434 -0
- package/server/io/legacy-shim.ts +108 -0
- package/server/io/ownership.ts +8 -0
- package/server/io/private-file.ts +86 -0
- package/server/paseo/bounded.ts +13 -0
- package/server/paseo/handlers.ts +124 -0
- package/server/paseo/hooks.ts +106 -0
- package/server/paseo/plugin.ts +341 -0
- package/server/paseo/runtime.ts +409 -0
- package/server/paseo/tools.ts +180 -0
- package/shared/bytes.ts +100 -0
- package/shared/canonical.ts +32 -0
- package/shared/card.ts +41 -0
- package/shared/contracts.ts +128 -0
- package/shared/errors.ts +48 -0
- package/shared/limits.ts +118 -0
- package/shared/request-id.ts +9 -0
- package/shared/request.ts +66 -0
- package/shared/sanitize.ts +101 -0
- package/shared/seal.ts +292 -0
- package/shared/shown.ts +12 -0
- package/shared/text.ts +39 -0
- package/shared/view.ts +42 -0
- package/skills/secure-input/SKILL.md +148 -0
|
@@ -0,0 +1,555 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { SecureInputError } from "../../shared/errors";
|
|
3
|
+
import { STORED_AGENT_ID_MAX } from "../../shared/limits";
|
|
4
|
+
import { REQUEST_ID_PATTERN } from "../../shared/request-id";
|
|
5
|
+
import { shown } from "../../shared/shown";
|
|
6
|
+
import { writePrivateFile } from "../io/atomic";
|
|
7
|
+
import { raceDeadline } from "../io/deadline";
|
|
8
|
+
import { privateFileRefusal, readPrivateFile } from "../io/private-file";
|
|
9
|
+
|
|
10
|
+
export interface AgentPort {
|
|
11
|
+
isIdle(agentId: string): Promise<boolean>;
|
|
12
|
+
send(agentId: string, text: string): Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** The most items the file holds. When it is full the oldest go: the newest message is the one an agent is waiting for. */
|
|
16
|
+
export const MAX_OUTBOX_ITEMS = 256;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The most of `outbox.json` that is read. An item is under a kilobyte (a 256 character agent id of three-byte
|
|
20
|
+
* characters, an id, a kind and a time), so a full honest file is under half of this, and a larger one was not written
|
|
21
|
+
* by this module. It also bounds the work done before the items are checked: the entries of a file this size can only
|
|
22
|
+
* be so many.
|
|
23
|
+
*/
|
|
24
|
+
export const MAX_OUTBOX_BYTES = 512 * 1024;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* How long an item may wait for an idle agent, measured from the moment it was enqueued, not from the creation of the
|
|
28
|
+
* request. A request stays open for eight hours at most and its message is enqueued when it ends; that message must
|
|
29
|
+
* outlive the longest turn an agent may be busy with by then, so a day (three request lifetimes) covers an overnight
|
|
30
|
+
* run, and an item that was abandoned (an agent that never became idle, a planted one) cannot stay in the file for ever.
|
|
31
|
+
*/
|
|
32
|
+
export const MAX_OUTBOX_AGE_MS = 24 * 60 * 60 * 1000;
|
|
33
|
+
|
|
34
|
+
/** A time stamped this far ahead of the clock is taken for a clock that was set back a little. A year 3000 is not. */
|
|
35
|
+
export const OUTBOX_CLOCK_SKEW_MS = 60 * 1000;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* How long the outbox waits for the agent port, per call. A call to the daemon answers in well under a second, a slow
|
|
39
|
+
* one (a loaded machine, an agent being resumed) in a few; half a minute is long enough not to mistake those for a
|
|
40
|
+
* dead port and short enough that a port that has stopped answering costs a flush that long and not for ever.
|
|
41
|
+
*/
|
|
42
|
+
export const PORT_TIMEOUT_MS = 30 * 1000;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* How long one flush may take in all, however many agents have something waiting. One agent whose port does not
|
|
46
|
+
* answer costs `PORT_TIMEOUT_MS` of it, and the quarter of a minute beyond that is for the agents after it in the same
|
|
47
|
+
* flush, so one silent agent never uses up a flush alone. It is also less than the minute between two ticks of the
|
|
48
|
+
* plugin's timer, so a flush that used all of it has ended before the next one is asked for. A call that the end of
|
|
49
|
+
* the budget cuts short is given up on like one that reached its own bound, and a call that starts after it is given
|
|
50
|
+
* `PORT_FLOOR_MS`.
|
|
51
|
+
*/
|
|
52
|
+
export const FLUSH_BUDGET_MS = 45 * 1000;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* What a call to the port is given when it starts with the budget of its flush already used up: the least any call
|
|
56
|
+
* gets. Before that a call has its own bound or what is left of the budget, whichever is less (the end of the budget
|
|
57
|
+
* cuts it short). The two calls that can still start after the budget ended are the idle check and the send of the
|
|
58
|
+
* agent whose turn it was: a send must be attempted once its item is out of the file. A daemon that answers at all
|
|
59
|
+
* answers within this.
|
|
60
|
+
*/
|
|
61
|
+
export const PORT_FLOOR_MS = 1_000;
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Where a message goes and which of the two fixed messages it is. The file holds exactly this and the time it was
|
|
65
|
+
* enqueued, never the words: it is writable by the agent, so the words are rebuilt from the plugin's own record when
|
|
66
|
+
* the message is sent.
|
|
67
|
+
*
|
|
68
|
+
* The identity of an item is derived from these fields and is not a field of its own: `<kind>:<request id>:<agent id>`
|
|
69
|
+
* (a kind and a request id contain no colon, so the form is unambiguous). Two items are the same message when their
|
|
70
|
+
* identities are equal; an item for another agent is another message and cannot shadow the genuine one.
|
|
71
|
+
*/
|
|
72
|
+
export interface OutboxItem {
|
|
73
|
+
agentId: string;
|
|
74
|
+
requestId: string;
|
|
75
|
+
kind: "continuation" | "tamper";
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface ResolvedMessage {
|
|
79
|
+
/** The agent the record belongs to. The outbox sends only when it is the item's agent. */
|
|
80
|
+
agentId: string;
|
|
81
|
+
text: string;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Builds a message from the plugin's own records at the moment it is sent. It must look the record up by
|
|
86
|
+
* `item.requestId` and return `{ agentId: record.agentId, text: messageFor(record, item.kind) }`, or `null` when there
|
|
87
|
+
* is no such record or `messageFor` has nothing to say. The outbox drops an item whose resolved agent is not the
|
|
88
|
+
* item's agent, so a message can only go to the agent whose request it is about; the resolver is never given, and never
|
|
89
|
+
* returns, text that came from the file.
|
|
90
|
+
*/
|
|
91
|
+
export type MessageResolver = (item: OutboxItem) => ResolvedMessage | null;
|
|
92
|
+
|
|
93
|
+
export interface OutboxOptions {
|
|
94
|
+
/** The clock, in milliseconds. */
|
|
95
|
+
now?: () => number;
|
|
96
|
+
/** How long a call to the port may take before it is given up on; `PORT_TIMEOUT_MS` unless a test wants less. */
|
|
97
|
+
portTimeoutMs?: number;
|
|
98
|
+
/** How long one flush may take in all; `FLUSH_BUDGET_MS` unless a test wants less. */
|
|
99
|
+
flushBudgetMs?: number;
|
|
100
|
+
/**
|
|
101
|
+
* Told of an item it is handing over, right before the send of its message is attempted and after the item is out of
|
|
102
|
+
* the file: once per item, as the send is. It is given the three fields of the item. What it does, throws or rejects
|
|
103
|
+
* with changes nothing here: the send is attempted all the same.
|
|
104
|
+
*/
|
|
105
|
+
onSend?(item: OutboxItem): void;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const ItemSchema = z
|
|
109
|
+
.object({
|
|
110
|
+
agentId: shown(STORED_AGENT_ID_MAX, 1),
|
|
111
|
+
requestId: z.string().regex(REQUEST_ID_PATTERN),
|
|
112
|
+
kind: z.enum(["continuation", "tamper"]),
|
|
113
|
+
})
|
|
114
|
+
.strict();
|
|
115
|
+
|
|
116
|
+
/** `z.number()` refuses NaN and the infinities, which JSON can still carry as `1e999`. */
|
|
117
|
+
const StoredSchema = ItemSchema.extend({ enqueuedAt: z.number().min(0) }).strict();
|
|
118
|
+
|
|
119
|
+
type Stored = z.output<typeof StoredSchema>;
|
|
120
|
+
|
|
121
|
+
const identityOf = (item: OutboxItem): string => `${item.kind}:${item.requestId}:${item.agentId}`;
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Whether the reader refused the file for what it is: a link, a pipe or a directory, a file over the cap, bytes that
|
|
125
|
+
* are not UTF-8 (the reader's own tokens say which). Such a file is not one this module wrote and may be replaced. Any
|
|
126
|
+
* other rejection (EMFILE, EIO, EACCES, ...) means the file could not be read just now, which says nothing about what
|
|
127
|
+
* it holds; it is not replaced.
|
|
128
|
+
*/
|
|
129
|
+
const isNotOurFile = (error: unknown): boolean => privateFileRefusal(error) !== null;
|
|
130
|
+
|
|
131
|
+
const UNSETTLED = Symbol("unsettled");
|
|
132
|
+
|
|
133
|
+
/** Which agents a flush is for: the ones named, in the order they were named, and then, when `all`, everyone else who has something waiting. */
|
|
134
|
+
interface Scope {
|
|
135
|
+
all: boolean;
|
|
136
|
+
agents: string[];
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* What an operation works with. `status` says what became of the file: `ok` (read, or not there), `replace` (it is not a
|
|
141
|
+
* file this module wrote, so the next write may replace it) or `unreadable` (it could not be read just now, so it is not
|
|
142
|
+
* written to and what is not on it is kept in memory). `onDisk` are the valid items of the file; `all` also holds the
|
|
143
|
+
* items kept in memory, newest `MAX_OUTBOX_ITEMS` at most; `dropped` counts what reading left out.
|
|
144
|
+
*/
|
|
145
|
+
interface Loaded {
|
|
146
|
+
status: "ok" | "replace" | "unreadable";
|
|
147
|
+
onDisk: Stored[];
|
|
148
|
+
all: Stored[];
|
|
149
|
+
dropped: number;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Delivers each message at most once, and only to an agent that says it is idle: a send to a busy agent would
|
|
154
|
+
* interrupt its turn. An item leaves the file (or, when it never reached the file, memory) before the send is
|
|
155
|
+
* attempted, so a crash or an unknown send outcome can lose a message but can never repeat one. Only the answer
|
|
156
|
+
* "idle" allows a send: an idle check that fails, or is not answered in time, is no answer, and the item stays for a
|
|
157
|
+
* later flush (until it is too old, `MAX_OUTBOX_AGE_MS`). Whoever asked to know (`onSend`) is told of each item in
|
|
158
|
+
* between: out of the file, right before its send is attempted.
|
|
159
|
+
*
|
|
160
|
+
* `outbox.json` is a file the agent can write, so it is read as hostile input (`readPrivateFile`, then a strict schema,
|
|
161
|
+
* item by item) and it holds references, not text: the words come from the resolver, which rebuilds them from the
|
|
162
|
+
* plugin's own record and names the agent they are for. A planted item can at most make the plugin repeat a message
|
|
163
|
+
* of its own to the agent its record names (a record that was itself planted in `requests.json` is such a record
|
|
164
|
+
* too, and fills that message with its names: SECURITY.md).
|
|
165
|
+
*
|
|
166
|
+
* Memory is the truth: an item whose save failed (or that was enqueued while the file could not be read) stays in
|
|
167
|
+
* memory, is delivered in this process like any other, and is written at the next save that works. A restart forgets
|
|
168
|
+
* what was never saved; that is the accepted loss.
|
|
169
|
+
*
|
|
170
|
+
* What a flush costs. The port is called for one agent after another. A call has `PORT_TIMEOUT_MS`, or what is left
|
|
171
|
+
* of the flush's budget (`FLUSH_BUDGET_MS`) when that is less: the end of the budget cuts short the call that is under
|
|
172
|
+
* way, and no further agent is begun. What can still start after it are the calls of the agent whose turn it was, an
|
|
173
|
+
* idle check and a send at most, and each of those is given `PORT_FLOOR_MS`. So the calls of a flush take
|
|
174
|
+
* `FLUSH_BUDGET_MS` and twice `PORT_FLOOR_MS` at the very most, however many agents are waiting and whatever their
|
|
175
|
+
* ports do; the reads and writes of the plugin's own file come on top. An agent that answers costs milliseconds. One
|
|
176
|
+
* whose port has stopped answering costs up to half a minute for the idle check, and as much again for a send that
|
|
177
|
+
* does not return, so a flush reaches one or two such agents and then ends. The next flush for everyone starts with
|
|
178
|
+
* the agent after the last one that had its whole turn: an agent whose turn the end of the budget cut short was not
|
|
179
|
+
* served, and the rotation does not pass it, so it is the first of the next flush (or the first of those that gave
|
|
180
|
+
* no answer). An agent behind silent ones is thus reached on a later flush instead of never: behind n silent agents,
|
|
181
|
+
* within n such flushes (the plugin's tick asks for one a minute). A flush for one agent (its turn ended, its
|
|
182
|
+
* request ended) does not wait its turn in that rotation.
|
|
183
|
+
* And an agent whose last idle check got no answer is served after the others in every flush until one is answered,
|
|
184
|
+
* so that an agent that has gone silent holds an agent that answers back once, and not at every flush.
|
|
185
|
+
*
|
|
186
|
+
* There is one flush at a time. A flush asked for while one is under way makes that one be followed by exactly one
|
|
187
|
+
* more, which serves the agents that were named meanwhile first; it never starts a second chain. The file is not held
|
|
188
|
+
* during a call to the port: saving a new item waits for other reads and writes of the file, never for an agent.
|
|
189
|
+
*
|
|
190
|
+
* After `stop` nothing more is asked of the port: no idle check starts, no item is taken out of the file, and a call
|
|
191
|
+
* that is under way is no longer waited for. An idle check given up on this way leaves its item in the file. A send
|
|
192
|
+
* given up on this way is an unknown outcome, like any other: its item was already out and is not sent again. The
|
|
193
|
+
* one call that can still start is the send of an item that was being taken out of the file at the very moment of
|
|
194
|
+
* the stop: taking an item out and sending it are one step, or the item would be lost without an attempt.
|
|
195
|
+
*/
|
|
196
|
+
export class Outbox {
|
|
197
|
+
private port: AgentPort | null = null;
|
|
198
|
+
/** The reads and writes of the file, one at a time. Never held across a call to the port. */
|
|
199
|
+
private queue: Promise<unknown> = Promise.resolve();
|
|
200
|
+
/**
|
|
201
|
+
* Identities handed over by this process, by request: a copy of one that reappears in the file (planted, or put there
|
|
202
|
+
* again) is not sent a second time. Not persisted: a restart relies on the file, from which an item is gone before its
|
|
203
|
+
* send. An entry goes when its request leaves the registry's history (`retire`), after which the resolver has
|
|
204
|
+
* nothing to say for it anyway; so this holds at most two identities for each request the registry still knows.
|
|
205
|
+
*/
|
|
206
|
+
private readonly delivered = new Map<string, Set<string>>();
|
|
207
|
+
/** Items not known to be on disk. */
|
|
208
|
+
private held: Stored[] = [];
|
|
209
|
+
private persistence: "ok" | "failing" = "ok";
|
|
210
|
+
private dropped = 0;
|
|
211
|
+
/** The flush under way, and the one that follows it when somebody asked meanwhile. */
|
|
212
|
+
private inFlight: Promise<void> | null = null;
|
|
213
|
+
private next: { scope: Scope; promise: Promise<void>; run(flush: Promise<void>): void } | null = null;
|
|
214
|
+
/** The last agent a flush for everyone served to the end of its turn: the next one starts after it. */
|
|
215
|
+
private servedLast: string | null = null;
|
|
216
|
+
/** The budget of the flush under way is used up. There is one flush at a time. */
|
|
217
|
+
private spent = false;
|
|
218
|
+
/** The agents whose last idle check got no answer. Only agents with something waiting are kept. */
|
|
219
|
+
private readonly unanswered = new Set<string>();
|
|
220
|
+
/** Gives up on the call to the port that is under way. There is at most one. */
|
|
221
|
+
private abandon: (() => void) | null = null;
|
|
222
|
+
private stopped = false;
|
|
223
|
+
private readonly now: () => number;
|
|
224
|
+
private readonly portTimeoutMs: number;
|
|
225
|
+
private readonly flushBudgetMs: number;
|
|
226
|
+
private readonly onSend: ((item: OutboxItem) => void) | undefined;
|
|
227
|
+
|
|
228
|
+
constructor(
|
|
229
|
+
private readonly file: string,
|
|
230
|
+
private readonly resolver: MessageResolver,
|
|
231
|
+
options: OutboxOptions = {},
|
|
232
|
+
) {
|
|
233
|
+
this.now = options.now ?? Date.now;
|
|
234
|
+
this.portTimeoutMs = options.portTimeoutMs ?? PORT_TIMEOUT_MS;
|
|
235
|
+
this.flushBudgetMs = options.flushBudgetMs ?? FLUSH_BUDGET_MS;
|
|
236
|
+
this.onSend = options.onSend;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
private serial<T>(task: () => Promise<T>): Promise<T> {
|
|
240
|
+
const next = this.queue.catch(() => undefined).then(task);
|
|
241
|
+
this.queue = next;
|
|
242
|
+
return next;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
private isCurrent(item: Stored, now: number): boolean {
|
|
246
|
+
return now - item.enqueuedAt <= MAX_OUTBOX_AGE_MS && item.enqueuedAt - now <= OUTBOX_CLOCK_SKEW_MS;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* The valid items of the file, oldest first, one per identity; whatever else it holds is counted in `dropped`. The
|
|
251
|
+
* whole array is checked (its length is bounded by the size cap), and only then are the newest items kept, so
|
|
252
|
+
* padding after a genuine item cannot push it out of the window.
|
|
253
|
+
*/
|
|
254
|
+
private async readFile(): Promise<{ status: Loaded["status"]; items: Stored[]; dropped: number }> {
|
|
255
|
+
let text: string | null;
|
|
256
|
+
try {
|
|
257
|
+
text = await readPrivateFile(this.file, MAX_OUTBOX_BYTES);
|
|
258
|
+
} catch (error) {
|
|
259
|
+
return isNotOurFile(error) ? { status: "replace", items: [], dropped: 1 } : { status: "unreadable", items: [], dropped: 0 };
|
|
260
|
+
}
|
|
261
|
+
if (text === null) return { status: "ok", items: [], dropped: 0 };
|
|
262
|
+
let parsed: unknown;
|
|
263
|
+
try {
|
|
264
|
+
parsed = JSON.parse(text);
|
|
265
|
+
} catch {
|
|
266
|
+
return { status: "replace", items: [], dropped: 1 };
|
|
267
|
+
}
|
|
268
|
+
if (!Array.isArray(parsed)) return { status: "replace", items: [], dropped: 1 };
|
|
269
|
+
const now = this.now();
|
|
270
|
+
const seen = new Set<string>();
|
|
271
|
+
const items: Stored[] = [];
|
|
272
|
+
for (const candidate of parsed) {
|
|
273
|
+
const result = StoredSchema.safeParse(candidate);
|
|
274
|
+
if (!result.success || !this.isCurrent(result.data, now) || seen.has(identityOf(result.data))) continue;
|
|
275
|
+
seen.add(identityOf(result.data));
|
|
276
|
+
items.push(result.data);
|
|
277
|
+
}
|
|
278
|
+
return { status: "ok", items, dropped: parsed.length - items.length };
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
private async load(): Promise<Loaded> {
|
|
282
|
+
const file = await this.readFile();
|
|
283
|
+
const now = this.now();
|
|
284
|
+
this.held = this.held.filter((item) => this.isCurrent(item, now));
|
|
285
|
+
const known = new Set(file.items.map(identityOf));
|
|
286
|
+
const merged = [...file.items, ...this.held.filter((item) => !known.has(identityOf(item)))];
|
|
287
|
+
const all = merged.slice(-MAX_OUTBOX_ITEMS);
|
|
288
|
+
return { status: file.status, onDisk: file.items, all, dropped: file.dropped + merged.length - all.length };
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Writes `all` over the file, unless the file could not be read (then it holds things this module cannot see). When
|
|
293
|
+
* nothing was written, whatever is not on disk stays in memory and `health()` says so.
|
|
294
|
+
*/
|
|
295
|
+
private async commit(loaded: Loaded, all: Stored[]): Promise<boolean> {
|
|
296
|
+
const kept = all.slice(-MAX_OUTBOX_ITEMS);
|
|
297
|
+
if (loaded.status !== "unreadable") {
|
|
298
|
+
try {
|
|
299
|
+
await writePrivateFile(this.file, JSON.stringify(kept));
|
|
300
|
+
this.held = [];
|
|
301
|
+
this.persistence = "ok";
|
|
302
|
+
this.dropped += loaded.dropped + all.length - kept.length;
|
|
303
|
+
return true;
|
|
304
|
+
} catch {
|
|
305
|
+
// Kept below.
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
this.persistence = "failing";
|
|
309
|
+
const onDisk = new Set(loaded.onDisk.map(identityOf));
|
|
310
|
+
this.held = kept.filter((item) => !onDisk.has(identityOf(item)));
|
|
311
|
+
return false;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Takes an item out, so that it cannot be sent twice, and says whether it did. One that is on disk must leave the
|
|
316
|
+
* file: false when that cannot be done. One that only ever lived in memory just leaves memory. One that is no longer
|
|
317
|
+
* there (dropped with its agent, too old by now) was not taken out by this call: false, so nothing is sent for it.
|
|
318
|
+
*/
|
|
319
|
+
private async remove(item: OutboxItem): Promise<boolean> {
|
|
320
|
+
const id = identityOf(item);
|
|
321
|
+
const loaded = await this.load();
|
|
322
|
+
if (!loaded.all.some((other) => identityOf(other) === id)) return false;
|
|
323
|
+
const memoryOnly = !loaded.onDisk.some((other) => identityOf(other) === id);
|
|
324
|
+
const written = await this.commit(
|
|
325
|
+
loaded,
|
|
326
|
+
loaded.all.filter((other) => identityOf(other) !== id),
|
|
327
|
+
);
|
|
328
|
+
return written || memoryOnly;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
private wasDelivered(item: OutboxItem): boolean {
|
|
332
|
+
return this.delivered.get(item.requestId)?.has(identityOf(item)) === true;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* Whether saving works, how many items are only in memory, and how many entries reading and writing left out of the
|
|
337
|
+
* file (invalid, aged, repeated, over the limit; a file that is no file of ours counts as one), for the diagnostics.
|
|
338
|
+
*/
|
|
339
|
+
health(): { persistence: "ok" | "failing"; unsaved: number; dropped: number } {
|
|
340
|
+
return { persistence: this.persistence, unsaved: this.held.length, dropped: this.dropped };
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
attach(port: AgentPort): void {
|
|
344
|
+
this.port = port;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
pending(): Promise<number> {
|
|
348
|
+
return this.serial(async () => (await this.load()).all.length);
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* Rejects with `invalid_request` for an item the file could not hold (a mistake of the caller, not of the file). A file
|
|
353
|
+
* that cannot be written does not reject: the item stays in memory and `health()` reports it.
|
|
354
|
+
*/
|
|
355
|
+
enqueue(item: OutboxItem): Promise<void> {
|
|
356
|
+
return this.serial(async () => {
|
|
357
|
+
const parsed = ItemSchema.safeParse(item);
|
|
358
|
+
if (!parsed.success) throw new SecureInputError("invalid_request", "outbox item");
|
|
359
|
+
const id = identityOf(parsed.data);
|
|
360
|
+
const loaded = await this.load();
|
|
361
|
+
if (this.wasDelivered(parsed.data) || loaded.all.some((existing) => identityOf(existing) === id)) return;
|
|
362
|
+
await this.commit(loaded, [...loaded.all, { ...parsed.data, enqueuedAt: this.now() }]);
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Drops everything that waits for an agent, unsent. For an agent that is gone for good (archived): its messages
|
|
368
|
+
* could only wait out their day in the file.
|
|
369
|
+
*/
|
|
370
|
+
drop(agentId: string): Promise<void> {
|
|
371
|
+
return this.serial(async () => {
|
|
372
|
+
const loaded = await this.load();
|
|
373
|
+
if (!loaded.all.some((item) => item.agentId === agentId)) return;
|
|
374
|
+
await this.commit(
|
|
375
|
+
loaded,
|
|
376
|
+
loaded.all.filter((item) => item.agentId !== agentId),
|
|
377
|
+
);
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** Forgets what was handed over for a request that left the registry's history: the resolver has nothing to say for it any more. */
|
|
382
|
+
retire(requestId: string): void {
|
|
383
|
+
this.delivered.delete(requestId);
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* From now on nothing is asked of the port, and a call under way is no longer waited for. The file still takes new
|
|
388
|
+
* items, and a flush still writes what was held in memory; it serves nobody.
|
|
389
|
+
*/
|
|
390
|
+
stop(): void {
|
|
391
|
+
this.stopped = true;
|
|
392
|
+
this.abandon?.();
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/** Tells `onSend` of an item that is being handed over. Never throws, and leaves no rejection of an async one unhandled. */
|
|
396
|
+
private tellSent(item: OutboxItem): void {
|
|
397
|
+
try {
|
|
398
|
+
const result: unknown = this.onSend?.({ agentId: item.agentId, requestId: item.requestId, kind: item.kind });
|
|
399
|
+
if (typeof (result as PromiseLike<unknown> | undefined)?.then === "function") (result as PromiseLike<unknown>).then(undefined, () => undefined);
|
|
400
|
+
} catch {
|
|
401
|
+
// What whoever is told does with it never changes whether the message is sent.
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/** The text for an item, or null: no record, nothing to say, another agent's record, or a resolver that fails. */
|
|
406
|
+
private text(item: OutboxItem): string | null {
|
|
407
|
+
try {
|
|
408
|
+
const resolved = this.resolver({ agentId: item.agentId, requestId: item.requestId, kind: item.kind });
|
|
409
|
+
return resolved !== null && resolved.agentId === item.agentId ? resolved.text : null;
|
|
410
|
+
} catch {
|
|
411
|
+
return null;
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* What the call to the port returns; `UNSETTLED` when its bound, the end of the flush's budget or a stop comes
|
|
417
|
+
* first; its own error if it fails first. A result or an error that comes later is ignored. The bound is the
|
|
418
|
+
* port's own, and for a call that starts with the budget already used up, the floor.
|
|
419
|
+
*/
|
|
420
|
+
private async ask<T>(call: () => Promise<T>): Promise<T | typeof UNSETTLED> {
|
|
421
|
+
try {
|
|
422
|
+
return await raceDeadline(this.spent ? PORT_FLOOR_MS : this.portTimeoutMs, UNSETTLED, call, (abandon) => {
|
|
423
|
+
this.abandon = abandon;
|
|
424
|
+
});
|
|
425
|
+
} finally {
|
|
426
|
+
this.abandon = null;
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/**
|
|
431
|
+
* Delivers what can be delivered now: to one agent, or to everyone who has something waiting. Resolves when a flush
|
|
432
|
+
* that began after the call has ended. While one is under way the call does not start another: it marks that one
|
|
433
|
+
* more is wanted, and every call made meanwhile is answered by that one.
|
|
434
|
+
*/
|
|
435
|
+
flush(agentId?: string): Promise<void> {
|
|
436
|
+
if (this.inFlight === null) return this.begin({ all: agentId === undefined, agents: agentId === undefined ? [] : [agentId] });
|
|
437
|
+
if (this.next === null) {
|
|
438
|
+
let run!: (flush: Promise<void>) => void;
|
|
439
|
+
const promise = new Promise<void>((resolve) => {
|
|
440
|
+
run = resolve;
|
|
441
|
+
});
|
|
442
|
+
this.next = { scope: { all: false, agents: [] }, promise, run };
|
|
443
|
+
}
|
|
444
|
+
if (agentId === undefined) this.next.scope.all = true;
|
|
445
|
+
else if (!this.next.scope.agents.includes(agentId)) this.next.scope.agents.push(agentId);
|
|
446
|
+
return this.next.promise;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
private begin(scope: Scope): Promise<void> {
|
|
450
|
+
const flush = this.pass(scope).finally(() => {
|
|
451
|
+
this.inFlight = null;
|
|
452
|
+
const next = this.next;
|
|
453
|
+
this.next = null;
|
|
454
|
+
if (next !== null) next.run(this.begin(next.scope));
|
|
455
|
+
});
|
|
456
|
+
this.inFlight = flush;
|
|
457
|
+
return flush;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/** The agents of a flush for everyone, starting after the one the last such flush ended with. */
|
|
461
|
+
private inRotation(agents: string[]): string[] {
|
|
462
|
+
const last = this.servedLast === null ? -1 : agents.indexOf(this.servedLast);
|
|
463
|
+
return [...agents.slice(last + 1), ...agents.slice(0, last + 1)];
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
private async pass(scope: Scope): Promise<void> {
|
|
467
|
+
const port = this.port;
|
|
468
|
+
if (!port) return;
|
|
469
|
+
this.spent = false;
|
|
470
|
+
const budget = setTimeout(() => {
|
|
471
|
+
this.spent = true;
|
|
472
|
+
this.abandon?.();
|
|
473
|
+
}, this.flushBudgetMs);
|
|
474
|
+
try {
|
|
475
|
+
const items = await this.serial(async () => {
|
|
476
|
+
const loaded = await this.load();
|
|
477
|
+
// What an earlier failure left in memory gets its chance to be written, whether or not anything is sent now.
|
|
478
|
+
if (this.held.length > 0) await this.commit(loaded, loaded.all);
|
|
479
|
+
return loaded.all;
|
|
480
|
+
});
|
|
481
|
+
const waiting = [...new Set(items.map((item) => item.agentId))];
|
|
482
|
+
for (const agentId of this.unanswered) if (!waiting.includes(agentId)) this.unanswered.delete(agentId);
|
|
483
|
+
const named = scope.agents.filter((agentId) => waiting.includes(agentId));
|
|
484
|
+
const others = scope.all ? this.inRotation(waiting.filter((agentId) => !named.includes(agentId))) : [];
|
|
485
|
+
const order = [...named, ...others];
|
|
486
|
+
// Those that did not answer last time come after those that did, each group in the order it had.
|
|
487
|
+
const turns = [...order.filter((agentId) => !this.unanswered.has(agentId)), ...order.filter((agentId) => this.unanswered.has(agentId))];
|
|
488
|
+
for (const agentId of turns) {
|
|
489
|
+
if (this.spent) return;
|
|
490
|
+
await this.serve(
|
|
491
|
+
port,
|
|
492
|
+
items.filter((item) => item.agentId === agentId),
|
|
493
|
+
);
|
|
494
|
+
// An agent whose turn the end of the budget cut short was not served: the rotation stays before it, or with
|
|
495
|
+
// two agents waiting the order of every flush would be the same and the second would never have its turn.
|
|
496
|
+
if (!named.includes(agentId) && !this.spent) this.servedLast = agentId;
|
|
497
|
+
}
|
|
498
|
+
} finally {
|
|
499
|
+
clearTimeout(budget);
|
|
500
|
+
this.spent = false;
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/**
|
|
505
|
+
* One agent's turn in a flush: its oldest item that has something to say, if the agent says it is idle. One message
|
|
506
|
+
* at most. This is where a stop takes effect: before each item is looked at, and once more before one is taken out.
|
|
507
|
+
*/
|
|
508
|
+
private async serve(port: AgentPort, items: Stored[]): Promise<void> {
|
|
509
|
+
for (const item of items) {
|
|
510
|
+
if (this.stopped) return;
|
|
511
|
+
// An identity this process already handed over is never handed over again, wherever the file got it from.
|
|
512
|
+
if (this.wasDelivered(item) || this.text(item) === null) {
|
|
513
|
+
// Nothing to say, so the agent's turn is not used up. If the item cannot be taken out it stays and is met again.
|
|
514
|
+
await this.serial(() => this.remove(item));
|
|
515
|
+
continue;
|
|
516
|
+
}
|
|
517
|
+
let idle = false;
|
|
518
|
+
try {
|
|
519
|
+
// No answer in time is no answer either: the item stays for a later flush.
|
|
520
|
+
const answer = await this.ask(() => port.isIdle(item.agentId));
|
|
521
|
+
if (answer === UNSETTLED) this.unanswered.add(item.agentId);
|
|
522
|
+
else this.unanswered.delete(item.agentId);
|
|
523
|
+
idle = answer === true;
|
|
524
|
+
} catch {
|
|
525
|
+
// A check that failed says nothing about the agent: a daemon that could not answer just now would otherwise
|
|
526
|
+
// have a busy agent interrupted, or, if the send failed with it, the message lost before it could be sent.
|
|
527
|
+
// An agent that is really gone is dropped when it is archived (`drop`) or when its item is too old.
|
|
528
|
+
}
|
|
529
|
+
if (!idle) return;
|
|
530
|
+
const text = await this.serial(async () => {
|
|
531
|
+
// The agent said it is idle, and the plugin was stopped before the item's turn at the file came: it stays.
|
|
532
|
+
if (this.stopped) return null;
|
|
533
|
+
// Out first. If that cannot be done nothing is sent: the item stays for the next flush.
|
|
534
|
+
if (!(await this.remove(item))) return null;
|
|
535
|
+
// The words as the record has them now: the idle check took time. The mark is set in the same breath, while
|
|
536
|
+
// the record is known to be there, so `retire` always finds it when the record goes.
|
|
537
|
+
const words = this.text(item);
|
|
538
|
+
if (words === null) return null;
|
|
539
|
+
const marks = this.delivered.get(item.requestId) ?? new Set<string>();
|
|
540
|
+
this.delivered.set(item.requestId, marks.add(identityOf(item)));
|
|
541
|
+
return words;
|
|
542
|
+
});
|
|
543
|
+
if (text === null) return;
|
|
544
|
+
// Out of the file, and about to be sent: whoever asked to know is told now, before the agent can act on it.
|
|
545
|
+
this.tellSent(item);
|
|
546
|
+
try {
|
|
547
|
+
await this.ask(() => port.send(item.agentId, text));
|
|
548
|
+
} catch {
|
|
549
|
+
// The send failed. Whether the agent got the message is not known, and it is not sent again.
|
|
550
|
+
}
|
|
551
|
+
// No answer in time is an unknown outcome: the item is already out, and is not sent again either.
|
|
552
|
+
return;
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
}
|