paseo-follow-up 2.3.0-beta.2 → 2.3.0-beta.4

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/shared/created.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { modelName } from "./agent-settings";
3
3
  import { PRESENCE, type TaskAgentState } from "./task-status";
4
+ import { toolResult } from "./tool-result";
4
5
 
5
6
  /**
6
7
  * The chat card for an agent or workspace another agent creates (Paseo's create_agent / create_workspace tool calls).
@@ -42,21 +43,10 @@ export function createdKind(name: string): "agent" | "workspace" | null {
42
43
  return m ? m[1] as "agent" | "workspace" : null;
43
44
  }
44
45
 
45
- /** An MCP result: a JSON string, `{ content: [{ type: "text", text }] }`, or the object itself. */
46
- function resultObject(output: unknown): Record<string, unknown> | null {
47
- if (record(output) && Array.isArray(output.content)) {
48
- const text = output.content.map(c => record(c) && typeof c.text === "string" ? c.text : "").join("");
49
- return resultObject(text);
50
- }
51
- if (typeof output === "string") { try { const v: unknown = JSON.parse(output); return record(v) ? v : null; } catch { return null; } }
52
- return record(output) ? output : null;
53
- }
54
-
46
+ /** An error's words: Paseo's tool_result error ({ content }), { message }, or an MCP error result's text. */
55
47
  const errorText = (v: unknown): string | null => {
56
- if (typeof v === "string") return str(v);
57
- if (record(v)) return str(v.message) ?? str(v.error) ?? errorText(v.content);
58
- if (Array.isArray(v)) return str(v.map(c => record(c) && typeof c.text === "string" ? c.text : "").join(" "));
59
- return null;
48
+ if (record(v) && !Array.isArray(v.content) && !("output" in v)) return str(v.message) ?? str(v.error) ?? (v.content !== undefined ? errorText(v.content) : null);
49
+ return str(toolResult(v).text);
60
50
  };
61
51
 
62
52
  /** "claude/claude-opus-5-5" → { provider: "claude", model: "Opus 5.5" }; a bare provider has no model. */
@@ -75,7 +65,8 @@ export function createdCard(item: ToolCallLike): CreatedCard | null {
75
65
  const detail = record(item.detail) ? item.detail : {};
76
66
  const input = record(detail.input) ? detail.input : {};
77
67
  const output = "output" in detail ? detail.output : undefined;
78
- const failed = item.status === "failed" || (record(output) && output.isError === true);
68
+ const result = toolResult(output);
69
+ const failed = item.status === "failed" || result.isError;
79
70
  const { provider, model } = kind === "agent" ? providerModel(input.provider, input.model) : { provider: null, model: null };
80
71
  const base = {
81
72
  kind, title: str(input.title) ?? (kind === "workspace" ? str(input.branchName) ?? str(input.worktreeSlug) : null), model, provider,
@@ -84,13 +75,14 @@ export function createdCard(item: ToolCallLike): CreatedCard | null {
84
75
  };
85
76
  if (failed) return { ...base, phase: "failed", id: null, workspaceId: null, error: errorText(item.error) ?? errorText(output) ?? "The call failed" };
86
77
  if (item.status === "running") return { ...base, phase: "starting", id: null, workspaceId: null, error: null };
87
- const result = resultObject(output);
88
- if (!result) return null;
89
- const nested = record(result.workspace) ? result.workspace : null;
90
- const id = kind === "agent" ? str(result.agentId) ?? str(result.id) : str(result.workspaceId) ?? str(nested?.id) ?? str(result.id);
78
+ // Every shape Paseo sends (shared/tool-result.ts): Claude's { output }, Codex's MCP envelope, a JSON string.
79
+ const data = result.object;
80
+ if (!data) return null;
81
+ const nested = record(data.workspace) ? data.workspace : null;
82
+ const id = kind === "agent" ? str(data.agentId) ?? str(data.id) : str(data.workspaceId) ?? str(nested?.id) ?? str(data.id);
91
83
  if (!id) return null;
92
- return { ...base, phase: "created", id, title: base.title ?? (kind === "workspace" ? str(nested?.name) ?? str(result.name) : null),
93
- workspaceId: kind === "agent" ? str(result.workspaceId) : id, error: null };
84
+ return { ...base, phase: "created", id, title: base.title ?? (kind === "workspace" ? str(nested?.name) ?? str(data.title) ?? str(data.name) : null),
85
+ workspaceId: kind === "agent" ? str(data.workspaceId) : id, error: null };
94
86
  }
95
87
 
96
88
  /** Live facts the card reads (follow.created-items), from the engine's directory snapshot. Missing: not known yet. */
@@ -0,0 +1,63 @@
1
+ /** Standard Israeli SI-1452 key positions, not phonetic transliteration. Other scripts use physical capture. */
2
+ const EN = "qwertyuiopasdfghjkl;'zxcvbnm,./";
3
+ const HE = "/'קראטוןםפשדגכעיחלךף,זסבהנמצתץ.";
4
+ export function swapLayout(text: string, target: "english" | "hebrew"): string {
5
+ const from = target === "english" ? HE : EN, to = target === "english" ? EN : HE;
6
+ return [...text].map(c => { const i = from.indexOf(c.toLowerCase()); return target === "english" && c === "׳" ? "w" : i < 0 ? c : to[i]; }).join("");
7
+ }
8
+ /** Only offer script-appropriate variants. Mixed-script text keeps the already-correct words. */
9
+ export function layoutQueries(query: string, physical?: string | null): string[] {
10
+ const variants: string[] = [];
11
+ if (physical && physical !== query) return [physical];
12
+ if (/[\u0590-\u05ff]/u.test(query)) {
13
+ variants.push(swapLayout(query, "english"));
14
+ // Android Hebrew puts apostrophe and hyphen on Q/W; punctuation otherwise lives in its own row.
15
+ variants.push([...query].map(c => c === "'" ? "q" : c === "-" ? "w" : swapLayout(c, "english")).join(""));
16
+ }
17
+ else if (/[a-z]/i.test(query)) {
18
+ variants.push(swapLayout(query, "hebrew"));
19
+ variants.push([...query].map(c => c.toLowerCase() === "q" ? "'" : c.toLowerCase() === "w" ? "-" : swapLayout(c, "hebrew")).join(""));
20
+ }
21
+ const en = "`qwertyuiop[]asdfghjkl;'zxcvbnm,./", ru = "ёйцукенгшщзхъфывапролджэячсмитьбю.";
22
+ const russian = /[а-яё]/i.test(query);
23
+ if (russian || /[a-z]/i.test(query)) variants.push([...query].map(c => {
24
+ const from = russian ? ru : en, to = russian ? en : ru;
25
+ const i = from.indexOf(c.toLowerCase()); return i < 0 ? c : to[i];
26
+ }).join(""));
27
+ return [...new Set(variants)].filter(q => q !== query && q.trim());
28
+ }
29
+
30
+ export type LayoutKey = { key: string; code: string; shiftKey?: boolean; ctrlKey?: boolean; metaKey?: boolean; altKey?: boolean; isComposing?: boolean };
31
+ const PUNCT: Record<string, string> = { Space: " ", Minus: "-_", Equal: "=+", BracketLeft: "[{", BracketRight: "]}", Backslash: "\\|", Semicolon: ";:", Quote: "'\"", Comma: ",<", Period: ".>", Slash: "/?", Backquote: "`~" };
32
+ export function usKey(e: LayoutKey): string | null {
33
+ if (/^Key[A-Z]$/.test(e.code)) return e.shiftKey ? e.code.slice(3) : e.code.slice(3).toLowerCase();
34
+ if (/^Digit[0-9]$/.test(e.code)) return e.shiftKey ? ")!@#$%^&*("[Number(e.code.slice(5))] : e.code.slice(5);
35
+ const pair = PUNCT[e.code];
36
+ return pair ? pair[e.shiftKey && pair.length > 1 ? 1 : 0] : null;
37
+ }
38
+ /** Append-only reconstruction. Anything the key event cannot explain invalidates it until the field is empty. */
39
+ export class LayoutCapture {
40
+ private value = "";
41
+ private rebuilt: string | null = "";
42
+ private pending: { value: string; rebuilt: string } | null = null;
43
+ reset() { this.rebuilt = null; this.pending = null; }
44
+ key(e: LayoutKey, value: string, start: number | null, end: number | null) {
45
+ this.pending = null;
46
+ if (e.isComposing || e.altKey || e.ctrlKey || e.metaKey) { this.reset(); return; }
47
+ if (["Shift", "Control", "Alt", "Meta", "CapsLock"].includes(e.key)) return;
48
+ if (!value) { this.value = ""; this.rebuilt = ""; }
49
+ if (value !== this.value || start !== value.length || end !== start) { this.reset(); return; }
50
+ if (e.key === "Backspace" && this.rebuilt !== null) {
51
+ this.pending = { value: value.slice(0, -1), rebuilt: this.rebuilt.slice(0, -1) }; return;
52
+ }
53
+ if (e.key.length !== 1) { if (!["Enter", "Escape", "Tab"].includes(e.key)) this.reset(); return; }
54
+ const key = usKey(e);
55
+ if (!key || this.rebuilt === null) { this.reset(); return; }
56
+ this.pending = { value: value + e.key, rebuilt: this.rebuilt + key };
57
+ }
58
+ change(value: string): string | null {
59
+ this.rebuilt = !value ? "" : this.pending?.value === value ? this.pending.rebuilt : null;
60
+ this.value = value; this.pending = null;
61
+ return this.rebuilt && this.rebuilt !== value ? this.rebuilt : null;
62
+ }
63
+ }
package/shared/model.ts CHANGED
@@ -178,6 +178,11 @@ export const workspaceSchema = z.object({
178
178
  * clears an entry once its item is sent or cancelled; Needs you shows each with Retry and Cancel.
179
179
  */
180
180
  undelivered: z.array(z.object({ id: z.string().max(400), agentId: idSchema, agentTitle: z.string().nullable(), state: z.enum(["queued", "failed"]), reason: z.string().nullable(), since: z.string() })).max(20).optional(),
181
+ /**
182
+ * Follow-up is holding back its GitHub reads for this workspace's PRs until `until` (GitHub's reset): the account's
183
+ * GraphQL budget is under the reserve Follow-up leaves for agents (shared/poll.ts). Null or absent: reads run.
184
+ */
185
+ githubWait: z.object({ until: z.string() }).nullable().optional(),
181
186
  /** The main agent's title from Paseo, for "Next message to <title>". Absent: "the main agent". */
182
187
  mainAgentTitle: z.string().nullable().optional(),
183
188
  /** Open tasks kept out of the next message (reconcile): capped (sent NO_PROGRESS_CAP times unchanged), manual (Auto off for that task) or person (the agent said only a person can move it: Batch.humanOnly). */
@@ -1,3 +1,4 @@
1
+ import { searchRows } from "./search";
1
2
  import { sendingOf, type Sending } from "./sending";
2
3
  import { parseAnswersMessage } from "./questions";
3
4
  import { envelopeParts } from "./queue";
@@ -171,7 +172,12 @@ export const WORKSTREAMS_PAGE = 40;
171
172
  export function pageRows(rows: WorkstreamRow[], opts: { page?: number; size?: number; group?: HomeGroupId; query?: string } = {}) {
172
173
  const size = Math.min(Math.max(opts.size ?? WORKSTREAMS_PAGE, 1), 100);
173
174
  const q = opts.query?.trim().toLowerCase();
174
- const filtered = orderRows(rows).filter(r => (!opts.group || r.group === opts.group) && (!q || [r.title, r.branch, r.project, r.ask, r.activity, ...r.keys, ...r.prs.map(p => `#${p.number}`)].some(x => x?.toLowerCase().includes(q))));
175
+ const grouped = orderRows(rows).filter(r => !opts.group || r.group === opts.group);
176
+ const filtered = searchRows(grouped, r => [
177
+ { field: "name", text: r.title }, { field: "branch", text: r.branch ?? "" },
178
+ { field: "project", text: r.project ?? "" }, { field: "ask", text: [r.ask, r.activity].filter(Boolean).join(" ") },
179
+ { field: "linked", text: r.keys.join(" ") }, { field: "pr", text: r.prs.map(p => `#${p.number}`).join(" ") },
180
+ ], q ?? "");
175
181
  const pages = Math.max(1, Math.ceil(filtered.length / size));
176
182
  const page = Math.min(Math.max(opts.page ?? 1, 1), pages);
177
183
  // Resting workspaces come last and compact: no per-workspace detail, and their agents are likely unloaded.
package/shared/poll.ts CHANGED
@@ -62,26 +62,58 @@ export function cadence(s: Snapshot | null | undefined, error: string | null | u
62
62
  /** A merged PR is final: nothing on it feeds repairs, and its deploy state is probed separately every tick. */
63
63
  export const MERGED_POLL_MS = 30 * 60_000;
64
64
  /**
65
- * GitHub's GraphQL budget (5000 points an hour per account, shared with every agent). A read costs about one point
66
- * per PR. Under LOW_BUDGET points left, settled PRs wait LOW_IDLE_MS (and only in repositories with something
67
- * moving), merged PRs wait for the reset; under CRITICAL_BUDGET nothing is read until the reset.
65
+ * Change-first reads (server/github.ts). A due PR that was read in full before is first *probed*: one cheap query per
66
+ * account for every due PR (scalars, unresolved thread ids, check counts by state; ~1 point per 33 PRs). The full
67
+ * read (~1 point per PR) runs only when the probe saw something the full read decides on (`probeVerdict`), or
68
+ * SAFETY_READ_MS after the last one, for what a probe can't see (a reviewer request, branch protection, a parent).
69
+ * 2026-11-19 live: re-reading every due PR in full cost 4300-6400 points an hour, ~2000 more per pushed 60-PR stack.
68
70
  */
69
- export const LOW_BUDGET = 500;
71
+ export const SAFETY_READ_MS = 30 * 60_000;
72
+ /** Checks still running whose counts moved (one more finished, none failed) are read in full at most this often. */
73
+ export const RUNNING_FULL_MS = 5 * 60_000;
74
+ /** What a probe sees of a PR: `core` is everything but checks, as one string; checks are counts by state. */
75
+ export type Fingerprint = { core: string; checks: string; running: number; failed: number };
76
+ /**
77
+ * Whether a probe's fingerprint calls for a full read, given the fingerprint of the last full read and its age.
78
+ * Anything outside checks (head, updatedAt, state, base, draft, mergeability, review decision, merge queue, auto-merge,
79
+ * unresolved threads) reads at once; so does a change in failures, checks starting or all finishing. Running checks
80
+ * whose counts moved otherwise wait RUNNING_FULL_MS: a required check that passes changes mergeStateStatus, which is core.
81
+ */
82
+ export function probeVerdict(before: Fingerprint, now: Fingerprint, fullAge: number): "same" | "read" {
83
+ if (fullAge >= SAFETY_READ_MS) return "read";
84
+ if (before.core !== now.core || before.failed !== now.failed || (before.running === 0) !== (now.running === 0)) return "read";
85
+ if (before.checks !== now.checks && fullAge >= RUNNING_FULL_MS) return "read";
86
+ return "same";
87
+ }
88
+ /**
89
+ * GitHub's GraphQL budget (5000 points an hour per account, shared with every agent, gt and other plugins). A full
90
+ * read costs about one point per PR; a probe (below) about one point per 33 PRs.
91
+ * - `low` (under LOW_SHARE of the limit): settled PRs wait LOW_IDLE_MS, and only in repositories with something moving.
92
+ * - `reserve` (under RESERVE_SHARE): Follow-up's background reads stop until the reset, leaving the rest to agents.
93
+ * The developer's Refresh and agent tools (a fresh or foreground read of their own workspace) still read.
94
+ * - `critical` (under CRITICAL_BUDGET points): nothing is read until the reset.
95
+ * 2026-11-19 live: background reads ran the account down to 100 points left, so agents' gh calls failed first.
96
+ */
97
+ export const LOW_SHARE = 0.4;
98
+ export const RESERVE_SHARE = 0.2;
70
99
  export const CRITICAL_BUDGET = 100;
100
+ /** The limit GitHub reports for a user token; used when a response doesn't say. */
101
+ export const DEFAULT_LIMIT = 5000;
71
102
  export const LOW_IDLE_MS = 5 * 60_000;
72
- export type Budget = { remaining: number; resetAt: number };
73
- export type Tier = "normal" | "low" | "critical";
103
+ export type Budget = { remaining: number; resetAt: number; limit?: number };
104
+ export type Tier = "normal" | "low" | "reserve" | "critical";
74
105
  export function budgetTier(b: Budget | null | undefined, now: number): Tier {
75
106
  if (!b || now >= b.resetAt) return "normal";
76
- return b.remaining < CRITICAL_BUDGET ? "critical" : b.remaining < LOW_BUDGET ? "low" : "normal";
107
+ const limit = b.limit && b.limit > 0 ? b.limit : DEFAULT_LIMIT;
108
+ return b.remaining < CRITICAL_BUDGET ? "critical" : b.remaining < limit * RESERVE_SHARE ? "reserve" : b.remaining < limit * LOW_SHARE ? "low" : "normal";
77
109
  }
78
110
  /**
79
111
  * Whether a background tick reads this already-observed PR. Moving PRs: every tick, or every RUNNING_POLL_MS when
80
112
  * only checks are running (unless the budget is critical).
81
- * Settled open or closed PRs: every POLL_IDLE_MS. Merged: every MERGED_POLL_MS.
113
+ * Settled open PRs: every POLL_IDLE_MS. Merged (and closed): every MERGED_POLL_MS; server/github.ts skips final ones.
82
114
  */
83
115
  export function dueForRead(i: { snapshot: Snapshot | null | undefined; error: string | null | undefined; changedAt: number | null; readAt: number; now: number; tier: Tier; repoUrgent: boolean; since?: number | null }): boolean {
84
- if (i.tier === "critical") return false;
116
+ if (i.tier === "critical" || i.tier === "reserve") return false;
85
117
  const c = cadence(i.snapshot, i.error, i.changedAt, i.now);
86
118
  if (c === "tick") return true;
87
119
  const age = i.now - i.readAt;
@@ -90,6 +122,7 @@ export function dueForRead(i: { snapshot: Snapshot | null | undefined; error: st
90
122
  const long = i.since != null && i.now - i.since >= LONG_CHECKS_MS;
91
123
  return age >= (long ? LONG_RUNNING_POLL_MS : RUNNING_POLL_MS) - TICK_MS / 2;
92
124
  }
93
- if (i.tier === "low") return i.snapshot?.state !== "MERGED" && i.repoUrgent && age >= LOW_IDLE_MS;
94
- return age >= (i.snapshot?.state === "MERGED" ? MERGED_POLL_MS : POLL_IDLE_MS);
125
+ const settled = i.snapshot?.state === "MERGED" || i.snapshot?.state === "CLOSED";
126
+ if (i.tier === "low") return !settled && i.repoUrgent && age >= LOW_IDLE_MS;
127
+ return age >= (settled ? MERGED_POLL_MS : POLL_IDLE_MS);
95
128
  }
@@ -62,3 +62,17 @@ export function orderedStacks<P extends Pr>(prs: P[]): { name: string; prs: P[]
62
62
  const priority = (rows: Pr[]) => rows.every(settledForDisplay) ? 2 : rows.some(p => prPresentation(p).tone === "warning" || !statusKnown(p) || p.snapshot.state === "CLOSED" && !settled(p)) ? 0 : 1;
63
63
  return [...groups].map(([name, prs]) => ({ name, prs })).sort((a, b) => priority(a.prs) - priority(b.prs));
64
64
  }
65
+
66
+ /**
67
+ * The Pull requests card's line while Follow-up holds back its GitHub reads for the budget (Workspace.githubWait):
68
+ * what is happening, when checks resume (local time), and why the statuses below may be behind. Null when reads run.
69
+ */
70
+ export function githubWaitLine(w: { githubWait?: { until: string } | null }, now: number): { title: string; detail: string; label: string } | null {
71
+ const until = Date.parse(w.githubWait?.until ?? "");
72
+ if (!Number.isFinite(until) || until <= now) return null;
73
+ const at = new Date(until).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
74
+ // "updates", not "checks": this card also shows CI checks. "Limit", not "budget": GitHub's own word.
75
+ const title = `GitHub limit low · updates again at ${at}`;
76
+ const detail = "Follow-up paused to leave the rest to your agents. PR statuses here may be behind.";
77
+ return { title, detail, label: `${title}. ${detail}` };
78
+ }
package/shared/search.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { layoutQueries } from "./layout-swap";
1
2
  import type { HomeGroupId, HomeModel, PaseoWorkspaceLite } from "./home";
2
3
  import type { ArchivedListWorkspace, ListWorkspace as Workspace } from "./list";
3
4
  import { linkedSearchText, type LinkedSearchItem } from "./linked-display";
@@ -98,6 +99,8 @@ export type SearchHit = {
98
99
  * 1 a typo, 0 inside a word (the weakest token decides). Optional only for rows built outside `search`.
99
100
  */
100
101
  rank?: Rank;
102
+ /** Query reconstructed from another keyboard layout; absent on direct hits. */
103
+ layoutQuery?: string;
101
104
  };
102
105
  export type Rank = { tier: 0 | 1 | 2; strength: 0 | 1 | 2 };
103
106
  const strengthOf = (m: number): 0 | 1 | 2 => m >= 0.85 ? 2 : m >= 0.45 ? 1 : 0;
@@ -106,9 +109,9 @@ const LAST: Rank = { tier: 2, strength: 0 };
106
109
  * The one ranking for every search over workspaces (one-ranking-for-every-workspace-search): a lower tier first, then
107
110
  * a stronger title match. Equal ranks are a tie each caller breaks its own way (score, or the list's order).
108
111
  */
109
- export function byRank(a: Pick<SearchHit, "rank"> | undefined, b: Pick<SearchHit, "rank"> | undefined): number {
112
+ export function byRank(a: Pick<SearchHit, "rank" | "layoutQuery"> | undefined, b: Pick<SearchHit, "rank" | "layoutQuery"> | undefined): number {
110
113
  const x = a?.rank ?? LAST, y = b?.rank ?? LAST;
111
- return x.tier - y.tier || y.strength - x.strength;
114
+ return Number(!!a?.layoutQuery) - Number(!!b?.layoutQuery) || x.tier - y.tier || y.strength - x.strength;
112
115
  }
113
116
 
114
117
  const DAY = 86_400_000;
@@ -116,7 +119,36 @@ const DAY = 86_400_000;
116
119
  * Every workstream matching all the query's tokens, best first. Archived ones come last, after every live one.
117
120
  * An empty query returns nothing: Home shows its groups instead.
118
121
  */
119
- export function search(index: SearchIndex, query: string, now = Date.now(), limit = 60): SearchHit[] {
122
+ export function search(index: SearchIndex, query: string, now = Date.now(), limit = 60, physical?: string | null): SearchHit[] {
123
+ if (!queryTokens(query).length) return [];
124
+ const direct = searchTyped(index, query, now, Infinity);
125
+ const seen = new Set(direct.map(h => h.key));
126
+ const converted: SearchHit[] = [];
127
+ for (const variant of layoutQueries(query, physical)) for (const hit of searchTyped(index, variant, now, Infinity)) {
128
+ if (seen.has(hit.key)) continue;
129
+ seen.add(hit.key); converted.push({ ...hit, layoutQuery: variant });
130
+ }
131
+ // Keep archived rows under their own heading at the bottom. Inside each group, direct matches come first.
132
+ return [...direct, ...converted].sort((a, b) => Number(a.group === "archived") - Number(b.group === "archived") || byScore(a, b)).slice(0, limit);
133
+ }
134
+
135
+ /** Quiet explanation only when a converted query finds more rows than the typed query. */
136
+ export function layoutHint(hits: readonly SearchHit[]): string | null {
137
+ const direct = hits.filter(h => !h.layoutQuery).length;
138
+ const counts = new Map<string, number>();
139
+ for (const h of hits) if (h.layoutQuery) counts.set(h.layoutQuery, (counts.get(h.layoutQuery) ?? 0) + 1);
140
+ const best = [...counts].sort((a, b) => b[1] - a[1])[0];
141
+ return best && best[1] > direct ? best[0] : null;
142
+ }
143
+
144
+ /** Reuse the workspace matcher for agent-tool filters too. */
145
+ export function searchRows<T>(rows: readonly T[], fields: (row: T) => SearchDoc["fields"], query: string, now = Date.now()): T[] {
146
+ if (!query.trim()) return [...rows];
147
+ const index = indexDocs(rows.map((r, i) => ({ key: String(i), title: "", group: "quiet", at: null, fields: fields(r) })));
148
+ return search(index, query, now, Infinity).map(h => rows[Number(h.key)]);
149
+ }
150
+
151
+ function searchTyped(index: SearchIndex, query: string, now: number, limit: number): SearchHit[] {
120
152
  const qs = queryTokens(query);
121
153
  if (!qs.length) return [];
122
154
  const phrase = qs.join(" ");
@@ -236,8 +268,8 @@ export function overseerProvider(enabled: boolean): OmniboxProvider {
236
268
  export function defaultActive(results: readonly OmniboxItem[] | null): number {
237
269
  return results?.length === 1 && results[0].ask !== undefined && !/\s/.test(results[0].ask) ? -1 : 0;
238
270
  }
239
- export function workspaceProvider(index: SearchIndex, now = Date.now()): OmniboxProvider {
240
- return { id: "workspaces", results: query => search(index, query, now).map(hit => ({ provider: "workspaces", key: hit.key, hit })) };
271
+ export function workspaceProvider(index: SearchIndex, now = Date.now(), physical?: string | null): OmniboxProvider {
272
+ return { id: "workspaces", results: query => search(index, query, now, 60, physical).map(hit => ({ provider: "workspaces", key: hit.key, hit })) };
241
273
  }
242
274
 
243
275
  // ---------- documents from Home's sources ----------
@@ -357,9 +389,9 @@ export function rowHit(hit: SearchHit, row: { title: string; agent?: string | nu
357
389
  * keeps the chosen sort. Only matching rows stay, groups left empty drop out, and archived workspaces aren't listed
358
390
  * (Home's search finds those). An empty query returns the model unchanged.
359
391
  */
360
- export function filterHome(model: HomeModel, index: SearchIndex, query: string, now = Date.now()): { model: HomeModel; hits: Map<string, SearchHit> | null } {
392
+ export function filterHome(model: HomeModel, index: SearchIndex, query: string, now = Date.now(), physical?: string | null): { model: HomeModel; hits: Map<string, SearchHit> | null } {
361
393
  if (!queryTokens(query).length) return { model, hits: null };
362
- const hits = new Map(search(index, query, now, Infinity).filter(h => h.group !== "archived").map(h => [h.key, h]));
394
+ const hits = new Map(search(index, query, now, Infinity, physical).filter(h => h.group !== "archived").map(h => [h.key, h]));
363
395
  // Array sort is stable: an equal rank keeps the list's own order.
364
396
  const groups = model.groups.map(g => ({ ...g, items: g.items.filter(s => hits.has(s.key)).sort((a, b) => byRank(hits.get(a.key), hits.get(b.key))) }))
365
397
  .filter(g => g.items.length);
@@ -32,8 +32,20 @@ const memory = new Map<string, string>();
32
32
  let backend: KeyValue | null = null;
33
33
  const viewListeners = new Set<() => void>();
34
34
  let viewVersion = 0;
35
+ /**
36
+ * Writes made while the document is still loading (`writes-while-loading-reach-the-document`): a surface opened at
37
+ * start-up (a settings tab straight from a link, a fold) writes before the document arrives, and the document's older
38
+ * value must not win over it. They are replayed into the document when it arrives. A value merely cached from an
39
+ * earlier session is not one of them, so the document still wins over that.
40
+ */
41
+ const pending = new Map<string, string>();
35
42
  /** Swap in (or out, with null) the device document behind deviceStorage; re-renders whatever reads view state. */
36
- export function setDeviceBackend(next: KeyValue | null) { backend = next; if (next) status = "ready"; viewChanged(); }
43
+ export function setDeviceBackend(next: KeyValue | null) {
44
+ backend = next;
45
+ if (next) { status = "ready"; for (const [key, value] of pending) next.set(key, value); }
46
+ pending.clear();
47
+ viewChanged();
48
+ }
37
49
  /** none: this host keeps no device document (0.15). loading: expected, not loaded yet. ready / failed. */
38
50
  export type ViewStatus = "none" | "loading" | "ready" | "failed";
39
51
  let status: ViewStatus = "none";
@@ -48,7 +60,7 @@ const local = {
48
60
  };
49
61
  export const deviceStorage: KeyValue = {
50
62
  get(key) { return backend?.get(key) ?? local.get(key); },
51
- set(key, value) { local.set(key, value); backend?.set(key, value); viewChanged(); },
63
+ set(key, value) { local.set(key, value); if (backend) backend.set(key, value); else if (status === "loading") pending.set(key, value); viewChanged(); },
52
64
  };
53
65
  /** The localStorage cache alone: what a device migrates into its document once. */
54
66
  export const localViewStorage: KeyValue = local;
@@ -0,0 +1,70 @@
1
+ /**
2
+ * The one reader of a tool call's result as Paseo hands it to plugins (`tool_call` item `detail.output`). Every
3
+ * Follow-up reader of a tool result goes through `toolResult`, never `detail.output` directly
4
+ * (`every-tool-result-reads-through-one-normalizer`, tests/tool-result.test.ts). Paseo sends one of:
5
+ *
6
+ * - Claude: `{ output: X, files? }` (Paseo's Claude provider, `buildToolOutput`): X is the parsed JSON of the result's
7
+ * text when it parses, else the text itself.
8
+ * - Codex: the raw MCP result `{ content: [{ type: "text", text }], structuredContent?, isError?, _meta? }`. Paseo's own
9
+ * tools put a summary in front of the JSON in that text ("availableModes_count=3\n…\n\n{…}"); structuredContent
10
+ * holds the object.
11
+ * - A plain string (other providers, shell output, transcripts) or the object itself.
12
+ */
13
+ export type ToolResult = {
14
+ /** The result as text: the string itself, the MCP text blocks joined, or the object as JSON. "" when there's none. */
15
+ text: string;
16
+ /** The result as data: structuredContent, else the parsed JSON (whole text, else its trailing JSON object), else the object itself. */
17
+ value: unknown;
18
+ /** `value` when it's a plain object. */
19
+ object: Record<string, unknown> | null;
20
+ /** An MCP error result (`isError: true`), at any wrapper depth. */
21
+ isError: boolean;
22
+ };
23
+
24
+ const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v);
25
+ const CLAUDE_WRAPPER_KEYS = new Set(["output", "files"]);
26
+ const MAX_DEPTH = 8;
27
+
28
+ /** JSON text, or text whose JSON value starts on its own line after a preamble ("key=value" lines, a sentence). */
29
+ function parseJson(text: string): unknown {
30
+ const body = text.trim();
31
+ if (!body) return undefined;
32
+ try { return JSON.parse(body); } catch { /* not whole JSON */ }
33
+ const at = body.search(/(?:^|\n)\s*[[{]/);
34
+ if (at < 0) return undefined;
35
+ const tail = body.slice(at).trim();
36
+ try { return JSON.parse(tail); } catch { return undefined; }
37
+ }
38
+
39
+ const blockText = (blocks: unknown[]): string =>
40
+ blocks.map(b => typeof b === "string" ? b : record(b) && typeof b.text === "string" ? b.text : "").filter(Boolean).join("\n");
41
+
42
+ function read(output: unknown, depth: number): ToolResult {
43
+ if (output === null || output === undefined) return { text: "", value: undefined, object: null, isError: false };
44
+ if (typeof output === "string") {
45
+ const value = parseJson(output);
46
+ return { text: output, value, object: record(value) ? value : null, isError: false };
47
+ }
48
+ if (Array.isArray(output)) {
49
+ // Bare content blocks.
50
+ const text = blockText(output);
51
+ const value = parseJson(text);
52
+ return { text, value, object: record(value) ? value : null, isError: false };
53
+ }
54
+ if (!record(output)) return { text: String(output), value: output, object: null, isError: false };
55
+ if (depth < MAX_DEPTH && "output" in output && Object.keys(output).every(k => CLAUDE_WRAPPER_KEYS.has(k))) return read(output.output, depth + 1);
56
+ if (Array.isArray(output.content)) {
57
+ const text = blockText(output.content);
58
+ const isError = output.isError === true || output.is_error === true;
59
+ const structured = record(output.structuredContent) ? output.structuredContent : undefined;
60
+ const value = structured ?? parseJson(text);
61
+ return { text, value, object: record(value) ? value : null, isError };
62
+ }
63
+ // The object itself (Claude's wrapper already peeled, or a provider that hands the result as data).
64
+ const text = typeof output.text === "string" ? output.text : JSON.stringify(output, null, 2);
65
+ return { text, value: output, object: output, isError: output.isError === true || output.is_error === true };
66
+ }
67
+
68
+ export function toolResult(output: unknown): ToolResult {
69
+ return read(output, 0);
70
+ }