@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.
- package/README.md +24 -2
- package/dist/acp/agent.js +3 -2
- package/dist/acp/config-options.js +15 -1
- package/dist/acp/tool-map.js +2 -1
- package/dist/auth/commands.js +69 -13
- package/dist/autonomy/agent-cli.js +304 -0
- package/dist/autonomy/cloud-agent.js +439 -0
- package/dist/autonomy/cron-lifecycle.js +78 -0
- package/dist/autonomy/cron-lock.js +121 -0
- package/dist/autonomy/cron.js +216 -43
- package/dist/autonomy/delegate.js +5 -1
- package/dist/autonomy/incidents.js +135 -0
- package/dist/autonomy/session-factory.js +25 -16
- package/dist/background/index.js +40 -0
- package/dist/bus/inbox.js +20 -0
- package/dist/classifier/config.js +47 -0
- package/dist/classifier/modes.js +41 -0
- package/dist/classifier/types.js +1 -0
- package/dist/cli.js +529 -53
- package/dist/config/features.js +69 -0
- package/dist/config/persona.js +118 -99
- package/dist/config/scaffold.js +15 -0
- package/dist/config/settings.js +96 -6
- package/dist/consolidation/sleep.js +73 -11
- package/dist/engine/agent.js +275 -18
- package/dist/engine/anthropic-chat.js +343 -0
- package/dist/engine/aurora.js +101 -13
- package/dist/engine/batch-scheduler.js +41 -9
- package/dist/engine/classifier.js +85 -0
- package/dist/engine/compaction.js +24 -5
- package/dist/engine/fast-start.js +25 -0
- package/dist/engine/loop-guard.js +448 -0
- package/dist/engine/moa.js +5 -1
- package/dist/engine/net-error.js +24 -0
- package/dist/engine/repetition-guard.js +180 -0
- package/dist/engine/selfheal.js +8 -0
- package/dist/engine/toolcalls.js +51 -1
- package/dist/engine/verify-gate.js +2 -0
- package/dist/flywheel/processor.js +78 -31
- package/dist/flywheel/srft.js +13 -0
- package/dist/hooks/index.js +196 -0
- package/dist/mcp/config.js +21 -1
- package/dist/memory/index.js +0 -0
- package/dist/memory/providers.js +210 -0
- package/dist/memory/session-catalog.js +422 -0
- package/dist/memory/session-providers.js +121 -0
- package/dist/memory/session-sources.js +335 -0
- package/dist/memory/skylark.js +131 -0
- package/dist/models/bench.js +103 -0
- package/dist/models/registry.js +144 -0
- package/dist/models/switch.js +69 -0
- package/dist/observability/blackbox.js +37 -0
- package/dist/permissions/policy.js +31 -6
- package/dist/router/discovery.js +127 -0
- package/dist/router/models.js +117 -24
- package/dist/router/portal.js +100 -0
- package/dist/router/router.js +1 -1
- package/dist/services/preflight.js +55 -7
- package/dist/session.js +316 -46
- package/dist/tools/chauffeur.js +12 -0
- package/dist/tools/executor.js +19 -9
- package/dist/tools/find-files.js +483 -0
- package/dist/tools/git-pr.js +94 -0
- package/dist/tools/incident-tools.js +82 -0
- package/dist/tools/memory.js +12 -2
- package/dist/tools/registry.js +281 -85
- package/dist/tools/semantic-compress.js +124 -0
- package/dist/tools/shell-context.js +1 -0
- package/dist/tools/shell-jobs.js +160 -0
- package/dist/tools/shell-session.js +170 -4
- package/dist/tools/wave-tools.js +609 -0
- package/dist/tools/wave2-tools.js +411 -0
- package/dist/ui/App.js +15 -4
- package/dist/ui/BgPanel.js +30 -6
- package/dist/ui/Composer.js +11 -1
- package/dist/ui/QuestionPrompt.js +31 -11
- package/dist/ui/SessionPicker.js +86 -0
- package/dist/ui/StatusRule.js +5 -5
- package/dist/ui/ToolStep.js +2 -1
- package/dist/ui/Transcript.js +17 -1
- package/dist/ui/index.js +1 -1
- package/dist/ui/liveTools.js +21 -3
- package/dist/ui/slashCommands.js +2 -0
- package/dist/util/screenshots.js +74 -8
- package/dist/util/slash.js +2 -2
- package/package.json +8 -2
- package/dist/engine/cli.js +0 -1171
- package/dist/router/models.js.bak +0 -78
- package/dist/router/models.js.bak-1791259923 +0 -78
- package/dist/router/models.js.bak-pre-gateway +0 -78
- package/dist/router/models.js.bak-pre-patch2 +0 -78
- package/dist/router/models.js.bak2 +0 -78
- package/dist/services/model-autodetect.js +0 -240
- package/dist/tools/native-redirect.js +0 -140
- package/dist/tools/power-tools.js +0 -627
- package/dist/tools/registry.js.bak-1791259948 +0 -1914
- package/dist/tools/registry.js.bak-pre-plugins +0 -1914
- package/dist/ui/BusTray.js +0 -70
- package/dist/ui/resize.js +0 -160
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// Session-search providers: WHICH other agents' histories are searchable is configuration, not code. Each
|
|
2
|
+
// provider is one entry in the Operator home's agents.md — a name, where its history lives, which built-in
|
|
3
|
+
// reader understands it (a FORMAT), how to reopen a session in that agent, and whether it is on. Code knows
|
|
4
|
+
// only formats; labels, roots and resume commands all come from the file. Operator's own sessions are
|
|
5
|
+
// built in under the name "Operator" and need no entry.
|
|
6
|
+
//
|
|
7
|
+
// Pure parser + template (browser-safe); readProviders loads node builtins lazily and scaffolds the file
|
|
8
|
+
// on first use (config/scaffold.ts also writes it with the rest of the home).
|
|
9
|
+
import { operatorPath } from "../config/home.js";
|
|
10
|
+
const nodeImport = (m) => import(/* @vite-ignore */ m);
|
|
11
|
+
/** The built-in readers. A provider picks one; adding a reader is a code change, adding a provider is not. */
|
|
12
|
+
export const HISTORY_FORMATS = ["operator", "claude-jsonl", "codex-rollout"];
|
|
13
|
+
/** Operator's own sessions: always present, never configured here. */
|
|
14
|
+
export const OPERATOR_PROVIDER = {
|
|
15
|
+
slug: "operator", name: "Operator", history: "", format: "operator", resume: "cd {cwd} && operator --resume", enabled: true,
|
|
16
|
+
};
|
|
17
|
+
export const AGENTS_MD_TEMPLATE = `# Agent session providers
|
|
18
|
+
|
|
19
|
+
Operator's session search (/sessions, session_search) indexes Operator's own sessions plus every provider
|
|
20
|
+
listed here. One \`## Name\` section per provider, then \`key: value\` lines:
|
|
21
|
+
|
|
22
|
+
- \`history\` — the folder (or glob) holding that agent's session files; \`~\` is your home directory.
|
|
23
|
+
- \`format\` — which built-in reader understands the files: \`operator\`, \`claude-jsonl\` or \`codex-rollout\`.
|
|
24
|
+
- \`resume\` — the command that reopens a session in that agent; \`{id}\` is its session id, \`{cwd}\` its folder.
|
|
25
|
+
- \`enabled\` — \`true\` or \`false\`.
|
|
26
|
+
|
|
27
|
+
Add a provider by appending a section. An entry with a missing or unknown \`history\`/\`format\` is skipped.
|
|
28
|
+
The index stays on this machine.
|
|
29
|
+
|
|
30
|
+
## Claude Code
|
|
31
|
+
history: ~/.claude/projects
|
|
32
|
+
format: claude-jsonl
|
|
33
|
+
resume: cd {cwd} && claude --resume {id}
|
|
34
|
+
enabled: true
|
|
35
|
+
|
|
36
|
+
## Codex
|
|
37
|
+
history: ~/.codex/sessions
|
|
38
|
+
format: codex-rollout
|
|
39
|
+
resume: codex resume {id}
|
|
40
|
+
enabled: true
|
|
41
|
+
`;
|
|
42
|
+
export function slugify(name) {
|
|
43
|
+
return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "agent";
|
|
44
|
+
}
|
|
45
|
+
/** Parse agents.md: every `## Name` section with a known format and a history becomes a provider; anything
|
|
46
|
+
* else is reported in `skipped` (never thrown). Later duplicates of a slug, and the reserved "operator", are skipped. */
|
|
47
|
+
export function parseAgentsMd(text) {
|
|
48
|
+
const providers = [];
|
|
49
|
+
const skipped = [];
|
|
50
|
+
const sections = [];
|
|
51
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
52
|
+
const head = /^##\s+(.+?)\s*$/.exec(raw);
|
|
53
|
+
if (head) {
|
|
54
|
+
sections.push({ name: head[1], fields: {} });
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
const kv = /^\s*([A-Za-z_]+)\s*:\s*(.*?)\s*$/.exec(raw);
|
|
58
|
+
if (kv && sections.length)
|
|
59
|
+
sections[sections.length - 1].fields[kv[1].toLowerCase()] = kv[2];
|
|
60
|
+
}
|
|
61
|
+
const seen = new Set([OPERATOR_PROVIDER.slug]);
|
|
62
|
+
for (const { name, fields } of sections) {
|
|
63
|
+
const slug = slugify(name);
|
|
64
|
+
const format = fields.format;
|
|
65
|
+
if (seen.has(slug)) {
|
|
66
|
+
skipped.push(`${name}: duplicate or reserved name`);
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
if (!HISTORY_FORMATS.includes(format)) {
|
|
70
|
+
skipped.push(`${name}: unknown format "${fields.format ?? ""}"`);
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
if (!fields.history) {
|
|
74
|
+
skipped.push(`${name}: no history`);
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
seen.add(slug);
|
|
78
|
+
providers.push({ slug, name, history: fields.history, format, resume: fields.resume ?? "", enabled: !/^(false|no|off|0)$/i.test(fields.enabled ?? "true") });
|
|
79
|
+
}
|
|
80
|
+
return { providers, skipped };
|
|
81
|
+
}
|
|
82
|
+
/** The command that reopens a session in its own agent, from the provider's template. With no known folder,
|
|
83
|
+
* a leading `cd {cwd} &&` is dropped rather than left dangling. */
|
|
84
|
+
export function resumeCommand(template, id, cwd) {
|
|
85
|
+
let t = template;
|
|
86
|
+
if (!cwd)
|
|
87
|
+
t = t.replace(/^\s*cd\s+\{cwd\}\s*&&\s*/, "");
|
|
88
|
+
return t.replace(/\{id\}/g, id).replace(/\{cwd\}/g, cwd ? shellQuote(cwd) : ".");
|
|
89
|
+
}
|
|
90
|
+
function shellQuote(s) { return /^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`; }
|
|
91
|
+
/** agents.md's path: KODE_AGENTS_MD (tests point it at a fixture), else the Operator home. */
|
|
92
|
+
export function agentsMdPath() {
|
|
93
|
+
return (typeof process !== "undefined" && process.env.KODE_AGENTS_MD) || operatorPath("agents.md");
|
|
94
|
+
}
|
|
95
|
+
/** The configured providers (Operator's own first). Writes the template on first use; an unreadable file
|
|
96
|
+
* yields Operator only. */
|
|
97
|
+
export async function readProviders() {
|
|
98
|
+
let text = "";
|
|
99
|
+
try {
|
|
100
|
+
const fs = (await nodeImport("node:fs"));
|
|
101
|
+
const file = agentsMdPath();
|
|
102
|
+
if (!fs.existsSync(file)) {
|
|
103
|
+
try {
|
|
104
|
+
fs.writeFileSync(file, AGENTS_MD_TEMPLATE, { mode: 0o644 });
|
|
105
|
+
}
|
|
106
|
+
catch { /* read-only home — use the template as-is */ }
|
|
107
|
+
text = AGENTS_MD_TEMPLATE;
|
|
108
|
+
}
|
|
109
|
+
else
|
|
110
|
+
text = fs.readFileSync(file, "utf8");
|
|
111
|
+
}
|
|
112
|
+
catch { /* node-free host */ }
|
|
113
|
+
return [OPERATOR_PROVIDER, ...parseAgentsMd(text).providers];
|
|
114
|
+
}
|
|
115
|
+
/** Expand a leading "~" to the home directory. */
|
|
116
|
+
export async function expandHome(p) {
|
|
117
|
+
if (!p.startsWith("~"))
|
|
118
|
+
return p;
|
|
119
|
+
const os = (await nodeImport("node:os"));
|
|
120
|
+
return os.homedir() + p.slice(1);
|
|
121
|
+
}
|
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
// Session readers for session search, one per history FORMAT (session-providers.ts): `operator` (Operator's
|
|
2
|
+
// own transcripts), `claude-jsonl` (one JSON record per line, content blocks) and `codex-rollout`
|
|
3
|
+
// ({ type, payload } records). Which agents' histories exist, what they are called and where they live is
|
|
4
|
+
// configuration (agents.md) — nothing here names an agent. Each format becomes one SessionDoc shape so the
|
|
5
|
+
// catalog (session-catalog.ts) indexes them identically. The readers are pure line/JSON reducers — no I/O,
|
|
6
|
+
// unit-tested on fixtures; discovery + streaming reads load node builtins lazily (nodeImport, same idiom as
|
|
7
|
+
// session-index.ts) so the engine bundle stays browser-safe.
|
|
8
|
+
import { OPERATOR_PROVIDER, expandHome } from "./session-providers.js";
|
|
9
|
+
const nodeImport = (m) => import(/* @vite-ignore */ m);
|
|
10
|
+
const MSG_CHARS = 2000; // per message kept for search; a pasted log does not need to be indexed whole
|
|
11
|
+
const MAX_MESSAGES = 6000; // per session kept for search (the newest); msgCount still reports the total
|
|
12
|
+
const TITLE_CHARS = 80;
|
|
13
|
+
function clip(s, n) { return s.length > n ? s.slice(0, n) : s; }
|
|
14
|
+
function oneLine(s) { return s.replace(/\s+/g, " ").trim(); }
|
|
15
|
+
export function titleFrom(text) {
|
|
16
|
+
const t = oneLine(text);
|
|
17
|
+
return t.length > TITLE_CHARS ? t.slice(0, TITLE_CHARS - 1) + "…" : t;
|
|
18
|
+
}
|
|
19
|
+
function tsOf(v) {
|
|
20
|
+
if (typeof v === "number" && Number.isFinite(v))
|
|
21
|
+
return v;
|
|
22
|
+
if (typeof v === "string") {
|
|
23
|
+
const n = Date.parse(v);
|
|
24
|
+
return Number.isFinite(n) ? n : undefined;
|
|
25
|
+
}
|
|
26
|
+
return undefined;
|
|
27
|
+
}
|
|
28
|
+
// Harness wrappers both agents put in the user role (slash-command echoes, injected reminders,
|
|
29
|
+
// environment blocks) are not something anyone said — they would drown real matches.
|
|
30
|
+
function isWrapper(text) {
|
|
31
|
+
return /^\s*<(command-|local-command|system-reminder|environment_context|user_instructions|turn_aborted)/.test(text) || /^\s*Caveat: The messages below/.test(text);
|
|
32
|
+
}
|
|
33
|
+
/** Accumulates messages for one session: caps text, keeps the newest MAX_MESSAGES, counts all. */
|
|
34
|
+
class Collector {
|
|
35
|
+
messages = [];
|
|
36
|
+
count = 0;
|
|
37
|
+
firstUser = "";
|
|
38
|
+
first;
|
|
39
|
+
last;
|
|
40
|
+
add(role, raw, ts) {
|
|
41
|
+
const text = raw.trim();
|
|
42
|
+
if (!text || (role === "user" && isWrapper(text)))
|
|
43
|
+
return;
|
|
44
|
+
this.count++;
|
|
45
|
+
if (role === "user" && !this.firstUser)
|
|
46
|
+
this.firstUser = text;
|
|
47
|
+
if (ts !== undefined) {
|
|
48
|
+
this.first ??= ts;
|
|
49
|
+
this.last = Math.max(this.last ?? ts, ts);
|
|
50
|
+
}
|
|
51
|
+
this.messages.push({ role, text: clip(text, MSG_CHARS), ts });
|
|
52
|
+
if (this.messages.length > MAX_MESSAGES * 1.25)
|
|
53
|
+
this.messages = this.messages.slice(-MAX_MESSAGES);
|
|
54
|
+
}
|
|
55
|
+
done() { return this.messages.length > MAX_MESSAGES ? this.messages.slice(-MAX_MESSAGES) : this.messages; }
|
|
56
|
+
}
|
|
57
|
+
export function parseOperatorTranscript(json, id, file, mtimeMs) {
|
|
58
|
+
const archive = json && typeof json === "object" && !Array.isArray(json) ? json : null;
|
|
59
|
+
const msgs = archive ? archive.messages : json;
|
|
60
|
+
if (!Array.isArray(msgs))
|
|
61
|
+
return null;
|
|
62
|
+
const c = new Collector();
|
|
63
|
+
for (const m of msgs) {
|
|
64
|
+
if ((m?.role === "user" || m?.role === "assistant") && typeof m.content === "string")
|
|
65
|
+
c.add(m.role, m.content);
|
|
66
|
+
}
|
|
67
|
+
if (!c.count)
|
|
68
|
+
return null;
|
|
69
|
+
return {
|
|
70
|
+
id, source: OPERATOR_PROVIDER.slug, nativeId: id,
|
|
71
|
+
title: archive?.title || titleFrom(c.firstUser) || "(untitled)",
|
|
72
|
+
cwd: archive?.cwd, model: archive?.model,
|
|
73
|
+
messages: c.done(), msgCount: c.count,
|
|
74
|
+
startedAt: archive?.startedAt, updatedAt: archive?.updatedAt ?? mtimeMs, file,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
// ---------------------------------------------------------------------------
|
|
78
|
+
// claude-jsonl: one JSON record per line. user/assistant records carry message.content (a string or
|
|
79
|
+
// content blocks; only "text" blocks are conversation — tool_use/tool_result/thinking are not), cwd and
|
|
80
|
+
// timestamp; assistant records name the model; "ai-title"/"summary"/"custom-title" records name the
|
|
81
|
+
// session (latest wins). Sidechain (sub-agent) records are not the main conversation.
|
|
82
|
+
// ---------------------------------------------------------------------------
|
|
83
|
+
function blockText(content) {
|
|
84
|
+
if (typeof content === "string")
|
|
85
|
+
return content;
|
|
86
|
+
if (!Array.isArray(content))
|
|
87
|
+
return "";
|
|
88
|
+
return content.filter((b) => b && b.type === "text" && typeof b.text === "string").map((b) => b.text).join("\n");
|
|
89
|
+
}
|
|
90
|
+
export function claudeJsonlReader(slug, nativeId) {
|
|
91
|
+
const c = new Collector();
|
|
92
|
+
let title = "", summary = "", cwd, model;
|
|
93
|
+
return {
|
|
94
|
+
feed(line) {
|
|
95
|
+
// Most lines are attachments, file snapshots and tool results: test the type before paying for JSON.parse.
|
|
96
|
+
if (!/"type":"(user|assistant|ai-title|custom-title|summary)"/.test(line))
|
|
97
|
+
return;
|
|
98
|
+
let r;
|
|
99
|
+
try {
|
|
100
|
+
r = JSON.parse(line);
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
if (r.type === "ai-title" && typeof r.aiTitle === "string") {
|
|
106
|
+
title = r.aiTitle;
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
if (r.type === "custom-title" && typeof r.customTitle === "string") {
|
|
110
|
+
title = r.customTitle;
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
if (r.type === "summary" && typeof r.summary === "string") {
|
|
114
|
+
summary = r.summary;
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
if (r.isSidechain || r.isMeta)
|
|
118
|
+
return;
|
|
119
|
+
if (typeof r.cwd === "string")
|
|
120
|
+
cwd ??= r.cwd;
|
|
121
|
+
const msg = r.message;
|
|
122
|
+
if (r.type === "assistant" && typeof msg?.model === "string" && !msg.model.startsWith("<"))
|
|
123
|
+
model = msg.model;
|
|
124
|
+
c.add(r.type, blockText(msg?.content), tsOf(r.timestamp));
|
|
125
|
+
},
|
|
126
|
+
finish(file, mtimeMs) {
|
|
127
|
+
if (!c.count)
|
|
128
|
+
return null;
|
|
129
|
+
return {
|
|
130
|
+
id: `${slug}:${nativeId}`, source: slug, nativeId,
|
|
131
|
+
title: titleFrom(title || summary || c.firstUser) || "(untitled)",
|
|
132
|
+
cwd, model, messages: c.done(), msgCount: c.count,
|
|
133
|
+
startedAt: c.first, updatedAt: c.last ?? mtimeMs, file,
|
|
134
|
+
};
|
|
135
|
+
},
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
// ---------------------------------------------------------------------------
|
|
139
|
+
// codex-rollout: { timestamp, type, payload } per line. session_meta names the session id + cwd,
|
|
140
|
+
// turn_context the model, response_item/message the conversation (input_text / output_text blocks).
|
|
141
|
+
// event_msg repeats the same turns for the UI and is ignored.
|
|
142
|
+
// ---------------------------------------------------------------------------
|
|
143
|
+
export function codexRolloutReader(slug, fallbackId) {
|
|
144
|
+
const c = new Collector();
|
|
145
|
+
let nativeId = fallbackId, cwd, model, started;
|
|
146
|
+
return {
|
|
147
|
+
feed(line) {
|
|
148
|
+
if (!/"type":"(session_meta|turn_context|response_item)"/.test(line))
|
|
149
|
+
return;
|
|
150
|
+
let r;
|
|
151
|
+
try {
|
|
152
|
+
r = JSON.parse(line);
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
const p = r.payload ?? {};
|
|
158
|
+
if (r.type === "session_meta") {
|
|
159
|
+
if (typeof p.id === "string")
|
|
160
|
+
nativeId = p.id;
|
|
161
|
+
if (typeof p.cwd === "string")
|
|
162
|
+
cwd = p.cwd;
|
|
163
|
+
started = tsOf(p.timestamp) ?? tsOf(r.timestamp);
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
if (r.type === "turn_context") {
|
|
167
|
+
if (typeof p.model === "string")
|
|
168
|
+
model = p.model;
|
|
169
|
+
if (typeof p.cwd === "string")
|
|
170
|
+
cwd ??= p.cwd;
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
if (p.type !== "message" || (p.role !== "user" && p.role !== "assistant"))
|
|
174
|
+
return;
|
|
175
|
+
const text = Array.isArray(p.content)
|
|
176
|
+
? p.content.filter((b) => typeof b?.text === "string").map((b) => b.text).join("\n")
|
|
177
|
+
: typeof p.content === "string" ? p.content : "";
|
|
178
|
+
c.add(p.role, text, tsOf(r.timestamp));
|
|
179
|
+
},
|
|
180
|
+
finish(file, mtimeMs) {
|
|
181
|
+
if (!c.count)
|
|
182
|
+
return null;
|
|
183
|
+
return {
|
|
184
|
+
id: `${slug}:${nativeId}`, source: slug, nativeId,
|
|
185
|
+
title: titleFrom(c.firstUser) || "(untitled)",
|
|
186
|
+
cwd, model, messages: c.done(), msgCount: c.count,
|
|
187
|
+
startedAt: started ?? c.first, updatedAt: c.last ?? mtimeMs, file,
|
|
188
|
+
};
|
|
189
|
+
},
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
// ---------------------------------------------------------------------------
|
|
193
|
+
// Discovery + reading (node only). A provider's `history` is a root folder, read with its format's layout,
|
|
194
|
+
// or a glob (any `*`/`?`), whose matches are the session files.
|
|
195
|
+
// ---------------------------------------------------------------------------
|
|
196
|
+
// The session id a format's file name carries: a rollout file ends in the session uuid; the others are the
|
|
197
|
+
// file name without its extension.
|
|
198
|
+
export function nativeIdFromFile(format, name) {
|
|
199
|
+
if (format === "codex-rollout") {
|
|
200
|
+
const m = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i.exec(name);
|
|
201
|
+
if (m)
|
|
202
|
+
return m[1];
|
|
203
|
+
}
|
|
204
|
+
return name.replace(/\.jsonl?$/, "");
|
|
205
|
+
}
|
|
206
|
+
/** Glob → RegExp over a full path: `**` spans folders, `*` and `?` stay inside one. */
|
|
207
|
+
export function globToRegExp(glob) {
|
|
208
|
+
let re = "";
|
|
209
|
+
for (let i = 0; i < glob.length; i++) {
|
|
210
|
+
const ch = glob[i];
|
|
211
|
+
if (ch === "*" && glob[i + 1] === "*") {
|
|
212
|
+
re += ".*";
|
|
213
|
+
i++;
|
|
214
|
+
if (glob[i + 1] === "/")
|
|
215
|
+
i++;
|
|
216
|
+
}
|
|
217
|
+
else if (ch === "*")
|
|
218
|
+
re += "[^/]*";
|
|
219
|
+
else if (ch === "?")
|
|
220
|
+
re += "[^/]";
|
|
221
|
+
else
|
|
222
|
+
re += ch.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
223
|
+
}
|
|
224
|
+
return new RegExp(`^${re}$`);
|
|
225
|
+
}
|
|
226
|
+
/** Every session file of the given providers (Operator's own included when its provider is passed).
|
|
227
|
+
* Sub-agent transcripts nested under a claude-jsonl session are counted with it, not listed. */
|
|
228
|
+
export async function listSourceFiles(providers, operatorRoot) {
|
|
229
|
+
const fs = (await nodeImport("node:fs"));
|
|
230
|
+
const path = (await nodeImport("node:path"));
|
|
231
|
+
const out = [];
|
|
232
|
+
const stat = (file) => { try {
|
|
233
|
+
const st = fs.statSync(file);
|
|
234
|
+
return st.isFile() ? st.mtimeMs : null;
|
|
235
|
+
}
|
|
236
|
+
catch {
|
|
237
|
+
return null;
|
|
238
|
+
} };
|
|
239
|
+
const names = (dir) => { try {
|
|
240
|
+
return fs.readdirSync(dir).sort();
|
|
241
|
+
}
|
|
242
|
+
catch {
|
|
243
|
+
return [];
|
|
244
|
+
} };
|
|
245
|
+
const push = (p, file, native) => {
|
|
246
|
+
const m = stat(file);
|
|
247
|
+
if (m !== null)
|
|
248
|
+
out.push({ id: p.slug === OPERATOR_PROVIDER.slug ? native : `${p.slug}:${native}`, source: p.slug, format: p.format, file, mtimeMs: m });
|
|
249
|
+
};
|
|
250
|
+
const walk = (dir, depth, visit) => {
|
|
251
|
+
for (const n of names(dir)) {
|
|
252
|
+
const full = path.join(dir, n);
|
|
253
|
+
let isDir = false;
|
|
254
|
+
try {
|
|
255
|
+
isDir = fs.statSync(full).isDirectory();
|
|
256
|
+
}
|
|
257
|
+
catch {
|
|
258
|
+
continue;
|
|
259
|
+
}
|
|
260
|
+
if (isDir) {
|
|
261
|
+
if (depth > 0)
|
|
262
|
+
walk(full, depth - 1, visit);
|
|
263
|
+
}
|
|
264
|
+
else
|
|
265
|
+
visit(full, n);
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
for (const p of providers) {
|
|
269
|
+
const root = p.slug === OPERATOR_PROVIDER.slug && operatorRoot ? operatorRoot : await expandHome(p.history);
|
|
270
|
+
if (!root)
|
|
271
|
+
continue;
|
|
272
|
+
if (/[*?]/.test(root)) {
|
|
273
|
+
const base = root.slice(0, root.search(/[*?]/)).replace(/[^/]*$/, "") || "/";
|
|
274
|
+
const re = globToRegExp(root);
|
|
275
|
+
walk(base, 8, (file, name) => { if (re.test(file))
|
|
276
|
+
push(p, file, nativeIdFromFile(p.format, name)); });
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
if (p.format === "operator") {
|
|
280
|
+
// The per-folder resume file is a copy of that folder's newest archive, so it only counts for a folder
|
|
281
|
+
// with no archive yet (sessions from before archiving existed).
|
|
282
|
+
const archiveDir = path.join(root, "archive");
|
|
283
|
+
const archived = names(archiveDir).filter((n) => n.endsWith(".json"));
|
|
284
|
+
const hasArchive = new Set(archived.map((n) => n.split("-")[0]));
|
|
285
|
+
for (const n of names(root))
|
|
286
|
+
if (n.endsWith(".json") && !hasArchive.has(n.slice(0, -5)))
|
|
287
|
+
push(p, path.join(root, n), n.slice(0, -5));
|
|
288
|
+
for (const n of archived)
|
|
289
|
+
push(p, path.join(archiveDir, n), n.slice(0, -5));
|
|
290
|
+
}
|
|
291
|
+
else if (p.format === "claude-jsonl") {
|
|
292
|
+
for (const dir of names(root))
|
|
293
|
+
for (const n of names(path.join(root, dir)))
|
|
294
|
+
if (n.endsWith(".jsonl"))
|
|
295
|
+
push(p, path.join(root, dir, n), n.slice(0, -6));
|
|
296
|
+
}
|
|
297
|
+
else {
|
|
298
|
+
walk(root, 4, (file, name) => { if (name.endsWith(".jsonl"))
|
|
299
|
+
push(p, file, nativeIdFromFile(p.format, name)); });
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
return out;
|
|
303
|
+
}
|
|
304
|
+
/** Read one source file into a SessionDoc (streamed line by line — transcripts reach 100+ MB). */
|
|
305
|
+
export async function loadSessionDoc(f) {
|
|
306
|
+
const fs = (await nodeImport("node:fs"));
|
|
307
|
+
const path = (await nodeImport("node:path"));
|
|
308
|
+
try {
|
|
309
|
+
if (f.format === "operator") {
|
|
310
|
+
const doc = parseOperatorTranscript(JSON.parse(fs.readFileSync(f.file, "utf8")), f.id, f.file, f.mtimeMs);
|
|
311
|
+
if (doc)
|
|
312
|
+
doc.source = f.source;
|
|
313
|
+
return doc;
|
|
314
|
+
}
|
|
315
|
+
const native = f.id.slice(f.source.length + 1);
|
|
316
|
+
const parser = f.format === "claude-jsonl" ? claudeJsonlReader(f.source, native) : codexRolloutReader(f.source, native);
|
|
317
|
+
const readline = (await nodeImport("node:readline"));
|
|
318
|
+
const rl = readline.createInterface({ input: fs.createReadStream(f.file, { encoding: "utf8" }), crlfDelay: Infinity });
|
|
319
|
+
for await (const line of rl)
|
|
320
|
+
parser.feed(line);
|
|
321
|
+
const doc = parser.finish(f.file, f.mtimeMs);
|
|
322
|
+
if (doc)
|
|
323
|
+
doc.id = f.id; // the catalog keys on the file's id, whatever the transcript calls itself
|
|
324
|
+
if (doc && f.format === "claude-jsonl") {
|
|
325
|
+
try {
|
|
326
|
+
doc.subagents = fs.readdirSync(path.join(path.dirname(f.file), native, "subagents")).filter((n) => n.endsWith(".jsonl")).length || undefined;
|
|
327
|
+
}
|
|
328
|
+
catch { /* no sub-agents */ }
|
|
329
|
+
}
|
|
330
|
+
return doc;
|
|
331
|
+
}
|
|
332
|
+
catch {
|
|
333
|
+
return null; // unreadable / not a transcript — the catalog skips it and retries when the file changes
|
|
334
|
+
}
|
|
335
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// The ONE Skylark (knowledge-base) client — PV2-34 branch 2. Both the `knowledge_search` tool
|
|
2
|
+
// (tools/registry.ts) and the `skylark` memory provider (providers.ts) call through here, so the
|
|
3
|
+
// tree has exactly one implementation of the KB's config chain, wire shape, and error taxonomy.
|
|
4
|
+
//
|
|
5
|
+
// CONFIG RESOLUTION — one deterministic chain, first hit wins, no literal machine paths
|
|
6
|
+
// (decision 2026-10-21-config-resolution):
|
|
7
|
+
// url: provider cfg `url` → $KODE_KB_URL → kb.json `url` → http://127.0.0.1:5001
|
|
8
|
+
// token: provider cfg `token` → $KODE_KB_TOKEN → kb.json `token` → $KODE_KB_ENV_PATH (an
|
|
9
|
+
// explicit dotenv file the OPERATOR names — never a baked-in location) → unconfigured
|
|
10
|
+
// kb.json lives in the OPERATOR HOME (operatorPath — honors the home/profile overrides).
|
|
11
|
+
//
|
|
12
|
+
// Writes are tier-2 territory (document KB, may sit beside partner data): Skylark's ingest is
|
|
13
|
+
// FILE-based, so a stored note becomes a small named text file posted to /api/upload — and the
|
|
14
|
+
// provider only does that when the owner set `write:true` in its config. Default is read-only.
|
|
15
|
+
// Fetch is global; node builtins load lazily (neutral-bundle discipline).
|
|
16
|
+
import { operatorPath } from "../config/home.js";
|
|
17
|
+
const nodeImport = (m) => import(/* @vite-ignore */ m);
|
|
18
|
+
/** Resolve the KB endpoint + token. `over` (a provider's settings entry) wins over env over kb.json. */
|
|
19
|
+
export async function skylarkConfig(over) {
|
|
20
|
+
let fileCfg = {};
|
|
21
|
+
try {
|
|
22
|
+
const { readFile } = await nodeImport("node:fs/promises");
|
|
23
|
+
fileCfg = JSON.parse(await readFile(operatorPath("kb.json"), "utf8"));
|
|
24
|
+
}
|
|
25
|
+
catch { /* no kb.json — the chain continues */ }
|
|
26
|
+
let token = (typeof over?.token === "string" && over.token) || process.env.KODE_KB_TOKEN || fileCfg.token;
|
|
27
|
+
if (!token && process.env.KODE_KB_ENV_PATH) {
|
|
28
|
+
try {
|
|
29
|
+
const { readFile } = await nodeImport("node:fs/promises");
|
|
30
|
+
const env = await readFile(process.env.KODE_KB_ENV_PATH, "utf8");
|
|
31
|
+
token = env.match(/^KB_TOKEN=(.+)$/m)?.[1]?.trim();
|
|
32
|
+
}
|
|
33
|
+
catch { /* named file unreadable — fall through to unconfigured */ }
|
|
34
|
+
}
|
|
35
|
+
const base = (typeof over?.url === "string" && over.url) || process.env.KODE_KB_URL || fileCfg.url || "http://127.0.0.1:5001";
|
|
36
|
+
return { base: base.replace(/\/$/, ""), token };
|
|
37
|
+
}
|
|
38
|
+
/** Semantic search. Never throws; the caller maps the typed error to its own surface. */
|
|
39
|
+
export async function skylarkSearch(query, n = 5, timeoutMs = 15_000, cfg) {
|
|
40
|
+
const c = cfg ?? (await skylarkConfig());
|
|
41
|
+
if (!c.token)
|
|
42
|
+
return { ok: false, error: "unconfigured" };
|
|
43
|
+
const ctrl = new AbortController();
|
|
44
|
+
const timer = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
45
|
+
try {
|
|
46
|
+
const res = await fetch(`${c.base}/api/search?q=${encodeURIComponent(query)}&n=${Math.min(Math.max(n, 1), 20)}`, {
|
|
47
|
+
signal: ctrl.signal,
|
|
48
|
+
headers: { "X-KB-Token": c.token, "User-Agent": "operator/kode-tsi" },
|
|
49
|
+
});
|
|
50
|
+
if (res.status === 401)
|
|
51
|
+
return { ok: false, error: "unauthorized" };
|
|
52
|
+
if (!res.ok)
|
|
53
|
+
return { ok: false, error: "http", detail: `HTTP ${res.status} (${res.statusText})` };
|
|
54
|
+
const j = await res.json().catch(() => null);
|
|
55
|
+
const hits = j && Array.isArray(j.results) ? j.results : [];
|
|
56
|
+
return { ok: true, hits };
|
|
57
|
+
}
|
|
58
|
+
catch (e) {
|
|
59
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
60
|
+
return { ok: false, error: /abort/i.test(msg) ? "timeout" : "network", detail: msg };
|
|
61
|
+
}
|
|
62
|
+
finally {
|
|
63
|
+
clearTimeout(timer);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/** Opt-in note upload: the KB's ingest is file-based, so a note ships as a small named text file. */
|
|
67
|
+
export async function skylarkUpload(text, name, timeoutMs = 15_000, cfg) {
|
|
68
|
+
const c = cfg ?? (await skylarkConfig());
|
|
69
|
+
if (!c.token)
|
|
70
|
+
return false;
|
|
71
|
+
const ctrl = new AbortController();
|
|
72
|
+
const timer = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
73
|
+
try {
|
|
74
|
+
const form = new FormData();
|
|
75
|
+
form.append("file", new Blob([text], { type: "text/plain" }), name);
|
|
76
|
+
const res = await fetch(`${c.base}/api/upload`, {
|
|
77
|
+
method: "POST",
|
|
78
|
+
body: form,
|
|
79
|
+
signal: ctrl.signal,
|
|
80
|
+
headers: { "X-KB-Token": c.token, "User-Agent": "operator/kode-tsi" },
|
|
81
|
+
});
|
|
82
|
+
return res.ok;
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
finally {
|
|
88
|
+
clearTimeout(timer);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/** The tier-2 memory provider. Read-mostly: recall maps hits to MemoryHit with confidence 1−distance;
|
|
92
|
+
* store() is inert unless the owner set `write:true`, and an uploaded note is redacted upstream by
|
|
93
|
+
* the composite's secret gate. */
|
|
94
|
+
export function skylarkProvider(cfg) {
|
|
95
|
+
const write = cfg.write === true;
|
|
96
|
+
const over = { url: cfg.url, token: cfg.token };
|
|
97
|
+
let availCache;
|
|
98
|
+
return {
|
|
99
|
+
slug: "skylark",
|
|
100
|
+
backend: "skylark",
|
|
101
|
+
canStore: write,
|
|
102
|
+
available: async () => {
|
|
103
|
+
const now = Date.now();
|
|
104
|
+
if (availCache && now - availCache.at < 60_000)
|
|
105
|
+
return availCache.ok;
|
|
106
|
+
const ok = !!(await skylarkConfig(over)).token;
|
|
107
|
+
availCache = { at: now, ok };
|
|
108
|
+
return ok;
|
|
109
|
+
},
|
|
110
|
+
store: async (text, tags) => {
|
|
111
|
+
if (!write)
|
|
112
|
+
return false;
|
|
113
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
|
114
|
+
const tag = tags?.length ? `-${tags[0].replace(/[^a-zA-Z0-9_-]/g, "")}` : "";
|
|
115
|
+
return skylarkUpload(text, `operator-note-${stamp}${tag}.txt`, 15_000, await skylarkConfig(over));
|
|
116
|
+
},
|
|
117
|
+
recall: async (query, limit = 5) => {
|
|
118
|
+
if (!query)
|
|
119
|
+
return []; // the KB is semantic — "recent notes" is the local store's job
|
|
120
|
+
const r = await skylarkSearch(query, limit, 2_000, await skylarkConfig(over));
|
|
121
|
+
if (!r.ok)
|
|
122
|
+
return [];
|
|
123
|
+
return r.hits.slice(0, limit).map((h) => ({
|
|
124
|
+
ts: h.ingested_at ? Date.parse(h.ingested_at) || 0 : 0,
|
|
125
|
+
text: String(h.text ?? "").replace(/\s+/g, " ").trim(),
|
|
126
|
+
source: `skylark:${h.source}`,
|
|
127
|
+
confidence: Math.max(0, Math.min(1, 1 - h.distance)),
|
|
128
|
+
}));
|
|
129
|
+
},
|
|
130
|
+
};
|
|
131
|
+
}
|