paseo-quick-prompts 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kingsley
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/OVERVIEW.md ADDED
@@ -0,0 +1,22 @@
1
+ Quick prompts turns the messages you send often into pills above every agent's composer. Tap a pill and its text goes to that agent as your next message, the same as typing it and pressing send. If you prefer a tidier composer, show them all in one **Prompts** pill that opens a menu instead.
2
+
3
+ Use it for prompts you repeat across agents, such as "Review the uncommitted changes", "Run the tests and fix failures", or "Summarize what changed and open a PR".
4
+
5
+ ## Settings
6
+
7
+ Quick prompts needs Paseo 0.11.0 or later, with plugins enabled.
8
+
9
+ Open **Settings → Plugins → paseo-quick-prompts → Quick prompts** to add, edit, reorder, and delete prompts and to choose how they appear. Each one has a label, shown on the pill or menu item, and the prompt text that is sent. Changes save automatically: deleting, reordering, and the display option save right away, and an edited label or prompt saves when you leave the field. New prompts go in the last row and are added with **Add**. If another device deletes a prompt you were editing, your text stays on the page so you can copy it.
10
+
11
+ - Up to 20 prompts. Labels can be up to 40 characters.
12
+ - **Show prompts as** picks **Separate pills** (the default) or **One menu pill**. Either way, prompts follow the order of the list, on every agent that belongs to a workspace. The menu also has a **Manage prompts** item that opens the settings page.
13
+ - With no prompts saved, each agent shows an **Add quick prompt** pill that opens the settings page.
14
+
15
+ The settings page also has a tip with a prompt you can copy and send to an agent, which reads your Paseo agent history and suggests the quick prompts you would use most.
16
+
17
+ Prompts are stored on the Paseo host and shared by every app connected to it.
18
+
19
+ ## Limits
20
+
21
+ - A pill sends right away. It does not put the text in the composer for editing first.
22
+ - Pills appear on existing agents, not in the composer for a new agent.
package/README.md CHANGED
@@ -1,3 +1,111 @@
1
- # Temporary Holding Version
1
+ # paseo-quick-prompts
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Saved prompts as one-tap pills above every agent's composer in [Paseo](https://github.com/getpaseo/paseo).**
4
+
5
+ Save the messages you send often, like "Review the uncommitted changes" or "Run the tests and fix
6
+ failures". Each one becomes a pill above every agent's composer; tapping it sends the prompt to that
7
+ agent as a normal user message.
8
+
9
+ ## Features
10
+
11
+ - **One pill per prompt** on every agent with a workspace, in the order you set, or **one menu
12
+ pill** (Prompts) that lists them all with a **Manage prompts** shortcut.
13
+ - **Settings screen** under **Settings → Plugins → paseo-quick-prompts → Quick prompts** to add, edit, reorder, and delete
14
+ prompts and choose how they appear. Changes save automatically.
15
+ - **Prompt ideas.** A copyable prompt on the settings screen asks an agent to read your Paseo agent
16
+ history and suggest the quick prompts you would use most.
17
+ - **Shared per host.** Prompts are stored on the daemon and every connected app sees the same list;
18
+ pills update live when it changes.
19
+ - **Empty state.** With no prompts saved, each agent shows an **Add quick prompt** pill that opens
20
+ the settings screen.
21
+
22
+ ## Requirements
23
+
24
+ - Paseo **0.11.0** or later, with plugins enabled (**Settings → Plugins → Enable plugins**, or
25
+ `"pluginsEnabled": true` in `~/.paseo/config.json`)
26
+
27
+ ## Install
28
+
29
+ ```bash
30
+ paseo plugin install npm:paseo-quick-prompts
31
+ ```
32
+
33
+ You can also paste `npm:paseo-quick-prompts` into **Settings → Plugins → Plugin source**, or install
34
+ the latest source with `paseo plugin install github:kingsleydon/paseo-plugins:plugins/quick-prompts`.
35
+
36
+ ## Settings
37
+
38
+ | Field | Limit | Description |
39
+ |---|---|---|
40
+ | Label | 1–40 characters | Text on the pill |
41
+ | Prompt | 1–10,000 characters | Message sent to the agent |
42
+
43
+ Up to 20 prompts. Leading and trailing whitespace is trimmed when you save.
44
+
45
+ Each prompt is one compact row: label, prompt text (which grows to five lines, then scrolls), and
46
+ move up, move down, and delete buttons. Moving, deleting, and **Show prompts as** save right away.
47
+ An edited label or prompt saves when the field loses focus, if it is valid; an invalid value shows
48
+ an error under the field and is not saved. New prompts go in the last row and are saved with
49
+ **Add**. The section header shows **Saving…**, **Saved**, or **Not saved** for the latest save.
50
+
51
+ Saves go to the host one at a time, each applied to the latest prompts. If another app saved in the
52
+ meantime, the change is applied to its prompts and saved again once; when it no longer applies, a
53
+ toast says so and the latest prompts are shown. Text you are typing is never replaced by another
54
+ app's save. If another app deletes a prompt you were editing, your text stays in an **Unsaved
55
+ edits** card with **Copy** and **Dismiss**.
56
+
57
+ **Show prompts as** is **Separate pills** (default) or **One menu pill**. Settings saved before this
58
+ option existed keep separate pills.
59
+
60
+ ## How it works
61
+
62
+ - The settings document (`prompts`, host scope) is registered by the daemon entry and stored by Paseo.
63
+ - The app entry follows the agent directory with an owned list subscription, loading every page of
64
+ agents, and re-reads the prompts whenever any client saves them, then keeps one composer pill per
65
+ prompt (or one menu pill) on each non-archived agent that has a workspace. Prompt changes update
66
+ existing pills in place; a reorder of separate pills or a display switch re-registers that agent's
67
+ pills. A failed observation starts again after 1, 5, 15, and 60 seconds, then stops.
68
+ - A pill press or menu choice calls `paseo.agents.ref(agentId).send(text)`. Paseo shows the pill as busy until the
69
+ send settles and reports failures in a toast. A prompt is not sent to the same agent again while its
70
+ previous send is pending.
71
+
72
+ Not supported: pills in the new-agent composer, inserting text into the composer for editing, and
73
+ import or export.
74
+
75
+ ## Development
76
+
77
+ ```bash
78
+ npm install
79
+ npm run typecheck
80
+ npm test
81
+ paseo plugin install "$PWD"
82
+ paseo plugin reload paseo-quick-prompts # after changes
83
+ paseo plugin logs paseo-quick-prompts
84
+ ```
85
+
86
+ | Path | Contents |
87
+ |---|---|
88
+ | `index.server.ts` | Daemon entry: registers the settings document |
89
+ | `index.client.tsx` | App entry: settings screen and composer pills |
90
+ | `client/pills.ts` | Keeps each agent's pills in sync with the saved prompts |
91
+ | `client/follow.ts` | Follows the agent directory and settings changes |
92
+ | `client/settings-screen.tsx` | Autosaving editor for the prompts and display option, and the prompt-ideas tip |
93
+ | `client/autosave.ts` | Save queue for the settings screen: latest values, typed drafts, the new-prompt form, conflict retry |
94
+ | `client/edits.ts` | Prompt edits applied to the latest values |
95
+ | `shared/prompts.ts` | Settings schema and limits |
96
+
97
+ ## Releasing
98
+
99
+ Bump `version` in `package.json` and the two root `version` fields in `package-lock.json` in a PR
100
+ (`npm version <version> --no-git-tag-version` does both), merge it, then tag the merged commit with
101
+ `quick-prompts-v<version>`:
102
+
103
+ ```bash
104
+ git tag quick-prompts-v<version> && git push origin quick-prompts-v<version>
105
+ ```
106
+
107
+ See the [repository README](../../README.md#releasing) for how the publish workflow works.
108
+
109
+ ## License
110
+
111
+ [MIT](LICENSE)
@@ -0,0 +1,267 @@
1
+ import type { RpcInput, RpcOutput } from "@getpaseo/plugin";
2
+ import { newPromptId, QuickPromptSchema, quickPromptsSettings } from "../shared/prompts";
3
+ import { addPrompt, applyEdit, deletePrompt, settingsContract, updatePrompt, type Edit, type SettingsDoc } from "./edits";
4
+
5
+ export type Field = "label" | "text";
6
+
7
+ /** Text typed into a saved prompt's field that the saved prompt does not have yet. */
8
+ export interface Draft {
9
+ promptId: string;
10
+ field: Field;
11
+ text: string;
12
+ /**
13
+ * The latest save of this field that is queued or in flight. Its token tells its response apart
14
+ * from earlier saves of the same text; its text keeps the same text from being sent twice.
15
+ */
16
+ pending: { token: number; text: string } | null;
17
+ /** Set when the field loses focus with text that cannot be saved. */
18
+ showError: boolean;
19
+ }
20
+
21
+ export interface AutosaveState {
22
+ doc: SettingsDoc;
23
+ /** By `draftKey`. */
24
+ drafts: ReadonlyMap<string, Draft>;
25
+ /** Prompts with a delete queued or in flight. */
26
+ deleting: ReadonlySet<string>;
27
+ /** The form for a new prompt; `showErrors` is set by an Add with text that cannot be saved. */
28
+ newPrompt: { label: string; text: string; showErrors: boolean };
29
+ adding: boolean;
30
+ saving: boolean;
31
+ /** How the latest save that reached the host ended. */
32
+ last: "saved" | "failed" | null;
33
+ }
34
+
35
+ /** `unchanged`: nothing to send. `stale`: another client's change got there first and this one no longer applies. */
36
+ export type SaveResult = "saved" | "unchanged" | "stale" | "failed";
37
+
38
+ export interface SettingsIo {
39
+ write(input: RpcInput<typeof settingsContract.write>): Promise<RpcOutput<typeof settingsContract.write>>;
40
+ read(): Promise<RpcOutput<typeof settingsContract.read>>;
41
+ }
42
+
43
+ export interface Autosave {
44
+ getState(): AutosaveState;
45
+ subscribe(listener: () => void): () => void;
46
+ /** Another client may have saved: read again once earlier work is done. */
47
+ refresh(): void;
48
+ /** Saves one change, applied to the latest values when its turn comes. */
49
+ save(edit: Edit): Promise<SaveResult>;
50
+ setDraft(promptId: string, field: Field, text: string): void;
51
+ /** The field lost focus: save its text if it is valid and not already on its way. */
52
+ submit(promptId: string, field: Field): void;
53
+ remove(promptId: string): Promise<SaveResult>;
54
+ setNewPrompt(field: Field, text: string): void;
55
+ /** Adds the new prompt form's prompt; resolves `unchanged` when it cannot be saved or is already adding. */
56
+ add(): Promise<SaveResult>;
57
+ /** Forgets drafts whose prompt no longer exists. */
58
+ dismissOrphans(): void;
59
+ /** Submits every draft that can save; returns how many drafts cannot. */
60
+ flush(): number;
61
+ }
62
+
63
+ export interface AutosaveOptions {
64
+ io: SettingsIo;
65
+ onProblem(problem: "stale" | "failed", error?: unknown): void;
66
+ }
67
+
68
+ export const draftKey = (promptId: string, field: Field): string => `${promptId}:${field}`;
69
+
70
+ const hasPrompt = (doc: SettingsDoc, promptId: string): boolean =>
71
+ doc.values.prompts.some((prompt) => prompt.id === promptId);
72
+
73
+ /** Drafts whose prompt is gone, for example deleted on another device. */
74
+ export function orphanedDrafts(state: AutosaveState): Draft[] {
75
+ return [...state.drafts.values()].filter(
76
+ (draft) => !state.deleting.has(draft.promptId) && !hasPrompt(state.doc, draft.promptId),
77
+ );
78
+ }
79
+
80
+ const parseField = (field: Field, text: string) => QuickPromptSchema.shape[field].safeParse(text);
81
+
82
+ /**
83
+ * Owns the latest known settings document and saves changes to it one at a time. Reads and writes
84
+ * share one queue, so a response always describes the document at least as new as the previous
85
+ * one. Revisions are content hashes and can repeat, so they are only sent back, never compared.
86
+ *
87
+ * A factory rather than a class: Hermes rejects class syntax in plugin client bundles.
88
+ */
89
+ export function createAutosave(initial: SettingsDoc, { io, onProblem }: AutosaveOptions): Autosave {
90
+ let state: AutosaveState = {
91
+ doc: initial,
92
+ drafts: new Map(),
93
+ deleting: new Set(),
94
+ newPrompt: { label: "", text: "", showErrors: false },
95
+ adding: false,
96
+ saving: false,
97
+ last: null,
98
+ };
99
+ const listeners = new Set<() => void>();
100
+ let queue: Promise<unknown> = Promise.resolve();
101
+ /** Counts change notifications; `readAt` is the count when the latest successful read started. */
102
+ let notified = 0;
103
+ let readAt = 0;
104
+ let submissions = 0;
105
+
106
+ const set = (patch: Partial<AutosaveState>): void => {
107
+ state = { ...state, ...patch };
108
+ for (const listener of listeners) listener();
109
+ };
110
+ const setDoc = (doc: SettingsDoc): void => set({ doc });
111
+
112
+ const enqueue = <T>(task: () => Promise<T>): Promise<T> => {
113
+ const run = queue.then(task);
114
+ queue = run.catch(() => undefined);
115
+ return run;
116
+ };
117
+
118
+ const read = async (): Promise<void> => {
119
+ const startedAt = notified;
120
+ const result = await io.read();
121
+ const parsed = result.status === "ready" ? quickPromptsSettings.schema.safeParse(result.values) : undefined;
122
+ if (!parsed?.success) throw new Error("The saved quick prompts cannot be read");
123
+ readAt = startedAt;
124
+ setDoc({ values: parsed.data, revision: result.revision });
125
+ };
126
+
127
+ /** Applies `edit` to the latest values and writes it, reading and retrying once after a conflict. */
128
+ const write = async (edit: Edit): Promise<SaveResult> => {
129
+ for (let attempt = 0; ; attempt += 1) {
130
+ const values = applyEdit(edit, state.doc.values);
131
+ if (!values) return attempt === 0 ? "unchanged" : "stale";
132
+ if (JSON.stringify(values) === JSON.stringify(state.doc.values)) return "unchanged";
133
+ const startedAt = notified;
134
+ set({ saving: true });
135
+ const result = await io.write({ revision: state.doc.revision, values });
136
+ if (result.status === "saved") {
137
+ const saved = { values: quickPromptsSettings.schema.parse(result.values), revision: result.revision };
138
+ // Another client saved while this write was in flight: show the latest, not this older result.
139
+ if (notified === startedAt) setDoc(saved);
140
+ else await read().catch(() => setDoc(saved));
141
+ return "saved";
142
+ }
143
+ if (result.status === "invalid") throw new Error(result.error);
144
+ await read();
145
+ if (attempt === 1) return "stale";
146
+ }
147
+ };
148
+
149
+ const save = (edit: Edit): Promise<SaveResult> =>
150
+ enqueue(async () => {
151
+ let result: SaveResult;
152
+ try {
153
+ result = await write(edit);
154
+ } catch (error) {
155
+ result = "failed";
156
+ onProblem("failed", error);
157
+ }
158
+ if (result === "stale") onProblem("stale");
159
+ const last = result === "saved" ? "saved" : result === "unchanged" ? state.last : "failed";
160
+ set({ saving: false, last });
161
+ return result;
162
+ });
163
+
164
+ const setDraftEntry = (key: string, draft: Draft | null): void => {
165
+ const drafts = new Map(state.drafts);
166
+ if (draft) drafts.set(key, draft);
167
+ else drafts.delete(key);
168
+ set({ drafts });
169
+ };
170
+
171
+ const submit = (promptId: string, field: Field): void => {
172
+ const key = draftKey(promptId, field);
173
+ const draft = state.drafts.get(key);
174
+ if (!draft || draft.pending?.text === draft.text) return;
175
+ const parsed = parseField(field, draft.text);
176
+ if (!parsed.success) {
177
+ setDraftEntry(key, { ...draft, showError: true });
178
+ return;
179
+ }
180
+ const text = draft.text;
181
+ const token = ++submissions;
182
+ setDraftEntry(key, { ...draft, pending: { token, text }, showError: false });
183
+ void save(updatePrompt(promptId, field, parsed.data)).then((result) => {
184
+ const current = state.drafts.get(key);
185
+ // A later save of this field decides what happens to the draft.
186
+ if (current?.pending?.token !== token) return undefined;
187
+ const next = new Map(state.drafts);
188
+ const stored = result === "saved" || (result === "unchanged" && hasPrompt(state.doc, promptId));
189
+ // Saved as typed: a later change from another client wins. Otherwise a later blur may send it again.
190
+ if (stored && current.text === text) next.delete(key);
191
+ else next.set(key, { ...current, pending: null });
192
+ set({ drafts: next });
193
+ return undefined;
194
+ });
195
+ };
196
+
197
+ return {
198
+ getState: () => state,
199
+ subscribe(listener) {
200
+ listeners.add(listener);
201
+ return () => listeners.delete(listener);
202
+ },
203
+ refresh() {
204
+ const at = ++notified;
205
+ void enqueue(async () => {
206
+ // A read that started after this notification already brought the latest values.
207
+ if (readAt >= at) return;
208
+ await read().catch((error: unknown) => console.error("[paseo-quick-prompts] failed to read quick prompts", error));
209
+ });
210
+ },
211
+ save,
212
+ setDraft(promptId, field, text) {
213
+ const key = draftKey(promptId, field);
214
+ const draft = state.drafts.get(key);
215
+ setDraftEntry(key, { promptId, field, text, pending: draft?.pending ?? null, showError: draft?.showError ?? false });
216
+ },
217
+ submit,
218
+ async remove(promptId) {
219
+ if (state.deleting.has(promptId)) return "unchanged";
220
+ set({ deleting: new Set(state.deleting).add(promptId) });
221
+ const result = await save(deletePrompt(promptId));
222
+ const deleting = new Set(state.deleting);
223
+ deleting.delete(promptId);
224
+ // Typed text goes with a prompt deleted here, but only once it is gone.
225
+ const drafts = hasPrompt(state.doc, promptId)
226
+ ? state.drafts
227
+ : new Map([...state.drafts].filter(([, draft]) => draft.promptId !== promptId));
228
+ set({ deleting, drafts });
229
+ return result;
230
+ },
231
+ setNewPrompt(field, text) {
232
+ set({ newPrompt: { ...state.newPrompt, [field]: text } });
233
+ },
234
+ async add() {
235
+ if (state.adding) return "unchanged";
236
+ const { label, text } = state.newPrompt;
237
+ const parsed = QuickPromptSchema.safeParse({ id: newPromptId(), label, text });
238
+ if (!parsed.success) {
239
+ set({ newPrompt: { ...state.newPrompt, showErrors: true } });
240
+ return "unchanged";
241
+ }
242
+ set({ adding: true });
243
+ const result = await save(addPrompt(parsed.data));
244
+ const current = state.newPrompt;
245
+ // Keep anything typed while the prompt was being added.
246
+ const newPrompt =
247
+ result === "saved"
248
+ ? { label: current.label === label ? "" : current.label, text: current.text === text ? "" : current.text, showErrors: false }
249
+ : current;
250
+ set({ adding: false, newPrompt });
251
+ return result;
252
+ },
253
+ dismissOrphans() {
254
+ const orphans = new Set(orphanedDrafts(state));
255
+ set({ drafts: new Map([...state.drafts].filter(([, draft]) => !orphans.has(draft))) });
256
+ },
257
+ flush() {
258
+ let unsaved = 0;
259
+ for (const draft of state.drafts.values()) {
260
+ if (state.deleting.has(draft.promptId)) continue;
261
+ if (!hasPrompt(state.doc, draft.promptId) || !parseField(draft.field, draft.text).success) unsaved += 1;
262
+ else submit(draft.promptId, draft.field);
263
+ }
264
+ return unsaved;
265
+ },
266
+ };
267
+ }
@@ -0,0 +1,53 @@
1
+ import { settingsRpc } from "@getpaseo/plugin";
2
+ import { MAX_PROMPTS, quickPromptsSettings, type PromptDisplay, type QuickPrompt, type QuickPromptsSettings } from "../shared/prompts";
3
+
4
+ export const settingsContract = settingsRpc(quickPromptsSettings.id);
5
+
6
+ /** Saved values with the revision they were read or written at. */
7
+ export interface SettingsDoc {
8
+ values: QuickPromptsSettings;
9
+ revision: string;
10
+ }
11
+
12
+ /** One change, applied to whichever values are latest. `null` means it no longer applies. */
13
+ export type Edit = (values: QuickPromptsSettings) => QuickPromptsSettings | null;
14
+
15
+ export function updatePrompt(id: string, field: "label" | "text", value: string): Edit {
16
+ return (values) =>
17
+ values.prompts.some((prompt) => prompt.id === id)
18
+ ? { ...values, prompts: values.prompts.map((prompt) => (prompt.id === id ? { ...prompt, [field]: value } : prompt)) }
19
+ : null;
20
+ }
21
+
22
+ export function movePrompt(id: string, offset: -1 | 1): Edit {
23
+ return (values) => {
24
+ const index = values.prompts.findIndex((prompt) => prompt.id === id);
25
+ const target = index + offset;
26
+ if (index < 0 || target < 0 || target >= values.prompts.length) return null;
27
+ const prompts = [...values.prompts];
28
+ const [moved] = prompts.splice(index, 1);
29
+ if (moved) prompts.splice(target, 0, moved);
30
+ return { ...values, prompts };
31
+ };
32
+ }
33
+
34
+ export function deletePrompt(id: string): Edit {
35
+ return (values) =>
36
+ values.prompts.some((prompt) => prompt.id === id)
37
+ ? { ...values, prompts: values.prompts.filter((prompt) => prompt.id !== id) }
38
+ : null;
39
+ }
40
+
41
+ export function addPrompt(prompt: QuickPrompt): Edit {
42
+ return (values) => (values.prompts.length < MAX_PROMPTS ? { ...values, prompts: [...values.prompts, prompt] } : null);
43
+ }
44
+
45
+ export function setDisplay(display: PromptDisplay): Edit {
46
+ return (values) => ({ ...values, display });
47
+ }
48
+
49
+ /** The edit applied to `values`, or `null` when it no longer applies or the result would not save. */
50
+ export function applyEdit(edit: Edit, values: QuickPromptsSettings): QuickPromptsSettings | null {
51
+ const next = edit(values);
52
+ return next ? (quickPromptsSettings.schema.safeParse(next).data ?? null) : null;
53
+ }
@@ -0,0 +1,187 @@
1
+ import { settingsRpc } from "@getpaseo/plugin";
2
+ import type { PluginClientContext } from "@getpaseo/plugin/client";
3
+ import { quickPromptsSettings, settingsFromRead } from "../shared/prompts";
4
+ import type { PillAgent, PromptPills } from "./pills";
5
+
6
+ type Paseo = PluginClientContext["paseo"];
7
+ type Client = Pick<PluginClientContext, "paseo" | "rpc">;
8
+
9
+ /** The host's largest agent directory page, which is also its default. */
10
+ const PAGE_LIMIT = 200;
11
+ /** Waits before starting a failed observation again; after the last one it stops. */
12
+ const RETRY_DELAYS_MS = [1_000, 5_000, 15_000, 60_000];
13
+
14
+ interface Attempt {
15
+ /** Aborted when this attempt fails or the lifetime ends; releases its subscription. */
16
+ signal: AbortSignal;
17
+ /** The observation is fully up to date; later failures start the delays from the beginning. */
18
+ ready(): void;
19
+ failed(error: unknown): void;
20
+ }
21
+
22
+ /** Starts an observation and, after it fails, starts it again with bounded retries. */
23
+ function observeWithRetry(name: string, lifetime: AbortSignal, start: (attempt: Attempt) => void): void {
24
+ let failures = 0;
25
+ let timer: ReturnType<typeof setTimeout> | undefined;
26
+ lifetime.addEventListener("abort", () => clearTimeout(timer), { once: true });
27
+ const run = (): void => {
28
+ if (lifetime.aborted) return;
29
+ const controller = new AbortController();
30
+ const stop = (): void => controller.abort();
31
+ lifetime.addEventListener("abort", stop, { once: true });
32
+ start({
33
+ signal: controller.signal,
34
+ ready: () => {
35
+ failures = 0;
36
+ },
37
+ failed: (error) => {
38
+ if (controller.signal.aborted) return;
39
+ lifetime.removeEventListener("abort", stop);
40
+ controller.abort();
41
+ const delay = RETRY_DELAYS_MS[failures];
42
+ failures += 1;
43
+ if (delay === undefined) {
44
+ console.error(`[paseo-quick-prompts] ${name} failed; not retrying`, error);
45
+ return;
46
+ }
47
+ console.error(`[paseo-quick-prompts] ${name} failed; retrying in ${delay / 1000}s`, error);
48
+ timer = setTimeout(run, delay);
49
+ },
50
+ });
51
+ };
52
+ run();
53
+ }
54
+
55
+ type AgentListResult = Awaited<ReturnType<Paseo["agents"]["list"]>>;
56
+ type AgentSubscription = NonNullable<AgentListResult["subscription"]>;
57
+ type AgentMessage = Parameters<Parameters<AgentSubscription["subscribe"]>[0]["update"]>[0];
58
+
59
+ /** One page of the agent directory, with only what the pills read. */
60
+ export interface AgentPage {
61
+ entries: ReadonlyArray<{ agent: PillAgent }>;
62
+ pageInfo: { hasMore: boolean; nextCursor: string | null };
63
+ }
64
+
65
+ /** The part of `paseo.agents` that following the directory uses. */
66
+ export interface AgentDirectory {
67
+ /** A subscription that delivers the first page, then updates, and a fresh first page after a reconnect. */
68
+ subscribe(signal: AbortSignal): Promise<{
69
+ subscription: {
70
+ subscribe(observer: {
71
+ snapshot(page: AgentPage): void;
72
+ update(message: AgentMessage): void;
73
+ error(error: unknown): void;
74
+ }): () => void;
75
+ };
76
+ }>;
77
+ page(cursor: string): Promise<AgentPage>;
78
+ }
79
+
80
+ /** Follows every agent: all pages of existing agents first, then updates. */
81
+ export function followAgents(client: Client, pills: PromptPills, lifetime: AbortSignal): void {
82
+ followAgentDirectory(
83
+ {
84
+ subscribe: (signal) => client.paseo.agents.list({ subscribe: {}, signal }),
85
+ page: (cursor) => client.paseo.agents.list({ page: { limit: PAGE_LIMIT, cursor } }),
86
+ },
87
+ pills,
88
+ lifetime,
89
+ );
90
+ }
91
+
92
+ export function followAgentDirectory(directory: AgentDirectory, pills: PromptPills, lifetime: AbortSignal): void {
93
+ observeWithRetry("agent observation", lifetime, ({ signal, ready, failed }) => {
94
+ let bootstrap = 0;
95
+ /** Agents updated or removed (null) while later pages load; they are newer than those pages. */
96
+ let changed: Map<string, PillAgent | null> | null = null;
97
+
98
+ const loadAll = async (generation: number, agents: PillAgent[], cursor: string | null): Promise<void> => {
99
+ const updates = new Map<string, PillAgent | null>();
100
+ changed = updates;
101
+ while (cursor) {
102
+ const page = await directory.page(cursor);
103
+ if (signal.aborted || generation !== bootstrap) return;
104
+ agents.push(...page.entries.map(({ agent }) => agent));
105
+ cursor = page.pageInfo.hasMore ? page.pageInfo.nextCursor : null;
106
+ }
107
+ changed = null;
108
+ const byId = new Map(agents.map((agent) => [agent.id, agent]));
109
+ for (const [agentId, agent] of updates) {
110
+ if (agent) byId.set(agentId, agent);
111
+ else byId.delete(agentId);
112
+ }
113
+ pills.setAgents([...byId.values()]);
114
+ ready();
115
+ };
116
+
117
+ directory
118
+ .subscribe(signal)
119
+ .then(({ subscription }) => {
120
+ subscription.subscribe({
121
+ snapshot: ({ entries, pageInfo }) => {
122
+ const generation = ++bootstrap;
123
+ const agents = entries.map(({ agent }) => agent);
124
+ if (!pageInfo.hasMore) {
125
+ changed = null;
126
+ pills.setAgents(agents);
127
+ ready();
128
+ return;
129
+ }
130
+ loadAll(generation, agents, pageInfo.nextCursor).catch(failed);
131
+ },
132
+ update: (message) => {
133
+ if (message.type !== "agent_update") return;
134
+ const update = message.payload;
135
+ if (update.kind === "remove") {
136
+ changed?.set(update.agentId, null);
137
+ pills.removeAgent(update.agentId);
138
+ } else {
139
+ changed?.set(update.agent.id, update.agent);
140
+ pills.upsertAgent(update.agent);
141
+ }
142
+ },
143
+ error: failed,
144
+ });
145
+ return undefined;
146
+ })
147
+ .catch(failed);
148
+ });
149
+ }
150
+
151
+ /** Calls `onChange` now, after a reconnect, and whenever any client saves the quick prompts. */
152
+ export function followPromptChanges(paseo: Paseo, lifetime: AbortSignal, onChange: () => void): void {
153
+ observeWithRetry("settings observation", lifetime, ({ signal, ready, failed }) => {
154
+ paseo.observeEvents(["status.plugin_settings_changed"], { signal }).subscribe({
155
+ snapshot: () => {
156
+ ready();
157
+ onChange();
158
+ },
159
+ update: (message) => {
160
+ if (
161
+ message.type === "status" &&
162
+ message.payload.status === "plugin_settings_changed" &&
163
+ message.payload.settingsId === quickPromptsSettings.id
164
+ ) {
165
+ onChange();
166
+ }
167
+ },
168
+ error: failed,
169
+ });
170
+ });
171
+ }
172
+
173
+ /** Keeps the pills on the saved prompts. */
174
+ export function followPrompts(client: Client, pills: PromptPills, lifetime: AbortSignal): void {
175
+ const { read } = settingsRpc(quickPromptsSettings.id);
176
+ let latest = 0;
177
+ const load = async (): Promise<void> => {
178
+ const request = ++latest;
179
+ try {
180
+ const result = await client.rpc(read, {});
181
+ if (!lifetime.aborted && request === latest) pills.setSettings(settingsFromRead(result));
182
+ } catch (error) {
183
+ if (!lifetime.aborted) console.error("[paseo-quick-prompts] failed to load quick prompts", error);
184
+ }
185
+ };
186
+ followPromptChanges(client.paseo, lifetime, () => void load());
187
+ }