paseo-plugin-secure-input 0.2.2 → 0.4.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.
@@ -1,40 +1,22 @@
1
1
  import type { CardData } from "../shared/card";
2
2
  import type { RequestView } from "../shared/view";
3
- import { plural } from "./text";
3
+ import type { Translate } from "./messages";
4
4
  import type { Tone } from "./tone";
5
5
 
6
6
  /** What the form says of how the values travel: the cipher `shared/seal.ts` really uses, and nothing else. */
7
7
  export const FORM_BADGE = "X25519 · ChaCha20-Poly1305";
8
8
 
9
9
  /** The form's title: one key on screen, or several. */
10
- export function formTitle(rowsOnScreen: number): string {
11
- return rowsOnScreen > 1 ? "Секрети для агента" : "Секрет для агента";
10
+ export function formTitle(t: Translate, rowsOnScreen: number): string {
11
+ return t(rowsOnScreen > 1 ? "form.titleMany" : "form.titleOne");
12
12
  }
13
13
 
14
- /** What a screen reader says of each control that has an icon and no words, and of each input that shows no name of its own. */
15
- export const A11Y: Readonly<
16
- Record<"enter" | "decline" | "add" | "remove" | "show" | "hide" | "submit" | "pick" | "paste" | "removeFile" | "name" | "pasteArea", string>
17
- > = {
18
- enter: "Ввести значення",
19
- decline: "Відхилити запит",
20
- add: "Додати ключ",
21
- remove: "Прибрати ключ",
22
- show: "Показати значення",
23
- hide: "Сховати значення",
24
- submit: "Передати",
25
- pick: "Вибрати файл",
26
- paste: "Вставити з буфера",
27
- removeFile: "Прибрати файл",
28
- name: "Назва ключа",
29
- pasteArea: "Вміст файлу",
30
- };
31
-
32
14
  /** What the name input of a row of the human's shows while it is empty: the form a key has. */
33
15
  export const KEY_PLACEHOLDER = "KEY_NAME";
34
16
 
35
17
  /** The eye of a text row: what it shows, and what pressing it will do. */
36
- export function eye(shown: boolean): { icon: "Eye" | "EyeOff"; label: string } {
37
- return shown ? { icon: "EyeOff", label: A11Y.hide } : { icon: "Eye", label: A11Y.show };
18
+ export function eye(t: Translate, shown: boolean): { icon: "Eye" | "EyeOff"; label: string } {
19
+ return shown ? { icon: "EyeOff", label: t("a11y.hide") } : { icon: "Eye", label: t("a11y.show") };
38
20
  }
39
21
 
40
22
  /** The pill in the chat. Its look comes from the card's data alone, and nothing in it changes its height. */
@@ -50,33 +32,25 @@ export interface Pill {
50
32
  /** The height of the pill, in every state. The chat's list does not take a row whose height changes (getpaseo/paseo#7486). */
51
33
  export const PILL_HEIGHT = 36;
52
34
 
53
- /** The word for each way a request ends without its values. All of them are drawn the same way: dimmed and struck through. */
54
- const ENDED_AS: Readonly<Record<"declined" | "cancelled" | "expired" | "rejected", string>> = {
55
- declined: "Відхилено",
56
- cancelled: "Скасовано",
57
- expired: "Час минув",
58
- rejected: "Не прийнято",
59
- };
60
-
61
35
  /**
62
36
  * How a request looks as a pill in each state it can be in. Only a request that waits can be pressed, and not once a
63
37
  * second, different submission has come: that one is red in every state. A waiting request names its one key, or counts
64
38
  * several; every other state counts them.
65
39
  */
66
- export function pill(data: Pick<CardData, "state" | "tamper" | "keys">): Pill {
67
- const count = plural(data.keys.length, "ключ", "ключі", "ключів");
68
- if (data.tamper) return { tone: "danger", icon: "ShieldAlert", title: "Підозріле подання", detail: count, struck: false, pressable: false };
40
+ export function pill(t: Translate, data: Pick<CardData, "state" | "tamper" | "keys">): Pill {
41
+ const count = t("pill.keys", { count: data.keys.length });
42
+ if (data.tamper) return { tone: "danger", icon: "ShieldAlert", title: t("pill.tamper"), detail: count, struck: false, pressable: false };
69
43
  switch (data.state) {
70
44
  case "pending":
71
45
  return data.keys.length > 1
72
- ? { tone: "accent", icon: "Shield", title: "Секрети для агента", detail: count, struck: false, pressable: true }
73
- : { tone: "accent", icon: "Shield", title: "Секрет для агента", detail: data.keys[0] ?? "", struck: false, pressable: true };
46
+ ? { tone: "accent", icon: "Shield", title: t("form.titleMany"), detail: count, struck: false, pressable: true }
47
+ : { tone: "accent", icon: "Shield", title: t("form.titleOne"), detail: data.keys[0] ?? "", struck: false, pressable: true };
74
48
  case "delivered":
75
- return { tone: "success", icon: "ShieldCheck", title: "Передано", detail: count, struck: false, pressable: false };
49
+ return { tone: "success", icon: "ShieldCheck", title: t("pill.delivered"), detail: count, struck: false, pressable: false };
76
50
  case "released":
77
- return { tone: "muted", icon: "ShieldCheck", title: "Передано", detail: count, struck: false, pressable: false };
51
+ return { tone: "muted", icon: "ShieldCheck", title: t("pill.delivered"), detail: count, struck: false, pressable: false };
78
52
  default:
79
- return { tone: "dim", icon: "ShieldX", title: ENDED_AS[data.state], detail: count, struck: true, pressable: false };
53
+ return { tone: "dim", icon: "ShieldX", title: t(`pill.${data.state}`), detail: count, struck: true, pressable: false };
80
54
  }
81
55
  }
82
56
 
@@ -1,5 +1,6 @@
1
1
  import { fromBase64Url } from "../shared/bytes";
2
2
  import { MAX_PAYLOAD_BYTES, buildAad, digestHex, seal, type SealedEnvelope } from "../shared/seal";
3
+ import type { Translate } from "./messages";
3
4
 
4
5
  /**
5
6
  * What the self-test seals: the largest submission one Paseo call can carry. It proves on this device that the biggest thing
@@ -73,24 +74,21 @@ export async function runSelfTest(deps: SelfTestDeps, bytes: number = SELF_TEST_
73
74
  }
74
75
  }
75
76
 
76
- /** What a screen reader says of the spinner that stands in the place of the result while a run is going. */
77
- export const SELF_TEST_RUNNING = "Перевірка триває";
78
-
79
77
  /**
80
78
  * What the settings screen says of a run, next to the button: how long it took, or why it did not pass, in a fixed
81
79
  * sentence and never in the words of an error. Before a run and while one is going it says nothing: the screen shows a
82
- * spinner then (`SELF_TEST_RUNNING`).
80
+ * spinner then.
83
81
  */
84
- export function selfTestText(state: SelfTestState): string {
82
+ export function selfTestText(t: Translate, state: SelfTestState): string {
85
83
  switch (state.kind) {
86
84
  case "idle":
87
85
  case "running":
88
86
  return "";
89
87
  case "passed":
90
- return `✓ ${state.ms} мс`;
88
+ return t("selfTest.passed", { ms: state.ms });
91
89
  case "mismatch":
92
- return "✗ дані не збіглися";
90
+ return t("selfTest.mismatch");
93
91
  default:
94
- return state.stage === "seal" ? "✗ не вдалося зашифрувати" : "✗ плагін не відповів";
92
+ return t(state.stage === "seal" ? "selfTest.sealFailed" : "selfTest.noAnswer");
95
93
  }
96
94
  }
@@ -1,14 +1,15 @@
1
1
  import type { PluginSurfaceProps } from "@getpaseo/plugin/client";
2
- import { useRpc } from "@getpaseo/plugin/client";
2
+ import { useRpc, useTranslation } from "@getpaseo/plugin/client";
3
3
  import { Icon, SettingsAction, SettingsCard, SettingsRow, SettingsSection } from "@getpaseo/plugin/client/ui";
4
4
  import { useQuery } from "@tanstack/react-query";
5
5
  import { useState, type ReactElement } from "react";
6
6
  import { ActivityIndicator, Text, View } from "react-native";
7
7
  import { clearDrop, readDiagnostics, selfTestBegin, selfTestFinish, type Diagnostics } from "../shared/contracts";
8
8
  import { PASEO_SINCE, PLUGIN_VERSION } from "../shared/limits";
9
- import { DELETE_ALL, DELETE_FAILED, SETTINGS_BADGE, canDeleteAll, dotColor, statusRows, type StatusRow } from "./diagnostics-rows";
9
+ import { SETTINGS_BADGE, canDeleteAll, dotColor, statusRows, type StatusRow } from "./diagnostics-rows";
10
10
  import { MONO } from "./fields";
11
- import { IDLE, RUNNING, SELF_TEST_RUNNING, runSelfTest, selfTestText, type SelfTestState } from "./self-test";
11
+ import { messages, type Translate } from "./messages";
12
+ import { IDLE, RUNNING, runSelfTest, selfTestText, type SelfTestState } from "./self-test";
12
13
  import { tone, type Tone } from "./tone";
13
14
 
14
15
  /** How often the state is read again while the screen is open: a set that arrives or goes shows without leaving the screen. */
@@ -34,7 +35,7 @@ function Header({ colors }: { colors: Tone }) {
34
35
  * submission can have. It runs on the press and not on the render. What a run comes to, and what is said of it, is
35
36
  * `self-test.ts`'s to decide; a spinner stands in the place of the result while it runs.
36
37
  */
37
- function Encryption({ colors }: { colors: Tone }) {
38
+ function Encryption({ t, colors }: { t: Translate; colors: Tone }) {
38
39
  const begin = useRpc(selfTestBegin);
39
40
  const finish = useRpc(selfTestFinish);
40
41
  const [state, setState] = useState<SelfTestState>(IDLE);
@@ -47,20 +48,20 @@ function Encryption({ colors }: { colors: Tone }) {
47
48
  }
48
49
 
49
50
  return (
50
- <SettingsSection title="Шифрування">
51
+ <SettingsSection title={t("settings.encryption")}>
51
52
  <SettingsCard>
52
53
  <View style={{ paddingHorizontal: 16, paddingVertical: 12, alignItems: "flex-start" }}>
53
54
  <View style={{ borderWidth: 1, borderColor: colors.border, borderRadius: 6, paddingHorizontal: 8, paddingVertical: 3 }}>
54
55
  <Text style={{ color: colors.accent, fontFamily: MONO, fontSize: 11 }}>{SETTINGS_BADGE}</Text>
55
56
  </View>
56
57
  </View>
57
- <SettingsAction label="Цей пристрій" actionLabel="Перевірити" disabled={running} onPress={() => void run()} />
58
+ <SettingsAction label={t("settings.thisDevice")} actionLabel={t("settings.check")} disabled={running} onPress={() => void run()} />
58
59
  {state.kind === "idle" ? null : (
59
- <SettingsRow label="Результат">
60
+ <SettingsRow label={t("settings.result")}>
60
61
  {running ? (
61
- <ActivityIndicator size="small" color={colors.muted} accessibilityLabel={SELF_TEST_RUNNING} />
62
+ <ActivityIndicator size="small" color={colors.muted} accessibilityLabel={t("selfTest.running")} />
62
63
  ) : (
63
- <Text style={{ color: state.kind === "passed" ? colors.success : colors.danger, fontFamily: MONO, fontSize: 12 }}>{selfTestText(state)}</Text>
64
+ <Text style={{ color: state.kind === "passed" ? colors.success : colors.danger, fontFamily: MONO, fontSize: 12 }}>{selfTestText(t, state)}</Text>
64
65
  )}
65
66
  </SettingsRow>
66
67
  )}
@@ -85,21 +86,21 @@ function StatusValue({ row, colors }: { row: StatusRow; colors: Tone }) {
85
86
  * The four rows. The explanation is under a red row only (`error` of the row). Read-only: the RPC behind it is open to
86
87
  * agents too. A failed reading leaves the last answer in `data`; it is shown, and said to be old, instead of passing for current.
87
88
  */
88
- function Status({ data, failed, colors }: { data: Diagnostics | undefined; failed: boolean; colors: Tone }) {
89
- const stale = <SettingsRow key="stale" label="Оновлення" error="Не вдалося оновити: показано попередній стан" />;
89
+ function Status({ t, data, failed, colors }: { t: Translate; data: Diagnostics | undefined; failed: boolean; colors: Tone }) {
90
+ const stale = <SettingsRow key="stale" label={t("settings.refresh")} error={t("settings.refreshFailed")} />;
90
91
  const rows: ReactElement[] =
91
92
  data === undefined
92
- ? [<SettingsRow key="reading" label={failed ? "Не вдалося прочитати стан плагіна" : "Завантаження…"} />]
93
+ ? [<SettingsRow key="reading" label={t(failed ? "settings.readFailed" : "settings.loading")} />]
93
94
  : [
94
95
  ...(failed ? [stale] : []),
95
- ...statusRows(data).map((row) => (
96
- <SettingsRow key={row.label} label={row.label} error={row.explanation}>
96
+ ...statusRows(t, data).map((row) => (
97
+ <SettingsRow key={row.label} label={t(row.label)} error={row.explanation}>
97
98
  <StatusValue row={row} colors={colors} />
98
99
  </SettingsRow>
99
100
  )),
100
101
  ];
101
102
  return (
102
- <SettingsSection title="Стан">
103
+ <SettingsSection title={t("settings.status")}>
103
104
  <SettingsCard>{rows}</SettingsCard>
104
105
  </SettingsSection>
105
106
  );
@@ -108,10 +109,10 @@ function Status({ data, failed, colors }: { data: Diagnostics | undefined; faile
108
109
  /**
109
110
  * Deletes every set of files at once, and reads the state again. What the plugin could not remove shows in the rows that
110
111
  * are read. When the clear call fails (the plugin is stopping, `drop/` could not be swept), earlier removals may have
111
- * succeeded; one fixed line under the button, `DELETE_FAILED`, says that it failed, until a press succeeds: the words of
112
- * the failure are not the screen's to show.
112
+ * succeeded; one fixed line under the button, `settings.deleteFailed`, says that it failed until a press succeeds. The words of the
113
+ * failure are not the screen's to show.
113
114
  */
114
- function DeleteAll({ refresh }: { refresh(): Promise<unknown> }) {
115
+ function DeleteAll({ t, refresh }: { t: Translate; refresh(): Promise<unknown> }) {
115
116
  const clear = useRpc(clearDrop);
116
117
  const [busy, setBusy] = useState(false);
117
118
  const [refused, setRefused] = useState(false);
@@ -137,13 +138,14 @@ function DeleteAll({ refresh }: { refresh(): Promise<unknown> }) {
137
138
  return (
138
139
  <View style={{ marginTop: 12 }}>
139
140
  <SettingsCard>
140
- <SettingsAction label={DELETE_ALL} actionLabel="Видалити" error={refused ? DELETE_FAILED : null} disabled={busy} onPress={() => void run()} />
141
+ <SettingsAction label={t("settings.deleteAll")} actionLabel={t("settings.delete")} error={refused ? t("settings.deleteFailed") : null} disabled={busy} onPress={() => void run()} />
141
142
  </SettingsCard>
142
143
  </View>
143
144
  );
144
145
  }
145
146
 
146
147
  export function SettingsScreen({ theme }: PluginSurfaceProps) {
148
+ const { t } = useTranslation(messages);
147
149
  const colors = tone(theme.colors);
148
150
  const read = useRpc(readDiagnostics);
149
151
  const query = useQuery({ queryKey: ["secure-input", "diagnostics"], queryFn: () => read({}), refetchInterval: REFRESH_MS });
@@ -152,9 +154,9 @@ export function SettingsScreen({ theme }: PluginSurfaceProps) {
152
154
  return (
153
155
  <>
154
156
  <Header colors={colors} />
155
- <Encryption colors={colors} />
156
- <Status data={data} failed={query.isError} colors={colors} />
157
- {data !== undefined && canDeleteAll(data) ? <DeleteAll refresh={() => query.refetch()} /> : null}
157
+ <Encryption t={t} colors={colors} />
158
+ <Status t={t} data={data} failed={query.isError} colors={colors} />
159
+ {data !== undefined && canDeleteAll(data) ? <DeleteAll t={t} refresh={() => query.refetch()} /> : null}
158
160
  </>
159
161
  );
160
162
  }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "paseo-plugin-secure-input",
3
- "version": "0.2.2",
3
+ "version": "0.4.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "paseo-plugin-secure-input",
9
- "version": "0.2.2",
9
+ "version": "0.4.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@noble/ciphers": "2.4.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "paseo-plugin-secure-input",
3
- "version": "0.2.2",
3
+ "version": "0.4.0",
4
4
  "description": "Secure secret input for Paseo agents: a typed value or a whole file travels sealed to the daemon and lands in a short-lived file; the agent gets its path, never the value",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -40,19 +40,20 @@
40
40
  "@noble/hashes": "2.4.0"
41
41
  },
42
42
  "devDependencies": {
43
- "@getpaseo/client": "0.14.0-beta.1",
44
- "@getpaseo/plugin": "0.14.0-beta.1",
45
- "@getpaseo/protocol": "0.14.0-beta.1",
46
- "@getpaseo/relay": "0.14.0-beta.1",
43
+ "@getpaseo/client": "0.15.0",
44
+ "@getpaseo/plugin": "0.15.0",
45
+ "@getpaseo/protocol": "0.15.0",
46
+ "@getpaseo/relay": "0.15.0",
47
47
  "@modelcontextprotocol/sdk": "1.32.2",
48
48
  "@tanstack/react-query": "^5.105.0",
49
49
  "@types/node": "^22.0.0",
50
50
  "@types/react": "~19.2.0",
51
51
  "react": "19.1.0",
52
52
  "react-native": "0.81.5",
53
- "semver": "7.8.5",
53
+ "semver": "7.8.6",
54
54
  "typescript": "^7.0.2",
55
55
  "typescript-5": "npm:typescript@5.9.3",
56
+ "vite": "8.3.6",
56
57
  "vitest": "^5.0.5",
57
58
  "zod": "^4.6.7"
58
59
  },
package/paseo-plugin.json CHANGED
@@ -2,5 +2,5 @@
2
2
  "id": "secure-input",
3
3
  "description": "Agents ask for secrets through a form; each value or file lands in a short-lived file the agent moves without reading it",
4
4
  "icon": "assets/icon.png",
5
- "requirements": { "paseo": ">=0.14.0-beta.1" }
5
+ "requirements": { "paseo": ">=0.15.0" }
6
6
  }
@@ -86,7 +86,7 @@ function deliveredText(head: string, record: RequestRecord, drop: string): strin
86
86
  "The values were not shown to you. Never let the content of a file or directory whose name starts with si-secret- reach you: do not read, print, open, compare or log it, and do not pass it as an argument.",
87
87
  "Move each value where it is needed only by redirection or by copy, for example `command < PATH` or `cp PATH DESTINATION`.",
88
88
  `Then delete the directory (\`rm -r ${shellPath(setPath(drop, record.id))}\`) or call release_secret.`,
89
- `The files are deleted at the end of the turn this message starts, and at ${new Date(deleteBy).toISOString()} at the latest.`,
89
+ `The files are deleted at the end of the turn this message starts, or at the end of your next turn if it joins a running turn, and at ${new Date(deleteBy).toISOString()} at the latest.`,
90
90
  ].join("\n");
91
91
  }
92
92
 
@@ -103,6 +103,8 @@ export interface OutboxOptions {
103
103
  * with changes nothing here: the send is attempted all the same.
104
104
  */
105
105
  onSend?(item: OutboxItem): void;
106
+ /** Told of an item whose send was refused within its bound; not of one that went unanswered. What it does, throws or rejects with changes nothing here. */
107
+ onSendFailed?(item: OutboxItem): void;
106
108
  }
107
109
 
108
110
  const ItemSchema = z
@@ -224,6 +226,7 @@ export class Outbox {
224
226
  private readonly portTimeoutMs: number;
225
227
  private readonly flushBudgetMs: number;
226
228
  private readonly onSend: ((item: OutboxItem) => void) | undefined;
229
+ private readonly onSendFailed: ((item: OutboxItem) => void) | undefined;
227
230
 
228
231
  constructor(
229
232
  private readonly file: string,
@@ -234,6 +237,7 @@ export class Outbox {
234
237
  this.portTimeoutMs = options.portTimeoutMs ?? PORT_TIMEOUT_MS;
235
238
  this.flushBudgetMs = options.flushBudgetMs ?? FLUSH_BUDGET_MS;
236
239
  this.onSend = options.onSend;
240
+ this.onSendFailed = options.onSendFailed;
237
241
  }
238
242
 
239
243
  private serial<T>(task: () => Promise<T>): Promise<T> {
@@ -402,6 +406,16 @@ export class Outbox {
402
406
  }
403
407
  }
404
408
 
409
+ /** Tells `onSendFailed` of an item whose send failed. Never throws, and leaves no rejection of an async one unhandled. */
410
+ private tellSendFailed(item: OutboxItem): void {
411
+ try {
412
+ const result: unknown = this.onSendFailed?.({ agentId: item.agentId, requestId: item.requestId, kind: item.kind });
413
+ if (typeof (result as PromiseLike<unknown> | undefined)?.then === "function") (result as PromiseLike<unknown>).then(undefined, () => undefined);
414
+ } catch {
415
+ // What whoever is told does with it changes nothing: the message is not sent again either way.
416
+ }
417
+ }
418
+
405
419
  /** The text for an item, or null: no record, nothing to say, another agent's record, or a resolver that fails. */
406
420
  private text(item: OutboxItem): string | null {
407
421
  try {
@@ -547,6 +561,7 @@ export class Outbox {
547
561
  await this.ask(() => port.send(item.agentId, text));
548
562
  } catch {
549
563
  // The send failed. Whether the agent got the message is not known, and it is not sent again.
564
+ this.tellSendFailed(item);
550
565
  }
551
566
  // No answer in time is an unknown outcome: the item is already out, and is not sent again either.
552
567
  return;
@@ -36,11 +36,12 @@ export type ExpiredBy = (typeof EXPIRED_BY)[number];
36
36
 
37
37
  /**
38
38
  * How the files of a delivered request came to be gone, and so the request `released`: the agent released them or took
39
- * the set away itself (`agent`), the turn the delivery message started ended (`turn`), their time was up (`time`), the
40
- * plugin started again (`restart`) or stopped (`stop`), or the human deleted every set (`human`). A delivery message
41
- * that still waits says the files are gone for the last four, and is dropped for the first two (see `continuationText`).
39
+ * the set away itself (`agent`), the turn the delivery message started ended (`turn`), the agent was archived (`archived`),
40
+ * their time was up (`time`), the plugin started again (`restart`) or stopped (`stop`), or the human deleted every set
41
+ * (`human`). A delivery message that still waits says the files are gone for the last four, and is dropped for the first
42
+ * three (see `continuationText`).
42
43
  */
43
- export const RELEASED_BY = ["agent", "turn", "time", "restart", "stop", "human"] as const;
44
+ export const RELEASED_BY = ["agent", "turn", "archived", "time", "restart", "stop", "human"] as const;
44
45
  export type ReleasedBy = (typeof RELEASED_BY)[number];
45
46
 
46
47
  /** The keys a set was written with, in the order they were written: valid keys, of which no two name one file. */
@@ -777,6 +777,16 @@ export class Registry {
777
777
  this.turns.set(requestId, "sent");
778
778
  }
779
779
 
780
+ /**
781
+ * The send `messageSent` announced failed, so no turn is known to be the one the message starts, and a later turn of the
782
+ * agent must not take a set it was never told of. The mark goes, armed or not, and the set stays for the agent to ask
783
+ * after (`request_status`) until its deadline. A request that is no longer delivered, and an unknown one, are left alone.
784
+ */
785
+ messageSendFailed(requestId: string): void {
786
+ if (this.records.get(requestId)?.state !== "delivered") return;
787
+ this.turns.delete(requestId);
788
+ }
789
+
780
790
  /**
781
791
  * A turn of the agent began. Each of its requests whose message was handed over before this is armed: the end of this
782
792
  * turn takes its set. A request whose message is handed over later waits for a turn that begins after that, so a late
@@ -792,7 +802,8 @@ export class Registry {
792
802
  * A turn of the agent ended, with whatever outcome. The requests of that agent that are armed are taken now, as the
793
803
  * turn ends, and their sets are released in the queue as `turn` (as whoever took it, `takenBy`, for a set that is gone
794
804
  * by then), each that is still delivered. Taken now, and not when the queue comes to it: a request armed while this
795
- * waits in the queue was armed by a turn that began after this one, and its set is that turn's. A set that is stuck
805
+ * waits in the queue was armed by a turn that began after this one, and its set is that turn's; a set whose send was
806
+ * refused meanwhile has lost its mark and stays (`messageSendFailed`). A set that is stuck
796
807
  * keeps its mark, and the end of the next turn tries again. Once shutdown has begun no further set is released here
797
808
  * (the stop takes them); a removal that was already under way then reads a set its sweep took as the stop's.
798
809
  */
@@ -803,7 +814,24 @@ export class Registry {
803
814
  // For each request, as the tick does: the stop can begin while one of them is removed.
804
815
  if (this.stopped) return;
805
816
  const record = this.records.get(id);
806
- if (record?.state === "delivered") await this.releaseSet(record, "turn");
817
+ // A send refused while this waited took the mark away (`messageSendFailed`): the agent was never told of the set.
818
+ if (record?.state === "delivered" && this.turns.get(id) === "armed") await this.releaseSet(record, "turn");
819
+ }
820
+ });
821
+ }
822
+
823
+ /**
824
+ * The agent was archived. Its pending requests close as `cancelled`, which wipes their keys, and its delivered sets are
825
+ * released as `archived`, with no message for either. A set that cannot be removed stays delivered and is tried again
826
+ * like any other. Once shutdown has begun nothing further is closed here: the stop takes it.
827
+ */
828
+ agentArchived(agentId: string): Promise<void> {
829
+ return this.serial(async () => {
830
+ for (const record of [...this.records.values()]) {
831
+ if (this.stopped) return;
832
+ if (record.agentId !== agentId) continue;
833
+ if (record.state === "pending") await this.closePending(record.id, "cancelled");
834
+ else if (record.state === "delivered") await this.releaseSet(record, "archived");
807
835
  }
808
836
  });
809
837
  }
@@ -1,16 +1,16 @@
1
- import type { AgentToolDefinition, PluginBeforeRequests, PluginServerContext } from "@getpaseo/plugin/server";
1
+ import type { AgentToolDefinition, PluginHookRequests, PluginServerContext } from "@getpaseo/plugin/server";
2
2
  import { SecureInputError } from "../../shared/errors";
3
3
  import type { Registry } from "../core/registry";
4
4
  import { within } from "./bounded";
5
5
  import type { Runtime } from "./runtime";
6
6
  import { TOOL_NAMES } from "./tools";
7
7
 
8
- export type SessionOpenRequest = PluginBeforeRequests["agent.session_open"];
8
+ export type SessionOpenRequest = PluginHookRequests["agent.open.before"];
9
9
 
10
10
  /**
11
- * How long the handler of a turn's end waits at most for the sets that turn releases (`Registry.turnEnded`). Removing a
12
- * set is a few system calls; the bound is for a disk that stalls, and it ends the wait, not the removal, which goes on
13
- * in the registry's queue. Five seconds keeps an event handler that the daemon waits for from being held for longer.
11
+ * How long the handler of a turn's end, or of an agent's archiving, waits at most for what it closes (`Registry.turnEnded`,
12
+ * `Registry.agentArchived`). Removing a set is a few system calls; the bound is for a disk that stalls, and it ends the
13
+ * wait, not the removal, which goes on in the registry's queue. Five seconds keeps an event handler that the daemon waits for from being held for longer.
14
14
  */
15
15
  export const RELEASE_WAIT_MS = 5_000;
16
16
 
@@ -29,8 +29,8 @@ export function withTools(request: SessionOpenRequest, tools: readonly AgentTool
29
29
 
30
30
  export interface HookDeps {
31
31
  runtime: Pick<Runtime, "attach" | "turnEnded" | "agentArchived">;
32
- /** What a turn's start and end do to the sets of the agent's delivered requests: they arm the deletion, and fire it. */
33
- turns: Pick<Registry, "turnStarted" | "turnEnded">;
32
+ /** What a turn's start and end do to the sets of the agent's delivered requests (they arm the deletion, and fire it), and what its archiving does to its open requests. */
33
+ turns: Pick<Registry, "turnStarted" | "turnEnded" | "agentArchived">;
34
34
  /** The plugin's tools, built for the session that opens. One that cannot be built is a failure of the hook. */
35
35
  tools(): AgentToolDefinition[];
36
36
  /** Remembers, for the diagnostics, that a hook or an event handler failed. A code, never a message. */
@@ -46,61 +46,67 @@ export function failureCode(error: unknown): string {
46
46
 
47
47
  /**
48
48
  * The daemon runs the `before` hooks inside the opening of an agent's session: a throw from one fails that opening (0.14
49
- * passes it on as "Plugin … before agent.session_open failed"), and it gives a hook 30 seconds. So nothing here can
49
+ * passes it on as "Plugin … before agent.open.before failed"), and it gives a hook 30 seconds. So nothing here can
50
50
  * reject, and the session-open hook waits for nothing: it builds the tools and hands them over, and a call waits for the
51
51
  * start-up itself (`agentTools`). Any failure of the hook (tools that cannot be built, a payload that is not what the SDK
52
52
  * declares) is remembered as a code, and the request goes on as it came. The handlers of events are held to the same
53
- * rule, which the daemon only logs for; the one handler that waits, a turn's end for the sets it releases, waits within
53
+ * rule, which the daemon only logs for; the two handlers that wait, a turn's end and an agent's archiving, wait within
54
54
  * `RELEASE_WAIT_MS`.
55
55
  */
56
- export function registerHooks(host: Pick<PluginServerContext, "before" | "on">, deps: HookDeps): void {
57
- host.before("agent.session_open", ({ request }, { paseo }) => {
56
+ export function registerHooks(host: Pick<PluginServerContext, "addHook">, deps: HookDeps): void {
57
+ host.addHook("agent.open.before", async ({ request }, { paseo }) => {
58
58
  try {
59
59
  deps.runtime.attach(paseo);
60
60
  return withTools(request, deps.tools());
61
61
  } catch (error) {
62
- deps.failed("agent.session_open", failureCode(error));
62
+ deps.failed("agent.open.before", failureCode(error));
63
63
  return request;
64
64
  }
65
65
  });
66
66
 
67
67
  // A turn began: a delivered request whose message was handed over before it is armed, and the end of this turn takes
68
68
  // its set (`Registry.turnStarted`). The event is read inside the guard: a payload without an agent is a failure.
69
- host.on("agent.turn_started", (event, { paseo }) => {
69
+ host.addHook("agent.turn.before", async (event, { paseo }) => {
70
70
  try {
71
71
  deps.runtime.attach(paseo);
72
72
  deps.turns.turnStarted(event.agent.id);
73
73
  } catch (error) {
74
- deps.failed("agent.turn_started", failureCode(error));
74
+ deps.failed("agent.turn.before", failureCode(error));
75
75
  }
76
76
  });
77
77
 
78
78
  // A turn ended, with any outcome. First the sets it releases, waited for within `RELEASE_WAIT_MS`: a wait that runs out
79
79
  // is no failure, and the removal goes on in the registry. Then what waits for the agent is asked for, also when the
80
80
  // releases failed: a message is never held back by them.
81
- host.on("agent.turn_ended", async (event, { paseo }) => {
81
+ host.addHook("agent.turn.after", async (event, { paseo }) => {
82
82
  try {
83
83
  deps.runtime.attach(paseo);
84
84
  const agentId = event.agent.id;
85
85
  try {
86
86
  await within(deps.releaseWaitMs ?? RELEASE_WAIT_MS, () => deps.turns.turnEnded(agentId));
87
87
  } catch (error) {
88
- deps.failed("agent.turn_ended", failureCode(error));
88
+ deps.failed("agent.turn.after", failureCode(error));
89
89
  }
90
90
  deps.runtime.turnEnded(agentId);
91
91
  } catch (error) {
92
- deps.failed("agent.turn_ended", failureCode(error));
92
+ deps.failed("agent.turn.after", failureCode(error));
93
93
  }
94
94
  });
95
95
 
96
- // An archived agent is gone for good, so what waits for it is dropped. `agent.closed` is deliberately not used for
97
- // this: what "closed" means for an agent that can be opened again could not be established.
98
- host.on("agent.archived", ({ agent }, { paseo }) => {
96
+ // An archived agent has no use for what it asked for, so its requests close and what waits for it is dropped. `agent.closed`
97
+ // is deliberately not used for this: what "closed" means for an agent that can be opened again could not be established.
98
+ host.addHook("agent.archive.after", async (event, { paseo }) => {
99
99
  try {
100
100
  deps.runtime.attach(paseo);
101
- deps.runtime.agentArchived(agent.id);
101
+ const agentId = event.agent.id;
102
+ try {
103
+ await within(deps.releaseWaitMs ?? RELEASE_WAIT_MS, () => deps.turns.agentArchived(agentId));
104
+ } catch (error) {
105
+ deps.failed("agent.archive.after", failureCode(error));
106
+ }
107
+ deps.runtime.agentArchived(agentId);
102
108
  } catch (error) {
103
- deps.failed("agent.archived", failureCode(error));
109
+ deps.failed("agent.archive.after", failureCode(error));
104
110
  }
105
111
  });
106
112
  }
@@ -19,7 +19,7 @@ import { Runtime, SETTLE_BOUND_MS } from "./runtime";
19
19
  import { agentTools } from "./tools";
20
20
 
21
21
  /** The parts of the server context the plugin uses. */
22
- export type PluginHost = Pick<PluginServerContext, "handle" | "before" | "on">;
22
+ export type PluginHost = Pick<PluginServerContext, "handle" | "addHook">;
23
23
 
24
24
  /**
25
25
  * What the plugin runs in. Under plain Node the shim v1 left is pointed at `execPath`, which runs the stub in place of
@@ -171,6 +171,9 @@ export function assemble(options: PluginOptions): Parts {
171
171
  onSend: (item) => {
172
172
  if (item.kind === "continuation") registry.messageSent(item.requestId);
173
173
  },
174
+ onSendFailed: (item) => {
175
+ if (item.kind === "continuation") registry.messageSendFailed(item.requestId);
176
+ },
174
177
  });
175
178
  const runtime: Runtime = new Runtime(outbox, { callTimeoutMs: options.daemonCallTimeoutMs, report });
176
179
  const registry: Registry = new Registry({
@@ -50,7 +50,7 @@ const NOT_ATTACHED = "the plugin is not attached to the daemon yet; retry in a f
50
50
  export interface DaemonAgent {
51
51
  readonly status: string | null;
52
52
  refresh(): Promise<unknown>;
53
- send(text: string): Promise<void>;
53
+ send(text: string, options: { activeTurnBehavior: "steer" }): Promise<void>;
54
54
  readonly timeline: { append(item: TimelineItem): Promise<unknown> };
55
55
  }
56
56
 
@@ -230,7 +230,8 @@ export class Runtime implements AgentPort {
230
230
  }
231
231
 
232
232
  async send(agentId: string, text: string): Promise<void> {
233
- await this.api().agents.ref(agentId).send(text);
233
+ // A turn can begin after the idle check. Unasked, the daemon replaces it; a provider that can steer takes the message into it.
234
+ await this.api().agents.ref(agentId).send(text, { activeTurnBehavior: "steer" });
234
235
  }
235
236
 
236
237
  /**