@0perator/operator 0.0.6
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 +73 -0
- package/dist/auth/client.js +94 -0
- package/dist/auth/commands.js +99 -0
- package/dist/auth/store.js +99 -0
- package/dist/background/index.js +64 -0
- package/dist/cli.js +407 -0
- package/dist/config/settings.js +85 -0
- package/dist/engine/agent.js +232 -0
- package/dist/engine/aurora.js +213 -0
- package/dist/engine/compaction.js +111 -0
- package/dist/engine/contract.js +8 -0
- package/dist/engine/messages.js +85 -0
- package/dist/engine/router-adapter.js +29 -0
- package/dist/engine/selfheal.js +46 -0
- package/dist/engine/toolcalls.js +164 -0
- package/dist/index.browser.js +22 -0
- package/dist/index.js +23 -0
- package/dist/mcp/client.js +95 -0
- package/dist/mcp/config.js +73 -0
- package/dist/mcp/index.js +101 -0
- package/dist/mcp/stdio.js +149 -0
- package/dist/memory/index.js +0 -0
- package/dist/observability/index.js +60 -0
- package/dist/permissions/audit.js +50 -0
- package/dist/permissions/index.js +48 -0
- package/dist/permissions/policy.js +54 -0
- package/dist/router/router.js +94 -0
- package/dist/session.js +265 -0
- package/dist/tools/executor.js +0 -0
- package/dist/tools/registry.js +380 -0
- package/dist/tools/sandbox.js +90 -0
- package/dist/ui/ActivitySpinner.js +48 -0
- package/dist/ui/App.js +16 -0
- package/dist/ui/AuthScreen.js +17 -0
- package/dist/ui/BgPanel.js +24 -0
- package/dist/ui/Composer.js +119 -0
- package/dist/ui/Header.js +22 -0
- package/dist/ui/StatusRule.js +11 -0
- package/dist/ui/ThinkingSpinner.js +61 -0
- package/dist/ui/ToolStep.js +32 -0
- package/dist/ui/Transcript.js +22 -0
- package/dist/ui/format.js +6 -0
- package/dist/ui/index.js +9 -0
- package/dist/ui/types.js +3 -0
- package/dist/ui/useInputHistory.js +97 -0
- package/dist/update.js +57 -0
- package/package.json +47 -0
package/dist/session.js
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
// Headless session controller — owns the conversation + engine wiring for ONE interactive session,
|
|
2
|
+
// with no UI dependency, so it is testable end-to-end without a TTY. cli.tsx is a thin Ink shell
|
|
3
|
+
// that maps these callbacks onto React state; a test can drive the same `send()` directly.
|
|
4
|
+
import { runTurn, TurnAbortedError } from "./engine/agent.js";
|
|
5
|
+
import { Conversation } from "./engine/messages.js";
|
|
6
|
+
import { chat, health } from "./engine/aurora.js";
|
|
7
|
+
import { summaryPrompt, compact } from "./engine/compaction.js";
|
|
8
|
+
import { engineRouter } from "./engine/router-adapter.js";
|
|
9
|
+
import { AuroraRouter } from "./router/router.js";
|
|
10
|
+
import { Executor } from "./tools/executor.js";
|
|
11
|
+
import { toSchemas, registry } from "./tools/registry.js";
|
|
12
|
+
import { MemoryStore } from "./memory/index.js";
|
|
13
|
+
import { McpHub, withMcp } from "./mcp/index.js";
|
|
14
|
+
import { withPermissions, PermissionPolicy } from "./permissions/index.js";
|
|
15
|
+
import { Telemetry } from "./observability/index.js";
|
|
16
|
+
// The `spawn_agent` tool — a thin pass-through to the shell's delegate handler. The handler owns the
|
|
17
|
+
// policy (cap) and the reply text; the tool just guards against an empty task. safe:false so it's an
|
|
18
|
+
// action (gated when permissions are on), never run speculatively in the safe-parallel batch.
|
|
19
|
+
function makeSpawnTool(handler) {
|
|
20
|
+
return {
|
|
21
|
+
name: "spawn_agent",
|
|
22
|
+
safe: false,
|
|
23
|
+
description: "Delegate a self-contained subtask to a background sub-agent running on the same Aurora 1M model. " +
|
|
24
|
+
"Returns immediately with the sub-agent's id; it works in PARALLEL and posts its result back into " +
|
|
25
|
+
"this conversation when done. Use it for independent, parallelizable work — searching a large tree, " +
|
|
26
|
+
"drafting a file, a long build — so the foreground stays responsive. The sub-agent does NOT see this " +
|
|
27
|
+
"conversation, so make the task fully self-contained. The user watches each sub-agent's live tokens " +
|
|
28
|
+
"and elapsed time in the background panel. Don't spawn for trivial work you can do inline.",
|
|
29
|
+
parameters: {
|
|
30
|
+
type: "object",
|
|
31
|
+
properties: { task: { type: "string", description: "A complete, self-contained instruction for the sub-agent." } },
|
|
32
|
+
required: ["task"],
|
|
33
|
+
},
|
|
34
|
+
run: async (args) => {
|
|
35
|
+
const task = String(args.task ?? "").trim();
|
|
36
|
+
if (!task)
|
|
37
|
+
return "error: spawn_agent needs a non-empty task";
|
|
38
|
+
return handler(task);
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
const SUMMARY_MAX_TOKENS = 1200; // room for Aurora's reasoning before the summary content lands
|
|
43
|
+
export class Session {
|
|
44
|
+
convo = new Conversation();
|
|
45
|
+
inner;
|
|
46
|
+
router;
|
|
47
|
+
executor;
|
|
48
|
+
localSchemas;
|
|
49
|
+
hub;
|
|
50
|
+
tools;
|
|
51
|
+
policy;
|
|
52
|
+
approve;
|
|
53
|
+
telemetry;
|
|
54
|
+
mcpSchemas = []; // merged in after first-turn discovery (empty until then)
|
|
55
|
+
wantMcp;
|
|
56
|
+
systemPrompt;
|
|
57
|
+
maxTokens;
|
|
58
|
+
temperature;
|
|
59
|
+
ctrl = null;
|
|
60
|
+
memory;
|
|
61
|
+
wantRecall;
|
|
62
|
+
recallBlock = ""; // memory recalled on the first turn, folded into the system prompt thereafter
|
|
63
|
+
recalled = false;
|
|
64
|
+
constructor(cfg = {}) {
|
|
65
|
+
// Per-session tool registry: the base set, plus `spawn_agent` when the shell provides a delegate
|
|
66
|
+
// handler (foreground only). Both the executor (dispatch) and localSchemas (what the model sees)
|
|
67
|
+
// are built from the same map, so the tool is advertised iff it's runnable.
|
|
68
|
+
const reg = cfg.spawnAgent ? new Map(registry).set("spawn_agent", makeSpawnTool(cfg.spawnAgent)) : registry;
|
|
69
|
+
this.executor = new Executor(reg);
|
|
70
|
+
this.localSchemas = toSchemas(reg);
|
|
71
|
+
this.inner = cfg.router ?? new AuroraRouter();
|
|
72
|
+
this.router = engineRouter(this.inner);
|
|
73
|
+
this.systemPrompt = cfg.systemPrompt;
|
|
74
|
+
this.maxTokens = cfg.maxTokens ?? 2048;
|
|
75
|
+
this.temperature = cfg.temperature ?? 0.7;
|
|
76
|
+
this.memory = cfg.memory ?? new MemoryStore();
|
|
77
|
+
this.wantRecall = cfg.recall ?? true;
|
|
78
|
+
this.wantMcp = cfg.mcp === true || !!cfg.mcpHub;
|
|
79
|
+
this.hub = cfg.mcpHub;
|
|
80
|
+
this.policy = new PermissionPolicy(cfg.permissions);
|
|
81
|
+
this.approve = cfg.approve;
|
|
82
|
+
this.telemetry = new Telemetry(cfg.telemetry);
|
|
83
|
+
this.tools = this.buildTools(); // local-only until first-turn MCP discovery rebinds it
|
|
84
|
+
}
|
|
85
|
+
/** The effective system prompt: the base persona plus any memory recalled this session. Injected as
|
|
86
|
+
* ONE system prompt — never a second system message, which 400s llama.cpp's chat template. */
|
|
87
|
+
sys() {
|
|
88
|
+
if (!this.recallBlock)
|
|
89
|
+
return this.systemPrompt;
|
|
90
|
+
return this.systemPrompt ? `${this.systemPrompt}\n\n${this.recallBlock}` : this.recallBlock;
|
|
91
|
+
}
|
|
92
|
+
/** Compose the tool executor: local tools + MCP (composite) with the permission/audit layer on top.
|
|
93
|
+
* withPermissions returns the composite UNCHANGED when the policy is inert (bypass) — zero overhead. */
|
|
94
|
+
buildTools() {
|
|
95
|
+
return withPermissions(withMcp(this.executor, this.hub), this.policy, { approve: this.approve });
|
|
96
|
+
}
|
|
97
|
+
/** Is the currently-selected endpoint reachable? Lets the shell fail clearly before a turn. */
|
|
98
|
+
health() {
|
|
99
|
+
return health(this.inner.base);
|
|
100
|
+
}
|
|
101
|
+
/** Estimated context usage of the live conversation against the current endpoint's window, 0-99. */
|
|
102
|
+
ctxPct() {
|
|
103
|
+
const chars = JSON.stringify(this.convo.all).length + (this.sys()?.length ?? 0);
|
|
104
|
+
return Math.min(99, Math.round((Math.ceil(chars / 4) / this.inner.ctxLimit()) * 100));
|
|
105
|
+
}
|
|
106
|
+
/** Abort the in-flight turn (ESC / Stop). No-op when idle. */
|
|
107
|
+
interrupt() {
|
|
108
|
+
this.ctrl?.abort();
|
|
109
|
+
}
|
|
110
|
+
// ── Slash-command surface (used by the shell) ──────────────────────────
|
|
111
|
+
/** Configured endpoints, for /endpoints. */
|
|
112
|
+
endpoints() {
|
|
113
|
+
return this.inner.list().map((e) => ({ name: e.name, base: e.base, model: e.model, ctxWindow: e.ctxLimit }));
|
|
114
|
+
}
|
|
115
|
+
/** Health of every endpoint (parallel), for /endpoints. */
|
|
116
|
+
async endpointHealth() {
|
|
117
|
+
const eps = this.inner.list();
|
|
118
|
+
const results = await Promise.all(eps.map((e) => health(e.base).catch(() => false)));
|
|
119
|
+
return Object.fromEntries(eps.map((e, i) => [e.name, results[i]]));
|
|
120
|
+
}
|
|
121
|
+
/** Pin routing to a named endpoint, or "auto" to restore size-based routing (for /route). */
|
|
122
|
+
pinRoute(name) {
|
|
123
|
+
return this.inner.pin(name);
|
|
124
|
+
}
|
|
125
|
+
/** Force compaction now (for /compact). Returns how many messages were evicted. */
|
|
126
|
+
async compactNow() {
|
|
127
|
+
const before = this.convo.all.length;
|
|
128
|
+
this.convo.replaceAll(await compact(this.convo.all, {
|
|
129
|
+
ctxWindow: this.inner.ctxLimit(),
|
|
130
|
+
systemPrompt: this.sys(),
|
|
131
|
+
summarize: this.summarize,
|
|
132
|
+
threshold: 0, // force
|
|
133
|
+
minKeepTurns: 2,
|
|
134
|
+
}));
|
|
135
|
+
return Math.max(0, before - this.convo.all.length);
|
|
136
|
+
}
|
|
137
|
+
/** Reset the conversation to empty (for /new). */
|
|
138
|
+
reset() {
|
|
139
|
+
this.convo.replaceAll([]);
|
|
140
|
+
}
|
|
141
|
+
turnCount() {
|
|
142
|
+
return this.convo.all.filter((m) => m.role === "user").length;
|
|
143
|
+
}
|
|
144
|
+
/** Currently-selected endpoint name (for /model). */
|
|
145
|
+
currentRoute() {
|
|
146
|
+
return this.inner.currentName();
|
|
147
|
+
}
|
|
148
|
+
/** The full conversation, for persistence (auto-save / --resume). */
|
|
149
|
+
snapshot() {
|
|
150
|
+
return this.convo.all.map((m) => ({ ...m }));
|
|
151
|
+
}
|
|
152
|
+
/** Restore a saved conversation (from --resume). Ignores anything that isn't a valid message array. */
|
|
153
|
+
restore(msgs) {
|
|
154
|
+
if (!Array.isArray(msgs))
|
|
155
|
+
return false;
|
|
156
|
+
const ok = msgs.every((m) => m && typeof m === "object" && typeof m.role === "string" && typeof m.content === "string");
|
|
157
|
+
if (!ok)
|
|
158
|
+
return false;
|
|
159
|
+
this.convo.replaceAll(msgs);
|
|
160
|
+
return true;
|
|
161
|
+
}
|
|
162
|
+
/** The fact-preserving summarizer: engine prompt + content||reasoning fallback (Aurora empties content). */
|
|
163
|
+
summarize = async (span) => {
|
|
164
|
+
const r = await chat([{ role: "user", content: summaryPrompt(span) }], {
|
|
165
|
+
base: this.inner.base,
|
|
166
|
+
model: this.inner.model,
|
|
167
|
+
maxTokens: SUMMARY_MAX_TOKENS,
|
|
168
|
+
temperature: 0,
|
|
169
|
+
});
|
|
170
|
+
return (r.content && r.content.trim()) || (r.reasoningContent ?? "").trim() || "(summary unavailable)";
|
|
171
|
+
};
|
|
172
|
+
/** First-turn setup, once only. (1) Recall memory relevant to what the user is asking (plus recent
|
|
173
|
+
* notes) and fold it into the system prompt for the session. (2) Discover fleet MCP tools and merge
|
|
174
|
+
* their schemas + dispatch. Both are best-effort — a failure degrades (local-only), never blocks. */
|
|
175
|
+
async maybeRecall(text) {
|
|
176
|
+
if (this.recalled)
|
|
177
|
+
return;
|
|
178
|
+
this.recalled = true;
|
|
179
|
+
if (this.wantRecall) {
|
|
180
|
+
try {
|
|
181
|
+
this.recallBlock = await this.memory.recallText(text, 6);
|
|
182
|
+
}
|
|
183
|
+
catch {
|
|
184
|
+
this.recallBlock = "";
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
if (this.wantMcp) {
|
|
188
|
+
try {
|
|
189
|
+
if (!this.hub)
|
|
190
|
+
this.hub = await McpHub.fromConfig();
|
|
191
|
+
await this.hub.discover();
|
|
192
|
+
this.tools = this.buildTools(); // rebind so dispatch sees the discovered tools
|
|
193
|
+
this.mcpSchemas = this.hub.schemas();
|
|
194
|
+
}
|
|
195
|
+
catch { /* gateway unreachable — stay local-only */ }
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
/** Local registry schemas plus any fleet MCP tool schemas discovered this session. */
|
|
199
|
+
allSchemas() {
|
|
200
|
+
return this.mcpSchemas.length ? [...this.localSchemas, ...this.mcpSchemas] : this.localSchemas;
|
|
201
|
+
}
|
|
202
|
+
/** How many fleet MCP tools were discovered this session (0 until first turn / if MCP is off). */
|
|
203
|
+
mcpToolCount() {
|
|
204
|
+
return this.hub?.toolCount() ?? 0;
|
|
205
|
+
}
|
|
206
|
+
/** Tear down session resources (kills any spawned stdio MCP servers). Call on shell exit. */
|
|
207
|
+
shutdown() {
|
|
208
|
+
this.hub?.shutdown();
|
|
209
|
+
}
|
|
210
|
+
/** Store a durable memory note (for /remember and end-of-session capture). Best-effort. */
|
|
211
|
+
remember(text, tags) {
|
|
212
|
+
return this.memory.capture(text, tags);
|
|
213
|
+
}
|
|
214
|
+
/** What was recalled into this session's prompt (for a /memory view or tests). "" if none/not yet. */
|
|
215
|
+
recalledMemory() {
|
|
216
|
+
return this.recallBlock;
|
|
217
|
+
}
|
|
218
|
+
/** Formatted memory notes matching `query` (or most-recent), for the /memory command. "" if none. */
|
|
219
|
+
memoryText(query, limit = 10) {
|
|
220
|
+
return this.memory.recallText(query, limit);
|
|
221
|
+
}
|
|
222
|
+
/** Run one user turn to completion, streaming via handlers. Resolves with the settled outcome;
|
|
223
|
+
* an interrupt resolves (interrupted:true), it does not throw — only a real transport error does. */
|
|
224
|
+
async send(text, h = {}) {
|
|
225
|
+
if (this.ctrl)
|
|
226
|
+
throw new Error("Session.send called while a turn is in flight — serialize turns (the shell queues input)");
|
|
227
|
+
await this.maybeRecall(text); // fold past-session memory into the system prompt on the first turn
|
|
228
|
+
this.executor.resetTurn(); // clear the host executor's per-turn loop guard before this turn
|
|
229
|
+
this.inner.resetTurn(); // re-evaluate routing from the smallest endpoint + clear last turn's unhealthy set
|
|
230
|
+
const controller = new AbortController();
|
|
231
|
+
this.ctrl = controller;
|
|
232
|
+
const _t0 = performance.now();
|
|
233
|
+
try {
|
|
234
|
+
const res = await runTurn(text, this.convo, {
|
|
235
|
+
router: this.router,
|
|
236
|
+
tools: this.tools,
|
|
237
|
+
toolSchemas: this.allSchemas(),
|
|
238
|
+
systemPrompt: this.sys(),
|
|
239
|
+
summarize: this.summarize,
|
|
240
|
+
maxTokens: this.maxTokens,
|
|
241
|
+
temperature: this.temperature,
|
|
242
|
+
signal: controller.signal,
|
|
243
|
+
onDelta: h.onDelta,
|
|
244
|
+
onRoute: (ep) => h.onRoute?.(ep.label ?? "aurora", this.ctxPct()),
|
|
245
|
+
onToolStart: h.onToolStart,
|
|
246
|
+
onToolBatch: h.onToolBatch,
|
|
247
|
+
onAutoContinue: h.onAutoContinue,
|
|
248
|
+
onSelfHeal: (kind, attempt) => { this.telemetry.record({ type: "self_heal", kind, attempt }); h.onSelfHeal?.(kind, attempt); },
|
|
249
|
+
});
|
|
250
|
+
this.telemetry.record({ type: "turn", rounds: res.rounds, toolCalls: res.toolCalls, interrupted: false, durationMs: Math.round(performance.now() - _t0), ctxPct: this.ctxPct(), stopReason: res.stopReason });
|
|
251
|
+
return { ...res, interrupted: false, durationMs: Math.round(performance.now() - _t0) };
|
|
252
|
+
}
|
|
253
|
+
catch (e) {
|
|
254
|
+
if (e instanceof TurnAbortedError) {
|
|
255
|
+
this.telemetry.record({ type: "turn", rounds: 0, toolCalls: 0, interrupted: true, durationMs: Math.round(performance.now() - _t0), ctxPct: this.ctxPct() });
|
|
256
|
+
return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
|
|
257
|
+
}
|
|
258
|
+
this.telemetry.record({ type: "error", where: "send", errorClass: Telemetry.errorClass(e) });
|
|
259
|
+
throw e;
|
|
260
|
+
}
|
|
261
|
+
finally {
|
|
262
|
+
this.ctrl = null;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
Binary file
|
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
// Tool registry — SPEC §2. Lean core set; unknown/failing tools never crash the turn (executor.ts
|
|
2
|
+
// wraps run() in try/catch too, but each tool also guards its own I/O and returns an error string).
|
|
3
|
+
import { execFile } from "node:child_process";
|
|
4
|
+
import { promisify } from "node:util";
|
|
5
|
+
import { readFile, writeFile, mkdir, readdir } from "node:fs/promises";
|
|
6
|
+
import { dirname } from "node:path";
|
|
7
|
+
import { MemoryStore } from "../memory/index.js";
|
|
8
|
+
import { deniedWrite, wrapShell } from "./sandbox.js";
|
|
9
|
+
const pexecFile = promisify(execFile);
|
|
10
|
+
function str(v, fallback = "") {
|
|
11
|
+
return v === undefined || v === null ? fallback : String(v);
|
|
12
|
+
}
|
|
13
|
+
async function shellExec(args) {
|
|
14
|
+
const command = str(args.command);
|
|
15
|
+
if (!command)
|
|
16
|
+
return "error: no command given";
|
|
17
|
+
const cwd = args.cwd ? str(args.cwd) : undefined;
|
|
18
|
+
const timeout = Number(args.timeout_ms ?? 120_000);
|
|
19
|
+
const MAXBUF = 64 * 1024 * 1024; // 64MB — big greps/finds no longer hard-fail on a 10MB cap
|
|
20
|
+
// Run under the OS sandbox when KODE_SANDBOX is on (macOS sandbox-exec); otherwise plain bash. The
|
|
21
|
+
// wrapper is a no-op off-sandbox, so the owner's default experience is unchanged.
|
|
22
|
+
const { file, args: argv } = await wrapShell(command);
|
|
23
|
+
const fmt = (o, err) => (o + (err ? `\n[stderr]\n${err}` : "")).trim();
|
|
24
|
+
try {
|
|
25
|
+
const { stdout, stderr } = await pexecFile(file, argv, { cwd, timeout, maxBuffer: MAXBUF });
|
|
26
|
+
return fmt(String(stdout), String(stderr)) || "(no output)";
|
|
27
|
+
}
|
|
28
|
+
catch (e) {
|
|
29
|
+
// Node attaches stdout/stderr to the rejection. A non-zero exit is NOT always a failure: grep exits 1
|
|
30
|
+
// on no-match, `| head` can SIGPIPE a producer, `test`/`diff` signal via exit code. So NEVER discard
|
|
31
|
+
// real output — surface it. Only when there's genuinely nothing do we report the exit tersely.
|
|
32
|
+
const out = fmt(String(e.stdout ?? ""), String(e.stderr ?? ""));
|
|
33
|
+
if (e.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") {
|
|
34
|
+
return (out ? out + "\n" : "") + `[output exceeded ${Math.round(MAXBUF / 1e6)}MB and was truncated — narrow it: add a path, pipe to \`head\`, or use \`grep -l\`/\`grep -c\`]`;
|
|
35
|
+
}
|
|
36
|
+
if (e.killed || /ETIMEDOUT|timed out/i.test(String(e.message ?? ""))) {
|
|
37
|
+
return (out ? out + "\n" : "") + `[timed out after ${timeout}ms — narrow the command or pass a larger timeout_ms]`;
|
|
38
|
+
}
|
|
39
|
+
if (out)
|
|
40
|
+
return out; // command produced output but exited non-zero — the output is the answer
|
|
41
|
+
return `(no output; exit ${e.code ?? "?"})`; // grep no-match etc. — honest, not alarming
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
async function fileRead(args) {
|
|
45
|
+
const path = str(args.path);
|
|
46
|
+
if (!path)
|
|
47
|
+
return "error: no path given";
|
|
48
|
+
try {
|
|
49
|
+
const src = await readFile(path, "utf8");
|
|
50
|
+
const lines = src.split("\n");
|
|
51
|
+
const offset = Number(args.offset ?? 0);
|
|
52
|
+
const limit = Number(args.limit ?? lines.length);
|
|
53
|
+
return lines.slice(offset, offset + limit).map((l, i) => `${offset + i + 1}\t${l}`).join("\n");
|
|
54
|
+
}
|
|
55
|
+
catch (e) {
|
|
56
|
+
return `error: ${e.message}`;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
async function fileWrite(args) {
|
|
60
|
+
const path = str(args.path);
|
|
61
|
+
if (!path)
|
|
62
|
+
return "error: no path given";
|
|
63
|
+
const blocked = deniedWrite(path);
|
|
64
|
+
if (blocked)
|
|
65
|
+
return `error: ${blocked}`;
|
|
66
|
+
try {
|
|
67
|
+
await mkdir(dirname(path), { recursive: true });
|
|
68
|
+
await writeFile(path, str(args.content), "utf8");
|
|
69
|
+
return `wrote ${path}`;
|
|
70
|
+
}
|
|
71
|
+
catch (e) {
|
|
72
|
+
return `error: ${e.message}`;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
async function fileEdit(args) {
|
|
76
|
+
const path = str(args.path);
|
|
77
|
+
const oldStr = str(args.old_string);
|
|
78
|
+
const newStr = str(args.new_string);
|
|
79
|
+
const replaceAll = Boolean(args.replace_all);
|
|
80
|
+
if (!path || !oldStr)
|
|
81
|
+
return "error: path and old_string are required";
|
|
82
|
+
const blocked = deniedWrite(path);
|
|
83
|
+
if (blocked)
|
|
84
|
+
return `error: ${blocked}`;
|
|
85
|
+
try {
|
|
86
|
+
const src = await readFile(path, "utf8");
|
|
87
|
+
const count = src.split(oldStr).length - 1;
|
|
88
|
+
if (count === 0)
|
|
89
|
+
return `error: old_string not found in ${path}`;
|
|
90
|
+
if (!replaceAll && count > 1)
|
|
91
|
+
return `error: old_string matches ${count} times in ${path} — not unique, pass replace_all or narrow it`;
|
|
92
|
+
const next = replaceAll ? src.split(oldStr).join(newStr) : src.replace(oldStr, newStr);
|
|
93
|
+
await writeFile(path, next, "utf8");
|
|
94
|
+
const n = replaceAll ? count : 1;
|
|
95
|
+
return `edited ${path} (${n} replacement${n === 1 ? "" : "s"})`;
|
|
96
|
+
}
|
|
97
|
+
catch (e) {
|
|
98
|
+
return `error: ${e.message}`;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
async function grepSearch(args) {
|
|
102
|
+
const pattern = str(args.pattern);
|
|
103
|
+
const path = str(args.path, ".");
|
|
104
|
+
if (!pattern)
|
|
105
|
+
return "error: no pattern given";
|
|
106
|
+
const flags = ["-rn", "-I", "--exclude-dir=.git", "--exclude-dir=node_modules"];
|
|
107
|
+
if (args.glob)
|
|
108
|
+
flags.push(`--include=${str(args.glob)}`);
|
|
109
|
+
try {
|
|
110
|
+
const { stdout } = await pexecFile("grep", [...flags, "-E", pattern, path], { maxBuffer: 10 * 1024 * 1024 });
|
|
111
|
+
return stdout.trim() || "(no matches)";
|
|
112
|
+
}
|
|
113
|
+
catch (e) {
|
|
114
|
+
if (e.code === 1)
|
|
115
|
+
return "(no matches)";
|
|
116
|
+
return `error: ${e.stderr || e.message}`;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
async function listDirectory(args) {
|
|
120
|
+
const path = str(args.path, ".");
|
|
121
|
+
try {
|
|
122
|
+
const entries = await readdir(path, { withFileTypes: true });
|
|
123
|
+
return entries.map(e => `${e.isDirectory() ? "d" : "f"} ${e.name}`).join("\n") || "(empty)";
|
|
124
|
+
}
|
|
125
|
+
catch (e) {
|
|
126
|
+
return `error: ${e.message}`;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
async function gitCommand(args) {
|
|
130
|
+
const gitArgs = Array.isArray(args.args) ? args.args.map(String) : [];
|
|
131
|
+
const cwd = args.cwd ? str(args.cwd) : undefined;
|
|
132
|
+
if (!gitArgs.length)
|
|
133
|
+
return "error: no args given";
|
|
134
|
+
try {
|
|
135
|
+
const { stdout, stderr } = await pexecFile("git", gitArgs, { cwd, maxBuffer: 10 * 1024 * 1024 });
|
|
136
|
+
return (stdout + stderr).trim() || "(no output)";
|
|
137
|
+
}
|
|
138
|
+
catch (e) {
|
|
139
|
+
return `error: ${e.stderr || e.message}`;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
// ONE memory store (src/memory) backs the memory_store/memory_search/checkpoint tools AND the Session's
|
|
143
|
+
// start-of-session recall — a single JSONL file, so a note stored mid-turn is what a later session recalls.
|
|
144
|
+
// SPEC §8 eyes SQLite eventually; swapping the store's backing is a MemoryStore-internal change from here.
|
|
145
|
+
const memory = new MemoryStore();
|
|
146
|
+
async function memoryStore(args) {
|
|
147
|
+
const text = str(args.text);
|
|
148
|
+
if (!text)
|
|
149
|
+
return "error: no text given";
|
|
150
|
+
const tags = Array.isArray(args.tags) ? args.tags.map(String) : [];
|
|
151
|
+
const ok = await memory.capture(text, tags);
|
|
152
|
+
return ok ? `stored memory (${tags.join(",") || "no tags"})` : "error: could not store memory";
|
|
153
|
+
}
|
|
154
|
+
async function memorySearch(args) {
|
|
155
|
+
const query = str(args.query);
|
|
156
|
+
const limit = Number(args.limit ?? 10);
|
|
157
|
+
const hits = await memory.recall(query || undefined, limit);
|
|
158
|
+
return hits.length
|
|
159
|
+
? hits.map(h => `[${new Date(h.ts).toISOString()}] ${h.text}`).join("\n")
|
|
160
|
+
: "(no matches)";
|
|
161
|
+
}
|
|
162
|
+
// checkpoint = git add+commit in workspace + a memory note, one call (SPEC §8). Never adds
|
|
163
|
+
// Co-Authored-By / AI attribution — the commit message is exactly the caller's summary.
|
|
164
|
+
async function checkpoint(args) {
|
|
165
|
+
const summary = str(args.summary);
|
|
166
|
+
if (!summary)
|
|
167
|
+
return "error: no summary given";
|
|
168
|
+
const workspace = args.workspace ? str(args.workspace) : process.cwd();
|
|
169
|
+
const push = Boolean(args.push);
|
|
170
|
+
try {
|
|
171
|
+
await pexecFile("git", ["add", "-A"], { cwd: workspace });
|
|
172
|
+
await pexecFile("git", ["commit", "-m", summary], { cwd: workspace });
|
|
173
|
+
const { stdout: sha } = await pexecFile("git", ["rev-parse", "--short", "HEAD"], { cwd: workspace });
|
|
174
|
+
if (push)
|
|
175
|
+
await pexecFile("git", ["push"], { cwd: workspace });
|
|
176
|
+
await memory.capture(summary, ["checkpoint", workspace]);
|
|
177
|
+
return `checkpoint ${sha.trim()} — ${summary}${push ? " (pushed)" : ""}`;
|
|
178
|
+
}
|
|
179
|
+
catch (e) {
|
|
180
|
+
return `error: ${e.stderr || e.message}`;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
function htmlToText(html) {
|
|
184
|
+
return html
|
|
185
|
+
.replace(/<script[\s\S]*?<\/script>/gi, "")
|
|
186
|
+
.replace(/<style[\s\S]*?<\/style>/gi, "")
|
|
187
|
+
.replace(/<[^>]+>/g, " ")
|
|
188
|
+
.replace(/ /g, " ").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/'/g, "'").replace(/"/g, '"')
|
|
189
|
+
.replace(/[ \t]{2,}/g, " ").replace(/\n{3,}/g, "\n\n").trim();
|
|
190
|
+
}
|
|
191
|
+
async function webFetch(args) {
|
|
192
|
+
const url = str(args.url);
|
|
193
|
+
if (!/^https?:\/\//i.test(url))
|
|
194
|
+
return "error: web_fetch needs an http(s) URL";
|
|
195
|
+
const ctrl = new AbortController();
|
|
196
|
+
const timer = setTimeout(() => ctrl.abort(), Number(args.timeout_ms ?? 20_000));
|
|
197
|
+
try {
|
|
198
|
+
const res = await fetch(url, { signal: ctrl.signal, redirect: "follow", headers: { "User-Agent": "operator/kode-tsi" } });
|
|
199
|
+
if (!res.ok)
|
|
200
|
+
return `error: HTTP ${res.status} fetching ${url}`;
|
|
201
|
+
const ct = res.headers.get("content-type") ?? "";
|
|
202
|
+
let text = await res.text();
|
|
203
|
+
if (/html/i.test(ct))
|
|
204
|
+
text = htmlToText(text);
|
|
205
|
+
const max = Number(args.max_chars ?? 20_000);
|
|
206
|
+
return text.length > max ? `${text.slice(0, max)}\n…[truncated ${text.length - max} chars]` : (text.trim() || "(empty response)");
|
|
207
|
+
}
|
|
208
|
+
catch (e) {
|
|
209
|
+
const m = e instanceof Error ? e.message : String(e);
|
|
210
|
+
return `error fetching ${url}: ${/abort/i.test(m) ? "timed out" : m}`;
|
|
211
|
+
}
|
|
212
|
+
finally {
|
|
213
|
+
clearTimeout(timer);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
const TOOLS = [
|
|
217
|
+
{
|
|
218
|
+
name: "shell_exec", safe: false,
|
|
219
|
+
description: "Run a shell command and return its stdout/stderr.",
|
|
220
|
+
parameters: { type: "object", properties: {
|
|
221
|
+
command: { type: "string" }, cwd: { type: "string" }, timeout_ms: { type: "number" },
|
|
222
|
+
}, required: ["command"] },
|
|
223
|
+
run: shellExec,
|
|
224
|
+
},
|
|
225
|
+
{
|
|
226
|
+
name: "file_read", safe: true,
|
|
227
|
+
description: "Read a file, optionally a line range, with line numbers.",
|
|
228
|
+
parameters: { type: "object", properties: {
|
|
229
|
+
path: { type: "string" }, offset: { type: "number" }, limit: { type: "number" },
|
|
230
|
+
}, required: ["path"] },
|
|
231
|
+
run: fileRead,
|
|
232
|
+
},
|
|
233
|
+
{
|
|
234
|
+
name: "file_write", safe: false,
|
|
235
|
+
description: "Write (overwrite) a file, creating parent directories as needed.",
|
|
236
|
+
parameters: { type: "object", properties: {
|
|
237
|
+
path: { type: "string" }, content: { type: "string" },
|
|
238
|
+
}, required: ["path", "content"] },
|
|
239
|
+
run: fileWrite,
|
|
240
|
+
},
|
|
241
|
+
{
|
|
242
|
+
name: "file_edit", safe: false,
|
|
243
|
+
description: "Replace old_string with new_string in a file. old_string must be unique unless replace_all is set.",
|
|
244
|
+
parameters: { type: "object", properties: {
|
|
245
|
+
path: { type: "string" }, old_string: { type: "string" }, new_string: { type: "string" }, replace_all: { type: "boolean" },
|
|
246
|
+
}, required: ["path", "old_string", "new_string"] },
|
|
247
|
+
run: fileEdit,
|
|
248
|
+
},
|
|
249
|
+
{
|
|
250
|
+
name: "grep_search", safe: true,
|
|
251
|
+
description: "Recursively grep for a regex pattern under a path.",
|
|
252
|
+
parameters: { type: "object", properties: {
|
|
253
|
+
pattern: { type: "string" }, path: { type: "string" }, glob: { type: "string" },
|
|
254
|
+
}, required: ["pattern"] },
|
|
255
|
+
run: grepSearch,
|
|
256
|
+
},
|
|
257
|
+
{
|
|
258
|
+
name: "list_directory", safe: true,
|
|
259
|
+
description: "List entries in a directory.",
|
|
260
|
+
parameters: { type: "object", properties: { path: { type: "string" } } },
|
|
261
|
+
run: listDirectory,
|
|
262
|
+
},
|
|
263
|
+
{
|
|
264
|
+
name: "git_command", safe: false,
|
|
265
|
+
description: "Run an arbitrary git subcommand (args as an argv array, no shell).",
|
|
266
|
+
parameters: { type: "object", properties: {
|
|
267
|
+
args: { type: "array", items: { type: "string" } }, cwd: { type: "string" },
|
|
268
|
+
}, required: ["args"] },
|
|
269
|
+
run: gitCommand,
|
|
270
|
+
},
|
|
271
|
+
{
|
|
272
|
+
name: "checkpoint", safe: false,
|
|
273
|
+
description: "Git add+commit a workspace and leave a memory note, in one call.",
|
|
274
|
+
parameters: { type: "object", properties: {
|
|
275
|
+
summary: { type: "string" }, workspace: { type: "string" }, push: { type: "boolean" },
|
|
276
|
+
}, required: ["summary"] },
|
|
277
|
+
run: checkpoint,
|
|
278
|
+
},
|
|
279
|
+
{
|
|
280
|
+
name: "memory_search", safe: true,
|
|
281
|
+
description: "Search stored memory notes by substring/tag match, most recent first.",
|
|
282
|
+
parameters: { type: "object", properties: {
|
|
283
|
+
query: { type: "string" }, limit: { type: "number" },
|
|
284
|
+
} },
|
|
285
|
+
run: memorySearch,
|
|
286
|
+
},
|
|
287
|
+
{
|
|
288
|
+
name: "memory_store", safe: false,
|
|
289
|
+
description: "Store a durable memory note with optional tags.",
|
|
290
|
+
parameters: { type: "object", properties: {
|
|
291
|
+
text: { type: "string" }, tags: { type: "array", items: { type: "string" } },
|
|
292
|
+
}, required: ["text"] },
|
|
293
|
+
run: memoryStore,
|
|
294
|
+
},
|
|
295
|
+
{
|
|
296
|
+
name: "web_fetch", safe: true,
|
|
297
|
+
description: "Fetch an http(s) URL and return its text content (HTML is stripped to plain text, truncated to max_chars). Read-only.",
|
|
298
|
+
parameters: { type: "object", properties: {
|
|
299
|
+
url: { type: "string", description: "the http(s) URL to fetch" },
|
|
300
|
+
max_chars: { type: "number", description: "max characters to return (default 20000)" },
|
|
301
|
+
timeout_ms: { type: "number" },
|
|
302
|
+
}, required: ["url"] },
|
|
303
|
+
run: webFetch,
|
|
304
|
+
},
|
|
305
|
+
{
|
|
306
|
+
name: "skill_list", safe: true,
|
|
307
|
+
description: "List or search AXE skills from the Operator registry (operator.axe.onl /v1/skills) — reusable playbooks for code review, security audit, debugging, architecture, and more. Read-only.",
|
|
308
|
+
parameters: { type: "object", properties: {
|
|
309
|
+
query: { type: "string", description: "optional search term to filter skills" },
|
|
310
|
+
} },
|
|
311
|
+
run: (a) => skillList(str(a.query)),
|
|
312
|
+
},
|
|
313
|
+
{
|
|
314
|
+
name: "skill_fetch", safe: true,
|
|
315
|
+
description: "Fetch one AXE skill by slug from the Operator registry (operator.axe.onl /v1/skills/{slug}) and return its instructions to follow. Read-only.",
|
|
316
|
+
parameters: { type: "object", properties: {
|
|
317
|
+
slug: { type: "string", description: "the skill slug/name to fetch" },
|
|
318
|
+
}, required: ["slug"] },
|
|
319
|
+
run: (a) => skillFetch(str(a.slug)),
|
|
320
|
+
},
|
|
321
|
+
];
|
|
322
|
+
// AXE skill registry (parity with the Python core): a REMOTE HTTPS registry reachable from every surface
|
|
323
|
+
// (CLI/web/mobile), so skills work everywhere without local fleet access. Bearer from OPERATOR_TOKEN or
|
|
324
|
+
// ~/.axe/secrets/operator_token.txt; a real User-Agent is REQUIRED (the gateway WAF 403s the default).
|
|
325
|
+
const OPERATOR_URLS = [process.env.OPERATOR_URL ?? "https://operator.axe.onl", "https://skills.axe.onl"];
|
|
326
|
+
async function operatorToken() {
|
|
327
|
+
if (process.env.OPERATOR_TOKEN)
|
|
328
|
+
return process.env.OPERATOR_TOKEN;
|
|
329
|
+
try {
|
|
330
|
+
const { homedir } = await import("node:os");
|
|
331
|
+
const { join } = await import("node:path");
|
|
332
|
+
for (const fn of ["operator_token.txt", "axeclaw_token.txt"]) {
|
|
333
|
+
try {
|
|
334
|
+
return (await readFile(join(homedir(), ".axe", "secrets", fn), "utf8")).trim();
|
|
335
|
+
}
|
|
336
|
+
catch { /* next */ }
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
catch { /* no fs */ }
|
|
340
|
+
return "";
|
|
341
|
+
}
|
|
342
|
+
async function operatorGet(path) {
|
|
343
|
+
const token = await operatorToken();
|
|
344
|
+
const headers = { "User-Agent": "KODE/0.9 (axe-tsi)", Accept: "application/json" };
|
|
345
|
+
if (token)
|
|
346
|
+
headers.Authorization = `Bearer ${token}`;
|
|
347
|
+
for (const base of OPERATOR_URLS) {
|
|
348
|
+
try {
|
|
349
|
+
const ctrl = new AbortController();
|
|
350
|
+
const t = setTimeout(() => ctrl.abort(), 8000); // fast-fail: a hung gateway never blocks a turn
|
|
351
|
+
const res = await fetch(`${base}${path}`, { headers, signal: ctrl.signal });
|
|
352
|
+
clearTimeout(t);
|
|
353
|
+
if (res.ok)
|
|
354
|
+
return await res.json();
|
|
355
|
+
}
|
|
356
|
+
catch { /* try the next host */ }
|
|
357
|
+
}
|
|
358
|
+
return null;
|
|
359
|
+
}
|
|
360
|
+
async function skillList(query) {
|
|
361
|
+
const r = await operatorGet(`/v1/skills${query ? `?q=${encodeURIComponent(query)}` : ""}`);
|
|
362
|
+
if (r === null)
|
|
363
|
+
return "error: skill registry unreachable (operator.axe.onl / skills.axe.onl)";
|
|
364
|
+
return JSON.stringify(r).slice(0, 8000);
|
|
365
|
+
}
|
|
366
|
+
async function skillFetch(slug) {
|
|
367
|
+
if (!slug)
|
|
368
|
+
return "error: skill_fetch needs a slug";
|
|
369
|
+
const r = await operatorGet(`/v1/skills/${encodeURIComponent(slug)}`);
|
|
370
|
+
if (r === null)
|
|
371
|
+
return `error: skill '${slug}' unreachable or not found`;
|
|
372
|
+
return typeof r === "string" ? r : JSON.stringify(r).slice(0, 16000);
|
|
373
|
+
}
|
|
374
|
+
export const registry = new Map(TOOLS.map(t => [t.name, t]));
|
|
375
|
+
export function toSchemas(reg = registry) {
|
|
376
|
+
return [...reg.values()].map(t => ({
|
|
377
|
+
type: "function",
|
|
378
|
+
function: { name: t.name, description: t.description, parameters: t.parameters },
|
|
379
|
+
}));
|
|
380
|
+
}
|