@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
package/README.md
CHANGED
|
@@ -24,9 +24,17 @@ src/
|
|
|
24
24
|
│ ├── messages.ts # Msg/Conversation, buildMessages, tool-pair repair, shape validation
|
|
25
25
|
│ └── toolcalls.ts # recover text-emitted (Qwen XML / JSON) tool calls
|
|
26
26
|
├── router/router.ts # AuroraRouter — size-based routing, failover, Saddle fallback, pin/resetTurn
|
|
27
|
-
├── tools/ # the tool set (
|
|
27
|
+
├── tools/ # the tool set (63): shell/file/grep/git/memory/checkpoint/web_fetch/knowledge
|
|
28
|
+
│ │ # + wave 1-2 (missions, kanban boards, routines, validation, pkg, code search,
|
|
29
|
+
│ │ # semantic output compression) + incident tools — safe:true tools run NO shell
|
|
28
30
|
│ ├── registry.ts # Tool defs + JSON schemas (toSchemas) + safe/mutating flags
|
|
31
|
+
│ ├── find-files.ts # find_files: OS search index (Spotlight / Windows Search / locate) + rg/walk fallback
|
|
29
32
|
│ └── executor.ts # dispatch: parallel (read-only) vs sequential (mutating), per-turn loop guard
|
|
33
|
+
├── autonomy/ # unattended spine: cron with a cross-process locked store, atomic
|
|
34
|
+
│ # claim-then-execute, a 6-state observable run lifecycle (abandoned-run
|
|
35
|
+
│ # recovery, preflight seam) and auto-opened, deduped incidents
|
|
36
|
+
├── plugins/ # plugin framework base (manifest-driven, scoped storage/secrets) + MCP
|
|
37
|
+
│ # bridge on the canonical config loader; behavior-loading decision open
|
|
30
38
|
├── session.ts # Session controller — binds engine + router + tools + summarizer; the
|
|
31
39
|
│ # headless, testable API the shell drives (send / interrupt / slash surface)
|
|
32
40
|
├── cli.tsx # the Ink shell — maps Session's streaming callbacks onto React state,
|
|
@@ -50,6 +58,11 @@ src/
|
|
|
50
58
|
- **Streaming** — live token stream with a caret; interrupt (ESC) tears the stream down at the transport.
|
|
51
59
|
- **Slash commands** — `/help /model /endpoints /route /compact /new /clear /exit`.
|
|
52
60
|
- **Session persistence** — auto-saved per turn; `operator --resume` reloads it.
|
|
61
|
+
- **Unattended runs that survive reality** — cron jobs claim atomically under a cross-process lock (two
|
|
62
|
+
sessions never double-run a job), every run is an observable 6-state record (who claimed it, where, how far),
|
|
63
|
+
abandoned runs are recovered automatically, and failures open deduped incidents (`incident_list`).
|
|
64
|
+
- **Tier-aware model routing** — every profile carries a compute/cost class (`lite|economy|power|power_turbo`);
|
|
65
|
+
`resolveByTier` picks by class with explicit degrade semantics (never silently upgrades cost).
|
|
53
66
|
|
|
54
67
|
## Run
|
|
55
68
|
|
|
@@ -60,7 +73,16 @@ operator+ --resume # reload the last conversation
|
|
|
60
73
|
```
|
|
61
74
|
Requires Aurora serving locally (Air `:8098` / 1M `:8097`). Dev: `npm install && npm run dev`.
|
|
62
75
|
Env (the internal `KODE_` prefix is retained for compatibility): `KODE_AIR`, `KODE_1M`, `KODE_SADDLE`,
|
|
63
|
-
`KODE_TSI_ROUTER=1m`, `KODE_SYSTEM_PROMPT`, `KODE_SESSION_FILE
|
|
76
|
+
`KODE_TSI_ROUTER=1m`, `KODE_SYSTEM_PROMPT`, `KODE_SESSION_FILE`; knowledge base `KODE_KB_URL` /
|
|
77
|
+
`KODE_KB_TOKEN` / `KODE_KB_ENV_PATH` (see below); MCP config `KODE_MCP_CONFIG` / `KODE_MCP_SECRETS`
|
|
78
|
+
(default: Operator home, falling back to the legacy python-core location).
|
|
79
|
+
|
|
80
|
+
## Knowledge base
|
|
81
|
+
|
|
82
|
+
`knowledge_search` queries the configured vector KB. Config resolves through one chain, first hit wins:
|
|
83
|
+
`$KODE_KB_URL` / `$KODE_KB_TOKEN` env vars → `kb.json` in the Operator home (`{"url": "…", "token": "…"}`,
|
|
84
|
+
chmod 600 — per-tenant via `$KODE_HOME`/`$KODE_PROFILE`) → a dotenv file you name via `$KODE_KB_ENV_PATH`
|
|
85
|
+
(reads `KB_TOKEN=…`). Unconfigured, the tool tells you exactly these options; nothing is baked in.
|
|
64
86
|
|
|
65
87
|
## Testing
|
|
66
88
|
|
package/dist/acp/agent.js
CHANGED
|
@@ -14,7 +14,7 @@ import { readFileSync, rmSync, statSync } from "node:fs";
|
|
|
14
14
|
import { isAbsolute } from "node:path";
|
|
15
15
|
import { PROTOCOL_VERSION, RequestError } from "@zed-industries/agent-client-protocol";
|
|
16
16
|
import { createAutonomySession } from "../autonomy/session-factory.js";
|
|
17
|
-
import { modelRegistry
|
|
17
|
+
import { modelRegistry } from "../router/models.js";
|
|
18
18
|
import { hasByoToken } from "../auth/byo.js";
|
|
19
19
|
import { operatorPath } from "../config/home.js";
|
|
20
20
|
import { redactSecrets } from "../engine/redact.js";
|
|
@@ -183,7 +183,8 @@ export class OperatorAcpAgent {
|
|
|
183
183
|
modelOption(sessionId) {
|
|
184
184
|
const live = this.sessions.get(sessionId);
|
|
185
185
|
const moa = this.settings.moa;
|
|
186
|
-
return buildModelConfigOption(
|
|
186
|
+
return buildModelConfigOption(modelRegistry(this.settings.models), live?.session.currentModel() ?? "", !!moa?.proposers?.length, hasByoToken, // the builder is the single source of selector truth: hidden + unconnectable BYO
|
|
187
|
+
this.actor.tier === "admin"); // filtered there, active-but-hidden re-admitted there (never a lying currentValue)
|
|
187
188
|
}
|
|
188
189
|
/** SDK-0.4.5 legacy path (wire: session/set_model) — what Zed ships today. The spec-stable
|
|
189
190
|
* session/set_config_option is translated onto this method by the run.ts shim; both client
|
|
@@ -2,14 +2,28 @@
|
|
|
2
2
|
* MOA is omitted unless a moa block exists in settings (setModel refuses it otherwise, and a
|
|
3
3
|
* dropdown that can fail is the dishonesty SPEC/providers.md §1 bans). Descriptions carry ctx
|
|
4
4
|
* size and kind so the user can price a switch with their eyes. */
|
|
5
|
-
export function buildModelConfigOption(registry, currentId, moaAvailable) {
|
|
5
|
+
export function buildModelConfigOption(registry, currentId, moaAvailable, hasByo, isOwner = true) {
|
|
6
6
|
const options = [];
|
|
7
7
|
for (const p of registry) {
|
|
8
|
+
if (p.hidden)
|
|
9
|
+
continue; // picker truth: down slots aren't offered…
|
|
10
|
+
if (p.ownerOnly && !isOwner)
|
|
11
|
+
continue; // …nor owner-only lanes to a non-owner seat (setModel refuses them too)
|
|
12
|
+
if (p.byo && !(hasByo ? hasByo(p.byo) : false))
|
|
13
|
+
continue; // …nor unconnectable connectors
|
|
8
14
|
if (p.kind === "orchestrated" && !moaAvailable)
|
|
9
15
|
continue;
|
|
10
16
|
const bits = [p.desc, p.kind === "single" && p.ctx ? `${Math.round(p.ctx / 1000)}k ctx` : null, p.kind === "orchestrated" ? "mixture-of-agents" : null].filter(Boolean);
|
|
11
17
|
options.push({ value: p.id, name: p.label, description: bits.join(" · ") || undefined });
|
|
12
18
|
}
|
|
19
|
+
// …but a selector that misreports the session's REAL model is the deeper dishonesty: if the
|
|
20
|
+
// active profile is hidden (switched-to before it went down, scripted, or aliased), it joins
|
|
21
|
+
// the list labeled as such — selectModel resolves hidden ids, so the option is never a dead end.
|
|
22
|
+
if (currentId && !options.some((o) => o.value === currentId)) {
|
|
23
|
+
const cur = registry.find((p) => p.id === currentId);
|
|
24
|
+
if (cur)
|
|
25
|
+
options.push({ value: cur.id, name: cur.label, description: "active — hidden from the picker" });
|
|
26
|
+
}
|
|
13
27
|
return {
|
|
14
28
|
id: "model",
|
|
15
29
|
name: "Model",
|
package/dist/acp/tool-map.js
CHANGED
|
@@ -7,12 +7,13 @@ import { isErrorResult } from "../ui/format.js";
|
|
|
7
7
|
const KINDS = {
|
|
8
8
|
file_read: "read", read_files: "read", list_directory: "read", git_status: "read", session_read: "read",
|
|
9
9
|
skill_fetch: "read", skill_list: "read", task_list: "read", image_analyze: "read", video_analyze: "read",
|
|
10
|
-
grep_search: "search", search: "search", memory_search: "search", session_search: "search", web_search: "search",
|
|
10
|
+
grep_search: "search", search: "search", find_files: "search", memory_search: "search", session_search: "search", web_search: "search",
|
|
11
11
|
file_write: "edit", file_edit: "edit", memory_store: "edit", skill_save: "edit", scratchpad: "edit", session_handoff: "edit",
|
|
12
12
|
bash: "execute", shell_exec: "execute", shell_background: "execute", bash_kill: "execute", bash_output: "execute",
|
|
13
13
|
git_command: "execute", checkpoint: "execute", cronjob: "execute",
|
|
14
14
|
web_fetch: "fetch", http_request: "fetch", browser: "fetch", browser_read: "fetch",
|
|
15
15
|
delegate_task: "think",
|
|
16
|
+
delegate_to_agent: "execute",
|
|
16
17
|
};
|
|
17
18
|
export function toolKind(name) {
|
|
18
19
|
return KINDS[name] ?? "other";
|
package/dist/auth/commands.js
CHANGED
|
@@ -18,6 +18,8 @@ import { requestDeviceCode, awaitApproval, verifyToken, authBase, signupStart, s
|
|
|
18
18
|
import { saveCredentials, loadCredentials, clearCredentials } from "./store.js";
|
|
19
19
|
import { listByoAccounts, hasByoToken, deleteByoToken, setByoTokenInteractive } from "./byo.js";
|
|
20
20
|
import { auditControl } from "../telemetry/lifecycle.js";
|
|
21
|
+
import { loadSettings, saveSettings } from "../config/settings.js";
|
|
22
|
+
import { BYO_PRESETS } from "../router/models.js";
|
|
21
23
|
// Credential-lifecycle audit (inert unless the seat is audited — see telemetry/lifecycle.ts). Module-level
|
|
22
24
|
// because every login path ends in the same few exits; runAuth sets it once from the CLI's settings.
|
|
23
25
|
let auditCfg;
|
|
@@ -195,23 +197,26 @@ function flagValue(rest, flag) {
|
|
|
195
197
|
const i = rest.indexOf(flag);
|
|
196
198
|
return i >= 0 ? rest[i + 1] : undefined;
|
|
197
199
|
}
|
|
198
|
-
/** `operator auth byo
|
|
199
|
-
* hidden paste into the OS keychain under the SEPARATE `axe-operator-byo` service (an operator token
|
|
200
|
-
* and a vendor key can never be confused),
|
|
201
|
-
*
|
|
202
|
-
|
|
200
|
+
/** `operator auth byo-key <account> [--list|--rm]` — store a provider API key (any provider, stackable):
|
|
201
|
+
* a hidden paste into the OS keychain under the SEPARATE `axe-operator-byo` service (an operator token
|
|
202
|
+
* and a vendor key can never be confused), keyed by `account`. Use this when a model profile for the
|
|
203
|
+
* provider already exists (built-in SKU, a `byo-model` registration, or a settings.models entry); use
|
|
204
|
+
* `byo-model` to register the model AND store the key in one step. `byo` stays as a back-compat alias. */
|
|
205
|
+
async function byoKey(rest) {
|
|
203
206
|
const account = rest.find((a) => !a.startsWith("--"));
|
|
204
207
|
if (rest.includes("--list")) {
|
|
205
|
-
const
|
|
206
|
-
|
|
207
|
-
|
|
208
|
+
const stored = listByoAccounts();
|
|
209
|
+
const known = new Set([...stored, ...Object.keys(BYO_PRESETS)]);
|
|
210
|
+
const connected = [...known].filter((a) => hasByoToken(a));
|
|
211
|
+
if (connected.length)
|
|
212
|
+
for (const a of connected)
|
|
208
213
|
console.log(`connected: ${a}`);
|
|
209
|
-
|
|
210
|
-
console.log('(no BYO keys stored yet — e.g. "operator auth byo
|
|
214
|
+
else
|
|
215
|
+
console.log('(no BYO keys stored yet — e.g. "operator auth byo-key openai", or "operator auth byo-model --preset openai")');
|
|
211
216
|
return 0;
|
|
212
217
|
}
|
|
213
218
|
if (!account) {
|
|
214
|
-
console.error("usage: operator auth byo <account> | byo --list | byo <account> --rm");
|
|
219
|
+
console.error("usage: operator auth byo-key <account> | byo-key --list | byo-key <account> --rm");
|
|
215
220
|
return 1;
|
|
216
221
|
}
|
|
217
222
|
if (rest.includes("--rm")) {
|
|
@@ -228,6 +233,55 @@ async function byo(rest) {
|
|
|
228
233
|
console.error(`✗ could not store the ${account} key`);
|
|
229
234
|
return 1;
|
|
230
235
|
}
|
|
236
|
+
/** `operator auth byo-model` — register a provider model as a selectable /model entry AND store its key,
|
|
237
|
+
* in one step. Provider-agnostic and STACKABLE: run it once per cloud provider (OpenAI, Anthropic, Gemini,
|
|
238
|
+
* …) and each becomes its own `/model` pick, gated by its own key. Writes a ModelProfile into
|
|
239
|
+
* settings.models (replace-by-id) via saveSettings — no code change, survives restarts.
|
|
240
|
+
* operator auth byo-model --preset openai
|
|
241
|
+
* operator auth byo-model --id my-gpt --base https://api.openai.com/v1 --model gpt-5 --ctx 272000 [--account openai] [--dialect openai] */
|
|
242
|
+
async function byoModel(rest) {
|
|
243
|
+
if (rest.includes("--list")) {
|
|
244
|
+
const models = (loadSettings().models ?? []).filter((m) => m.byo);
|
|
245
|
+
if (!models.length) {
|
|
246
|
+
console.log("(no BYO models registered — e.g. \"operator auth byo-model --preset openai\")");
|
|
247
|
+
return 0;
|
|
248
|
+
}
|
|
249
|
+
for (const m of models)
|
|
250
|
+
console.log(`${hasByoToken(m.byo) ? "✓" : "○"} ${m.id} (${m.model} @ ${m.endpoint}, key "${m.byo}")`);
|
|
251
|
+
return 0;
|
|
252
|
+
}
|
|
253
|
+
const presetName = flagValue(rest, "--preset");
|
|
254
|
+
const preset = presetName ? BYO_PRESETS[presetName] : undefined;
|
|
255
|
+
if (presetName && !preset) {
|
|
256
|
+
console.error(`unknown preset "${presetName}" — choices: ${Object.keys(BYO_PRESETS).join(", ")}`);
|
|
257
|
+
return 1;
|
|
258
|
+
}
|
|
259
|
+
const base = flagValue(rest, "--base") ?? preset?.endpoint;
|
|
260
|
+
const model = flagValue(rest, "--model") ?? preset?.model;
|
|
261
|
+
const account = flagValue(rest, "--account") ?? preset?.account ?? presetName;
|
|
262
|
+
const id = flagValue(rest, "--id") ?? (presetName && model ? `${presetName}-${model}`.replace(/[^a-zA-Z0-9.-]+/g, "-").toLowerCase() : undefined);
|
|
263
|
+
const label = flagValue(rest, "--label") ?? preset?.label ?? id;
|
|
264
|
+
const ctxArg = flagValue(rest, "--ctx");
|
|
265
|
+
const ctx = ctxArg ? Number(ctxArg) : (preset?.ctx ?? 131072);
|
|
266
|
+
const dialect = (flagValue(rest, "--dialect") ?? preset?.transport ?? "openai");
|
|
267
|
+
if (!id || !base || !model || !account || !Number.isFinite(ctx)) {
|
|
268
|
+
console.error("usage: operator auth byo-model --preset <p> | --id <id> --base <url> --model <name> [--account <acct>] [--label <l>] [--ctx <n>] [--dialect openai|llama|anthropic]");
|
|
269
|
+
console.error(` presets: ${Object.keys(BYO_PRESETS).join(", ")}`);
|
|
270
|
+
return 1;
|
|
271
|
+
}
|
|
272
|
+
const profile = { id, label: label ?? id, kind: "single", desc: `BYO ${label ?? id} — your key`, endpoint: base, model, ctx, byo: account, transport: dialect };
|
|
273
|
+
const existing = loadSettings().models ?? [];
|
|
274
|
+
const models = [...existing.filter((m) => m.id !== id), profile];
|
|
275
|
+
saveSettings({ models });
|
|
276
|
+
console.log(`✓ model "${id}" registered (${model} @ ${base}, key account "${account}")`);
|
|
277
|
+
if (setByoTokenInteractive(account)) {
|
|
278
|
+
console.log(`✓ ${account} key stored — /model now offers "${id}"`);
|
|
279
|
+
await audit("credential_stored", `byo-model id=${id} account=${account}`);
|
|
280
|
+
return 0;
|
|
281
|
+
}
|
|
282
|
+
console.error(`model "${id}" registered but no key stored yet — run: operator auth byo-key ${account}`);
|
|
283
|
+
return 1;
|
|
284
|
+
}
|
|
231
285
|
/** Dispatch `operator auth <sub> [args]`. Returns a process exit code. */
|
|
232
286
|
export async function runAuth(argv, settings, stdin = process.stdin) {
|
|
233
287
|
auditCfg = settings;
|
|
@@ -257,9 +311,11 @@ export async function runAuth(argv, settings, stdin = process.stdin) {
|
|
|
257
311
|
case "logout": return logout();
|
|
258
312
|
case "status":
|
|
259
313
|
case "whoami": return status();
|
|
260
|
-
case "byo": return
|
|
314
|
+
case "byo-model": return byoModel(rest);
|
|
315
|
+
case "byo-key":
|
|
316
|
+
case "byo": return byoKey(rest); // byo = back-compat alias of byo-key
|
|
261
317
|
default:
|
|
262
|
-
console.log("usage: operator auth <login [--email <addr> | --browser | --token-stdin | --token <pat>] | logout | status | byo [
|
|
318
|
+
console.log("usage: operator auth <login [--email <addr> | --browser | --token-stdin | --token <pat>] | logout | status | byo-model [--preset <p> | --id <id> --base <url> --model <name> …] | byo-key <account> [--list | --rm]>");
|
|
263
319
|
return sub ? 1 : 0;
|
|
264
320
|
}
|
|
265
321
|
}
|
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
// delegate_to_agent — Operator's SECOND delegation path. Where delegate_task (./delegate.ts) hands ONE
|
|
2
|
+
// subtask to a sub-agent on a chosen fleet/BYO *model* inside Operator's own engine (our turn loop, our
|
|
3
|
+
// tools), delegate_to_agent hands it to a local *agent CLI* — a separate command-line coding agent
|
|
4
|
+
// (cursor-agent, Claude Code, Codex, …) that runs its OWN autonomous tool-loop in the workspace and reports
|
|
5
|
+
// back its final answer. The two coexist; neither touches the other.
|
|
6
|
+
//
|
|
7
|
+
// "Other users can have more or less," so the set of agent CLIs is a CONFIG-DRIVEN REGISTRY: built-in
|
|
8
|
+
// presets here, plus anything the owner adds under `settings.agentClis`, merged over the built-ins by id.
|
|
9
|
+
// Availability (the bin resolvable on PATH) gates what is actually usable, so a preset for a CLI that isn't
|
|
10
|
+
// installed never spawns blindly — it returns an actionable install hint.
|
|
11
|
+
//
|
|
12
|
+
// Browser-safe: reachable from the tool registry (which rides in the engine bundle graph), so every node
|
|
13
|
+
// builtin loads LAZILY via the nodeImport idiom (same as delegate.ts / cron.ts). `ownChild` is itself
|
|
14
|
+
// node-lazy, so importing it statically keeps this module loadable from the neutral/JSCore bundle.
|
|
15
|
+
import { ownChild } from "../util/owned-children.js";
|
|
16
|
+
const nodeImport = (m) => import(/* @vite-ignore */ m);
|
|
17
|
+
const msg = (e) => (e instanceof Error ? e.message : String(e));
|
|
18
|
+
/** Hard wall-clock bound on one delegation. The agent CLI runs its own loop (it can edit files, run shells,
|
|
19
|
+
* call out), and the tool.run that awaits it gets no abort signal, so a wedged CLI must not hold the planner
|
|
20
|
+
* forever. Configurable per-call (DelegateToAgentDeps.timeoutMs) and via `process.env.KODE_AGENT_CLI_TIMEOUT_MS`
|
|
21
|
+
* (milliseconds); this is the floor when neither is set. */
|
|
22
|
+
export const AGENT_CLI_TIMEOUT_MS = 10 * 60_000;
|
|
23
|
+
// ── Built-in presets ─────────────────────────────────────────────────────────
|
|
24
|
+
const CURSOR_HINT = "cursor-agent is not installed (not on PATH). Install the Cursor CLI — `curl https://cursor.com/install -fsS | bash` — then sign in with `cursor-agent login` or set CURSOR_API_KEY.";
|
|
25
|
+
const CLAUDE_HINT = "claude (Claude Code) is not installed (not on PATH). Install it — `npm i -g @anthropic-ai/claude-code` — then sign in by running `claude`.";
|
|
26
|
+
const CODEX_HINT = "codex (OpenAI Codex CLI) is not installed (not on PATH). Install it — `npm i -g @openai/codex` (or `brew install codex`) — then authenticate per its docs.";
|
|
27
|
+
/** The shipped agent CLIs. cursor-agent and claude are the two confirmed on the fleet; codex ships as a
|
|
28
|
+
* preset so it works the instant it's installed (availability-gated), and the shape is the template for
|
|
29
|
+
* future ones (gemini, aider, …) added here or via settings. */
|
|
30
|
+
export const BUILTIN_AGENT_CLIS = [
|
|
31
|
+
{
|
|
32
|
+
id: "cursor-agent",
|
|
33
|
+
label: "Cursor Agent",
|
|
34
|
+
bin: "cursor-agent",
|
|
35
|
+
taskVia: "arg",
|
|
36
|
+
mutating: true, // --force bypasses the workspace-trust prompt: it runs with full write + shell access
|
|
37
|
+
// `-p` = print/non-interactive; `--force` (alias --yolo) is REQUIRED or it stops at the trust prompt.
|
|
38
|
+
buildArgs: (task, o) => ["-p", "--force", "--output-format", "text", ...(o.model ? ["--model", o.model] : []), task],
|
|
39
|
+
parseOutput: (raw) => raw.trim(),
|
|
40
|
+
installHint: CURSOR_HINT,
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
id: "claude",
|
|
44
|
+
label: "Claude Code",
|
|
45
|
+
bin: "claude",
|
|
46
|
+
taskVia: "arg",
|
|
47
|
+
mutating: true,
|
|
48
|
+
buildArgs: (task, o) => ["-p", "--dangerously-skip-permissions", "--output-format", "text", ...(o.model ? ["--model", o.model] : []), task],
|
|
49
|
+
parseOutput: (raw) => raw.trim(),
|
|
50
|
+
installHint: CLAUDE_HINT,
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
id: "codex",
|
|
54
|
+
label: "OpenAI Codex CLI",
|
|
55
|
+
bin: "codex",
|
|
56
|
+
taskVia: "arg",
|
|
57
|
+
mutating: true,
|
|
58
|
+
buildArgs: (task, o) => ["exec", ...(o.model ? ["--model", o.model] : []), task],
|
|
59
|
+
parseOutput: (raw) => raw.trim(),
|
|
60
|
+
installHint: CODEX_HINT,
|
|
61
|
+
},
|
|
62
|
+
];
|
|
63
|
+
// ── Registry (built-ins merged with settings.agentClis) ──────────────────────
|
|
64
|
+
/** Substitute the template placeholders. "{{task}}" -> the task (arg mode only); "{{model}}" -> the model
|
|
65
|
+
* (the token is dropped when there's no model); a token embedded in a larger string is replaced in place. */
|
|
66
|
+
function expandTemplate(template, task, o, taskVia) {
|
|
67
|
+
const out = [];
|
|
68
|
+
let sawTask = false;
|
|
69
|
+
for (const seg of template) {
|
|
70
|
+
if (seg === "{{model}}") {
|
|
71
|
+
if (o.model)
|
|
72
|
+
out.push(o.model);
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
if (seg === "{{task}}") {
|
|
76
|
+
if (taskVia === "arg") {
|
|
77
|
+
out.push(task);
|
|
78
|
+
sawTask = true;
|
|
79
|
+
}
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
out.push(seg.replace(/\{\{model\}\}/g, o.model ?? ""));
|
|
83
|
+
}
|
|
84
|
+
if (taskVia === "arg" && !sawTask)
|
|
85
|
+
out.push(task);
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
/** Compile a user's declarative spec into a runtime preset. Agent CLIs are mutating by nature (write + shell),
|
|
89
|
+
* so `mutating` defaults to true unless the spec explicitly sets it false. */
|
|
90
|
+
export function compileSpec(spec) {
|
|
91
|
+
const taskVia = spec.taskVia === "stdin" ? "stdin" : "arg";
|
|
92
|
+
const template = spec.args ?? [];
|
|
93
|
+
return {
|
|
94
|
+
id: spec.id,
|
|
95
|
+
label: spec.label ?? spec.id,
|
|
96
|
+
bin: spec.bin,
|
|
97
|
+
taskVia,
|
|
98
|
+
mutating: spec.mutating !== false,
|
|
99
|
+
parseOutput: (raw) => raw.trim(),
|
|
100
|
+
installHint: spec.installHint ?? `"${spec.id}" is not installed — its bin \`${spec.bin}\` was not found on PATH (set an absolute \`bin\` in settings.agentClis, or install it).`,
|
|
101
|
+
buildArgs: (task, o) => expandTemplate(template, task, o, taskVia),
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
/** The live preset list: built-ins, then settings.agentClis merged over them by id (a user entry with a
|
|
105
|
+
* built-in's id overrides that built-in; a new id adds a preset). */
|
|
106
|
+
export function agentCliPresets(settings) {
|
|
107
|
+
const merged = new Map();
|
|
108
|
+
for (const p of BUILTIN_AGENT_CLIS)
|
|
109
|
+
merged.set(p.id, p);
|
|
110
|
+
for (const spec of settings?.agentClis ?? [])
|
|
111
|
+
if (spec && spec.id && spec.bin)
|
|
112
|
+
merged.set(spec.id, compileSpec(spec));
|
|
113
|
+
return [...merged.values()];
|
|
114
|
+
}
|
|
115
|
+
export function findAgentCliPreset(id, settings) {
|
|
116
|
+
return agentCliPresets(settings).find((p) => p.id === id);
|
|
117
|
+
}
|
|
118
|
+
// ── Availability detection (bin resolved on PATH, cached) ────────────────────
|
|
119
|
+
const _binCache = new Map();
|
|
120
|
+
/** Drop the cached bin resolutions (tests; after an install). */
|
|
121
|
+
export function clearAgentCliCache() { _binCache.clear(); }
|
|
122
|
+
/** Resolve a bin like `command -v`/`which`: an absolute/relative path is checked for an executable file;
|
|
123
|
+
* a bare name is looked up on each PATH entry. Returns the resolved path or null. */
|
|
124
|
+
async function defaultResolveBin(bin) {
|
|
125
|
+
try {
|
|
126
|
+
const fs = (await nodeImport("node:fs"));
|
|
127
|
+
const path = (await nodeImport("node:path"));
|
|
128
|
+
const ok = (p) => { try {
|
|
129
|
+
fs.accessSync(p, fs.constants.X_OK);
|
|
130
|
+
return fs.statSync(p).isFile();
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
return false;
|
|
134
|
+
} };
|
|
135
|
+
if (bin.includes("/"))
|
|
136
|
+
return ok(bin) ? path.resolve(bin) : null;
|
|
137
|
+
const PATH = globalThis.process?.env?.PATH ?? "";
|
|
138
|
+
for (const dir of PATH.split(path.delimiter))
|
|
139
|
+
if (dir && ok(path.join(dir, bin)))
|
|
140
|
+
return path.join(dir, bin);
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
/** The SYNCHRONOUS bin resolver powering the tool description at module load (no I/O awaited there, same
|
|
148
|
+
* idiom as registry.ownedMcpNote): uses process.getBuiltinModule so it's a no-op in the neutral bundle. */
|
|
149
|
+
function resolveBinSync(bin) {
|
|
150
|
+
try {
|
|
151
|
+
const proc = globalThis.process;
|
|
152
|
+
const fs = proc?.getBuiltinModule?.("node:fs");
|
|
153
|
+
const path = proc?.getBuiltinModule?.("node:path");
|
|
154
|
+
if (!fs || !path)
|
|
155
|
+
return null;
|
|
156
|
+
const ok = (p) => { try {
|
|
157
|
+
fs.accessSync(p, fs.constants.X_OK);
|
|
158
|
+
return fs.statSync(p).isFile();
|
|
159
|
+
}
|
|
160
|
+
catch {
|
|
161
|
+
return false;
|
|
162
|
+
} };
|
|
163
|
+
if (bin.includes("/"))
|
|
164
|
+
return ok(bin) ? path.resolve(bin) : null;
|
|
165
|
+
for (const dir of (proc?.env?.PATH ?? "").split(path.delimiter))
|
|
166
|
+
if (dir && ok(path.join(dir, bin)))
|
|
167
|
+
return path.join(dir, bin);
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
/** Is `preset`'s CLI installed? Resolves + caches the bin; a cached hit skips the PATH walk. */
|
|
175
|
+
export async function available(preset, deps = {}) {
|
|
176
|
+
const resolve = deps.resolveBin ?? defaultResolveBin;
|
|
177
|
+
let path = _binCache.get(preset.bin);
|
|
178
|
+
if (path === undefined) {
|
|
179
|
+
path = await resolve(preset.bin);
|
|
180
|
+
_binCache.set(preset.bin, path);
|
|
181
|
+
}
|
|
182
|
+
return path ? { available: true, path } : { available: false, error: preset.installHint };
|
|
183
|
+
}
|
|
184
|
+
// ── Dynamic tool description (lists only the INSTALLED agents) ────────────────
|
|
185
|
+
/** The `delegate_to_agent` tool description, naming only the agent CLIs actually installed right now (mirrors
|
|
186
|
+
* how delegate_task enumerates its targets). `isInstalled` is injectable for tests; by default it does a
|
|
187
|
+
* synchronous PATH resolve of each preset's bin. */
|
|
188
|
+
export function agentCliToolDescription(opts = {}) {
|
|
189
|
+
const presets = opts.presets ?? agentCliPresets();
|
|
190
|
+
const isInstalled = opts.isInstalled ?? ((p) => resolveBinSync(p.bin) !== null);
|
|
191
|
+
const installed = presets.filter(isInstalled);
|
|
192
|
+
const notInstalled = presets.filter((p) => !isInstalled(p)).map((p) => p.id);
|
|
193
|
+
const list = installed.length ? installed.map((p) => `"${p.id}" (${p.label})`).join(", ") : "NONE are installed on this machine right now — the call will return each one's install hint";
|
|
194
|
+
return `Delegate ONE self-contained task to a local AGENT CLI — a separate command-line coding agent (Cursor Agent, Claude Code, OpenAI Codex, …) that runs its OWN autonomous tool-loop in this workspace and reports back its final answer (blocks until it finishes). This is a SECOND delegation path alongside delegate_task: delegate_task runs a subtask on another MODEL inside Operator's own engine, whereas delegate_to_agent shells out to a whole external agent that edits files and runs shell commands by itself. INSTALLED agents you can pick now (\`agent\`): ${list}.${notInstalled.length ? ` Known but NOT installed here (don't pick these): ${notInstalled.join(", ")}.` : ""} \`task\` must be fully self-contained — the CLI has NO memory of this conversation and cannot ask questions; put every path, constraint and the exact deliverable in it. Optional \`model\` picks the CLI's underlying model. AUTONOMY/SAFETY: the delegate runs with FULL WRITE + SHELL access under the owner's environment and will modify the workspace and run commands on its own, so scope the task tightly to work you want done autonomously. If the chosen agent isn't installed the call fails with its exact install hint — it never spawns blindly.`;
|
|
195
|
+
}
|
|
196
|
+
const CAPTURE_CAP = 4 * 1024 * 1024; // in-memory stdout/stderr ceiling; the executor's capToolResult spills large results to disk downstream
|
|
197
|
+
/** Spawn the CLI in its own process group, capture stdout/stderr, enforce the timeout, and on timeout kill
|
|
198
|
+
* the WHOLE group (SIGTERM, then SIGKILL) so the CLI's own child processes are never orphaned. Never throws. */
|
|
199
|
+
async function runProcess(file, argv, opts) {
|
|
200
|
+
const cp = (await nodeImport("node:child_process"));
|
|
201
|
+
return new Promise((resolve) => {
|
|
202
|
+
let stdout = "", stderr = "", timedOut = false, settled = false;
|
|
203
|
+
let killTimer;
|
|
204
|
+
let child;
|
|
205
|
+
try {
|
|
206
|
+
// detached:true => the child is its own group leader, so process.kill(-pid) reaps it AND its children.
|
|
207
|
+
child = cp.spawn(file, argv, { cwd: opts.cwd, detached: true, env: process.env, stdio: [opts.stdin != null ? "pipe" : "ignore", "pipe", "pipe"] });
|
|
208
|
+
}
|
|
209
|
+
catch (e) {
|
|
210
|
+
resolve({ code: null, signal: null, stdout: "", stderr: "", timedOut: false, spawnError: msg(e) });
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
ownChild(child, `delegate_to_agent:${opts.label}`, { cmd: `${file} ${argv.join(" ")}`.slice(0, 240), group: true });
|
|
214
|
+
// ownChild unref's the child (background-job semantics). Here the tool AWAITS it, so re-ref it: while this
|
|
215
|
+
// delegation is in flight the child must keep the loop alive until it exits, or the await can never settle.
|
|
216
|
+
try {
|
|
217
|
+
child.ref?.();
|
|
218
|
+
}
|
|
219
|
+
catch { /* not a real ChildProcess */ }
|
|
220
|
+
const term = (sig) => { try {
|
|
221
|
+
if (child.pid)
|
|
222
|
+
process.kill(-child.pid, sig);
|
|
223
|
+
}
|
|
224
|
+
catch {
|
|
225
|
+
try {
|
|
226
|
+
child.kill(sig);
|
|
227
|
+
}
|
|
228
|
+
catch { /* already gone */ }
|
|
229
|
+
} };
|
|
230
|
+
const finish = (extra) => {
|
|
231
|
+
if (settled)
|
|
232
|
+
return;
|
|
233
|
+
settled = true;
|
|
234
|
+
clearTimeout(timer);
|
|
235
|
+
if (killTimer)
|
|
236
|
+
clearTimeout(killTimer);
|
|
237
|
+
resolve({ code: null, signal: null, stdout, stderr, timedOut, ...extra });
|
|
238
|
+
};
|
|
239
|
+
const timer = setTimeout(() => { timedOut = true; term("SIGTERM"); killTimer = setTimeout(() => term("SIGKILL"), 2000); killTimer.unref?.(); }, opts.timeoutMs);
|
|
240
|
+
timer.unref?.();
|
|
241
|
+
child.stdout?.on("data", (d) => { if (stdout.length < CAPTURE_CAP)
|
|
242
|
+
stdout += d.toString("utf8"); });
|
|
243
|
+
child.stderr?.on("data", (d) => { if (stderr.length < CAPTURE_CAP)
|
|
244
|
+
stderr += d.toString("utf8"); });
|
|
245
|
+
child.on("error", (e) => finish({ spawnError: msg(e) }));
|
|
246
|
+
child.on("close", (code, signal) => finish({ code, signal }));
|
|
247
|
+
if (opts.stdin != null) {
|
|
248
|
+
try {
|
|
249
|
+
child.stdin?.write(opts.stdin);
|
|
250
|
+
child.stdin?.end();
|
|
251
|
+
}
|
|
252
|
+
catch { /* stdin already closed */ }
|
|
253
|
+
}
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
function timeoutFor(deps) {
|
|
257
|
+
if (deps.timeoutMs && deps.timeoutMs > 0)
|
|
258
|
+
return deps.timeoutMs;
|
|
259
|
+
const env = Number(process.env.KODE_AGENT_CLI_TIMEOUT_MS);
|
|
260
|
+
return Number.isFinite(env) && env > 0 ? env : AGENT_CLI_TIMEOUT_MS;
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* Run `args.task` on the local agent CLI named by `args.agent` (optionally with `args.model`) in the workspace
|
|
264
|
+
* and return its final stdout, or an `error: ...` string (the tool contract: never throws). The CLI runs its
|
|
265
|
+
* OWN autonomous tool-loop with write + shell access; this only resolves the preset, gates on the bin being
|
|
266
|
+
* installed, spawns it, and brings its output back.
|
|
267
|
+
*/
|
|
268
|
+
export async function runDelegateToAgent(args, deps = {}) {
|
|
269
|
+
const task = String(args.task ?? "").trim();
|
|
270
|
+
if (!task)
|
|
271
|
+
return "error: delegate_to_agent needs a non-empty `task` — the agent CLI sees only this and cannot ask you questions";
|
|
272
|
+
const settings = deps.loadSettings
|
|
273
|
+
? await deps.loadSettings()
|
|
274
|
+
: await (await nodeImport("../config/settings.js")).loadSettings();
|
|
275
|
+
const presets = agentCliPresets(settings);
|
|
276
|
+
const ids = presets.map((p) => p.id).join(", ");
|
|
277
|
+
const agentId = String(args.agent ?? "").trim();
|
|
278
|
+
if (!agentId)
|
|
279
|
+
return `error: delegate_to_agent needs an \`agent\` — one of: ${ids}`;
|
|
280
|
+
const preset = presets.find((p) => p.id === agentId);
|
|
281
|
+
if (!preset)
|
|
282
|
+
return `error: delegate_to_agent: unknown agent "${agentId}" — known agents: ${ids}`;
|
|
283
|
+
const avail = await available(preset, { resolveBin: deps.resolveBin });
|
|
284
|
+
if (!avail.available || !avail.path)
|
|
285
|
+
return `error: delegate_to_agent: ${avail.error ?? preset.installHint}`;
|
|
286
|
+
const model = String(args.model ?? "").trim() || undefined;
|
|
287
|
+
const argv = preset.buildArgs(task, { model });
|
|
288
|
+
const cwd = deps.cwd ?? process.cwd();
|
|
289
|
+
const timeoutMs = timeoutFor(deps);
|
|
290
|
+
const stdin = preset.taskVia === "stdin" ? task : undefined;
|
|
291
|
+
const r = await runProcess(avail.path, argv, { cwd, timeoutMs, stdin, label: preset.id });
|
|
292
|
+
if (r.spawnError)
|
|
293
|
+
return `error: delegate_to_agent: could not launch ${preset.id} (${preset.bin}) — ${r.spawnError}`;
|
|
294
|
+
if (r.timedOut)
|
|
295
|
+
return `error: delegate_to_agent: ${preset.id} timed out after ${Math.round(timeoutMs / 1000)}s and was killed — narrow the task or raise the timeout`;
|
|
296
|
+
if (r.code !== 0) {
|
|
297
|
+
const tail = (r.stderr || r.stdout).trim().slice(-800);
|
|
298
|
+
return `error: delegate_to_agent: ${preset.id} exited ${r.signal ? `on ${r.signal}` : `with code ${r.code}`}${tail ? ` — ${tail}` : ""}`;
|
|
299
|
+
}
|
|
300
|
+
const answer = preset.parseOutput(r.stdout).trim();
|
|
301
|
+
if (!answer)
|
|
302
|
+
return `error: delegate_to_agent: ${preset.id} finished but produced no output on stdout${r.stderr.trim() ? ` (stderr tail: ${r.stderr.trim().slice(-400)})` : ""}`;
|
|
303
|
+
return answer;
|
|
304
|
+
}
|