@gpambrozio/paseo-herald 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.
@@ -0,0 +1,194 @@
1
+ /**
2
+ * One entry per agent: the most recent reason it is waiting on the user, and
3
+ * the summary for it. Newer events replace older ones for the same agent —
4
+ * an agent has one composer and one thing it is waiting for.
5
+ *
6
+ * Paseo's own `requiresAttention` flag stays the authority on *who* is waiting;
7
+ * this store only explains *why*. Entries are removed when the hooks see the
8
+ * agent move on (a new turn, a resolved permission, an archive), and by
9
+ * `Liveness` when the agent turns out to be archived or gone. There is no age
10
+ * limit: an agent that asked a question a week ago is still waiting for the
11
+ * answer.
12
+ *
13
+ * Mirrored to a JSON file so a plugin reload does not lose the summaries
14
+ * already written; a summary still pending at load time is marked failed,
15
+ * because the helper that was writing it died with the old process.
16
+ */
17
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
18
+ import { dirname } from "node:path";
19
+
20
+ import { AttentionEntrySchema, type AttentionEntry, type SummaryState } from "../shared/herald";
21
+ import { fallbackSpeech } from "./timeline";
22
+
23
+ export class AttentionStore {
24
+ private readonly entries = new Map<string, AttentionEntry>();
25
+ private writes: Promise<void> = Promise.resolve();
26
+ /**
27
+ * Agents changed since this store was made. `load` runs while the plugin is
28
+ * already answering events — a contribution registers its handlers
29
+ * synchronously, so the file read cannot be awaited first — and whatever
30
+ * arrived live is newer than anything on disk. Cleared once `load` is done.
31
+ */
32
+ private readonly touched = new Set<string>();
33
+ /**
34
+ * Set while `load()` is reading. Writes queued in that window wait for it:
35
+ * otherwise one would truncate the very file being read, and it would
36
+ * serialise a map that has not been merged yet.
37
+ */
38
+ private loading: Promise<void> | null = null;
39
+ /**
40
+ * Conditional removals that arrived before the entry they test had been
41
+ * read. `remove` can mark its agent `touched` unconditionally; `removeIf`
42
+ * cannot, because its test needs the very entry still on disk. So the test
43
+ * is kept here and applied to that entry as it is merged — otherwise a
44
+ * permission answered during the read is silently restored by the merge.
45
+ */
46
+ private readonly deferredRemovals = new Map<string, Array<(entry: AttentionEntry) => boolean>>();
47
+
48
+ /** `path === null` keeps everything in memory, which is what the tests want. */
49
+ constructor(private readonly path: string | null) {}
50
+
51
+ async load(): Promise<void> {
52
+ if (this.path === null) return;
53
+ const run = this.read();
54
+ // Never rejects, so a failed read cannot wedge the write chain behind it.
55
+ this.loading = run.catch(() => {});
56
+ try {
57
+ await run;
58
+ } finally {
59
+ this.loading = null;
60
+ }
61
+ }
62
+
63
+ private async read(): Promise<void> {
64
+ if (this.path === null) return;
65
+ let raw: string;
66
+ try {
67
+ raw = await readFile(this.path, "utf8");
68
+ } catch (error) {
69
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
70
+ throw error;
71
+ }
72
+ const json: unknown = JSON.parse(raw);
73
+ if (!Array.isArray(json)) throw new Error(`${this.path}: expected an array of entries`);
74
+ let dropped = false;
75
+ for (const item of json) {
76
+ const parsed = AttentionEntrySchema.safeParse(item);
77
+ if (!parsed.success) {
78
+ console.error(`[herald] dropping unreadable entry from ${this.path}: ${parsed.error.message}`);
79
+ continue;
80
+ }
81
+ const entry = parsed.data;
82
+ // Never undo a live upsert or removal that landed during the read.
83
+ if (this.touched.has(entry.agentId)) continue;
84
+ const held = this.deferredRemovals.get(entry.agentId);
85
+ if (held !== undefined && held.some((matches) => matches(entry))) {
86
+ dropped = true;
87
+ continue;
88
+ }
89
+ this.entries.set(
90
+ entry.agentId,
91
+ entry.summary.status === "pending"
92
+ ? {
93
+ ...entry,
94
+ summary: {
95
+ status: "failed",
96
+ error: "The plugin restarted before the summary was written.",
97
+ fallback: fallbackSpeech(entry),
98
+ },
99
+ }
100
+ : entry,
101
+ );
102
+ }
103
+ // Nothing else is going to write the dropped rows out of the file.
104
+ if (dropped) this.persist();
105
+ this.touched.clear();
106
+ this.deferredRemovals.clear();
107
+ }
108
+
109
+ list(): AttentionEntry[] {
110
+ return [...this.entries.values()].sort((a, b) => b.createdAt.localeCompare(a.createdAt));
111
+ }
112
+
113
+ get(agentId: string): AttentionEntry | null {
114
+ return this.entries.get(agentId) ?? null;
115
+ }
116
+
117
+ upsert(entry: AttentionEntry): void {
118
+ this.touched.add(entry.agentId);
119
+ this.entries.set(entry.agentId, entry);
120
+ this.persist();
121
+ }
122
+
123
+ /**
124
+ * Applies a summary only if the agent is still waiting on the same event.
125
+ * A helper that finishes after the user has already moved on — or after a
126
+ * newer event replaced this one — must not overwrite what is there now.
127
+ */
128
+ updateSummary(agentId: string, eventId: string, summary: SummaryState): boolean {
129
+ const current = this.entries.get(agentId);
130
+ if (current === undefined || current.eventId !== eventId) return false;
131
+ this.entries.set(agentId, { ...current, summary });
132
+ this.persist();
133
+ return true;
134
+ }
135
+
136
+ remove(agentId: string): AttentionEntry | null {
137
+ this.touched.add(agentId);
138
+ const current = this.entries.get(agentId) ?? null;
139
+ if (current !== null) {
140
+ this.entries.delete(agentId);
141
+ this.persist();
142
+ }
143
+ return current;
144
+ }
145
+
146
+ removeIf(agentId: string, predicate: (entry: AttentionEntry) => boolean): boolean {
147
+ const current = this.entries.get(agentId);
148
+ if (current === undefined) {
149
+ // Absent, or simply not read yet. While loading it is the second, so the
150
+ // test is held for the merge rather than thrown away.
151
+ if (this.loading !== null) {
152
+ const held = this.deferredRemovals.get(agentId) ?? [];
153
+ held.push(predicate);
154
+ this.deferredRemovals.set(agentId, held);
155
+ }
156
+ return false;
157
+ }
158
+ if (!predicate(current)) return false;
159
+ this.touched.add(agentId);
160
+ this.entries.delete(agentId);
161
+ this.persist();
162
+ return true;
163
+ }
164
+
165
+ /** Resolves once every write issued so far has landed; for tests and cleanup. */
166
+ flush(): Promise<void> {
167
+ return this.writes;
168
+ }
169
+
170
+ /**
171
+ * Writes are chained so two events a millisecond apart cannot interleave
172
+ * halves of a file. A failed write is reported and never thrown: the store
173
+ * in memory is still right, and the next write tries again.
174
+ */
175
+ private persist(): void {
176
+ if (this.path === null) return;
177
+ const path = this.path;
178
+ const loaded = this.loading ?? Promise.resolve();
179
+ this.writes = this.writes
180
+ .then(() => loaded)
181
+ .then(async () => {
182
+ // Serialised here rather than at the call, so a write that waited for
183
+ // `load()` puts the merged map on disk rather than the map as it stood
184
+ // when it was queued. The file mirrors the map, it is not a log, so
185
+ // writing the latest state is always the right thing.
186
+ const snapshot = JSON.stringify([...this.entries.values()], null, 2);
187
+ await mkdir(dirname(path), { recursive: true });
188
+ await writeFile(path, `${snapshot}\n`, "utf8");
189
+ })
190
+ .catch((error: unknown) => {
191
+ console.error(`[herald] could not write ${path}:`, error);
192
+ });
193
+ }
194
+ }
@@ -0,0 +1,223 @@
1
+ /**
2
+ * One summary is one short-lived Paseo agent: created as a delegated child of
3
+ * the agent it describes, so it shows under that agent's subagent track rather
4
+ * than as a tab of its own, and archived by the daemon the moment its single
5
+ * turn ends (`autoArchive`).
6
+ *
7
+ * The SDK cannot mark an agent internal, so this helper is visible and fires
8
+ * this plugin's own hooks. `HELPER_TITLE` is one of the two things
9
+ * `server/hooks.ts` uses to recognise and ignore it; the id reported through
10
+ * `onHelperCreated` is the other.
11
+ */
12
+ import type { PaseoApi } from "@getpaseo/client";
13
+ import { DEFAULT_SUMMARY_PROMPT, type AttentionReason, type PromptPlaceholder } from "../shared/herald";
14
+ import { displayName, firstWords, plainText } from "./timeline";
15
+
16
+ export const HELPER_TITLE = "Herald summary";
17
+
18
+ /** Enough of a final message for a summary; the rest is never what the user needs to hear. */
19
+ const MAX_OUTPUT_CHARS = 6000;
20
+ const MAX_USER_CHARS = 600;
21
+
22
+ export interface SummaryRequest {
23
+ agent: { id: string; workspaceId: string | null; workspaceTitle: string | null; cwd: string; title: string | null };
24
+ reason: AttentionReason;
25
+ headline: string;
26
+ detail: string | null;
27
+ /** What the agent said after the user's last message; empty for a pause. */
28
+ output: string;
29
+ lastUser: string | null;
30
+ }
31
+
32
+ export interface SummarizerDeps {
33
+ paseo: PaseoApi;
34
+ /** `provider/model`, as the SDK takes it. */
35
+ provider: string;
36
+ timeoutMs: number;
37
+ /** The user's prompt template. Blank or absent means the default one. */
38
+ prompt?: string;
39
+ /** Called as soon as the helper exists, before its first turn can end. */
40
+ onHelperCreated?: (helperId: string) => void;
41
+ }
42
+
43
+ export interface Summary {
44
+ text: string;
45
+ model: string;
46
+ }
47
+
48
+ const SUMMARY_OUTPUT_SCHEMA = {
49
+ type: "object",
50
+ properties: {
51
+ speech: {
52
+ type: "string",
53
+ description: "One or two spoken sentences, under 35 words, plain text.",
54
+ },
55
+ },
56
+ required: ["speech"],
57
+ additionalProperties: false,
58
+ } as const;
59
+
60
+ /** Everything the helper wrote in code fences, with the fences and language tags removed. */
61
+ function stripFences(text: string): string {
62
+ return text.replace(/```[a-zA-Z0-9_-]*\s*([\s\S]*?)```/g, "$1").trim();
63
+ }
64
+
65
+ /**
66
+ * The sentence inside the helper's JSON: the `speech` property the schema
67
+ * asks for, or — because a model has been seen answering under `spoken` —
68
+ * whatever the first non-empty string property is.
69
+ */
70
+ function sentenceIn(json: unknown): string | null {
71
+ if (typeof json !== "object" || json === null || Array.isArray(json)) return null;
72
+ const record = json as Record<string, unknown>;
73
+ const preferred = record.speech;
74
+ if (typeof preferred === "string" && preferred.trim() !== "") return preferred;
75
+ for (const value of Object.values(record)) {
76
+ if (typeof value === "string" && value.trim() !== "") return value;
77
+ }
78
+ return null;
79
+ }
80
+
81
+ function describeReason(reason: AttentionReason): string {
82
+ switch (reason) {
83
+ case "question":
84
+ return "The agent has paused to ask the user a question.";
85
+ case "plan":
86
+ return "The agent has written a plan and is waiting for the user to approve it.";
87
+ case "permission":
88
+ return "The agent has paused for permission to do something.";
89
+ case "finished":
90
+ return "The agent finished its turn and is waiting for the user.";
91
+ case "error":
92
+ return "The agent's turn failed with an error.";
93
+ case "canceled":
94
+ return "The agent's turn was interrupted.";
95
+ }
96
+ }
97
+
98
+ function clip(text: string, max: number): string {
99
+ return text.length <= max ? text : `${text.slice(0, max)}\n[…truncated]`;
100
+ }
101
+
102
+ function basename(path: string): string {
103
+ const parts = path.split("/").filter((part) => part !== "");
104
+ return parts[parts.length - 1] ?? path;
105
+ }
106
+
107
+ /** What each `{{placeholder}}` is worth for one event. Empty means "not there for this one". */
108
+ export function promptValues(request: SummaryRequest): Record<PromptPlaceholder, string> {
109
+ const name = displayName({ workspaceTitle: request.agent.workspaceTitle, agentTitle: request.agent.title }) ?? "an agent";
110
+ const folder = basename(request.agent.cwd);
111
+ return {
112
+ agent: name,
113
+ workspace: request.agent.workspaceTitle?.trim() || folder,
114
+ folder,
115
+ event: describeReason(request.reason),
116
+ headline: request.headline.trim(),
117
+ detail: request.detail?.trim() ?? "",
118
+ request: request.lastUser === null ? "" : clip(request.lastUser.trim(), MAX_USER_CHARS),
119
+ output: request.output.trim() === "" ? "" : clip(request.output.trim(), MAX_OUTPUT_CHARS),
120
+ };
121
+ }
122
+
123
+ /**
124
+ * The user's template with this event's values in it.
125
+ *
126
+ * Two rules, both of them things the settings screen tells the user:
127
+ *
128
+ * - **A line whose placeholder is empty for this event is left out whole.**
129
+ * That is what keeps `Detail: {{detail}}` from reaching the model as a bare
130
+ * `Detail:` when the event carries none, without the template needing any
131
+ * notion of a conditional. Runs of blank lines left behind are collapsed.
132
+ * - **A name we do not know is left exactly as typed**, so a prompt that talks
133
+ * about `{{ }}` for its own reasons is not quietly mangled.
134
+ */
135
+ export function renderPrompt(template: string, values: Readonly<Record<string, string>>): string {
136
+ const kept: string[] = [];
137
+ for (const line of template.split("\n")) {
138
+ let missing = false;
139
+ const rendered = line.replace(/\{\{\s*([a-zA-Z][a-zA-Z0-9_]*)\s*\}\}/g, (whole, name: string) => {
140
+ const value = values[name];
141
+ if (value === undefined) return whole;
142
+ if (value === "") missing = true;
143
+ return value;
144
+ });
145
+ if (missing) continue;
146
+ if (rendered.trim() === "" && kept[kept.length - 1]?.trim() === "") continue;
147
+ kept.push(rendered);
148
+ }
149
+ return kept.join("\n").trim();
150
+ }
151
+
152
+ export function buildPrompt(request: SummaryRequest, template?: string): string {
153
+ const chosen = template?.trim() === "" || template === undefined ? DEFAULT_SUMMARY_PROMPT : template;
154
+ return renderPrompt(chosen, promptValues(request));
155
+ }
156
+
157
+ /**
158
+ * `outputSchema` is a request, not a guarantee: against a live daemon Claude
159
+ * has returned the object inside a ```json fence, and once under a key of its
160
+ * own choosing. So: fences off, then the JSON object anywhere in the text,
161
+ * then any string in it; and a model that wrote plain prose instead is still
162
+ * worth hearing, so that is the last resort rather than a failure.
163
+ */
164
+ export function parseSummaryText(lastMessage: string | null): string {
165
+ const raw = lastMessage?.trim() ?? "";
166
+ if (raw === "") throw new Error("The summary agent returned nothing.");
167
+ const unfenced = stripFences(raw);
168
+ const candidates = [unfenced];
169
+ const braces = unfenced.match(/\{[\s\S]*\}/);
170
+ if (braces !== null && braces[0] !== unfenced) candidates.push(braces[0]);
171
+ for (const candidate of candidates) {
172
+ try {
173
+ const sentence = sentenceIn(JSON.parse(candidate));
174
+ if (sentence !== null) return plainText(sentence);
175
+ } catch {
176
+ // Not JSON; try the next candidate.
177
+ }
178
+ }
179
+ return firstWords(unfenced, 45);
180
+ }
181
+
182
+ export async function summarize(request: SummaryRequest, deps: SummarizerDeps): Promise<Summary> {
183
+ if (request.agent.workspaceId === null) {
184
+ throw new Error("The agent has no workspace, so there is nowhere to place a summary helper.");
185
+ }
186
+ const workspace = deps.paseo.workspaces.ref(request.agent.workspaceId);
187
+ const helper = await workspace.agents.create({
188
+ config: { provider: deps.provider },
189
+ parent: request.agent.id,
190
+ title: HELPER_TITLE,
191
+ autoArchive: true,
192
+ outputSchema: SUMMARY_OUTPUT_SCHEMA as unknown as Record<string, unknown>,
193
+ prompt: buildPrompt(request, deps.prompt),
194
+ labels: { "herald.role": "summarizer" },
195
+ });
196
+ deps.onHelperCreated?.(helper.id);
197
+ try {
198
+ const result = await helper.waitForFinish(deps.timeoutMs);
199
+ if (result.status === "permission") {
200
+ // The prompt forbids tools; a helper that asks anyway is answered so it
201
+ // does not sit in the subagent track waiting forever, then given up on.
202
+ const pending = result.final?.pendingPermissions ?? [];
203
+ await Promise.all(
204
+ pending.map((request) =>
205
+ helper.respondToPermission({
206
+ requestId: request.id,
207
+ response: { behavior: "deny", message: "Herald summaries must not use tools.", interrupt: true },
208
+ }),
209
+ ),
210
+ );
211
+ throw new Error("The summary agent tried to use a tool.");
212
+ }
213
+ if (result.status !== "idle") {
214
+ throw new Error(result.error ?? `The summary agent ended with status ${result.status}.`);
215
+ }
216
+ return { text: parseSummaryText(result.lastMessage), model: deps.provider };
217
+ } catch (error) {
218
+ // autoArchive only fires on a finished turn; a helper that timed out or
219
+ // was denied is still there and has to be put away by hand.
220
+ void helper.archive().catch(() => {});
221
+ throw error;
222
+ }
223
+ }
@@ -0,0 +1,194 @@
1
+ /**
2
+ * Turns what the hooks hand us — a timeline snapshot or a permission request —
3
+ * into the plain text an entry carries and a summary is written from. Nothing
4
+ * here touches the network or a model, which is what makes it the part with
5
+ * tests.
6
+ */
7
+ import type { AgentPermissionRequest, AgentTimelineItem } from "@getpaseo/protocol/agent-types";
8
+
9
+ import type { AttentionReason } from "../shared/herald";
10
+
11
+ /**
12
+ * Everything the agent said after the user's last message. Only assistant text
13
+ * and errors count: reasoning is the agent talking to itself, and tool calls
14
+ * are how it got there, neither of which the user is being told.
15
+ */
16
+ export function latestOutputText(timeline: readonly AgentTimelineItem[]): string {
17
+ let output = "";
18
+ for (const item of timeline) {
19
+ if (item.type === "user_message") {
20
+ output = "";
21
+ } else if (item.type === "assistant_message") {
22
+ output = joinText(output, item.text);
23
+ } else if (item.type === "error" && item.message.trim() !== "") {
24
+ output = `${output.trimEnd()}\nError: ${item.message.trim()}\n`;
25
+ }
26
+ }
27
+ return output.trim();
28
+ }
29
+
30
+ /**
31
+ * A streamed reply reaches the snapshot as several `assistant_message` items
32
+ * that can split anywhere — between words, or in the middle of one — and the
33
+ * whitespace is inside the chunks. So chunks are concatenated as they are,
34
+ * which is what Paseo's own helper does. The one exception is two separate
35
+ * messages in one turn, text before and after a tool call, which arrive
36
+ * without a space between them: a sentence end followed by a capital letter
37
+ * gets one. A mid-word split never looks like that.
38
+ */
39
+ function joinText(left: string, right: string): string {
40
+ if (left === "") return right;
41
+ if (/[.!?]$/.test(left) && /^[A-Z]/.test(right)) return `${left} ${right}`;
42
+ return left + right;
43
+ }
44
+
45
+ /** The user's most recent message, so the summary knows what was asked for. */
46
+ export function lastUserMessage(timeline: readonly AgentTimelineItem[]): string | null {
47
+ for (let index = timeline.length - 1; index >= 0; index -= 1) {
48
+ const item = timeline[index];
49
+ if (item?.type === "user_message" && item.text.trim() !== "") return item.text.trim();
50
+ }
51
+ return null;
52
+ }
53
+
54
+ export interface PermissionDescription {
55
+ reason: AttentionReason;
56
+ headline: string;
57
+ detail: string | null;
58
+ }
59
+
60
+ function isRecord(value: unknown): value is Record<string, unknown> {
61
+ return typeof value === "object" && value !== null && !Array.isArray(value);
62
+ }
63
+
64
+ function optionLabels(options: unknown): string[] {
65
+ if (!Array.isArray(options)) return [];
66
+ return options
67
+ .map((option) => {
68
+ if (typeof option === "string") return option.trim();
69
+ if (isRecord(option) && typeof option.label === "string") return option.label.trim();
70
+ return "";
71
+ })
72
+ .filter((label) => label !== "");
73
+ }
74
+
75
+ /**
76
+ * The shell command behind a tool permission, wherever the provider put it.
77
+ * Paseo's typed `detail` is preferred; the raw input keys are what Claude and
78
+ * Codex send when the detail is absent.
79
+ */
80
+ export function shellCommand(request: AgentPermissionRequest): string | null {
81
+ if (request.detail?.type === "shell" && request.detail.command.trim() !== "") {
82
+ return request.detail.command.trim();
83
+ }
84
+ const input = request.input;
85
+ if (!isRecord(input)) return null;
86
+ if (typeof input.command === "string" && input.command.trim() !== "") return input.command.trim();
87
+ if (typeof input.cmd === "string" && input.cmd.trim() !== "") return input.cmd.trim();
88
+ return null;
89
+ }
90
+
91
+ /**
92
+ * What to show and say for a pause. Paseo already flattens the first
93
+ * AskUserQuestion into `title` and `description`; the raw `questions` array is
94
+ * read as well so the count and the options survive a provider that did not.
95
+ */
96
+ export function describePermission(request: AgentPermissionRequest): PermissionDescription {
97
+ if (request.kind === "question") {
98
+ const questions = isRecord(request.input) && Array.isArray(request.input.questions)
99
+ ? request.input.questions.filter(isRecord)
100
+ : [];
101
+ const first = questions[0];
102
+ const headline =
103
+ request.title?.trim() ||
104
+ (typeof first?.question === "string" ? first.question.trim() : "") ||
105
+ "Has a question for you";
106
+ const options = optionLabels(first?.options);
107
+ const suffix = questions.length > 1 ? ` (${questions.length} questions)` : "";
108
+ return {
109
+ reason: "question",
110
+ headline: `${headline}${suffix}`,
111
+ detail: options.length > 0 ? options.join(" / ") : request.description?.trim() || null,
112
+ };
113
+ }
114
+ if (request.kind === "plan") {
115
+ return {
116
+ reason: "plan",
117
+ headline: request.title?.trim() || "Plan ready for your approval",
118
+ detail: request.description?.trim() || null,
119
+ };
120
+ }
121
+ const command = shellCommand(request);
122
+ return {
123
+ reason: "permission",
124
+ headline: request.title?.trim() || `Wants to use ${request.name}`,
125
+ detail: command ?? request.description?.trim() ?? null,
126
+ };
127
+ }
128
+
129
+ /** Markdown and code punctuation read aloud is noise; strip what a voice would spell out. */
130
+ export function plainText(text: string): string {
131
+ return text
132
+ .replace(/```[\s\S]*?```/g, " code block ")
133
+ .replace(/`([^`]*)`/g, "$1")
134
+ .replace(/^\s{0,3}#{1,6}\s+/gm, "")
135
+ .replace(/[*_~>]/g, "")
136
+ .replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
137
+ .replace(/\s+/g, " ")
138
+ .trim();
139
+ }
140
+
141
+ /** The first `maxWords` words, cut at a sentence end when one comes first. */
142
+ export function firstWords(text: string, maxWords: number): string {
143
+ const words = plainText(text).split(" ").filter((word) => word !== "");
144
+ if (words.length === 0) return "";
145
+ const taken = words.slice(0, maxWords);
146
+ const joined = taken.join(" ");
147
+ const sentenceEnd = joined.search(/[.!?](\s|$)/);
148
+ if (sentenceEnd > 20) return joined.slice(0, sentenceEnd + 1);
149
+ return taken.length < words.length ? `${joined}…` : joined;
150
+ }
151
+
152
+ /** One line of at most `max` characters, for a preview under a title. */
153
+ export function preview(text: string, max = 90): string {
154
+ const line = plainText(text);
155
+ return line.length <= max ? line : `${line.slice(0, max - 1).trimEnd()}…`;
156
+ }
157
+
158
+ export interface SpeechSource {
159
+ workspaceTitle: string | null;
160
+ agentTitle: string | null;
161
+ reason: AttentionReason;
162
+ headline: string;
163
+ detail: string | null;
164
+ }
165
+
166
+ /** What to call the work: the agent's title if it has one, else the workspace's. */
167
+ export function displayName(source: { workspaceTitle: string | null; agentTitle: string | null }): string | null {
168
+ return source.agentTitle?.trim() || source.workspaceTitle?.trim() || null;
169
+ }
170
+
171
+ /**
172
+ * What is said when no model wrote a summary: the event kind stated plainly,
173
+ * with the headline and whatever detail there is. Deliberately dull — it has
174
+ * to be right without having read anything.
175
+ */
176
+ export function fallbackSpeech(source: SpeechSource): string {
177
+ const name = displayName(source) ?? "An agent";
178
+ const headline = plainText(source.headline);
179
+ const detail = source.detail === null ? "" : plainText(source.detail);
180
+ switch (source.reason) {
181
+ case "question":
182
+ return `${name} has a question: ${headline}${detail === "" ? "" : ` Options: ${detail}.`}`;
183
+ case "plan":
184
+ return `${name} has a plan ready for your approval. ${headline}`;
185
+ case "permission":
186
+ return `${name} is asking for permission. ${headline}${detail === "" ? "" : ` Command: ${detail}.`}`;
187
+ case "finished":
188
+ return detail === "" ? `${name} finished.` : `${name} finished. ${firstWords(detail, 30)}`;
189
+ case "error":
190
+ return `${name} stopped with an error. ${headline}`;
191
+ case "canceled":
192
+ return `${name} was interrupted. ${headline}`;
193
+ }
194
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The title of a workspace, for naming the work out loud. Agents are usually
3
+ * untitled; the workspace is what the user calls it. Cached, because titles
4
+ * change rarely and every event would otherwise page through the workspace
5
+ * list.
6
+ */
7
+ import type { PaseoApi } from "@getpaseo/client";
8
+
9
+ export const WORKSPACE_TITLE_TTL_MS = 5 * 60 * 1000;
10
+
11
+ export type WorkspaceTitleLookup = (workspaceId: string | null, paseo: PaseoApi) => Promise<string | null>;
12
+
13
+ export function createWorkspaceTitleLookup(now: () => number = Date.now): WorkspaceTitleLookup {
14
+ const cache = new Map<string, { at: number; title: string | null }>();
15
+ return async function workspaceTitle(workspaceId, paseo) {
16
+ if (workspaceId === null) return null;
17
+ const cached = cache.get(workspaceId);
18
+ const at = now();
19
+ if (cached !== undefined && at - cached.at < WORKSPACE_TITLE_TTL_MS) return cached.title;
20
+ let title: string | null = null;
21
+ try {
22
+ const workspace = await paseo.workspaces.ref(workspaceId).refresh();
23
+ title = workspace?.title?.trim() || workspace?.name?.trim() || null;
24
+ } catch (error) {
25
+ console.warn(
26
+ `[herald] could not read the title of workspace ${workspaceId}:`,
27
+ error instanceof Error ? error.message : error,
28
+ );
29
+ }
30
+ cache.set(workspaceId, { at, title });
31
+ return title;
32
+ };
33
+ }