paseo-plugin-secure-input 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/LICENSE +21 -0
  2. package/OVERVIEW.md +28 -0
  3. package/README.md +105 -2
  4. package/SECURITY.md +84 -0
  5. package/assets/icon.png +0 -0
  6. package/client/card.tsx +74 -0
  7. package/client/codes.ts +32 -0
  8. package/client/diagnostics-rows.ts +139 -0
  9. package/client/dialog-state.ts +59 -0
  10. package/client/dialog.tsx +292 -0
  11. package/client/envelope-cache.ts +85 -0
  12. package/client/fields.tsx +255 -0
  13. package/client/file-entry.ts +142 -0
  14. package/client/form-state.ts +198 -0
  15. package/client/globals.d.ts +19 -0
  16. package/client/outcome.ts +96 -0
  17. package/client/presentation.ts +114 -0
  18. package/client/sealing.ts +27 -0
  19. package/client/self-test.ts +96 -0
  20. package/client/settings.tsx +160 -0
  21. package/client/submit.ts +92 -0
  22. package/client/text.ts +47 -0
  23. package/client/tone.ts +36 -0
  24. package/client/web.ts +184 -0
  25. package/index.client.tsx +29 -0
  26. package/index.server.ts +6 -0
  27. package/npm-shrinkwrap.json +60 -0
  28. package/package.json +68 -4
  29. package/paseo-plugin.json +6 -0
  30. package/server/core/continuation.ts +151 -0
  31. package/server/core/entries.ts +89 -0
  32. package/server/core/outbox.ts +555 -0
  33. package/server/core/registry-store.ts +185 -0
  34. package/server/core/registry.ts +1031 -0
  35. package/server/core/selftest.ts +60 -0
  36. package/server/core/view.ts +38 -0
  37. package/server/io/atomic.ts +119 -0
  38. package/server/io/deadline.ts +28 -0
  39. package/server/io/descriptor.ts +36 -0
  40. package/server/io/directory.ts +40 -0
  41. package/server/io/drop.ts +434 -0
  42. package/server/io/legacy-shim.ts +108 -0
  43. package/server/io/ownership.ts +8 -0
  44. package/server/io/private-file.ts +86 -0
  45. package/server/paseo/bounded.ts +13 -0
  46. package/server/paseo/handlers.ts +124 -0
  47. package/server/paseo/hooks.ts +106 -0
  48. package/server/paseo/plugin.ts +341 -0
  49. package/server/paseo/runtime.ts +409 -0
  50. package/server/paseo/tools.ts +178 -0
  51. package/shared/bytes.ts +100 -0
  52. package/shared/canonical.ts +32 -0
  53. package/shared/card.ts +41 -0
  54. package/shared/contracts.ts +128 -0
  55. package/shared/errors.ts +48 -0
  56. package/shared/limits.ts +118 -0
  57. package/shared/request-id.ts +9 -0
  58. package/shared/request.ts +66 -0
  59. package/shared/sanitize.ts +101 -0
  60. package/shared/seal.ts +292 -0
  61. package/shared/shown.ts +12 -0
  62. package/shared/text.ts +39 -0
  63. package/shared/view.ts +42 -0
  64. package/skills/secure-input/SKILL.md +150 -0
@@ -0,0 +1,409 @@
1
+ import type { PluginHandlerContext } from "@getpaseo/plugin/server";
2
+ import { CARD_KIND, CARD_VERSION, cardData } from "../../shared/card";
3
+ import { SecureInputError } from "../../shared/errors";
4
+ import { announces } from "../core/continuation";
5
+ import type { AgentPort, Outbox, OutboxItem } from "../core/outbox";
6
+ import type { RecordChange, RequestRecord } from "../core/registry";
7
+ import { raceDeadline } from "../io/deadline";
8
+ import { TIMED_OUT, within } from "./bounded";
9
+
10
+ type PaseoApi = PluginHandlerContext["paseo"];
11
+ type AgentHandle = ReturnType<PaseoApi["agents"]["ref"]>;
12
+ /** What the daemon takes for a timeline row. */
13
+ export type TimelineItem = Parameters<AgentHandle["timeline"]["append"]>[0];
14
+
15
+ /**
16
+ * How long a call into the daemon API may take when a card waits for it. The daemon answers these in a few
17
+ * milliseconds, a slow one (an agent being resumed, a loaded machine) in a second or two. Five seconds does not give
18
+ * up on those, and a daemon that has stopped answering costs a card those five seconds, and not the plugin its life.
19
+ */
20
+ export const DAEMON_CALL_TIMEOUT_MS = 5_000;
21
+
22
+ /**
23
+ * How long `settled` waits, once the runtime was stopped, for what is still under way: the saves of messages that
24
+ * were just enqueued, and the unwinding of a flush and of a card that were given up on. Those are a handful of small
25
+ * writes to the plugin's own directory, a few milliseconds; the bound is for a disk that stalls. It is the last wait of
26
+ * the plugin's stop, after the registry's, and the whole stop has to end before Paseo ends the process
27
+ * (`PASEO_STOP_WINDOW_MS` in `server/paseo/plugin.ts`): what is still unsaved when the bound passes stays for this
28
+ * process to save while it lives, and is lost with it otherwise, as any message that was never saved.
29
+ */
30
+ export const SETTLE_BOUND_MS = 300;
31
+
32
+ /**
33
+ * How many appends for one request may be out (given up on at the bound, and not answered since) while its card is
34
+ * still tried at every chance: on each tick and whenever the daemon calls in. With this many out the card is tried
35
+ * more slowly (`SLOW_RETRY_TICKS`), and never given up: a daemon that takes calls and does not answer them is not
36
+ * handed one more every minute, and a daemon that left three unanswered and then recovers still gets the card.
37
+ */
38
+ export const MAX_UNSETTLED_APPENDS = 3;
39
+
40
+ /**
41
+ * While `MAX_UNSETTLED_APPENDS` appends of a request are out, its card is tried once in this many ticks of the plugin
42
+ * (`flushAll`, once a minute), and at no other occasion. Five minutes is what a human who was asked for a value can
43
+ * still wait for a card, and twelve calls an hour is what a daemon that answers none of them is handed at most.
44
+ */
45
+ export const SLOW_RETRY_TICKS = 5;
46
+
47
+ const NOT_ATTACHED = "the plugin is not attached to the daemon yet; retry in a few seconds";
48
+
49
+ /** The agent, as far as the plugin uses it. The daemon's own handle satisfies this. */
50
+ export interface DaemonAgent {
51
+ readonly status: string | null;
52
+ refresh(): Promise<unknown>;
53
+ send(text: string): Promise<void>;
54
+ readonly timeline: { append(item: TimelineItem): Promise<unknown> };
55
+ }
56
+
57
+ /**
58
+ * The part of the daemon API the plugin calls. `PaseoApi` is the client package's type, which plugins do not import;
59
+ * it is reached through the SDK's handler context, and a handler passes that context here, so the compiler checks
60
+ * the real API against this port at every place it is handed over. A test fakes exactly this.
61
+ */
62
+ export interface DaemonPort {
63
+ readonly agents: { ref(agentId: string): DaemonAgent };
64
+ }
65
+
66
+ export interface RuntimeOptions {
67
+ /** `DAEMON_CALL_TIMEOUT_MS` unless a test wants less. */
68
+ callTimeoutMs?: number;
69
+ /** Told a code (never a message) when something the runtime does not stop for goes wrong. */
70
+ report?(code: string): void;
71
+ }
72
+
73
+ /**
74
+ * A card the timeline may not show yet. `record` is the latest state of the request, the only one kept; `owed` says
75
+ * that no append of that state is known to have landed; `unsettled` counts the appends that were given up on and
76
+ * have not come back; `triedAt` is the tick during which the last append was made; `failing` says a failure was
77
+ * already reported for this state, so it is reported once.
78
+ */
79
+ interface Card {
80
+ record: RequestRecord;
81
+ owed: boolean;
82
+ unsettled: number;
83
+ triedAt: number;
84
+ failing: boolean;
85
+ }
86
+
87
+ /**
88
+ * Holds the daemon API. Paseo creates it before the plugin loads but only hands it to hooks and RPC handlers, so
89
+ * the plugin captures it on first use and defers anything that needs it until then.
90
+ *
91
+ * Cards. The card on the timeline is the only way the human reaches the form, so a card stays owed until an append
92
+ * of it is known to have landed: one that failed, or was not answered within the bound, is tried again on the
93
+ * plugin's tick and whenever the daemon next calls in, and once `MAX_UNSETTLED_APPENDS` unanswered appends are out
94
+ * for it, on every `SLOW_RETRY_TICKS`-th tick; it is never given up. Only the latest state of a request is kept, so
95
+ * a request that closed while its first card was owed gets the closed card and no other. The order of two states on the timeline
96
+ * is best effort, not a guarantee: an append that was given up on is not cancelled and can still land, after a
97
+ * newer one. When it does, the latest state is appended again after it, so the older state does not stay the last
98
+ * row. What is kept is one entry for a request with a card owed or an append still out, and it goes when the
99
+ * registry forgets the request.
100
+ *
101
+ * Messages. A message is saved in the outbox the moment its request changes, and saving waits for no agent. What
102
+ * waits is sent by the outbox's flush, of which there is one at a time (`Outbox`). No flush runs before the registry
103
+ * has loaded (`holdMessages`): until then the outbox could not tell a request that is not loaded yet from one that
104
+ * does not exist, and would drop what waited across a restart.
105
+ *
106
+ * After `stop` nothing more is asked of the daemon for cards or messages, and `settled` returns within
107
+ * `SETTLE_BOUND_MS`. A message enqueued after that is still saved, for the next start to send.
108
+ */
109
+ export class Runtime implements AgentPort {
110
+ private paseo: DaemonPort | null = null;
111
+ private readonly cards = new Map<string, Card>();
112
+ /** A drain of the cards is under way, and another was asked for meanwhile. */
113
+ private draining = false;
114
+ private drainAgain = false;
115
+ /** Gives up on the append that is under way. There is at most one. */
116
+ private abandonAppend: (() => void) | null = null;
117
+ /** Flushes are held back until the registry has loaded; one was asked for meanwhile. */
118
+ private holding = false;
119
+ private flushWanted = false;
120
+ /** Everything under way, for `settled`. */
121
+ private readonly work = new Set<Promise<unknown>>();
122
+ private stopped = false;
123
+ /** How many ticks there were (`flushAll`): what a card with many appends out is paced by. */
124
+ private ticks = 0;
125
+ private readonly callTimeoutMs: number;
126
+ private readonly report: (code: string) => void;
127
+
128
+ constructor(
129
+ private readonly outbox: Pick<Outbox, "attach" | "enqueue" | "flush" | "drop" | "retire" | "stop">,
130
+ options: RuntimeOptions = {},
131
+ ) {
132
+ this.callTimeoutMs = options.callTimeoutMs ?? DAEMON_CALL_TIMEOUT_MS;
133
+ this.report = options.report ?? (() => undefined);
134
+ }
135
+
136
+ get attached(): boolean {
137
+ return this.paseo !== null;
138
+ }
139
+
140
+ /** Every hook, event and RPC calls this first. A daemon API that is new is taken; one that is known only gives the owed cards another try. */
141
+ attach(paseo: DaemonPort): void {
142
+ if (this.paseo !== paseo) {
143
+ this.paseo = paseo;
144
+ this.outbox.attach(this);
145
+ this.flush().catch(() => this.report("outbox_flush_failed"));
146
+ }
147
+ this.drainCards();
148
+ }
149
+
150
+ private track(task: Promise<unknown>): void {
151
+ const tracked: Promise<unknown> = task.catch(() => undefined).finally(() => this.work.delete(tracked));
152
+ this.work.add(tracked);
153
+ }
154
+
155
+ /**
156
+ * Resolves when everything that was asked for so far has ended: the cards that could be appended, the messages
157
+ * saved, the flushes. After `stop` that is soon, because nothing is waited for from the daemon any more, and it is
158
+ * never longer than `SETTLE_BOUND_MS`.
159
+ */
160
+ async settled(): Promise<void> {
161
+ const quiet = async (): Promise<void> => {
162
+ while (this.work.size > 0) await Promise.all([...this.work]);
163
+ };
164
+ if (this.stopped) await within(SETTLE_BOUND_MS, quiet);
165
+ else await quiet();
166
+ }
167
+
168
+ /**
169
+ * From now on no card is appended and no agent is asked or sent anything; what is under way is given up on. An idle
170
+ * check given up on leaves its message in the file, a send given up on is an unknown outcome and is not repeated,
171
+ * and a card that was owed is still owed when the process ends (the dialog shows the request's true state).
172
+ */
173
+ stop(): void {
174
+ this.stopped = true;
175
+ this.outbox.stop();
176
+ this.abandonAppend?.();
177
+ }
178
+
179
+ /** No flush from now until `releaseMessages`: the registry has not loaded. A flush asked for meanwhile runs then. */
180
+ holdMessages(): void {
181
+ this.holding = true;
182
+ }
183
+
184
+ /**
185
+ * Whether flushes are held back. That is so from `holdMessages` until the registry has loaded, and for good when a
186
+ * start-up fails before the load or never gets there: what waits then stays in the file for the next start, and
187
+ * the diagnostics say so, because nothing else would.
188
+ */
189
+ get messagesHeld(): boolean {
190
+ return this.holding;
191
+ }
192
+
193
+ /** The registry has loaded: what waits may be looked at, and a flush that was asked for meanwhile runs now. */
194
+ releaseMessages(): void {
195
+ if (!this.holding) return;
196
+ this.holding = false;
197
+ if (!this.flushWanted) return;
198
+ this.flushWanted = false;
199
+ this.flush().catch(() => this.report("outbox_flush_failed"));
200
+ }
201
+
202
+ /**
203
+ * One flush of the outbox, for an agent or for everyone, unless flushes are held back. After a stop the outbox
204
+ * serves nobody: a flush then only writes what it still held in memory.
205
+ */
206
+ private flush(agentId?: string): Promise<void> {
207
+ if (this.holding) {
208
+ this.flushWanted = true;
209
+ return Promise.resolve();
210
+ }
211
+ let flushing: Promise<void>;
212
+ try {
213
+ flushing = this.outbox.flush(agentId);
214
+ } catch (error) {
215
+ flushing = Promise.reject(error);
216
+ }
217
+ this.track(flushing);
218
+ return flushing;
219
+ }
220
+
221
+ private api(): DaemonPort {
222
+ if (!this.paseo) throw new SecureInputError("unknown_agent", NOT_ATTACHED);
223
+ return this.paseo;
224
+ }
225
+
226
+ async isIdle(agentId: string): Promise<boolean> {
227
+ const handle = this.api().agents.ref(agentId);
228
+ await handle.refresh();
229
+ return handle.status === "idle";
230
+ }
231
+
232
+ async send(agentId: string, text: string): Promise<void> {
233
+ await this.api().agents.ref(agentId).send(text);
234
+ }
235
+
236
+ /**
237
+ * The registry calls this on every change of a record, and says what the change was. The card is the record as it
238
+ * is now, whatever changed. A message is for one change only: the continuation when the state changed to one that
239
+ * is announced (`announces`: not `released`, which a message still waiting says instead), the warning when the tamper
240
+ * flag was raised, and nothing for any other change, so a record that changes again after its message was sent (in
241
+ * this process or in an earlier one) does not make the message a second time. Both are references (which request,
242
+ * which of the two messages); the words are built from the registry's record when they are sent.
243
+ */
244
+ publish(record: RequestRecord, change: RecordChange): void {
245
+ const card = this.cards.get(record.id);
246
+ if (card === undefined) {
247
+ this.cards.set(record.id, { record, owed: true, unsettled: 0, triedAt: this.ticks, failing: false });
248
+ } else {
249
+ card.record = record;
250
+ card.owed = true;
251
+ card.failing = false;
252
+ }
253
+ this.drainCards();
254
+ if (change === "state" && announces(record)) this.announce({ agentId: record.agentId, requestId: record.id, kind: "continuation" });
255
+ if (change === "tamper") this.announce({ agentId: record.agentId, requestId: record.id, kind: "tamper" });
256
+ }
257
+
258
+ /** The registry forgot a request: what is kept for it here and in the outbox goes with it. */
259
+ forget(requestId: string): void {
260
+ this.cards.delete(requestId);
261
+ this.outbox.retire(requestId);
262
+ }
263
+
264
+ /** How many requests have a card the timeline is not known to show yet. */
265
+ get cardsOwed(): number {
266
+ let owed = 0;
267
+ for (const card of this.cards.values()) if (card.owed) owed += 1;
268
+ return owed;
269
+ }
270
+
271
+ /** Saves the message, which waits for no agent, and then asks for it to be delivered. */
272
+ private announce(item: OutboxItem): void {
273
+ this.track(
274
+ (async () => {
275
+ try {
276
+ await this.outbox.enqueue(item);
277
+ } catch {
278
+ this.report("outbox_enqueue_failed");
279
+ }
280
+ await this.flush(item.agentId).catch(() => this.report("outbox_flush_failed"));
281
+ })(),
282
+ );
283
+ }
284
+
285
+ turnEnded(agentId: string): void {
286
+ this.drainCards();
287
+ this.flush(agentId).catch(() => this.report("outbox_flush_failed"));
288
+ }
289
+
290
+ /**
291
+ * The agent was archived: it is gone for good. What waits for it is dropped: its messages, which could only wait out
292
+ * their day in the file, and its owed cards, which would be tried once a minute for a timeline nobody opens.
293
+ */
294
+ agentArchived(agentId: string): void {
295
+ for (const [id, card] of this.cards) if (card.record.agentId === agentId) this.cards.delete(id);
296
+ this.track(this.outbox.drop(agentId).catch(() => this.report("outbox_drop_failed")));
297
+ }
298
+
299
+ /**
300
+ * The plugin's tick. Delivers what is waiting for an agent that has become idle without a turn ending that anyone
301
+ * told us of, and gives the cards that are still owed another try. Resolves when the flush is done and rejects if it
302
+ * fails. While a flush is under way the outbox does not start another: it runs one more after it.
303
+ */
304
+ flushAll(): Promise<void> {
305
+ this.ticks += 1;
306
+ this.drainCards();
307
+ return this.flush();
308
+ }
309
+
310
+ /** Starts a drain of the owed cards, unless one is under way: then one more follows it. After a stop a drain appends nothing. */
311
+ private drainCards(): void {
312
+ if (this.paseo === null) return;
313
+ if (this.draining) {
314
+ this.drainAgain = true;
315
+ return;
316
+ }
317
+ if (this.cardsOwed === 0) return;
318
+ this.draining = true;
319
+ this.track(
320
+ this.drain()
321
+ .catch(() => this.report("card_failed"))
322
+ .finally(() => {
323
+ this.draining = false;
324
+ if (!this.drainAgain) return;
325
+ this.drainAgain = false;
326
+ this.drainCards();
327
+ }),
328
+ );
329
+ }
330
+
331
+ /** What the append answers; `TIMED_OUT` when the bound or a stop comes first; its own error if it fails first. */
332
+ private async answered(append: Promise<unknown>): Promise<unknown> {
333
+ try {
334
+ return await raceDeadline(this.callTimeoutMs, TIMED_OUT, () => append, (giveUp) => {
335
+ this.abandonAppend = giveUp;
336
+ });
337
+ } finally {
338
+ this.abandonAppend = null;
339
+ }
340
+ }
341
+
342
+ /** An entry is kept only while something is owed or out for it. */
343
+ private settle(id: string, card: Card): void {
344
+ if (!card.owed && card.unsettled === 0 && this.cards.get(id) === card) this.cards.delete(id);
345
+ }
346
+
347
+ private fail(card: Card, code: string): void {
348
+ if (card.failing) return;
349
+ card.failing = true;
350
+ this.report(code);
351
+ }
352
+
353
+ private async drain(): Promise<void> {
354
+ const port = this.paseo;
355
+ if (port === null) return;
356
+ for (const [id, card] of [...this.cards]) {
357
+ // Before every card: a stop can come between the answer to one append and the next.
358
+ if (this.stopped) return;
359
+ if (!card.owed || this.cards.get(id) !== card) continue;
360
+ // With that many appends out and unanswered the card is not dropped, only tried more seldom: see `SLOW_RETRY_TICKS`.
361
+ if (card.unsettled >= MAX_UNSETTLED_APPENDS && this.ticks - card.triedAt < SLOW_RETRY_TICKS) continue;
362
+ const record = card.record;
363
+ card.triedAt = this.ticks;
364
+ let append: Promise<unknown>;
365
+ try {
366
+ append = Promise.resolve(
367
+ port.agents.ref(record.agentId).timeline.append({ type: "plugin", id: record.id, kind: CARD_KIND, version: CARD_VERSION, data: cardData(record) }),
368
+ );
369
+ } catch {
370
+ this.fail(card, "card_failed");
371
+ continue;
372
+ }
373
+ let answer: unknown;
374
+ try {
375
+ answer = await this.answered(append);
376
+ } catch {
377
+ // Still owed: tried again on the tick and when the daemon next calls in.
378
+ this.fail(card, "card_failed");
379
+ continue;
380
+ }
381
+ if (answer !== TIMED_OUT) {
382
+ // It landed. Unless a newer state came meanwhile, the timeline shows the request as it is.
383
+ if (card.record === record) card.owed = false;
384
+ this.settle(id, card);
385
+ continue;
386
+ }
387
+ // Given up on because of the stop, not because the daemon was slow: nothing to report, and nothing more to do.
388
+ if (this.stopped) return;
389
+ this.fail(card, "daemon_timeout");
390
+ // Given up on, not cancelled: it stays owed and is tried again, and this call can still land later.
391
+ card.unsettled += 1;
392
+ append.then(
393
+ () => {
394
+ card.unsettled -= 1;
395
+ // It landed after all, behind anything appended since. If that was a newer state, the row is an older one
396
+ // again and the latest is owed once more; if this was the latest, it is shown and nothing is owed.
397
+ card.owed = card.record !== record;
398
+ this.settle(id, card);
399
+ this.drainCards();
400
+ },
401
+ () => {
402
+ card.unsettled -= 1;
403
+ this.settle(id, card);
404
+ this.drainCards();
405
+ },
406
+ );
407
+ }
408
+ }
409
+ }
@@ -0,0 +1,178 @@
1
+ import { defineAgentTool, type AgentToolContext, type AgentToolDefinition } from "@getpaseo/plugin/server";
2
+ import { z } from "zod";
3
+ import { SecureInputError } from "../../shared/errors";
4
+ import { DROP_TTL_MS } from "../../shared/limits";
5
+ import { SecretRequestShape } from "../../shared/request";
6
+ import { REQUEST_ID_PATTERN } from "../../shared/request-id";
7
+ import type { AgentIdentity, Registry, RequestRecord } from "../core/registry";
8
+ import { filePath } from "../io/drop";
9
+ import type { StartupProblem } from "./plugin";
10
+ import type { Runtime } from "./runtime";
11
+
12
+ /** The agent the daemon hands to a tool's `execute`: the SDK's `PluginHookAgent`. */
13
+ export interface ToolAgent {
14
+ id: string;
15
+ workspaceId: string | null;
16
+ parentAgentId: string | null;
17
+ provider: string;
18
+ cwd: string;
19
+ title: string | null;
20
+ }
21
+
22
+ /** The names of the plugin's tools. A tool of one of these names that comes with a session is an older one of its own. */
23
+ export const TOOL_NAMES = ["request_secret", "request_status", "cancel_request", "release_secret"] as const;
24
+
25
+ export const NOT_STARTED = "the plugin has not finished starting; retry in a few seconds";
26
+ export const START_FAILED = (code: string) => `the plugin did not start (${code}). Tell the user. Do not ask for the secret in chat instead.`;
27
+ /** What any failure that is not one of the plugin's refusals becomes: nothing of its own message is passed on. */
28
+ export const NOT_HANDLED = "the request could not be handled";
29
+
30
+ export interface ToolDeps {
31
+ registry: Pick<Registry, "create" | "get" | "cancel" | "release" | "check">;
32
+ runtime: Pick<Runtime, "attach">;
33
+ /** How the start-up ended, waited for within `STARTUP_WAIT_MS`: its problem, `null` for none, or "pending" when it has not ended. */
34
+ started(): Promise<StartupProblem | null | "pending">;
35
+ /** `<data>/drop`, where the sets are: the paths a status names. */
36
+ drop: string;
37
+ }
38
+
39
+ /** The most minutes a set of files stays: what the agent is told. */
40
+ const MINUTES = DROP_TTL_MS / 60_000;
41
+
42
+ // Each member of the input is described in its own schema (`SecretRequestShape`), which the daemon hands on to the agent.
43
+ const REQUEST_SECRET =
44
+ "Ask the human for secret values (passwords, API keys, tokens, private keys, connection strings, whole credential files) through a secure form in the Paseo app. " +
45
+ "Each value is written, exactly as typed or as the file was, to its own short-lived file that only your OS user can read; you receive the paths, never the values. " +
46
+ "Use this instead of asking for a secret in chat or asking the user to edit a file. " +
47
+ 'It returns at once with status "pending": end your turn, and a message with the paths arrives when the user has submitted. Do not poll. ' +
48
+ "Never read, print, open, compare or log a file or directory whose name starts with si-secret-. " +
49
+ "Move each value where it belongs without reading it (`command < PATH`, `cp PATH DESTINATION`), then delete the directory or call release_secret. " +
50
+ `The files are deleted at the end of the turn the message starts, and ${MINUTES} minutes after they were written at the latest.`;
51
+
52
+ const REQUEST_STATUS =
53
+ "The state of one of your requests, its keys and whether a second submission reached it; while its files exist, the path of each file and when they are deleted. Never returns values. " +
54
+ "Use it when the user says no form appeared or that they answered and you heard nothing; it is not for polling.";
55
+
56
+ const CANCEL_REQUEST =
57
+ "Withdraw one of your own pending requests, when the values are no longer needed. " +
58
+ "Never use it to clear request_already_pending for a request the user may be answering: wait for that request instead.";
59
+
60
+ const RELEASE_SECRET = `Delete the files of one of your delivered requests now, once each value is where it belongs. The same as deleting its directory. Without it the files go at the end of the turn the message started, or after ${MINUTES} minutes.`;
61
+
62
+ const RequestIdInput = z.object({ requestId: z.string().regex(REQUEST_ID_PATTERN) }).strict();
63
+
64
+ /**
65
+ * Where the files of a delivered request are, key by key in the order they were written, and when they are deleted at
66
+ * the latest (ISO 8601); both null for a request that has no files. Paths only: what is in the files is never read.
67
+ */
68
+ function filesOf(record: RequestRecord, drop: string): { files: Record<string, string> | null; deleteBy: string | null } {
69
+ if (record.state !== "delivered" || record.written === null || record.deleteBy === null) return { files: null, deleteBy: null };
70
+ return { files: Object.fromEntries(record.written.map((key) => [key, filePath(drop, record.id, key)])), deleteBy: new Date(record.deleteBy).toISOString() };
71
+ }
72
+
73
+ /**
74
+ * Who is asking: the agent identity Paseo supplies with the call, and nothing the call itself says (an argument, the
75
+ * agent's environment, a marker). Cross-agent impersonation is a host limitation; see SECURITY.md.
76
+ */
77
+ export function identityOf(agent: ToolAgent): AgentIdentity {
78
+ return { agentId: agent.id, cwd: agent.cwd, title: agent.title };
79
+ }
80
+
81
+ /**
82
+ * What a tool gives back. An answer is its JSON, as text and as structured content alike. The plugin's own refusal is
83
+ * its code and its words, which are the plugin's (a key, a request id, a fixed phrase). Anything else, and an answer JSON
84
+ * cannot carry, is one fixed refusal: what a library or the system wrote is never passed on. Never rejects.
85
+ */
86
+ export async function toolResult(run: () => Promise<object>): Promise<{ text: string; structuredContent?: object; isError?: true }> {
87
+ try {
88
+ const answer = await run();
89
+ const text: unknown = JSON.stringify(answer);
90
+ if (typeof text !== "string") throw new TypeError("the answer is not JSON");
91
+ return { text, structuredContent: answer };
92
+ } catch (error) {
93
+ const refusal = error instanceof SecureInputError ? error : new SecureInputError("service_unavailable", NOT_HANDLED);
94
+ return { isError: true, text: JSON.stringify({ error: refusal.code, message: refusal.message }) };
95
+ }
96
+ }
97
+
98
+ /**
99
+ * The tools the session-open hook gives every agent. Each call is made as the agent the daemon hands to `execute`.
100
+ * It takes the daemon's API first, as every hook and RPC does; then waits for the start-up, within its bound, and is
101
+ * refused in fixed words while that has not ended or when it failed; and only then does what it is for.
102
+ */
103
+ export function agentTools({ registry, runtime, started, drop }: ToolDeps): AgentToolDefinition[] {
104
+ // Each operation goes to the registry with the call's signal (`CallTerms`): an operation whose call was canceled, or
105
+ // whose turn in the registry's queue has not come within `ADMISSION_WAIT_MS`, is refused and never begun, and one that
106
+ // has begun is waited for to the end.
107
+ const answer = (paseo: AgentToolContext["paseo"], operation: () => Promise<object>) =>
108
+ toolResult(async () => {
109
+ runtime.attach(paseo);
110
+ const state = await started();
111
+ if (state === "pending") throw new SecureInputError("service_unavailable", NOT_STARTED);
112
+ if (state !== null) throw new SecureInputError("service_unavailable", START_FAILED(state.code));
113
+ return operation();
114
+ });
115
+
116
+ /** The caller's own request. One that is not theirs and one that does not exist are answered alike, before anything else is looked at. */
117
+ const own = (agent: ToolAgent, requestId: string) => {
118
+ const record = registry.get(requestId);
119
+ if (record === undefined || record.agentId !== agent.id) throw new SecureInputError("invalid_request", "unknown request");
120
+ return record;
121
+ };
122
+
123
+ return [
124
+ defineAgentTool({
125
+ name: "request_secret",
126
+ description: REQUEST_SECRET,
127
+ input: SecretRequestShape,
128
+ // The shape is what the daemon checks a call against; the registry holds the input to the whole request schema.
129
+ execute: (input, { agent, paseo, signal }) => answer(paseo, () => registry.create(identityOf(agent), input, { signal })),
130
+ }),
131
+ defineAgentTool({
132
+ name: "request_status",
133
+ description: REQUEST_STATUS,
134
+ input: RequestIdInput,
135
+ // What an agent may know of its own request: the state, the keys it asked for and the keys that were written as
136
+ // files, how it ended, whether a second, different submission reached it (`tamper`), and while its files exist,
137
+ // the path of each and when they go. Names, codes and paths only. The owner is checked before the registry looks:
138
+ // the look releases a set the agent took away itself, which nobody else's call may do.
139
+ execute: (input, { agent, paseo, signal }) =>
140
+ answer(paseo, async () => {
141
+ own(agent, input.requestId);
142
+ const record = await registry.check(input.requestId, { signal });
143
+ // Gone from the history between the two looks: as unknown as any other.
144
+ if (record === undefined) throw new SecureInputError("invalid_request", "unknown request");
145
+ return {
146
+ requestId: input.requestId,
147
+ state: record.state,
148
+ keys: record.request.fields.map((field) => field.key),
149
+ written: record.written,
150
+ tamper: record.tamper,
151
+ errorCode: record.errorCode,
152
+ ...filesOf(record, drop),
153
+ };
154
+ }),
155
+ }),
156
+ defineAgentTool({
157
+ name: "cancel_request",
158
+ description: CANCEL_REQUEST,
159
+ input: RequestIdInput,
160
+ execute: (input, { agent, paseo, signal }) =>
161
+ answer(paseo, async () => {
162
+ own(agent, input.requestId);
163
+ return { requestId: input.requestId, state: (await registry.cancel(agent.id, input.requestId, { signal })).state };
164
+ }),
165
+ }),
166
+ defineAgentTool({
167
+ name: "release_secret",
168
+ description: RELEASE_SECRET,
169
+ input: RequestIdInput,
170
+ // The registry holds the request to its owner again, and refuses one with no files in its own words.
171
+ execute: (input, { agent, paseo, signal }) =>
172
+ answer(paseo, async () => {
173
+ own(agent, input.requestId);
174
+ return { requestId: input.requestId, state: (await registry.release(agent.id, input.requestId, { signal })).state };
175
+ }),
176
+ }),
177
+ ];
178
+ }