@0perator/operator 0.1.262 → 0.1.274
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/dist/auth/client.js +8 -0
- package/dist/autonomy/delegate.js +21 -2
- package/dist/autonomy/session-factory.js +4 -0
- package/dist/cli.js +221 -70
- package/dist/config/persona.js +41 -15
- package/dist/config/settings.js +47 -6
- package/dist/engine/agent.js +36 -7
- package/dist/engine/anthropic.js +48 -0
- package/dist/engine/batch-scheduler.js +68 -21
- package/dist/mcp/index.js +2 -1
- package/dist/permissions/index.js +11 -4
- package/dist/remote/host.js +46 -5
- package/dist/remote/pairing.js +70 -0
- package/dist/router/models.js +9 -2
- package/dist/services/model-autodetect.js +240 -0
- package/dist/services/preflight.js +46 -2
- package/dist/session.js +19 -2
- package/dist/tools/deferred.js +2 -1
- package/dist/tools/executor.js +15 -3
- package/dist/tools/native-redirect.js +140 -0
- package/dist/tools/power-tools.js +627 -0
- package/dist/tools/registry.js +527 -115
- package/dist/tools/searxng.js +8 -1
- package/dist/ui/App.js +5 -4
- package/dist/ui/BgPanel.js +13 -1
- package/dist/ui/Composer.js +28 -1
- package/dist/ui/ToolStep.js +1 -1
- package/dist/ui/format.js +18 -0
- package/dist/ui/liveTools.js +2 -5
- package/dist/ui/qr.js +10 -0
- package/dist/ui/resize.js +160 -0
- package/dist/ui/slashCommands.js +43 -0
- package/dist/ui/term.js +22 -0
- package/dist/util/slash.js +1 -1
- package/package.json +3 -1
package/dist/remote/host.js
CHANGED
|
@@ -1,4 +1,15 @@
|
|
|
1
|
+
import { frameKey as deriveFrameKey, pairingId as derivePairingId, encryptFrame, decryptFrame } from "./pairing.js";
|
|
1
2
|
const V = 1;
|
|
3
|
+
// Paired (QR) mode: only DATA-frame payloads are e2e-encrypted; the header (v/type/sessionId/seq/ts) and
|
|
4
|
+
// control frames stay plaintext so the relay can route blind. These sets mirror the mobile's frozen
|
|
5
|
+
// dataFrameTypes byte-for-byte (kode-mobile RemoteSession.swift). The INNER encrypted bytes are
|
|
6
|
+
// JSON.stringify(payloadDict) — just the payload dict, never {type,payload}.
|
|
7
|
+
const DATA_HOST_TYPES = new Set(["snapshot", "transcript", "tool_step", "activity", "status", "capabilities", "approval_request", "ask_user", "delta"]);
|
|
8
|
+
const DATA_DRIVE_TYPES = new Set(["prompt", "command", "approval_response", "ask_user_response", "interrupt"]);
|
|
9
|
+
// A paired snapshot is encrypted (base64 ≈ 1.37× plaintext), and the relay drops/truncates any frame over
|
|
10
|
+
// its 256 KB cap — which would corrupt ciphertext. Cap the paired snapshot's plaintext so the encrypted
|
|
11
|
+
// frame stays comfortably under 256 KB; token-mode keeps the full 512 KB budget.
|
|
12
|
+
const SNAPSHOT_MAX_BYTES_PAIRED = 170 * 1024;
|
|
2
13
|
// SPEC §8 limits (relay-enforced per spec, but host.ts didn't honor either one — REMOTE_RICH_HEAD_AUDIT.md
|
|
3
14
|
// §1/§4 BLOCKER: this repo's own MCP surface is 600+ tools across a handful of servers, which put
|
|
4
15
|
// `capabilities.mcpServers` alone at 70-100+ KB before this fix, on top of an already-uncapped transcript.
|
|
@@ -45,11 +56,23 @@ export class RemoteHost {
|
|
|
45
56
|
livePending = null;
|
|
46
57
|
turnN = 0;
|
|
47
58
|
capabilities = null;
|
|
48
|
-
|
|
59
|
+
// Paired (QR) mode — set from the one-time code the owner shows as a QR. When paired, the host registers
|
|
60
|
+
// its pairingId with the relay and e2e-encrypts every DATA-frame payload with frameKey; the relay (and
|
|
61
|
+
// anyone but the scanning phone) sees only ciphertext.
|
|
62
|
+
paired = false;
|
|
63
|
+
frameKey = null;
|
|
64
|
+
pairingId = null;
|
|
65
|
+
constructor(url, token, meta, cb, pairing) {
|
|
49
66
|
this.url = url;
|
|
50
67
|
this.token = token;
|
|
51
68
|
this.meta = meta;
|
|
52
69
|
this.cb = cb;
|
|
70
|
+
if (pairing) {
|
|
71
|
+
this.sessionId = pairing.sessionId; // deterministic, so the QR's s=<sessionId> is known before connect
|
|
72
|
+
this.paired = true;
|
|
73
|
+
this.frameKey = deriveFrameKey(pairing.code);
|
|
74
|
+
this.pairingId = derivePairingId(pairing.code);
|
|
75
|
+
}
|
|
53
76
|
}
|
|
54
77
|
connect() {
|
|
55
78
|
this.cb.onState?.("connecting");
|
|
@@ -93,11 +116,24 @@ export class RemoteHost {
|
|
|
93
116
|
}
|
|
94
117
|
if (f.v !== V)
|
|
95
118
|
return;
|
|
119
|
+
// Paired mode: a follower's DATA (drive) frame carries an encrypted payload string — decrypt it back to
|
|
120
|
+
// the payload dict before the switch reads f.payload.text / .id / etc. Control frames (welcome, attach,
|
|
121
|
+
// error) stay plaintext and skip this. An undecryptable frame (wrong key / tamper) is dropped.
|
|
122
|
+
if (this.paired && DATA_DRIVE_TYPES.has(f.type) && typeof f.payload === "string") {
|
|
123
|
+
try {
|
|
124
|
+
f.payload = JSON.parse(decryptFrame(this.frameKey, f.payload).toString("utf8"));
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
96
130
|
switch (f.type) {
|
|
97
131
|
case "welcome":
|
|
98
132
|
this.sessionId = f.payload?.sessionId ?? this.sessionId;
|
|
99
133
|
this.ownerSub = f.payload?.ownerSub ?? null;
|
|
100
134
|
this.send("register", this.sessionId, { title: this.meta.title, surface: this.meta.surface ?? "cli", cwd: this.meta.cwd, host: this.meta.host });
|
|
135
|
+
if (this.paired && this.pairingId)
|
|
136
|
+
this.send("pair-register", this.sessionId, { pairingId: this.pairingId }); // control frame (plaintext) — binds pairingId -> this session at the relay
|
|
101
137
|
this.cb.onState?.("live");
|
|
102
138
|
break;
|
|
103
139
|
case "attach": // a follower joined — send a full snapshot BEFORE any further delta (§8)
|
|
@@ -152,7 +188,12 @@ export class RemoteHost {
|
|
|
152
188
|
send(type, sessionId, payload, seq = null) {
|
|
153
189
|
if (!this.ws || this.ws.readyState !== 1)
|
|
154
190
|
return;
|
|
155
|
-
|
|
191
|
+
// Paired mode: encrypt the payload of DATA frames (control frames — hello/register/pair-register — stay
|
|
192
|
+
// plaintext so the relay routes them). INNER = JSON.stringify(payloadDict); wire payload = base64(iv||ct||tag).
|
|
193
|
+
const wirePayload = this.paired && this.frameKey && DATA_HOST_TYPES.has(type) && payload != null
|
|
194
|
+
? encryptFrame(this.frameKey, Buffer.from(JSON.stringify(payload)))
|
|
195
|
+
: payload;
|
|
196
|
+
const frame = { v: V, type, sessionId: sessionId ?? this.sessionId, seq, ts: Date.now(), payload: wirePayload };
|
|
156
197
|
try {
|
|
157
198
|
this.ws.send(JSON.stringify(frame));
|
|
158
199
|
}
|
|
@@ -161,7 +202,7 @@ export class RemoteHost {
|
|
|
161
202
|
state(type, payload) { this.send(type, this.sessionId, payload, ++this.seq); }
|
|
162
203
|
sendSnapshot() {
|
|
163
204
|
this.flushLive();
|
|
164
|
-
const { transcript, truncated, omittedBefore } = this.capTranscript(this.entries);
|
|
205
|
+
const { transcript, truncated, omittedBefore } = this.capTranscript(this.entries, this.paired ? SNAPSHOT_MAX_BYTES_PAIRED : SNAPSHOT_MAX_BYTES);
|
|
165
206
|
this.send("snapshot", this.sessionId, {
|
|
166
207
|
transcript, activity: this.activity, status: { ctxPct: this.ctxPct, route: this.route, ...(this.tokens != null ? { tokens: this.tokens } : {}) },
|
|
167
208
|
...(truncated ? { truncated: true, omittedBefore } : {}),
|
|
@@ -174,14 +215,14 @@ export class RemoteHost {
|
|
|
174
215
|
* time (entries carry no seq of their own): enough for a follower to know only scrollback before
|
|
175
216
|
* "now" was cut, not that live driving is affected. Cheap to call on every attach — at most O(200)
|
|
176
217
|
* serializations of a shrinking slice, and attach is not a hot path. */
|
|
177
|
-
capTranscript(entries) {
|
|
218
|
+
capTranscript(entries, maxBytes = SNAPSHOT_MAX_BYTES) {
|
|
178
219
|
let out = entries;
|
|
179
220
|
let truncated = false;
|
|
180
221
|
if (out.length > SNAPSHOT_MAX_ENTRIES) {
|
|
181
222
|
out = out.slice(-SNAPSHOT_MAX_ENTRIES);
|
|
182
223
|
truncated = true;
|
|
183
224
|
}
|
|
184
|
-
while (out.length > 1 && byteLen(out) >
|
|
225
|
+
while (out.length > 1 && byteLen(out) > maxBytes) {
|
|
185
226
|
out = out.slice(1);
|
|
186
227
|
truncated = true;
|
|
187
228
|
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// Operator RC pairing crypto — the DESKTOP (host) half of the mobile "Pair Desktop" flow.
|
|
2
|
+
// Byte-for-byte conformant with the mobile Swift CryptoKit impl (kode-mobile PairingCrypto.swift); the
|
|
3
|
+
// frozen test vectors in test/pairing.test.mts pin it so the two can never drift. The RELAY needs none of
|
|
4
|
+
// this — it routes by the opaque `pairingId` and stays blind; only the host and the phone hold frameKey.
|
|
5
|
+
//
|
|
6
|
+
// Contract (frozen on the mobile side):
|
|
7
|
+
// code = 16 random bytes (crypto.randomBytes(16)). NEVER sent to the relay.
|
|
8
|
+
// QR / link = `operator://pair?c=<base64url(code),no-pad>&s=<sessionId>`
|
|
9
|
+
// pairingId = sha256(code) hex -> sent to the relay (the blind id)
|
|
10
|
+
// frameKey = HKDF-SHA256(ikm=code, salt="operator-pair-v1", info="e2e-frame-key", 32)
|
|
11
|
+
// DATA frame = base64( iv(12) || ciphertext || gcm-tag(16) ), aes-256-gcm, fresh iv, no AAD
|
|
12
|
+
// Only DATA frames are encrypted; control frames (pair-register, pair-join, welcome, sessions,
|
|
13
|
+
// attach, detach, error) stay plaintext so the relay can route them.
|
|
14
|
+
import crypto from "node:crypto";
|
|
15
|
+
export function b64url(buf) {
|
|
16
|
+
return Buffer.from(buf).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
17
|
+
}
|
|
18
|
+
export function b64urlDecode(s) {
|
|
19
|
+
let t = s.replace(/-/g, "+").replace(/_/g, "/");
|
|
20
|
+
while (t.length % 4)
|
|
21
|
+
t += "=";
|
|
22
|
+
return Buffer.from(t, "base64");
|
|
23
|
+
}
|
|
24
|
+
/** A fresh 128-bit pairing secret. Stays on the desktop + the phone that scans it; never touches the relay. */
|
|
25
|
+
export function newCode() {
|
|
26
|
+
return crypto.randomBytes(16);
|
|
27
|
+
}
|
|
28
|
+
/** pairingId = hex(SHA256(code)) — the blind id the relay routes by. */
|
|
29
|
+
export function pairingId(code) {
|
|
30
|
+
return crypto.createHash("sha256").update(code).digest("hex");
|
|
31
|
+
}
|
|
32
|
+
/** frameKey = HKDF-SHA256(code, "operator-pair-v1", "e2e-frame-key", 32). Node hkdfSync is RFC-5869,
|
|
33
|
+
* which is exactly what CryptoKit's HKDF uses, so host and phone derive the same key. */
|
|
34
|
+
export function frameKey(code) {
|
|
35
|
+
return Buffer.from(crypto.hkdfSync("sha256", code, Buffer.from("operator-pair-v1"), Buffer.from("e2e-frame-key"), 32));
|
|
36
|
+
}
|
|
37
|
+
/** encryptFrame(key, plaintextBytes) -> base64( iv(12) || ciphertext || gcm-tag(16) ). */
|
|
38
|
+
export function encryptFrame(key, plaintext, iv = crypto.randomBytes(12)) {
|
|
39
|
+
const c = crypto.createCipheriv("aes-256-gcm", key, iv);
|
|
40
|
+
const ct = Buffer.concat([c.update(plaintext), c.final()]);
|
|
41
|
+
return Buffer.concat([iv, ct, c.getAuthTag()]).toString("base64");
|
|
42
|
+
}
|
|
43
|
+
/** decryptFrame(key, base64) -> Buffer. Throws on tamper / wrong key (GCM auth). */
|
|
44
|
+
export function decryptFrame(key, b64) {
|
|
45
|
+
const raw = Buffer.from(b64, "base64");
|
|
46
|
+
const iv = raw.subarray(0, 12);
|
|
47
|
+
const tag = raw.subarray(raw.length - 16);
|
|
48
|
+
const ct = raw.subarray(12, raw.length - 16);
|
|
49
|
+
const d = crypto.createDecipheriv("aes-256-gcm", key, iv);
|
|
50
|
+
d.setAuthTag(tag);
|
|
51
|
+
return Buffer.concat([d.update(ct), d.final()]);
|
|
52
|
+
}
|
|
53
|
+
/** The scannable payload: `operator://pair?c=<b64url(code)>&s=<sessionId>` (valid scheme for the QR). */
|
|
54
|
+
export function pairURL(code, sessionId) {
|
|
55
|
+
return `operator://pair?c=${b64url(code)}&s=${encodeURIComponent(sessionId)}`;
|
|
56
|
+
}
|
|
57
|
+
/** Parse a QR/paste payload. Accepts operator://…, 0perator://… (digit-leading), or a bare query string —
|
|
58
|
+
* mirrors the mobile parser. Returns null unless it carries a 16-byte code + a sessionId. */
|
|
59
|
+
export function parsePairURL(raw) {
|
|
60
|
+
const t = (raw || "").trim();
|
|
61
|
+
const q = t.includes("?") ? t.slice(t.indexOf("?") + 1) : t;
|
|
62
|
+
const p = new URLSearchParams(q);
|
|
63
|
+
const c = p.get("c"), s = p.get("s");
|
|
64
|
+
if (!c || !s)
|
|
65
|
+
return null;
|
|
66
|
+
const code = b64urlDecode(c);
|
|
67
|
+
if (code.length !== 16)
|
|
68
|
+
return null;
|
|
69
|
+
return { code, sessionId: s };
|
|
70
|
+
}
|
package/dist/router/models.js
CHANGED
|
@@ -9,7 +9,7 @@ export const MODEL_ALIASES = {
|
|
|
9
9
|
"spectre": "cortana", // flagship renamed Spectre -> Cortana 35B (2026-10-07); old id keeps resolving
|
|
10
10
|
};
|
|
11
11
|
export const BUILTIN_MODELS = [
|
|
12
|
-
{ id: "operator-1m", label: "Operator
|
|
12
|
+
{ id: "operator-1m", label: "Operator 128K", kind: "single", desc: "131,072-token (128K) context (:8097) — matched to the server's --ctx-size so the engine compacts BEFORE the wall (no overflow/interruption on long autonomous turns)", endpoint: "http://127.0.0.1:8097/v1", model: "aurora-code-1", ctx: 128000 },
|
|
13
13
|
{ id: "operator-128k", label: "Operator 128K", kind: "single", desc: "128K context, lighter RAM (:8096)", endpoint: "http://127.0.0.1:8096/v1", model: "aurora-code-1", ctx: 131072 },
|
|
14
14
|
// QwenCloud Token Plan BYO connectors (SPEC/providers.md §2 "API-key connectors"). Same keychain
|
|
15
15
|
// account ("qwen") serves both; the picker hides them until connected (§1 honest availability), and
|
|
@@ -36,7 +36,7 @@ export const BUILTIN_MODELS = [
|
|
|
36
36
|
// truncated a round at token 32767 (finish=length) mid-tool-call, and that cut call poisoned the session (0.1.259).
|
|
37
37
|
// 32000 sits just UNDER the real wall (margin) AND under LEAN_HARNESS_CTX so Cortana drops the heavy memory/handoff
|
|
38
38
|
// (which alone was ~16K = half the window) — persona + unrestricted layer kept. Raise ONLY if the server's --ctx-size does.
|
|
39
|
-
{ id: "cortana", label: "Cortana 35B", kind: "single", desc: "flagship — abliterated Qwen3.6-35B-A3B MoE (~3B active, ~40 tok/s), uncensored + vision (JL1:8112, llama.cpp,
|
|
39
|
+
{ id: "cortana", label: "Cortana 35B", kind: "single", desc: "flagship — abliterated Qwen3.6-35B-A3B MoE (~3B active, ~40 tok/s), uncensored + vision (JL1:8112, llama.cpp, 256K ctx)", endpoint: "http://192.168.1.103:8112/v1", model: "/Volumes/Ai Storage/jl1-local/models/aurorax/Huihui-Qwen3.6-35B-A3B-abliterated.Q4_K_M.gguf", ctx: 262144 },
|
|
40
40
|
// Qwen3-4B — fast LOCAL tier (stock qwen3-4b-mlx-q4, 2.26GB MLX 4-bit, ctx 40960) served via mlx_lm.server
|
|
41
41
|
// on JL1:8110. Qwen3 vocab (151936) — the same family as ghost-32b, so it's the review-recommended quick tier
|
|
42
42
|
// AND the vocab lineage for ghost spec-decode (the actual draft is Qwen3-0.6B, too small to list here). Runs
|
|
@@ -48,6 +48,13 @@ export const BUILTIN_MODELS = [
|
|
|
48
48
|
// JL1:8114 via llama.cpp (--jinja, q8 KV). ctx 32768 ≥ LEAN_HARNESS_CTX → full harness. A quick drop-in to
|
|
49
49
|
// test a smaller/different flavour alongside Spectre without the 35B footprint.
|
|
50
50
|
{ id: "venice-24b", label: "Venice 24B", kind: "single", desc: "lighter uncensored tier — Dolphin-Mistral-24B-Venice + vision (JL1:8114, llama.cpp)", endpoint: "http://192.168.1.103:8114/v1", model: "/Volumes/Ai Storage/exotic-models/dolphin-mistral-24b-venice-gguf/cognitivecomputations_Dolphin-Mistral-24B-Venice-Edition-Q4_K_M.gguf", ctx: 32768 },
|
|
51
|
+
// Code tier for the coding/Replit-clone surface — Qwen2.5-Coder-3B has a real chat template + tool-calling
|
|
52
|
+
// + FIM (ollama reports "completion, tools, insert"), unlike StarCoder2/replit-code (completion-only, can't
|
|
53
|
+
// drive an agent loop). Ollama on JL1, on-demand (loads ~3GB, so SELECT only when JL1 swap has headroom).
|
|
54
|
+
// ctx 32000 stays just under the 32768 train wall (the 0.1.259/260 overrun bug) and below LEAN_HARNESS_CTX
|
|
55
|
+
// so a 3B gets the lean harness. LICENCE: Qwen Research Licence (non-commercial) — fine for owner/eval use;
|
|
56
|
+
// the paid product should use an Apache-2.0 size (qwen2.5-coder 1.5b/7b). transport:"openai" = Ollama /v1.
|
|
57
|
+
{ id: "qwen-coder", label: "Qwen Coder 3B", kind: "single", desc: "code tier — Qwen2.5-Coder-3B Q4_K_M (chat + tool-calling + FIM), Ollama on JL1 (on-demand ~3GB); Qwen Research Licence, non-commercial", endpoint: "http://127.0.0.1:11434/v1", model: "qwen2.5-coder:3b", ctx: 32000, transport: "openai", autodetect: false },
|
|
51
58
|
{ id: "moa", label: "MOA (Mixture of Agents)", kind: "orchestrated", desc: "fan out to proposers, synthesize with an aggregator" },
|
|
52
59
|
];
|
|
53
60
|
/** The runtime registry: the built-ins, with any settings.models entries merged in (overriding a
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
// Model auto-detect boot — connect to whatever model is HEALTHY, local or remote, instead of hard-launching
|
|
2
|
+
// one port and freezing the boot when it is down. (Incident 2026-10-10: the JL2 Aurora gguf vanished, the
|
|
3
|
+
// boot kickstarted com.imi.aurora-serve and HARD-WAITED 90s on a dead :8097, then quit — bricking Operator
|
|
4
|
+
// while cortana, a healthy 35B, answered on JL1:8112 the whole time.)
|
|
5
|
+
//
|
|
6
|
+
// The shape, and the split that makes it testable:
|
|
7
|
+
// • buildCandidates() PURE — the ordered list to try: (a) the active model's endpoint, (b) same-model
|
|
8
|
+
// standbys (failover, fleet nodes), (c) every other registry profile; cloud/BYO last.
|
|
9
|
+
// • detectBoot() the decision flow over an INJECTED probe/launch/sleep (no network in tests):
|
|
10
|
+
// probe → first healthy by priority wins → (only if none) wait out a model that is
|
|
11
|
+
// already loading → cloud tier → Service-lever launch as the LAST resort → degraded.
|
|
12
|
+
// • probeCandidate() the real network probe (short timeout, /health and /v1/models raced in parallel).
|
|
13
|
+
// Nothing here knows what "aurora" is: every entry is just {base, model, ctx}. Aurora is one candidate.
|
|
14
|
+
import { authHeaders } from "../engine/aurora.js";
|
|
15
|
+
import { endpointBase } from "../router/models.js";
|
|
16
|
+
const norm = (base) => base.replace(/\/+$/, "").toLowerCase();
|
|
17
|
+
const keyOf = (c) => `${norm(c.base)}|${c.model}`;
|
|
18
|
+
/** host:port of a base, for the one-line "→ model: …" notice. Falls back to the raw string. */
|
|
19
|
+
export function hostPort(base) {
|
|
20
|
+
try {
|
|
21
|
+
return new URL(base).host;
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return base;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/** The ordered candidate list. PURE. Priority: active → standbys → registry (local/LAN first, cloud last);
|
|
28
|
+
* de-duplicated on base+model so the registry's own copy of the active profile never probes twice. */
|
|
29
|
+
export function buildCandidates(i) {
|
|
30
|
+
const out = [];
|
|
31
|
+
const seen = new Set();
|
|
32
|
+
const add = (c) => {
|
|
33
|
+
const k = keyOf(c);
|
|
34
|
+
if (seen.has(k))
|
|
35
|
+
return;
|
|
36
|
+
seen.add(k);
|
|
37
|
+
out.push(c);
|
|
38
|
+
};
|
|
39
|
+
const a = i.active;
|
|
40
|
+
// An active BYO profile (the owner's /model qwen3.8-max) carries its vendor key + dialect on the registry entry.
|
|
41
|
+
const ap = i.registry.find((p) => p.id === a.id);
|
|
42
|
+
add({ id: a.id, label: a.label ?? a.id, base: a.base, model: a.model, ctx: a.ctx, profileId: a.id, token: a.token ?? (ap?.byo ? i.byoToken?.(ap.byo) : undefined), transport: a.transport ?? ap?.transport, cloud: false, source: "active" });
|
|
43
|
+
if (i.enabled === false)
|
|
44
|
+
return out;
|
|
45
|
+
for (const s of i.standby) {
|
|
46
|
+
if (!s.base)
|
|
47
|
+
continue;
|
|
48
|
+
add({ id: s.id, label: s.id, base: s.base, model: s.model, ctx: s.ctx, cloud: false, source: "standby" });
|
|
49
|
+
}
|
|
50
|
+
const profiles = i.registry.filter((p) => p.kind === "single" && !!p.endpoint && p.autodetect !== false);
|
|
51
|
+
const cloud = (p) => !!p.byo;
|
|
52
|
+
for (const p of [...profiles.filter((p) => !cloud(p)), ...(i.allowCloud === false ? [] : profiles.filter(cloud))]) {
|
|
53
|
+
const token = p.byo ? i.byoToken?.(p.byo) : undefined;
|
|
54
|
+
if (p.byo && !token)
|
|
55
|
+
continue; // a connector with no resolvable key can never answer — don't list a guaranteed ✗
|
|
56
|
+
add({ id: p.id, label: p.label, base: endpointBase(p.endpoint), model: p.model ?? p.id, ctx: p.ctx ?? a.ctx, profileId: p.id, token, transport: p.transport, cloud: cloud(p), source: "registry" });
|
|
57
|
+
}
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
/** The router chain to adopt for a chosen candidate: it first, then the other LOCAL candidates that serve the
|
|
61
|
+
* SAME model (the aurora nodes), so a mid-session death still hops to a sibling instead of stranding. A
|
|
62
|
+
* different model is never mixed in — a failover must not silently change which model answers. PURE. */
|
|
63
|
+
export function routerChain(chosen, all) {
|
|
64
|
+
const toEp = (c) => ({ name: c.id, base: c.base, model: c.model, ctxLimit: c.ctx, token: c.token, transport: c.transport });
|
|
65
|
+
const sib = all.filter((c) => c !== chosen && !c.cloud && !chosen.cloud && c.model === chosen.model && keyOf(c) !== keyOf(chosen));
|
|
66
|
+
return [toEp(chosen), ...sib.map(toEp)];
|
|
67
|
+
}
|
|
68
|
+
/** Probe one candidate. `/health` (llama.cpp, mlx_lm, gateways) and `/v1/models` (Ollama, any OpenAI-compatible
|
|
69
|
+
* server with no /health) are raced IN PARALLEL under ONE short timeout, so the worst case is the timeout, not
|
|
70
|
+
* a serial pair. ready = a 2xx that doesn't say it is still starting; loading = the port answered 503 (llama.cpp
|
|
71
|
+
* serves 503 while it mmaps the model — alive, must not be restarted); down = refused / timed out / 4xx. Never throws. */
|
|
72
|
+
export async function probeCandidate(c, o = {}) {
|
|
73
|
+
const f = o.fetchImpl ?? fetch;
|
|
74
|
+
const ctrl = new AbortController();
|
|
75
|
+
const timer = setTimeout(() => ctrl.abort(), o.timeoutMs ?? 2500);
|
|
76
|
+
const onAbort = () => ctrl.abort();
|
|
77
|
+
o.signal?.addEventListener("abort", onAbort, { once: true });
|
|
78
|
+
const headers = authHeaders({ base: c.base, model: c.model, token: c.token });
|
|
79
|
+
const base = c.base.replace(/\/+$/, "");
|
|
80
|
+
const get = async (path) => {
|
|
81
|
+
try {
|
|
82
|
+
const r = await f(`${base}${path}`, { signal: ctrl.signal, headers });
|
|
83
|
+
if (r.status === 503)
|
|
84
|
+
return "loading";
|
|
85
|
+
if (!r.ok)
|
|
86
|
+
return "down";
|
|
87
|
+
if (path !== "/health")
|
|
88
|
+
return "ready";
|
|
89
|
+
const j = await r.json().catch(() => undefined);
|
|
90
|
+
return j && typeof j.status === "string" && j.status !== "ok" ? "loading" : "ready"; // 200 {"status":"loading model"} is alive-but-not-serving
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
return "down";
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
try {
|
|
97
|
+
// First `ready` wins at once (a healthy endpoint must not wait on its slower sibling request); otherwise the
|
|
98
|
+
// verdict is "loading" if either request saw a 503, else "down".
|
|
99
|
+
return await new Promise((resolve) => {
|
|
100
|
+
const seen = [];
|
|
101
|
+
for (const p of [get("/health"), get("/v1/models")]) {
|
|
102
|
+
void p.then((s) => {
|
|
103
|
+
if (s === "ready")
|
|
104
|
+
return resolve("ready");
|
|
105
|
+
seen.push(s);
|
|
106
|
+
if (seen.length === 2)
|
|
107
|
+
resolve(seen.includes("loading") ? "loading" : "down");
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
finally {
|
|
113
|
+
clearTimeout(timer);
|
|
114
|
+
o.signal?.removeEventListener("abort", onAbort);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/** Fire every probe in parallel, then walk them in PRIORITY order: the first `ready` wins the moment every
|
|
118
|
+
* higher-priority candidate has settled — so a healthy active endpoint returns at once and never waits on a
|
|
119
|
+
* dead LAN host's timeout further down the list. Stragglers are aborted. */
|
|
120
|
+
async function pickFirstReady(cands, deps) {
|
|
121
|
+
const ctrl = new AbortController();
|
|
122
|
+
const memo = new Map(); // one probe per base+token — qwen3.8-max and -flash share a host
|
|
123
|
+
const run = (c) => {
|
|
124
|
+
const k = `${norm(c.base)}|${c.token ? "t" : ""}`;
|
|
125
|
+
let p = memo.get(k);
|
|
126
|
+
if (!p) {
|
|
127
|
+
p = deps.probe(c, ctrl.signal).catch(() => "down");
|
|
128
|
+
memo.set(k, p);
|
|
129
|
+
}
|
|
130
|
+
return p;
|
|
131
|
+
};
|
|
132
|
+
const pending = cands.map(run);
|
|
133
|
+
const attempts = [];
|
|
134
|
+
try {
|
|
135
|
+
for (let i = 0; i < cands.length; i++) {
|
|
136
|
+
const status = await pending[i];
|
|
137
|
+
attempts.push({ candidate: cands[i], status });
|
|
138
|
+
if (status === "ready")
|
|
139
|
+
return { chosen: cands[i], attempts };
|
|
140
|
+
}
|
|
141
|
+
return { attempts };
|
|
142
|
+
}
|
|
143
|
+
finally {
|
|
144
|
+
ctrl.abort();
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
/** The boot decision flow. Never throws, never blocks longer than: one probe timeout (+ `waitSec` if a model is
|
|
148
|
+
* already loading, + the caller-bounded launch when nothing is healthy and one is configured). */
|
|
149
|
+
export async function detectBoot(cands, deps) {
|
|
150
|
+
const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
151
|
+
const now = deps.now ?? Date.now;
|
|
152
|
+
const waitSec = deps.waitSec ?? 25;
|
|
153
|
+
const local = cands.filter((c) => !c.cloud);
|
|
154
|
+
const cloud = cands.filter((c) => c.cloud);
|
|
155
|
+
const tried = [];
|
|
156
|
+
const note = (a) => { for (const x of a)
|
|
157
|
+
if (!tried.some((t) => t.candidate === x.candidate))
|
|
158
|
+
tried.push(x); };
|
|
159
|
+
const done = (chosen, launch) => {
|
|
160
|
+
const failed = tried.filter((t) => t.candidate !== chosen && t.status !== "ready");
|
|
161
|
+
if (launch?.state === "started")
|
|
162
|
+
return { kind: "launched", chosen, tried: failed, launch };
|
|
163
|
+
return { kind: chosen === cands[0] ? "primary" : "alternate", chosen, tried: failed };
|
|
164
|
+
};
|
|
165
|
+
const first = await pickFirstReady(local, deps);
|
|
166
|
+
note(first.attempts);
|
|
167
|
+
if (first.chosen)
|
|
168
|
+
return done(first.chosen);
|
|
169
|
+
// Something is already coming up on its own (llama.cpp 503 while it mmaps): wait it out, bounded — never
|
|
170
|
+
// restart a mid-load model, and never freeze on it past `waitSec`.
|
|
171
|
+
const loading = local.filter((c) => tried.some((t) => t.candidate === c && t.status === "loading"));
|
|
172
|
+
if (loading.length) {
|
|
173
|
+
deps.onProgress?.(`${loading[0].label} is loading…`);
|
|
174
|
+
const deadline = now() + waitSec * 1000;
|
|
175
|
+
while (now() < deadline) {
|
|
176
|
+
await sleep(1000);
|
|
177
|
+
const r = await pickFirstReady(loading, deps);
|
|
178
|
+
for (const a of r.attempts) {
|
|
179
|
+
const t = tried.find((x) => x.candidate === a.candidate);
|
|
180
|
+
if (t)
|
|
181
|
+
t.status = a.status;
|
|
182
|
+
}
|
|
183
|
+
if (r.chosen)
|
|
184
|
+
return done(r.chosen);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
if (cloud.length) {
|
|
188
|
+
deps.onProgress?.("no local model answered — trying connected cloud models…");
|
|
189
|
+
const r = await pickFirstReady(cloud, deps);
|
|
190
|
+
note(r.attempts);
|
|
191
|
+
if (r.chosen)
|
|
192
|
+
return done(r.chosen);
|
|
193
|
+
}
|
|
194
|
+
// LAST resort — and never while something is mid-load (that service is already starting itself).
|
|
195
|
+
let launch;
|
|
196
|
+
if (deps.launch && !loading.length) {
|
|
197
|
+
deps.onProgress?.("no model reachable — trying the local launchd model…");
|
|
198
|
+
launch = await deps.launch().catch((e) => ({ state: "down", detail: String(e?.message ?? e) }));
|
|
199
|
+
if (launch.state === "up" || launch.state === "started") {
|
|
200
|
+
const r = await pickFirstReady(local, deps);
|
|
201
|
+
for (const a of r.attempts) {
|
|
202
|
+
const t = tried.find((x) => x.candidate === a.candidate);
|
|
203
|
+
if (t)
|
|
204
|
+
t.status = a.status;
|
|
205
|
+
else
|
|
206
|
+
tried.push(a);
|
|
207
|
+
}
|
|
208
|
+
if (r.chosen)
|
|
209
|
+
return done(r.chosen, launch);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return { kind: "degraded", tried, launch };
|
|
213
|
+
}
|
|
214
|
+
/** What a boot outcome says about ONE base, for the dashboard's service tiles. undefined = it was never probed
|
|
215
|
+
* (e.g. a healthy higher-priority endpoint won before the walk reached it) — never claim a state we didn't observe. PURE. */
|
|
216
|
+
export function stateOfBase(o, base) {
|
|
217
|
+
const b = norm(base);
|
|
218
|
+
if (o.kind !== "degraded" && norm(o.chosen.base) === b)
|
|
219
|
+
return o.kind === "launched" ? "started" : "up";
|
|
220
|
+
return o.tried.some((t) => norm(t.candidate.base) === b) ? "down" : undefined;
|
|
221
|
+
}
|
|
222
|
+
const mark = (s) => (s === "ready" ? "✓" : s === "loading" ? "…" : "✗");
|
|
223
|
+
/** The scrollback notice for an outcome — "" for the happy path (the services line already confirms it). PURE. */
|
|
224
|
+
export function describeOutcome(o) {
|
|
225
|
+
if (o.kind === "primary")
|
|
226
|
+
return "";
|
|
227
|
+
if (o.kind === "degraded") {
|
|
228
|
+
const rows = o.tried.map((t) => ` ${mark(t.status)} ${t.candidate.id} ${hostPort(t.candidate.base)} ${t.status}`);
|
|
229
|
+
const lane = o.launch ? `\n launch: ${o.launch.detail ?? o.launch.state}` : "";
|
|
230
|
+
return `no model reachable — tried:\n${rows.join("\n")}${lane}\nOperator is open but has no model yet. Pick one with /model <id>, pin an endpoint with /route <name>, or point Operator at a running model in your settings and relaunch. The next message re-checks.`;
|
|
231
|
+
}
|
|
232
|
+
const c = o.chosen;
|
|
233
|
+
const where = `${c.id} @ ${hostPort(c.base)}`;
|
|
234
|
+
const cloudNote = c.cloud ? " (cloud — your own API key; nothing local was reachable)" : "";
|
|
235
|
+
// Two endpoints can share an id (KODE_AURORA re-points the active operator-1m while the registry still lists its
|
|
236
|
+
// own) — name the host only where the id alone would be ambiguous.
|
|
237
|
+
const nameOf = (c) => (o.tried.filter((t) => t.candidate.id === c.id).length > 1 ? `${c.id}@${hostPort(c.base)}` : c.id);
|
|
238
|
+
const skipped = o.tried.length ? `\n skipped: ${o.tried.map((t) => `${nameOf(t.candidate)} (${t.status})`).join(", ")}` : "";
|
|
239
|
+
return `→ model: ${where}${cloudNote}${o.kind === "launched" ? " (launched)" : ""}${skipped}`;
|
|
240
|
+
}
|
|
@@ -39,6 +39,41 @@ async function launchctl(args, timeoutMs = 15_000) {
|
|
|
39
39
|
child.on?.("error", () => resolve({ code: 127, out: "launchctl not available" }));
|
|
40
40
|
});
|
|
41
41
|
}
|
|
42
|
+
/** Pull the model file a launchd plist serves: an explicit `-m`/`--model` argument, or any string that is a
|
|
43
|
+
* .gguf path (a ProgramArguments element, or inside a `bash -c` command, quoted or not). Undefined when the
|
|
44
|
+
* plist names no gguf (an MLX directory, a wrapper script) — an unknown model is never grounds to refuse a
|
|
45
|
+
* launch, only a KNOWN-missing one is. PURE. */
|
|
46
|
+
export function parseModelPathFromPlist(xml) {
|
|
47
|
+
const unesc = (v) => v.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, "&");
|
|
48
|
+
const strings = [...xml.matchAll(/<string>([\s\S]*?)<\/string>/g)].map((m) => unesc(m[1]).trim());
|
|
49
|
+
for (let i = 0; i < strings.length - 1; i++) {
|
|
50
|
+
if ((strings[i] === "-m" || strings[i] === "--model") && /\.gguf$/i.test(strings[i + 1]))
|
|
51
|
+
return strings[i + 1];
|
|
52
|
+
}
|
|
53
|
+
for (const v of strings) {
|
|
54
|
+
if (/^(\/|~\/).*\.gguf$/i.test(v))
|
|
55
|
+
return v;
|
|
56
|
+
const m = /(?:^|\s)(?:-m|--model)\s+(?:"([^"]+\.gguf)"|'([^']+\.gguf)'|(\S+\.gguf))/i.exec(v);
|
|
57
|
+
if (m)
|
|
58
|
+
return m[1] ?? m[2] ?? m[3];
|
|
59
|
+
}
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
/** The model file a launchd service needs, if knowable: explicit config first, else read from its plist. */
|
|
63
|
+
async function resolveModelPath(cfg) {
|
|
64
|
+
if (cfg.modelPath)
|
|
65
|
+
return expandHome(cfg.modelPath);
|
|
66
|
+
if (!cfg.plistPath)
|
|
67
|
+
return undefined;
|
|
68
|
+
try {
|
|
69
|
+
const { readFile } = await nodeImport("node:fs/promises");
|
|
70
|
+
const found = parseModelPathFromPlist(await readFile(expandHome(cfg.plistPath), "utf8"));
|
|
71
|
+
return found ? expandHome(found) : undefined;
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
return undefined;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
42
77
|
/** Probe a health URL. `ready` = 2xx. `loading` = the port answered but not 2xx (llama.cpp serves 503
|
|
43
78
|
* while it mmaps the model — the service is coming up on its own and must NOT be restarted). `refused`
|
|
44
79
|
* = nothing is listening. When okOnly is false any answer counts as `ready` (autopilot has no /health). */
|
|
@@ -99,6 +134,13 @@ async function ensureLaunchd(name, healthUrl, okOnly, cfg, onProgress) {
|
|
|
99
134
|
}
|
|
100
135
|
return { name, state: "skipped", detail: `not installed (${expandHome(cfg.plistPath)} missing) — run: operator setup-services` };
|
|
101
136
|
}
|
|
137
|
+
// A job whose model file is GONE can never come up — kickstarting it just crash-loops while we poll a dead
|
|
138
|
+
// port for waitSec (the 2026-10-10 Aurora incident: gguf vanished, boot hard-waited 90s, then quit). Refuse
|
|
139
|
+
// INSTANTLY with the real reason. Unknown model path = proceed; only a known-missing file blocks.
|
|
140
|
+
const modelPath = await resolveModelPath(cfg);
|
|
141
|
+
if (modelPath && !(await fileExists(modelPath))) {
|
|
142
|
+
return { name, state: "down", detail: `model file missing: ${modelPath} — not launching ${label}` };
|
|
143
|
+
}
|
|
102
144
|
onProgress?.(`starting ${name} via launchd…`);
|
|
103
145
|
const target = `gui/${uid}/${label}`;
|
|
104
146
|
// 1) fast path: the job is loaded but its port died — kick it.
|
|
@@ -120,11 +162,13 @@ async function ensureLaunchd(name, healthUrl, okOnly, cfg, onProgress) {
|
|
|
120
162
|
? { name, state: "started" }
|
|
121
163
|
: { name, state: "down", detail: `started the launchd job but ${name} did not report ready at ${healthUrl} within ${waitSec}s` };
|
|
122
164
|
}
|
|
123
|
-
/** Ensure the services Operator depends on are up.
|
|
165
|
+
/** Ensure the services Operator depends on are up. The model service (health-gated) when `aurora` is given —
|
|
166
|
+
* the boot passes it ONLY as the last resort after model auto-detect found nothing healthy; autopilot is
|
|
124
167
|
* optional and never blocks. Returns one report per service for the boot UI. */
|
|
125
168
|
export async function ensureServices(cfg) {
|
|
126
169
|
const reports = [];
|
|
127
|
-
|
|
170
|
+
if (cfg.aurora)
|
|
171
|
+
reports.push(await ensureLaunchd("aurora", `${cfg.aurora.base.replace(/\/$/, "")}/health`, true, cfg.aurora, cfg.onProgress));
|
|
128
172
|
if (cfg.autopilot) {
|
|
129
173
|
const url = (cfg.autopilot.url ?? "http://127.0.0.1:9333").replace(/\/$/, "");
|
|
130
174
|
// Optional service: cap the readiness wait hard so a present-but-unhealthy autopilot can never hold
|
package/dist/session.js
CHANGED
|
@@ -272,9 +272,9 @@ export class Session {
|
|
|
272
272
|
// Per-session tool registry: the base set, plus `spawn_agent` when the shell provides a delegate
|
|
273
273
|
// handler (foreground only). Both the executor (dispatch) and localSchemas (what the model sees)
|
|
274
274
|
// are built from the same map, so the tool is advertised iff it's runnable.
|
|
275
|
-
let reg = registry;
|
|
275
|
+
let reg = cfg.toolRegistry ?? registry; // visibleRegistry(settings.powerTools) from the surface; full native set otherwise
|
|
276
276
|
if (cfg.spawnAgent || cfg.askUser || cfg.messageAgent || cfg.agentStatus || cfg.stopAgent) {
|
|
277
|
-
reg = new Map(
|
|
277
|
+
reg = new Map(reg);
|
|
278
278
|
if (cfg.spawnAgent)
|
|
279
279
|
reg.set("spawn_agent", makeSpawnTool(cfg.spawnAgent));
|
|
280
280
|
if (cfg.messageAgent)
|
|
@@ -568,6 +568,16 @@ export class Session {
|
|
|
568
568
|
this.modelId = profile.id;
|
|
569
569
|
return { ok: true };
|
|
570
570
|
}
|
|
571
|
+
/** Re-point THIS session at an explicit endpoint chain without changing the active /model id. The boot auto-detect
|
|
572
|
+
* (services/model-autodetect.ts) uses it when the configured endpoint is down and a same-model standby — the
|
|
573
|
+
* failover or another fleet node — is the one that is alive. Same router rebuild as setModel; session-only, never
|
|
574
|
+
* persisted, so the owner's preferred model is still the one named next launch. */
|
|
575
|
+
adoptEndpoints(eps) {
|
|
576
|
+
if (!eps.length)
|
|
577
|
+
return;
|
|
578
|
+
this.inner = new AuroraRouter(eps);
|
|
579
|
+
this.router = engineRouter(this.inner);
|
|
580
|
+
}
|
|
571
581
|
/** The full conversation, for persistence (auto-save / --resume). */
|
|
572
582
|
snapshot() {
|
|
573
583
|
return this.convo.all.map((m) => ({ ...m }));
|
|
@@ -900,6 +910,13 @@ export class Session {
|
|
|
900
910
|
catch (e) {
|
|
901
911
|
if (e instanceof TurnAbortedError) {
|
|
902
912
|
this.telemetry.record({ type: "turn", rounds: 0, toolCalls: 0, interrupted: true, durationMs: Math.round(performance.now() - _t0), ctxPct: this.ctxPct() });
|
|
913
|
+
// A user esc throws with no reason → the host shows its own "interrupted" note. An ENGINE stop (loop
|
|
914
|
+
// guard) throws WITH a message — surface it as the turn's content so a mission-critical user is never
|
|
915
|
+
// left with a bare "interrupted": they see WHY it stopped and that nothing was lost. interrupted:false
|
|
916
|
+
// so the host finalizes it as a normal assistant message, not the esc banner.
|
|
917
|
+
const engineStop = typeof e.message === "string" && e.message.length > 0 && e.message !== "turn aborted";
|
|
918
|
+
if (engineStop)
|
|
919
|
+
return { content: `[${e.message}]`, rounds: 0, toolCalls: 0, interrupted: false, stopReason: "repetition" };
|
|
903
920
|
return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
|
|
904
921
|
}
|
|
905
922
|
this.telemetry.record({ type: "error", where: "send", errorClass: Telemetry.errorClass(e) });
|
package/dist/tools/deferred.js
CHANGED
|
@@ -84,7 +84,7 @@ export function withDeferred(base, st) {
|
|
|
84
84
|
return runMeta(name, args);
|
|
85
85
|
return base.execute(name, args);
|
|
86
86
|
},
|
|
87
|
-
async executeParallel(calls, onSettle) {
|
|
87
|
+
async executeParallel(calls, onSettle, signal) {
|
|
88
88
|
// BTX finding B/C follow-through: meta trio and base calls share ONE scheduled batch —
|
|
89
89
|
// tool_call used to runMeta-inline (racing the base batch it dispatches INTO), and the meta
|
|
90
90
|
// Promise.all barrier made base calls wait for every meta first. Now: search/describe classify
|
|
@@ -98,6 +98,7 @@ export function withDeferred(base, st) {
|
|
|
98
98
|
runOne: (c) => (DEFERRED_META_NAMES.includes(c.name)
|
|
99
99
|
? runMeta(c.name, c.args) : base.execute(c.name, c.args)),
|
|
100
100
|
onSettle,
|
|
101
|
+
signal,
|
|
101
102
|
});
|
|
102
103
|
},
|
|
103
104
|
sched: {
|
package/dist/tools/executor.js
CHANGED
|
@@ -9,8 +9,9 @@
|
|
|
9
9
|
// new user turn (not required by SPEC §3's
|
|
10
10
|
// round loop itself, but needed so the guard
|
|
11
11
|
// doesn't bleed across turns)
|
|
12
|
-
import { isAbsolute, join } from "node:path";
|
|
12
|
+
import { isAbsolute, join, resolve } from "node:path";
|
|
13
13
|
import { registry } from "./registry.js";
|
|
14
|
+
import { expandPath } from "./paths.js";
|
|
14
15
|
import { shellKeyStore } from "./shell-context.js";
|
|
15
16
|
// Re-exported for back-compat (existing importers reach it via executor.js) — moved to its own
|
|
16
17
|
// file since it's a pure helper with no node deps; see result-cap.ts for why that separation matters.
|
|
@@ -25,6 +26,12 @@ const PATH_ARGS = ["path", "file", "filename", "workspace"];
|
|
|
25
26
|
// Tools that take an optional `workspace` and otherwise fall back to process.cwd() — a rooted session must
|
|
26
27
|
// default it to its own root or the call lands in whatever directory the host process happens to run in.
|
|
27
28
|
const WORKSPACE_TOOLS = new Set(["checkpoint"]);
|
|
29
|
+
// BTX conflict keys must be the ABSOLUTE path a call will really touch, or "d.txt", "./d.txt", "/cwd/d.txt" and
|
|
30
|
+
// "~/d.txt" each look like a different resource and a batched write+read of one file races. Only path-named args
|
|
31
|
+
// are resolved (array elements and nested objects included, by the arg name they sit under); a url, or an id
|
|
32
|
+
// under target/handle/token, is left as-is.
|
|
33
|
+
const KEY_PATH_ARG = /path|dir|file|cwd|^(out|output|dest|destination)$/i;
|
|
34
|
+
const URL_LIKE = /^[a-z][a-z0-9+.-]*:\/\//i;
|
|
28
35
|
/** Reroot a tool call's args under `root` so a session's file/shell tools all act inside its own directory
|
|
29
36
|
* (e.g. a background agent's git worktree) instead of the shared process cwd. Pure: relative path args are
|
|
30
37
|
* joined under root; command tools default their cwd to root; absolute and ~ paths are left untouched
|
|
@@ -101,9 +108,13 @@ export class Executor {
|
|
|
101
108
|
}
|
|
102
109
|
sched = {
|
|
103
110
|
classify: defaultClassify("", (n) => this.reg.get(n)?.safe === true),
|
|
104
|
-
keys: defaultKeys,
|
|
111
|
+
keys: (n, a) => defaultKeys(n, a, (p, arg) => this.resolveKey(p, arg)),
|
|
105
112
|
};
|
|
106
|
-
|
|
113
|
+
/** Same resolution the tools apply (root join, ~ expansion), done lexically so a not-yet-written file still keys. */
|
|
114
|
+
resolveKey(p, argName) {
|
|
115
|
+
return KEY_PATH_ARG.test(argName) && !URL_LIKE.test(p) ? resolve(this.root ?? process.cwd(), expandPath(p)) : p;
|
|
116
|
+
}
|
|
117
|
+
async executeParallel(calls, onSettle, signal) {
|
|
107
118
|
// BTX: one shared DAG scheduler (engine/batch-scheduler.ts) — per-resource write chains,
|
|
108
119
|
// reads wait only for conflicting prior writes, device tools barrier-serialize. This replaces
|
|
109
120
|
// the 0.1.225 contiguous walk: same guarantees, strictly more overlap.
|
|
@@ -112,6 +123,7 @@ export class Executor {
|
|
|
112
123
|
keys: (n, a) => this.sched.keys(n, a),
|
|
113
124
|
runOne: (c) => this.execute(c.name, c.args),
|
|
114
125
|
onSettle,
|
|
126
|
+
signal,
|
|
115
127
|
});
|
|
116
128
|
}
|
|
117
129
|
}
|