@0perator/operator 0.1.284 → 0.1.313

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +24 -2
  2. package/dist/acp/agent.js +3 -2
  3. package/dist/acp/config-options.js +15 -1
  4. package/dist/acp/tool-map.js +2 -1
  5. package/dist/auth/commands.js +69 -13
  6. package/dist/autonomy/agent-cli.js +304 -0
  7. package/dist/autonomy/cloud-agent.js +439 -0
  8. package/dist/autonomy/cron-lifecycle.js +78 -0
  9. package/dist/autonomy/cron-lock.js +121 -0
  10. package/dist/autonomy/cron.js +216 -43
  11. package/dist/autonomy/delegate.js +5 -1
  12. package/dist/autonomy/incidents.js +135 -0
  13. package/dist/autonomy/session-factory.js +25 -16
  14. package/dist/background/index.js +40 -0
  15. package/dist/bus/inbox.js +20 -0
  16. package/dist/classifier/config.js +47 -0
  17. package/dist/classifier/modes.js +41 -0
  18. package/dist/classifier/types.js +1 -0
  19. package/dist/cli.js +529 -53
  20. package/dist/config/features.js +69 -0
  21. package/dist/config/persona.js +118 -99
  22. package/dist/config/scaffold.js +15 -0
  23. package/dist/config/settings.js +96 -6
  24. package/dist/consolidation/sleep.js +73 -11
  25. package/dist/engine/agent.js +275 -18
  26. package/dist/engine/anthropic-chat.js +343 -0
  27. package/dist/engine/aurora.js +101 -13
  28. package/dist/engine/batch-scheduler.js +41 -9
  29. package/dist/engine/classifier.js +85 -0
  30. package/dist/engine/compaction.js +24 -5
  31. package/dist/engine/fast-start.js +25 -0
  32. package/dist/engine/loop-guard.js +448 -0
  33. package/dist/engine/moa.js +5 -1
  34. package/dist/engine/net-error.js +24 -0
  35. package/dist/engine/repetition-guard.js +180 -0
  36. package/dist/engine/selfheal.js +8 -0
  37. package/dist/engine/toolcalls.js +51 -1
  38. package/dist/engine/verify-gate.js +2 -0
  39. package/dist/flywheel/processor.js +78 -31
  40. package/dist/flywheel/srft.js +13 -0
  41. package/dist/hooks/index.js +196 -0
  42. package/dist/mcp/config.js +21 -1
  43. package/dist/memory/index.js +0 -0
  44. package/dist/memory/providers.js +210 -0
  45. package/dist/memory/session-catalog.js +422 -0
  46. package/dist/memory/session-providers.js +121 -0
  47. package/dist/memory/session-sources.js +335 -0
  48. package/dist/memory/skylark.js +131 -0
  49. package/dist/models/bench.js +103 -0
  50. package/dist/models/registry.js +144 -0
  51. package/dist/models/switch.js +69 -0
  52. package/dist/observability/blackbox.js +37 -0
  53. package/dist/permissions/policy.js +31 -6
  54. package/dist/router/discovery.js +127 -0
  55. package/dist/router/models.js +117 -24
  56. package/dist/router/portal.js +100 -0
  57. package/dist/router/router.js +1 -1
  58. package/dist/services/preflight.js +55 -7
  59. package/dist/session.js +316 -46
  60. package/dist/tools/chauffeur.js +12 -0
  61. package/dist/tools/executor.js +19 -9
  62. package/dist/tools/find-files.js +483 -0
  63. package/dist/tools/git-pr.js +94 -0
  64. package/dist/tools/incident-tools.js +82 -0
  65. package/dist/tools/memory.js +12 -2
  66. package/dist/tools/registry.js +281 -85
  67. package/dist/tools/semantic-compress.js +124 -0
  68. package/dist/tools/shell-context.js +1 -0
  69. package/dist/tools/shell-jobs.js +160 -0
  70. package/dist/tools/shell-session.js +170 -4
  71. package/dist/tools/wave-tools.js +609 -0
  72. package/dist/tools/wave2-tools.js +411 -0
  73. package/dist/ui/App.js +15 -4
  74. package/dist/ui/BgPanel.js +30 -6
  75. package/dist/ui/Composer.js +11 -1
  76. package/dist/ui/QuestionPrompt.js +31 -11
  77. package/dist/ui/SessionPicker.js +86 -0
  78. package/dist/ui/StatusRule.js +5 -5
  79. package/dist/ui/ToolStep.js +2 -1
  80. package/dist/ui/Transcript.js +17 -1
  81. package/dist/ui/index.js +1 -1
  82. package/dist/ui/liveTools.js +21 -3
  83. package/dist/ui/slashCommands.js +2 -0
  84. package/dist/util/screenshots.js +74 -8
  85. package/dist/util/slash.js +2 -2
  86. package/package.json +8 -2
  87. package/dist/engine/cli.js +0 -1171
  88. package/dist/router/models.js.bak +0 -78
  89. package/dist/router/models.js.bak-1791259923 +0 -78
  90. package/dist/router/models.js.bak-pre-gateway +0 -78
  91. package/dist/router/models.js.bak-pre-patch2 +0 -78
  92. package/dist/router/models.js.bak2 +0 -78
  93. package/dist/services/model-autodetect.js +0 -240
  94. package/dist/tools/native-redirect.js +0 -140
  95. package/dist/tools/power-tools.js +0 -627
  96. package/dist/tools/registry.js.bak-1791259948 +0 -1914
  97. package/dist/tools/registry.js.bak-pre-plugins +0 -1914
  98. package/dist/ui/BusTray.js +0 -70
  99. package/dist/ui/resize.js +0 -160
@@ -9,13 +9,33 @@
9
9
  // esbuild --platform=neutral can't resolve a variable specifier, so it leaves these as true runtime
10
10
  // imports on the node path. A browser host only uses http MCP servers and injects its config directly;
11
11
  // this file-reading path is the node CLI / Electron-main path and never runs in JSCore.
12
+ import { operatorPath } from "../config/home.js"; // neutral-safe (resolves per call)
12
13
  const nodeImport = (m) => import(/* @vite-ignore */ m);
13
14
  const env = () => (typeof process !== "undefined" ? process.env : {});
14
15
  const VAR_RE = /\$\{([A-Z0-9_]+)\}/g;
16
+ // Config file resolution — probe reality, in order, first hit wins:
17
+ // 1. the OPERATOR HOME (operatorPath — honors $KODE_HOME/$KODE_PROFILE; the product's own
18
+ // location, where a fresh install and every enterprise tenant writes), then
19
+ // 2. the legacy python-core location (compat: existing fleet boxes keep working untouched).
20
+ // When NEITHER exists, the operator-home path is returned so a first write lands in the right
21
+ // place. Env overrides ($KODE_MCP_CONFIG/$KODE_MCP_SECRETS) bypass this entirely in the caller.
15
22
  async function defaultPath(file) {
23
+ const modern = operatorPath(file);
24
+ const { access } = await nodeImport("node:fs/promises");
25
+ try {
26
+ await access(modern);
27
+ return modern;
28
+ }
29
+ catch { /* not there — probe legacy */ }
16
30
  const { homedir } = await nodeImport("node:os");
17
31
  const { join } = await nodeImport("node:path");
18
- return join(homedir(), ".axe", "cli", "backend", file);
32
+ const legacy = join(homedir(), ".axe", "cli", "backend", file);
33
+ try {
34
+ await access(legacy);
35
+ return legacy;
36
+ }
37
+ catch { /* neither — new installs use the home */ }
38
+ return modern;
19
39
  }
20
40
  async function readJson(path) {
21
41
  const { readFile } = await nodeImport("node:fs/promises");
Binary file
@@ -0,0 +1,210 @@
1
+ // Memory providers (PV2-34, branch 1 — the contract). WHICH memory backends recall/store is
2
+ // configuration, not code — the same split session-providers.ts made for session search. Code knows
3
+ // only BACKENDS (a closed enum; adding one is a code change); which providers are on, and how they
4
+ // are tuned, comes from settings. `MemoryStore` (./index.js) is NOT abstracted away: it stays the
5
+ // proven local backend, and this module adds the interface, the registry, and the composite beside
6
+ // it. With no `memory.providers` configured, `buildMemory` returns the bare `MemoryStore` — the
7
+ // default path is byte-identical to the pre-provider engine, proven by test.
8
+ //
9
+ // The composite is where the cross-cutting guarantees live, once:
10
+ // - SECRET GATE: every store() runs redactSecrets BEFORE any provider sees the text — the flywheel
11
+ // already does this at its disk boundary (selfimprove/index.ts); the provider layer does it for
12
+ // every backend, local included. (The bare-store default keeps today's behavior; the gate rides
13
+ // the provider layer.)
14
+ // - DEGRADE, NEVER THROW: recall fans out with a per-provider timeout (settings-tunable); a
15
+ // provider that errors or times out contributes nothing. Consecutive failures put a provider on
16
+ // an in-memory cooldown (mem0's circuit breaker, simplified) so a down backend costs one timeout,
17
+ // not one per turn.
18
+ // - WRITE SCOPE IS A TYPE: `canStore:false` (the commons tier) is enforced in the composite — a
19
+ // memory-layer write can never bypass a proposal-gated backend's review path.
20
+ // - MERGE DISCIPLINE: local hits first, then other providers by confidence (desc), dedup by text,
21
+ // cap — the recallText contract MemoryStore already honors.
22
+ //
23
+ // Factories: "local" (branch 1) and "skylark" (branch 2 — ./skylark.js, the one KB client);
24
+ // "commons" parses as config (so settings can be staged ahead) but builds to nothing until its
25
+ // branch lands — an unbuildable entry is skipped, never thrown, exactly like an unknown agents.md
26
+ // section. Pure parse/merge logic, node-free: the composite only touches disk through providers.
27
+ import { MemoryStore } from "./index.js";
28
+ import { redactSecrets } from "../engine/redact.js";
29
+ import { skylarkProvider } from "./skylark.js";
30
+ /** The built-in backends. A provider picks one; adding a backend is a code change, enabling a provider is not. */
31
+ export const MEMORY_BACKENDS = ["local", "skylark", "commons"];
32
+ export const DEFAULT_PROVIDER_TIMEOUT_MS = 2000;
33
+ const COOLDOWN_FAILURES = 3; // consecutive failures that open a provider's breaker…
34
+ const COOLDOWN_MS = 60_000; // …and how long it stays open
35
+ /** Parse + normalize the configured provider list. Pure. `KODE_MEMORY_PROVIDERS=local,skylark` (ids,
36
+ * comma-separated) narrows the enabled set without touching settings — absent env leaves config as-is.
37
+ * Returns entries in config order with duplicates (by id) and disabled entries dropped; `skipped`
38
+ * reports what fell out and why (diagnostics, never a throw). */
39
+ export function parseProviderConfig(cfg, env = typeof process !== "undefined" ? process.env : {}) {
40
+ const skipped = [];
41
+ const raw = cfg?.providers ?? [];
42
+ const envSet = env.KODE_MEMORY_PROVIDERS
43
+ ? new Set(env.KODE_MEMORY_PROVIDERS.split(",")
44
+ .map((s) => s.trim().toLowerCase())
45
+ .filter(Boolean))
46
+ : undefined;
47
+ const seen = new Set();
48
+ const entries = [];
49
+ for (const e of raw) {
50
+ const id = String(e?.id ?? "").trim().toLowerCase();
51
+ if (!id) {
52
+ skipped.push("(entry with no id)");
53
+ continue;
54
+ }
55
+ if (seen.has(id)) {
56
+ skipped.push(`${id}: duplicate`);
57
+ continue;
58
+ }
59
+ seen.add(id);
60
+ if (e.enabled === false) {
61
+ skipped.push(`${id}: disabled`);
62
+ continue;
63
+ }
64
+ if (envSet && !envSet.has(id)) {
65
+ skipped.push(`${id}: excluded by the environment provider override`);
66
+ continue;
67
+ }
68
+ entries.push({ ...e, id });
69
+ }
70
+ return { entries, skipped };
71
+ }
72
+ const FACTORIES = {
73
+ local: (_cfg, store) => localProvider(store),
74
+ skylark: (cfg) => skylarkProvider(cfg),
75
+ };
76
+ /** The built-in store wrapped as a provider. Always first, always storable. */
77
+ export function localProvider(store = new MemoryStore()) {
78
+ return {
79
+ slug: "local",
80
+ backend: "local",
81
+ canStore: true,
82
+ available: async () => true,
83
+ store: (text, tags, supersedes) => store.capture(text, tags, supersedes),
84
+ recall: (query, limit) => store.recall(query, limit),
85
+ };
86
+ }
87
+ /** Fan-out memory over the enabled providers, with the MemoryStore-shaped surface callers use. */
88
+ export class CompositeMemory {
89
+ providers;
90
+ timeoutMs;
91
+ now;
92
+ breakers = new Map();
93
+ constructor(providers, timeoutMs = DEFAULT_PROVIDER_TIMEOUT_MS, now = Date.now) {
94
+ this.providers = providers;
95
+ this.timeoutMs = timeoutMs;
96
+ this.now = now;
97
+ }
98
+ breaker(slug) {
99
+ let b = this.breakers.get(slug);
100
+ if (!b) {
101
+ b = { failures: 0, openUntil: 0 };
102
+ this.breakers.set(slug, b);
103
+ }
104
+ return b;
105
+ }
106
+ /** Run one provider call under the budget; failures/timeouts count toward the breaker and yield the fallback. */
107
+ async guarded(p, fallback, run) {
108
+ const b = this.breaker(p.slug);
109
+ if (this.now() < b.openUntil)
110
+ return fallback;
111
+ try {
112
+ const out = await Promise.race([
113
+ run(),
114
+ new Promise((resolve) => setTimeout(() => resolve(fallback), this.timeoutMs)),
115
+ ]);
116
+ b.failures = 0;
117
+ return out;
118
+ }
119
+ catch {
120
+ if (++b.failures >= COOLDOWN_FAILURES) {
121
+ b.openUntil = this.now() + COOLDOWN_MS;
122
+ b.failures = 0;
123
+ }
124
+ return fallback;
125
+ }
126
+ }
127
+ /** Secret-gated write: local (first storable provider) is awaited — its verdict is the return —
128
+ * and every other storable provider is fire-and-forget. canStore:false providers never see it.
129
+ * `supersedes` (an id from that SAME store's own recall) only means anything to the provider that
130
+ * issued the id, so it rides along to every provider but only the one that recognizes it acts on it. */
131
+ async capture(text, tags, supersedes) {
132
+ const clean = redactSecrets(text);
133
+ const storable = this.providers.filter((p) => p.canStore);
134
+ if (!storable.length)
135
+ return false;
136
+ const [first, ...rest] = storable;
137
+ for (const p of rest)
138
+ void this.guarded(p, false, () => p.store(clean, tags, supersedes));
139
+ return this.guarded(first, false, () => first.store(clean, tags, supersedes));
140
+ }
141
+ /** Fan out, then merge: local hits in their own order first, then other providers' by confidence
142
+ * (desc, missing = 0), dedup by text, cap at `limit`. */
143
+ async recall(query, limit = 5) {
144
+ const cap = Math.max(1, limit);
145
+ const results = await Promise.all(this.providers.map((p) => this.guarded(p, [], () => p.recall(query, cap))));
146
+ const local = [];
147
+ const remote = [];
148
+ this.providers.forEach((p, i) => (p.backend === "local" ? local : remote).push(...results[i]));
149
+ remote.sort((a, b) => (b.confidence ?? 0) - (a.confidence ?? 0));
150
+ const seen = new Set();
151
+ const merged = [];
152
+ for (const n of [...local, ...remote]) {
153
+ const key = n.text.trim();
154
+ if (!key || seen.has(key))
155
+ continue;
156
+ seen.add(key);
157
+ merged.push(n);
158
+ if (merged.length >= cap)
159
+ break;
160
+ }
161
+ return merged;
162
+ }
163
+ /** The system-prompt block — the exact relevant-then-recent, dedup, cap discipline MemoryStore has,
164
+ * over the composite. Non-local hits carry their source in the line so the agent can cite/confirm. */
165
+ async recallText(query, limit = 6) {
166
+ const relevant = query ? await this.recall(query, limit) : [];
167
+ const recent = await this.recall(undefined, limit);
168
+ const seen = new Set();
169
+ const merged = [];
170
+ for (const n of [...relevant, ...recent]) {
171
+ const key = `${n.ts} ${n.text}`;
172
+ if (seen.has(key))
173
+ continue;
174
+ seen.add(key);
175
+ merged.push(n);
176
+ if (merged.length >= limit)
177
+ break;
178
+ }
179
+ if (!merged.length)
180
+ return "";
181
+ const lines = merged.map((n) => {
182
+ const tag = n.tags?.length ? ` [${n.tags.join(", ")}]` : "";
183
+ const src = n.source ? ` (${n.source})` : "";
184
+ return `- ${n.text}${tag}${src}`;
185
+ });
186
+ return `## Operator Memory (recalled from past sessions)\n${lines.join("\n")}`;
187
+ }
188
+ }
189
+ /** The one entry point consumers use. No `memory.providers` configured → the bare MemoryStore
190
+ * (byte-identical to the pre-provider engine). Configured → the composite over every enabled entry
191
+ * a factory exists for; entries without a factory yet (skylark/commons before their branches) are
192
+ * skipped. A config that nets zero usable providers falls back to the bare store rather than a
193
+ * memory-less engine. */
194
+ export function buildMemory(cfg, store = new MemoryStore()) {
195
+ const { entries } = parseProviderConfig(cfg);
196
+ if (!entries.length)
197
+ return store;
198
+ const providers = [];
199
+ for (const e of entries) {
200
+ const made = FACTORIES[e.id]?.(e, store);
201
+ if (made)
202
+ providers.push(made);
203
+ }
204
+ if (!providers.length)
205
+ return store;
206
+ // Local always participates and always first: tier-1 memory is the floor, not an option.
207
+ if (!providers.some((p) => p.backend === "local"))
208
+ providers.unshift(localProvider(store));
209
+ return new CompositeMemory(providers, cfg?.timeoutMs ?? DEFAULT_PROVIDER_TIMEOUT_MS);
210
+ }
@@ -0,0 +1,422 @@
1
+ // Agent session search: one index over Operator's own sessions and other agents' sessions (providers
2
+ // configured in agents.md — session-providers.ts; read by format in session-sources.ts), searchable by what
3
+ // was said in it. Lives beside the transcript index in
4
+ // $KODE_HOME/state/state.db as its own tables (catalog_sessions + catalog_fts, one FTS row per message so
5
+ // a hit can say WHO said it), with a JSON fallback at state/session-catalog.json when node:sqlite/FTS5
6
+ // is missing. Separate tables on purpose: state-maintenance audits sessions_meta/sessions_fts against
7
+ // $KODE_HOME/sessions/*.json, and this catalog holds sessions that are not Operator's to repair.
8
+ // Derived data only — every row is re-readable from the source files. Incremental by mtime.
9
+ // Browser-safe like session-index.ts: node builtins load lazily, every probe is try/catch.
10
+ import { get_operator_home, operatorPath } from "../config/home.js";
11
+ import { redactSecrets } from "../engine/redact.js";
12
+ import { listSourceFiles, loadSessionDoc } from "./session-sources.js";
13
+ import { readProviders, resumeCommand } from "./session-providers.js";
14
+ const nodeImport = (m) => import(/* @vite-ignore */ m);
15
+ export const SESSION_SCOPES = ["workspace", "project", "all"];
16
+ const SNIPPET_CHARS = 160;
17
+ const READ_CAP = 24_000;
18
+ const CONTEXT_CAP = 12_000;
19
+ function tokenize(s) { return s.toLowerCase().match(/[a-z0-9]+/g) ?? []; }
20
+ function flat(s) { return s.replace(/\s+/g, " ").trim(); }
21
+ function snippetAround(body, query) {
22
+ const text = flat(body);
23
+ const lower = text.toLowerCase();
24
+ let at = -1;
25
+ for (const t of tokenize(query)) {
26
+ const i = lower.indexOf(t);
27
+ if (i >= 0 && (at < 0 || i < at))
28
+ at = i;
29
+ }
30
+ const start = at < 0 ? 0 : Math.max(0, at - Math.floor(SNIPPET_CHARS / 2));
31
+ const end = Math.min(text.length, start + SNIPPET_CHARS);
32
+ return (start > 0 ? "…" : "") + text.slice(start, end) + (end < text.length ? "…" : "");
33
+ }
34
+ // ---------------------------------------------------------------------------
35
+ // Config: providers come from agents.md; settings.sessionSearch.sources switches one on/off by slug (unset =
36
+ // what agents.md says). Read straight from the settings file (config/settings.ts imports node builtins
37
+ // statically, so the engine bundle cannot import it). Env wins: KODE_SESSION_SEARCH=0 turns search off,
38
+ // KODE_SESSION_SEARCH_SOURCES=<slug,slug> narrows it.
39
+ // ---------------------------------------------------------------------------
40
+ export async function sessionSearchConfig() {
41
+ let file = {};
42
+ try {
43
+ const fs = (await nodeImport("node:fs"));
44
+ const s = JSON.parse(fs.readFileSync(process.env.KODE_TSI_SETTINGS || operatorPath("settings.json"), "utf8"));
45
+ if (s && typeof s.sessionSearch === "object")
46
+ file = s.sessionSearch;
47
+ }
48
+ catch { /* no settings file — defaults */ }
49
+ const env = typeof process !== "undefined" ? process.env : {};
50
+ const enabled = env.KODE_SESSION_SEARCH === "0" ? false : env.KODE_SESSION_SEARCH === "1" ? true : file.enabled !== false;
51
+ const pick = env.KODE_SESSION_SEARCH_SOURCES?.split(",").map((x) => x.trim());
52
+ const providers = (await readProviders()).filter((p) => (pick ? pick.includes(p.slug) : file.sources?.[p.slug] ?? p.enabled));
53
+ return { enabled, providers };
54
+ }
55
+ function preview(doc) {
56
+ const last = doc.messages[doc.messages.length - 1];
57
+ return last ? { previewRole: last.role, preview: flat(last.text).slice(0, SNIPPET_CHARS) } : {};
58
+ }
59
+ function toEntry(doc) {
60
+ return {
61
+ id: doc.id, source: doc.source, nativeId: doc.nativeId, title: doc.title, cwd: doc.cwd, model: doc.model,
62
+ msgs: doc.msgCount, subagents: doc.subagents, startedAt: doc.startedAt, updatedAt: doc.updatedAt, file: doc.file, ...preview(doc),
63
+ };
64
+ }
65
+ const COLS = "id, source, native_id, title, cwd, model, msgs, subagents, started, updated, mtime, file, preview_role, preview";
66
+ function rowEntry(r) {
67
+ return {
68
+ id: r.id, source: r.source, nativeId: r.native_id, title: r.title, cwd: r.cwd ?? undefined, model: r.model ?? undefined,
69
+ msgs: Number(r.msgs), subagents: r.subagents == null ? undefined : Number(r.subagents),
70
+ startedAt: r.started == null ? undefined : Number(r.started), updatedAt: Number(r.updated), file: r.file,
71
+ previewRole: r.preview_role ?? undefined, preview: r.preview ?? undefined,
72
+ };
73
+ }
74
+ class SqliteStore {
75
+ db;
76
+ kind = "sqlite";
77
+ constructor(db) {
78
+ this.db = db;
79
+ }
80
+ mtimes() {
81
+ return new Map(this.db.prepare("SELECT id, mtime FROM catalog_sessions").all().map((r) => [r.id, Number(r.mtime)]));
82
+ }
83
+ upsert(doc, mtimeMs) {
84
+ const e = toEntry(doc);
85
+ this.db.exec("BEGIN");
86
+ try {
87
+ this.db.prepare("DELETE FROM catalog_sessions WHERE id = ?").run(e.id);
88
+ this.db.prepare("DELETE FROM catalog_fts WHERE id = ?").run(e.id);
89
+ this.db.prepare(`INSERT INTO catalog_sessions (${COLS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(e.id, e.source, e.nativeId, e.title, e.cwd ?? null, e.model ?? null, e.msgs, e.subagents ?? null, e.startedAt ?? null, e.updatedAt, mtimeMs, e.file, e.previewRole ?? null, e.preview ?? null);
90
+ const ins = this.db.prepare("INSERT INTO catalog_fts (id, role, body) VALUES (?, ?, ?)");
91
+ for (const m of doc.messages)
92
+ ins.run(e.id, m.role, m.text);
93
+ this.db.exec("COMMIT");
94
+ }
95
+ catch (err) {
96
+ try {
97
+ this.db.exec("ROLLBACK");
98
+ }
99
+ catch { /* already rolled back */ }
100
+ throw err;
101
+ }
102
+ }
103
+ remove(ids) {
104
+ for (const id of ids) {
105
+ this.db.prepare("DELETE FROM catalog_sessions WHERE id = ?").run(id);
106
+ this.db.prepare("DELETE FROM catalog_fts WHERE id = ?").run(id);
107
+ }
108
+ }
109
+ entries() { return this.db.prepare(`SELECT ${COLS} FROM catalog_sessions`).all().map(rowEntry); }
110
+ entry(id) {
111
+ const r = this.db.prepare(`SELECT ${COLS} FROM catalog_sessions WHERE id = ?`).all(id)[0];
112
+ return r ? rowEntry(r) : null;
113
+ }
114
+ match(query, cap) {
115
+ const terms = tokenize(query);
116
+ if (!terms.length)
117
+ return [];
118
+ // Each term as an FTS5 string literal: a user query never parses as FTS syntax.
119
+ const expr = terms.map((t) => `"${t}"`).join(" ");
120
+ try {
121
+ return this.db.prepare("SELECT id, role, snippet(catalog_fts, 2, '', '', '…', 24) AS snip, bm25(catalog_fts) AS score FROM catalog_fts WHERE catalog_fts MATCH ? ORDER BY score LIMIT ?")
122
+ .all(expr, cap)
123
+ .map((r) => ({ id: r.id, role: r.role === "user" ? "user" : "assistant", snippet: flat(String(r.snip)), score: Number(r.score) }));
124
+ }
125
+ catch {
126
+ return []; // malformed expression or damaged index — "no matches", never a crash
127
+ }
128
+ }
129
+ messageCount() {
130
+ return Number(this.db.prepare("SELECT COALESCE(SUM(msgs), 0) AS n FROM catalog_sessions").all()[0].n);
131
+ }
132
+ close() { try {
133
+ this.db.close();
134
+ }
135
+ catch { /* best-effort */ } }
136
+ }
137
+ class JsonStore {
138
+ file;
139
+ fs;
140
+ kind = "json";
141
+ data = { version: 1, sessions: {} };
142
+ constructor(file, fs) {
143
+ this.file = file;
144
+ this.fs = fs;
145
+ try {
146
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
147
+ if (parsed?.version === 1 && parsed.sessions)
148
+ this.data = parsed;
149
+ }
150
+ catch { /* missing/corrupt — start fresh */ }
151
+ }
152
+ save() { this.fs.writeFileSync(this.file, JSON.stringify(this.data)); }
153
+ mtimes() { return new Map(Object.values(this.data.sessions).map((s) => [s.id, s.mtimeMs])); }
154
+ upsert(doc, mtimeMs) {
155
+ this.data.sessions[doc.id] = { ...toEntry(doc), mtimeMs, messages: doc.messages.map((m) => [m.role, m.text]) };
156
+ this.save();
157
+ }
158
+ remove(ids) { for (const id of ids)
159
+ delete this.data.sessions[id]; if (ids.length)
160
+ this.save(); }
161
+ entries() { return Object.values(this.data.sessions).map(({ mtimeMs: _m, messages: _x, ...e }) => e); }
162
+ entry(id) { const s = this.data.sessions[id]; if (!s)
163
+ return null; const { mtimeMs: _m, messages: _x, ...e } = s; return e; }
164
+ match(query, cap) {
165
+ const terms = [...new Set(tokenize(query))];
166
+ if (!terms.length)
167
+ return [];
168
+ const out = [];
169
+ for (const s of Object.values(this.data.sessions)) {
170
+ for (const [role, text] of s.messages) {
171
+ const toks = new Set(tokenize(text));
172
+ if (terms.every((t) => toks.has(t))) {
173
+ out.push({ id: s.id, role: role === "user" ? "user" : "assistant", snippet: snippetAround(text, query), score: 0 });
174
+ if (out.length >= cap)
175
+ return out;
176
+ }
177
+ }
178
+ }
179
+ return out;
180
+ }
181
+ messageCount() { return Object.values(this.data.sessions).reduce((n, s) => n + s.msgs, 0); }
182
+ close() { }
183
+ }
184
+ let _store = null;
185
+ let _storeHome = null;
186
+ async function store() {
187
+ const home = get_operator_home();
188
+ if (_store && _storeHome === home)
189
+ return _store;
190
+ if (_store) {
191
+ _store.close();
192
+ _store = null;
193
+ }
194
+ const fs = (await nodeImport("node:fs"));
195
+ fs.mkdirSync(operatorPath("state"), { recursive: true });
196
+ try {
197
+ const sqlite = await nodeImport("node:sqlite");
198
+ if (!sqlite?.DatabaseSync)
199
+ throw new Error("no node:sqlite");
200
+ const db = new sqlite.DatabaseSync(operatorPath("state", "state.db"));
201
+ db.exec(`CREATE TABLE IF NOT EXISTS catalog_sessions (id TEXT PRIMARY KEY, source TEXT NOT NULL, native_id TEXT NOT NULL, title TEXT NOT NULL,
202
+ cwd TEXT, model TEXT, msgs INTEGER NOT NULL, subagents INTEGER, started REAL, updated REAL NOT NULL, mtime REAL NOT NULL, file TEXT NOT NULL,
203
+ preview_role TEXT, preview TEXT)`);
204
+ db.exec("CREATE VIRTUAL TABLE IF NOT EXISTS catalog_fts USING fts5(id UNINDEXED, role UNINDEXED, body)");
205
+ _store = new SqliteStore(db);
206
+ }
207
+ catch {
208
+ _store = new JsonStore(operatorPath("state", "session-catalog.json"), fs);
209
+ }
210
+ _storeHome = home;
211
+ return _store;
212
+ }
213
+ // ---------------------------------------------------------------------------
214
+ // Index
215
+ // ---------------------------------------------------------------------------
216
+ let inflight = null;
217
+ /** Bring the catalog up to date with the enabled sources (only changed files are re-read). Concurrent
218
+ * callers share one pass. */
219
+ export function indexCatalog(providers) {
220
+ inflight ??= (async () => {
221
+ const t0 = Date.now();
222
+ const st = await store();
223
+ const enabled = providers ?? (await sessionSearchConfig()).providers;
224
+ const files = await listSourceFiles(enabled, operatorPath("sessions"));
225
+ const known = st.mtimes();
226
+ let indexed = 0, skipped = 0;
227
+ for (const f of files) {
228
+ if (known.get(f.id) === f.mtimeMs) {
229
+ skipped++;
230
+ continue;
231
+ }
232
+ const doc = await loadSessionDoc(f);
233
+ if (!doc) {
234
+ skipped++;
235
+ continue;
236
+ }
237
+ st.upsert(doc, f.mtimeMs);
238
+ indexed++;
239
+ }
240
+ const live = new Set(files.map((f) => f.id));
241
+ const gone = [...known.keys()].filter((id) => !live.has(id));
242
+ st.remove(gone);
243
+ return { indexed, skipped, removed: gone.length, sessions: st.entries().length, messages: st.messageCount(), ms: Date.now() - t0 };
244
+ })().finally(() => { inflight = null; });
245
+ return inflight;
246
+ }
247
+ export async function catalogStats() {
248
+ const st = await store();
249
+ return { sessions: st.entries().length, messages: st.messageCount() };
250
+ }
251
+ export async function catalogEntry(id) {
252
+ const e = (await store()).entry(id);
253
+ return e && decorate(e, await providerMap());
254
+ }
255
+ // The provider (agents.md) behind each slug, for labels, resume commands and the reader format.
256
+ async function providerMap() {
257
+ return new Map((await readProviders()).map((p) => [p.slug, p]));
258
+ }
259
+ function decorate(e, providers) {
260
+ const p = providers.get(e.source);
261
+ return { ...e, agent: p?.name ?? e.source, resume: p?.resume ? resumeCommand(p.resume, e.nativeId, e.cwd) : undefined };
262
+ }
263
+ export async function catalogBackendKind() { return (await store()).kind; }
264
+ // ---------------------------------------------------------------------------
265
+ // Search
266
+ // ---------------------------------------------------------------------------
267
+ /** The git root above `cwd` (the "project"), or `cwd` itself when it is not in a repo. */
268
+ export async function projectRoot(cwd) {
269
+ try {
270
+ const fs = (await nodeImport("node:fs"));
271
+ const path = (await nodeImport("node:path"));
272
+ for (let dir = cwd;; dir = path.dirname(dir)) {
273
+ if (fs.existsSync(path.join(dir, ".git")))
274
+ return dir;
275
+ if (path.dirname(dir) === dir)
276
+ return cwd;
277
+ }
278
+ }
279
+ catch {
280
+ return cwd;
281
+ }
282
+ }
283
+ /** Pure: does a session's folder fall inside the scope? (workspace = same folder, project = under root) */
284
+ export function inScope(entryCwd, scope, cwd, root) {
285
+ if (scope === "all")
286
+ return true;
287
+ if (!entryCwd)
288
+ return false;
289
+ const norm = (p) => p.replace(/\/+$/, "");
290
+ if (scope === "workspace")
291
+ return norm(entryCwd) === norm(cwd);
292
+ const r = norm(root);
293
+ return norm(entryCwd) === r || norm(entryCwd).startsWith(r + "/");
294
+ }
295
+ /** Sessions matching `query` (every term in one message), newest first. An empty query lists the newest
296
+ * sessions with their latest message as the snippet. Snippets are secret-redacted. */
297
+ export async function searchCatalog(query, opts = {}) {
298
+ const st = await store();
299
+ const limit = Number.isFinite(opts.limit) ? Math.max(1, Math.min(200, Math.floor(opts.limit))) : 20;
300
+ const scope = opts.scope ?? "all";
301
+ const cwd = opts.cwd ?? (typeof process !== "undefined" ? process.cwd() : "/");
302
+ const root = scope === "project" ? await projectRoot(cwd) : cwd;
303
+ const keep = (e) => (!opts.source || e.source === opts.source) && inScope(e.cwd, scope, cwd, root);
304
+ let hits;
305
+ if (!tokenize(query).length) {
306
+ hits = st.entries().filter(keep).map((e) => ({ ...e, role: e.previewRole, snippet: e.preview ?? "" }));
307
+ }
308
+ else {
309
+ const best = new Map();
310
+ for (const m of st.match(query, 4000))
311
+ if (!best.has(m.id))
312
+ best.set(m.id, m); // rows arrive best-first
313
+ hits = [];
314
+ for (const [id, m] of best) {
315
+ const e = st.entry(id);
316
+ if (e && keep(e))
317
+ hits.push({ ...e, role: m.role, snippet: m.snippet, score: m.score });
318
+ }
319
+ }
320
+ const providers = await providerMap();
321
+ return hits
322
+ .sort((a, b) => b.updatedAt - a.updatedAt)
323
+ .slice(0, limit)
324
+ .map((h) => decorate({ ...h, snippet: redactSecrets(h.snippet), preview: h.preview && redactSecrets(h.preview) }, providers));
325
+ }
326
+ // ---------------------------------------------------------------------------
327
+ // Presentation + reading
328
+ // ---------------------------------------------------------------------------
329
+ export function formatAge(ms, now = Date.now()) {
330
+ const s = Math.max(0, Math.round((now - ms) / 1000));
331
+ if (s < 60)
332
+ return "just now";
333
+ const m = Math.round(s / 60);
334
+ if (m < 60)
335
+ return `${m}m`;
336
+ const h = Math.round(m / 60);
337
+ if (h < 48)
338
+ return `${h}h`;
339
+ const d = Math.round(h / 24);
340
+ if (d < 14)
341
+ return `${d}d`;
342
+ return `${Math.round(d / 7)}w`;
343
+ }
344
+ export const roleLabel = (r) => (r === "user" ? "User" : r === "assistant" ? "Assistant" : "");
345
+ /** The meta line shared by the tool output and the /sessions picker: "<agent> · 42 msgs · 3 subagents · 12m · <model>". */
346
+ export function metaLine(h, now = Date.now()) {
347
+ return [h.agent ?? h.source, `${h.msgs} msg${h.msgs === 1 ? "" : "s"}`, h.subagents ? `${h.subagents} subagent${h.subagents === 1 ? "" : "s"}` : "", formatAge(h.updatedAt, now), h.model ?? ""]
348
+ .filter(Boolean).join(" · ");
349
+ }
350
+ export async function folderExists(dir) {
351
+ if (!dir)
352
+ return false;
353
+ try {
354
+ return (await nodeImport("node:fs")).existsSync(dir);
355
+ }
356
+ catch {
357
+ return false;
358
+ }
359
+ }
360
+ /** session_search's text output: three lines per hit. */
361
+ export async function formatHits(hits, now = Date.now()) {
362
+ if (!hits.length)
363
+ return "no matches";
364
+ const out = [];
365
+ for (const h of hits) {
366
+ const where = h.cwd ? ` · ${h.cwd}${(await folderExists(h.cwd)) ? "" : " (folder gone)"}` : "";
367
+ out.push(`${h.title} · ${metaLine(h, now)}${where}`);
368
+ if (h.snippet)
369
+ out.push(` ${roleLabel(h.role) ? roleLabel(h.role) + ": " : ""}${h.snippet}`);
370
+ out.push(` id: ${h.id}`);
371
+ }
372
+ return out.join("\n");
373
+ }
374
+ function render(doc, agent, messages = doc.messages) {
375
+ const head = `${doc.title} — ${agent} session ${doc.nativeId}${doc.cwd ? ` in ${doc.cwd}` : ""}${doc.model ? ` (${doc.model})` : ""}, ${doc.msgCount} messages`;
376
+ return [head, ...messages.map((m) => `${roleLabel(m.role)}: ${m.text}`)].join("\n\n");
377
+ }
378
+ async function docFor(id) {
379
+ const e = (await store()).entry(id);
380
+ const p = e && (await providerMap()).get(e.source);
381
+ if (!e || !p)
382
+ return null; // gone, or its provider was removed from agents.md
383
+ try {
384
+ const fs = (await nodeImport("node:fs"));
385
+ const doc = await loadSessionDoc({ id: e.id, source: e.source, format: p.format, file: e.file, mtimeMs: fs.statSync(e.file).mtimeMs });
386
+ return doc && { doc, agent: p.name };
387
+ }
388
+ catch {
389
+ return null;
390
+ }
391
+ }
392
+ /** One catalogued session as readable "User:/Assistant:" text, capped at 24k chars (secret-redacted). */
393
+ export async function readCatalogSession(id) {
394
+ const found = await docFor(id);
395
+ if (!found)
396
+ return null;
397
+ const text = redactSecrets(render(found.doc, found.agent));
398
+ return text.length > READ_CAP ? text.slice(0, READ_CAP) + "\n\n[... transcript truncated at 24000 chars — the newest messages are in /sessions ...]" : text;
399
+ }
400
+ /** The framed hand-off for continuing another agent's session in Operator: header + the newest messages
401
+ * that fit CONTEXT_CAP, oldest first. */
402
+ export async function continuationContext(id) {
403
+ const found = await docFor(id);
404
+ if (!found)
405
+ return null;
406
+ const { doc, agent } = found;
407
+ const kept = [];
408
+ let size = 0;
409
+ for (let i = doc.messages.length - 1; i >= 0; i--) {
410
+ const m = doc.messages[i];
411
+ size += m.text.length + 16;
412
+ if (size > CONTEXT_CAP && kept.length)
413
+ break;
414
+ kept.unshift(m);
415
+ }
416
+ const omitted = doc.msgCount - kept.length;
417
+ const text = redactSecrets(`[Continuing a ${agent} session in Operator: "${doc.title}"${doc.cwd ? ` (folder ${doc.cwd})` : ""}. ` +
418
+ `${omitted > 0 ? `The newest ${kept.length} of ${doc.msgCount} messages are below; session_read ${doc.id} has more. ` : "The whole conversation is below. "}` +
419
+ `Read it, say in two or three lines where it left off and what the next step was, then wait for my instruction.]\n\n` +
420
+ kept.map((m) => `${roleLabel(m.role)}: ${m.text}`).join("\n\n"));
421
+ return { doc, text };
422
+ }