@0perator/operator 0.1.277 → 0.1.282
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/acp/agent.js +8 -3
- package/dist/auth/commands.js +1 -0
- package/dist/autonomy/delegate.js +6 -11
- package/dist/autonomy/keepawake.js +2 -0
- package/dist/browser/cdp.js +5 -0
- package/dist/cli.js +103 -20
- package/dist/config/persona.js +24 -5
- package/dist/config/scaffold.js +1 -1
- package/dist/engine/agent.js +12 -0
- package/dist/engine/aurora.js +6 -0
- package/dist/engine/grandmaster.js +29 -4
- package/dist/mcp/stdio.js +2 -0
- package/dist/permissions/audit.js +29 -0
- package/dist/permissions/index.js +25 -13
- package/dist/remote/host.js +106 -5
- package/dist/services/preflight.js +1 -0
- package/dist/session-teardown.js +11 -0
- package/dist/session.js +42 -2
- package/dist/telemetry/events.js +22 -2
- package/dist/telemetry/ingest.js +574 -0
- package/dist/telemetry/lifecycle.js +35 -0
- package/dist/telemetry/sha256.js +75 -0
- package/dist/tools/document.js +203 -0
- package/dist/tools/registry.js +30 -2
- package/dist/tools/sandbox.js +3 -1
- package/dist/tools/shell-session.js +2 -0
- package/dist/ui/App.js +2 -2
- package/dist/util/owned-children.js +265 -0
- package/dist/util/screenshots.js +47 -0
- package/dist/util/teardown.js +64 -0
- package/package.json +4 -1
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// a "who did what" review needs while never leaking secrets or bloating the line. Pure + node-free, so it
|
|
4
4
|
// is safe to import from any bundle (the CLI and the JSCore/browser engine alike).
|
|
5
5
|
import { redactSecrets } from "../engine/redact.js";
|
|
6
|
+
import { sha256Hex } from "../telemetry/sha256.js";
|
|
6
7
|
/** Summarize args for the log without leaking secrets or bloating the line. Keeps the shape a reviewer
|
|
7
8
|
* needs (which path, which command head) and drops values that could be sensitive. */
|
|
8
9
|
export function digestArgs(_name, args) {
|
|
@@ -20,3 +21,31 @@ export function digestArgs(_name, args) {
|
|
|
20
21
|
const keys = Object.keys(args);
|
|
21
22
|
return keys.length ? `{${keys.join(",")}}` : "";
|
|
22
23
|
}
|
|
24
|
+
// Canonical JSON: object keys sorted at every depth, arrays in order — the same args always serialize to the same
|
|
25
|
+
// bytes, so the hash below is stable across key order and engine versions.
|
|
26
|
+
function canonical(v) {
|
|
27
|
+
if (Array.isArray(v))
|
|
28
|
+
return v.map(canonical);
|
|
29
|
+
if (v && typeof v === "object") {
|
|
30
|
+
const o = v;
|
|
31
|
+
return Object.fromEntries(Object.keys(o).sort().map((k) => [k, canonical(o[k])]));
|
|
32
|
+
}
|
|
33
|
+
return v;
|
|
34
|
+
}
|
|
35
|
+
/** sha256 of the canonical-JSON args: the central ledger's identity for "this exact call". Unlike digestArgs (a
|
|
36
|
+
* redacted, truncated human summary) this is a real digest of the RAW args, so identical calls match and the args
|
|
37
|
+
* themselves never leave the machine. Falls back to hashing `digest` for args JSON cannot serialize (a cycle). */
|
|
38
|
+
export function argHashOf(args, digest) {
|
|
39
|
+
try {
|
|
40
|
+
return sha256Hex(JSON.stringify(canonical(args)) ?? "");
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return sha256Hex(digest);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/** The MCP connector namespace of a tool name: `compose` for `compose:compose_list` (mcp/index.ts namespaces remote
|
|
47
|
+
* tools `<server>:<tool>`, the same split the batch scheduler keys on), undefined for a local tool. */
|
|
48
|
+
export function connectorOf(name) {
|
|
49
|
+
const i = name.indexOf(":");
|
|
50
|
+
return i > 0 ? name.slice(0, i) : undefined;
|
|
51
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { digestArgs } from "./audit.js";
|
|
1
|
+
import { digestArgs, argHashOf, connectorOf } from "./audit.js";
|
|
2
2
|
import { EventSink } from "../telemetry/events.js";
|
|
3
|
+
import { centralRecording } from "../telemetry/ingest.js";
|
|
3
4
|
import { runBatch, defaultClassify, defaultKeys, cancelledResult } from "../engine/batch-scheduler.js";
|
|
4
5
|
import { registrySafeTools } from "./tier.js";
|
|
5
6
|
export { PermissionPolicy } from "./policy.js";
|
|
@@ -8,27 +9,35 @@ const DENIED = (name) => `Permission denied: "${name}" was refused by the operat
|
|
|
8
9
|
const TIER_DENIED = (name, tier) => `Permission denied: "${name}" is not available on the "${tier}" tier. ` +
|
|
9
10
|
`This seat has a narrowed toolset; a full-access (admin) seat is required for this tool.`;
|
|
10
11
|
export function withPermissions(inner, policy, opts = {}) {
|
|
11
|
-
if (policy.inert)
|
|
12
|
-
return inner; // bypass + admin tier + no rules → nothing to enforce or log; skip entirely
|
|
13
|
-
|
|
12
|
+
if (policy.inert && !centralRecording())
|
|
13
|
+
return inner; // bypass + admin tier + no rules, signed out → nothing to enforce or log; skip entirely
|
|
14
|
+
// Recording is decided per call, not at wrap time: `policy.audits` is config (fixed), but sign-in/out can change while
|
|
15
|
+
// a session is live, and the sink is only built once something is actually recorded.
|
|
16
|
+
const recording = () => policy.audits || centralRecording();
|
|
17
|
+
let lazySink = opts.sink;
|
|
18
|
+
const sinkNow = () => (recording() ? (lazySink ??= new EventSink()) : undefined);
|
|
14
19
|
const actor = opts.actor ?? { tier: policy.currentTier(), surface: "cli" };
|
|
15
20
|
const session = opts.session ?? "";
|
|
16
|
-
const tool = (t) =>
|
|
21
|
+
const tool = (t, argHash) => {
|
|
22
|
+
const connectorId = connectorOf(t.name);
|
|
23
|
+
sinkNow()?.emit({ kind: "tool", session, actor, tool: { ...t, ...(argHash ? { argHash } : {}), ...(connectorId ? { connectorId } : {}) } });
|
|
24
|
+
};
|
|
17
25
|
// `batch` carries the round identity a PendingToolCall was stamped with (engine/agent.ts's
|
|
18
26
|
// runToolCalls) onto every ToolEvent this call emits — absent for the single-call execute() path,
|
|
19
27
|
// which has no round context.
|
|
20
28
|
async function gate(name, args, exec, batch, signal) {
|
|
21
29
|
const digest = digestArgs(name, args);
|
|
30
|
+
const argHash = recording() ? argHashOf(args, digest) : undefined; // hashed BEFORE the tool runs: the args as issued
|
|
22
31
|
const decision = policy.decide(name, args);
|
|
23
32
|
const t0 = performance.now();
|
|
24
33
|
if (decision === "deny") {
|
|
25
34
|
// Distinguish a tier-ceiling denial (this seat can't have the tool at all) from a rule/mode denial.
|
|
26
35
|
if (!policy.allowsTool(name)) {
|
|
27
|
-
|
|
28
|
-
tool({ name, args: digest, decision, outcome: "denied", approved: false, ...batch });
|
|
36
|
+
sinkNow()?.emit({ kind: "control", session, actor, control: { event: "tool_denied_by_tier", detail: `${name} @ ${actor.tier}` } });
|
|
37
|
+
tool({ name, args: digest, decision, outcome: "denied", approved: false, ...batch }, argHash);
|
|
29
38
|
return TIER_DENIED(name, actor.tier);
|
|
30
39
|
}
|
|
31
|
-
tool({ name, args: digest, decision, outcome: "denied", approved: false, ...batch });
|
|
40
|
+
tool({ name, args: digest, decision, outcome: "denied", approved: false, ...batch }, argHash);
|
|
32
41
|
return DENIED(name);
|
|
33
42
|
}
|
|
34
43
|
let approved;
|
|
@@ -37,17 +46,17 @@ export function withPermissions(inner, policy, opts = {}) {
|
|
|
37
46
|
// mobile flags WHY a human was pulled in — and a background sub-agent (no approver) is denied below.
|
|
38
47
|
const line = policy.signatureLineFor(name, args);
|
|
39
48
|
if (line)
|
|
40
|
-
|
|
49
|
+
sinkNow()?.emit({ kind: "control", session, actor, control: { event: "signature_required", detail: `${line}: ${name}` } });
|
|
41
50
|
approved = opts.approve ? await opts.approve(name, args) : false; // no approver ⇒ fail-safe deny
|
|
42
51
|
if (!approved) {
|
|
43
|
-
tool({ name, args: digest, decision, outcome: "denied", approved: false, ...batch });
|
|
52
|
+
tool({ name, args: digest, decision, outcome: "denied", approved: false, ...batch }, argHash);
|
|
44
53
|
return DENIED(name);
|
|
45
54
|
}
|
|
46
55
|
}
|
|
47
56
|
// An esc during the (human) approval wait: the approval may land AFTER the interrupt, and an approved edit
|
|
48
57
|
// must not then execute. Recorded as an error (the wire outcome enum is frozen; nothing was refused by policy).
|
|
49
58
|
if (signal?.aborted) {
|
|
50
|
-
tool({ name, args: digest, decision, outcome: "error", approved, durationMs: performance.now() - t0, ...batch });
|
|
59
|
+
tool({ name, args: digest, decision, outcome: "error", approved, durationMs: performance.now() - t0, ...batch }, argHash);
|
|
51
60
|
return cancelledResult(name);
|
|
52
61
|
}
|
|
53
62
|
let result;
|
|
@@ -56,14 +65,17 @@ export function withPermissions(inner, policy, opts = {}) {
|
|
|
56
65
|
}
|
|
57
66
|
catch (e) {
|
|
58
67
|
// The inner executor's contract is resolve-not-reject; if one ever throws, record + surface as a string.
|
|
59
|
-
tool({ name, args: digest, decision, outcome: "error", approved, durationMs: performance.now() - t0, ...batch });
|
|
68
|
+
tool({ name, args: digest, decision, outcome: "error", approved, durationMs: performance.now() - t0, ...batch }, argHash);
|
|
60
69
|
return `error: ${e instanceof Error ? e.message : String(e)}`;
|
|
61
70
|
}
|
|
62
71
|
const outcome = /^error/i.test(result.trim()) ? "error" : "ok";
|
|
63
|
-
tool({ name, args: digest, decision, outcome, approved, durationMs: performance.now() - t0, ...batch });
|
|
72
|
+
tool({ name, args: digest, decision, outcome, approved, durationMs: performance.now() - t0, ...batch }, argHash);
|
|
64
73
|
return result;
|
|
65
74
|
}
|
|
66
75
|
return {
|
|
76
|
+
// The inner toolset's batch-classification truth, forwarded: withDeferred (and any outer wrapper) reads `.sched`
|
|
77
|
+
// to decide which calls may overlap. Dropping it silently serialized every call of a wrapped session.
|
|
78
|
+
sched: inner.sched,
|
|
67
79
|
execute: (name, args) => gate(name, args, () => inner.execute(name, args)),
|
|
68
80
|
// BTX: batch ordering is SCHEDULED, not Promise.raced. Each slot's run is the FULL gate chain
|
|
69
81
|
// (decision + approval + inner.execute), so per-call modal latency pipelines exactly as before —
|
package/dist/remote/host.js
CHANGED
|
@@ -1,11 +1,18 @@
|
|
|
1
1
|
import { frameKey as deriveFrameKey, pairingId as derivePairingId, encryptFrame, decryptFrame } from "./pairing.js";
|
|
2
2
|
const V = 1;
|
|
3
|
+
// RC v2 (engine contract 1.7.0, wire v:1). The host advertises these on hello so the relay/followers can
|
|
4
|
+
// version-gate; everything is additive, so an old relay simply ignores the extra fields.
|
|
5
|
+
const ENGINE_CONTRACT = "1.7.0";
|
|
6
|
+
const HOST_FEATURES = ["keepalive.app", "resume.epoch", "drain.v1", "agents.ctl"];
|
|
7
|
+
const KEEPALIVE_MS = 20_000; // A1: app-level ping cadence (undici has no ws.ping API, so we send a frame)
|
|
8
|
+
const RECONNECT_BASE_MS = 1000; // A2: reconnect backoff base (capped, jittered)
|
|
9
|
+
const RECONNECT_MAX_MS = 15_000;
|
|
3
10
|
// Paired (QR) mode: only DATA-frame payloads are e2e-encrypted; the header (v/type/sessionId/seq/ts) and
|
|
4
11
|
// control frames stay plaintext so the relay can route blind. These sets mirror the mobile's frozen
|
|
5
12
|
// dataFrameTypes byte-for-byte (kode-mobile RemoteSession.swift). The INNER encrypted bytes are
|
|
6
13
|
// JSON.stringify(payloadDict) — just the payload dict, never {type,payload}.
|
|
7
14
|
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"]);
|
|
15
|
+
const DATA_DRIVE_TYPES = new Set(["prompt", "command", "approval_response", "ask_user_response", "interrupt", "agent_stop", "agent_steer"]);
|
|
9
16
|
// A paired snapshot is encrypted (base64 ≈ 1.37× plaintext), and the relay drops/truncates any frame over
|
|
10
17
|
// its 256 KB cap — which would corrupt ciphertext. Cap the paired snapshot's plaintext so the encrypted
|
|
11
18
|
// frame stays comfortably under 256 KB; token-mode keeps the full 512 KB budget.
|
|
@@ -62,6 +69,14 @@ export class RemoteHost {
|
|
|
62
69
|
paired = false;
|
|
63
70
|
frameKey = null;
|
|
64
71
|
pairingId = null;
|
|
72
|
+
// RC v2 A1/A2: zero-disconnect resilience. epoch is the session incarnation from `welcome`; the keepalive
|
|
73
|
+
// sends an app-level `ping` (undici has no ws.ping); the reconnect loop re-dials the SAME sessionId on an
|
|
74
|
+
// unexpected drop and the host proactively re-snapshots so a resuming follower's gap is filled.
|
|
75
|
+
epoch = null;
|
|
76
|
+
everWelcomed = false; // ≥1 welcome on this sessionId → a later welcome is a RESUME (re-snapshot)
|
|
77
|
+
keepaliveTimer = null;
|
|
78
|
+
reconnectTimer = null;
|
|
79
|
+
reconnectAttempts = 0;
|
|
65
80
|
constructor(url, token, meta, cb, pairing) {
|
|
66
81
|
this.url = url;
|
|
67
82
|
this.token = token;
|
|
@@ -74,7 +89,11 @@ export class RemoteHost {
|
|
|
74
89
|
this.pairingId = derivePairingId(pairing.code);
|
|
75
90
|
}
|
|
76
91
|
}
|
|
77
|
-
connect() {
|
|
92
|
+
connect() { this.closedByUs = false; this.openSocket(); }
|
|
93
|
+
// RC v2 A2: one socket attempt, reusing this.sessionId so the relay resumes the SAME session (dormant
|
|
94
|
+
// re-attach). An unexpected close re-dials with backoff instead of dying — the host never gives up a
|
|
95
|
+
// session on a blip (the battlefield no-disconnect requirement). A deliberate stop() short-circuits it.
|
|
96
|
+
openSocket() {
|
|
78
97
|
this.cb.onState?.("connecting");
|
|
79
98
|
let ws;
|
|
80
99
|
try {
|
|
@@ -82,16 +101,49 @@ export class RemoteHost {
|
|
|
82
101
|
}
|
|
83
102
|
catch (e) {
|
|
84
103
|
this.cb.onState?.("error", String(e));
|
|
104
|
+
this.scheduleReconnect();
|
|
85
105
|
return;
|
|
86
106
|
}
|
|
87
107
|
this.ws = ws;
|
|
88
108
|
ws.addEventListener("open", () => {
|
|
89
|
-
|
|
109
|
+
// §1: advertise the engine contract + features so the relay/followers can version-gate. sessionId (when
|
|
110
|
+
// set) makes this a RESUME. Additive — an old relay ignores proto/features.
|
|
111
|
+
this.send("hello", null, { token: this.token, role: "host", sessionId: this.sessionId ?? undefined, proto: ENGINE_CONTRACT, features: HOST_FEATURES });
|
|
90
112
|
});
|
|
91
113
|
ws.addEventListener("message", (ev) => this.onMessage(String(ev.data)));
|
|
92
|
-
ws.addEventListener("close", () => {
|
|
93
|
-
|
|
114
|
+
ws.addEventListener("close", () => {
|
|
115
|
+
this.stopKeepalive();
|
|
116
|
+
if (this.closedByUs) {
|
|
117
|
+
this.cb.onState?.("closed");
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
this.cb.onState?.("connecting", "reconnecting"); // NOT a hard error — we re-dial the same session
|
|
121
|
+
this.scheduleReconnect();
|
|
122
|
+
});
|
|
123
|
+
ws.addEventListener("error", () => { });
|
|
94
124
|
}
|
|
125
|
+
/** Re-dial the same sessionId after an exponential-backoff (jittered, capped) delay. No-op once the owner
|
|
126
|
+
* has stopped, or when a reconnect is already scheduled. */
|
|
127
|
+
scheduleReconnect(afterMs) {
|
|
128
|
+
if (this.closedByUs || this.reconnectTimer)
|
|
129
|
+
return;
|
|
130
|
+
const n = this.reconnectAttempts++;
|
|
131
|
+
const delay = afterMs ?? Math.min(RECONNECT_MAX_MS, RECONNECT_BASE_MS * 2 ** Math.min(n, 4)) + Math.floor(Math.random() * 500);
|
|
132
|
+
this.reconnectTimer = setTimeout(() => { this.reconnectTimer = null; if (!this.closedByUs)
|
|
133
|
+
this.openSocket(); }, delay);
|
|
134
|
+
}
|
|
135
|
+
startKeepalive() {
|
|
136
|
+
this.stopKeepalive();
|
|
137
|
+
this.keepaliveTimer = setInterval(() => {
|
|
138
|
+
if (this.ws && this.ws.readyState === 1)
|
|
139
|
+
this.send("ping", this.sessionId, { nonce: Date.now().toString(36) });
|
|
140
|
+
}, KEEPALIVE_MS);
|
|
141
|
+
this.keepaliveTimer.unref?.();
|
|
142
|
+
}
|
|
143
|
+
stopKeepalive() { if (this.keepaliveTimer) {
|
|
144
|
+
clearInterval(this.keepaliveTimer);
|
|
145
|
+
this.keepaliveTimer = null;
|
|
146
|
+
} }
|
|
95
147
|
get id() { return this.sessionId; }
|
|
96
148
|
get connected() { return !!this.ws && this.ws.readyState === 1; }
|
|
97
149
|
stop() {
|
|
@@ -100,6 +152,11 @@ export class RemoteHost {
|
|
|
100
152
|
clearTimeout(this.liveTimer);
|
|
101
153
|
this.liveTimer = null;
|
|
102
154
|
}
|
|
155
|
+
if (this.reconnectTimer) {
|
|
156
|
+
clearTimeout(this.reconnectTimer);
|
|
157
|
+
this.reconnectTimer = null;
|
|
158
|
+
} // RC v2 A2: cancel any pending re-dial
|
|
159
|
+
this.stopKeepalive();
|
|
103
160
|
try {
|
|
104
161
|
this.ws?.close();
|
|
105
162
|
}
|
|
@@ -131,11 +188,47 @@ export class RemoteHost {
|
|
|
131
188
|
case "welcome":
|
|
132
189
|
this.sessionId = f.payload?.sessionId ?? this.sessionId;
|
|
133
190
|
this.ownerSub = f.payload?.ownerSub ?? null;
|
|
191
|
+
if (typeof f.payload?.epoch === "number")
|
|
192
|
+
this.epoch = f.payload.epoch; // RC v2 A2
|
|
193
|
+
this.reconnectAttempts = 0; // a successful welcome resets the backoff ladder
|
|
134
194
|
this.send("register", this.sessionId, { title: this.meta.title, surface: this.meta.surface ?? "cli", cwd: this.meta.cwd, host: this.meta.host });
|
|
135
195
|
if (this.paired && this.pairingId)
|
|
136
196
|
this.send("pair-register", this.sessionId, { pairingId: this.pairingId }); // control frame (plaintext) — binds pairingId -> this session at the relay
|
|
197
|
+
// RC v2 A2: a welcome AFTER the first is a RESUME. While the socket was down, state frames were dropped
|
|
198
|
+
// but seq advanced, so the relay's buffer has a gap a follower's lastSeq can't bridge — re-snapshot now.
|
|
199
|
+
if (this.everWelcomed || f.payload?.resumed)
|
|
200
|
+
this.sendSnapshot();
|
|
201
|
+
this.everWelcomed = true;
|
|
202
|
+
this.startKeepalive(); // RC v2 A1 app-level heartbeat
|
|
137
203
|
this.cb.onState?.("live");
|
|
138
204
|
break;
|
|
205
|
+
// RC v2 A1 control: echo a relay/follower ping; a pong is pure liveness.
|
|
206
|
+
case "ping":
|
|
207
|
+
this.send("pong", f.sessionId ?? this.sessionId, { nonce: f.payload?.nonce });
|
|
208
|
+
break;
|
|
209
|
+
case "pong": break;
|
|
210
|
+
// RC v2 A4: relay is draining for a planned restart — re-dial the SAME session after its backoff, as a
|
|
211
|
+
// quiet reconnect (NOT an error). Schedule first (wins the delay), then close so the socket is released.
|
|
212
|
+
case "reconnect": {
|
|
213
|
+
const after = (typeof f.payload?.afterMs === "number" ? f.payload.afterMs : 1500) + Math.floor(Math.random() * 500);
|
|
214
|
+
this.cb.onState?.("connecting", "reconnecting");
|
|
215
|
+
this.scheduleReconnect(after);
|
|
216
|
+
try {
|
|
217
|
+
this.ws?.close();
|
|
218
|
+
}
|
|
219
|
+
catch { /* ignore */ }
|
|
220
|
+
break;
|
|
221
|
+
}
|
|
222
|
+
// RC v2 B1: per-sub-agent Stop / Steer from a follower → the shell's BackgroundAgents; ack so the row
|
|
223
|
+
// can show "stopped/steered ✓" or "couldn't" (steer can fail silently without this).
|
|
224
|
+
case "agent_stop":
|
|
225
|
+
if (this.isOwnFrame(f) && f.payload?.id)
|
|
226
|
+
this.ackAgent(String(f.payload.id), "stop", this.cb.onAgentStop?.(String(f.payload.id)));
|
|
227
|
+
break;
|
|
228
|
+
case "agent_steer":
|
|
229
|
+
if (this.isOwnFrame(f) && f.payload?.id)
|
|
230
|
+
this.ackAgent(String(f.payload.id), "steer", this.cb.onAgentSteer?.(String(f.payload.id), String(f.payload?.text ?? "")));
|
|
231
|
+
break;
|
|
139
232
|
case "attach": // a follower joined — send a full snapshot BEFORE any further delta (§8)
|
|
140
233
|
this.sendSnapshot();
|
|
141
234
|
break;
|
|
@@ -200,11 +293,19 @@ export class RemoteHost {
|
|
|
200
293
|
catch { /* dropped; follower re-attaches on gap */ }
|
|
201
294
|
}
|
|
202
295
|
state(type, payload) { this.send(type, this.sessionId, payload, ++this.seq); }
|
|
296
|
+
/** RC v2 B1: emit the follower-facing ack for a per-agent control. `r` is the shell callback's result —
|
|
297
|
+
* a bare boolean, or {ok, detail}. agent_ack is a plaintext STATE frame (low-sensitivity {id,action,ok}). */
|
|
298
|
+
ackAgent(id, action, r) {
|
|
299
|
+
const ok = typeof r === "boolean" ? r : !!(r && r.ok);
|
|
300
|
+
const detail = r && typeof r === "object" ? r.detail : undefined;
|
|
301
|
+
this.state("agent_ack", { id, action, ok, ...(detail ? { detail } : {}) });
|
|
302
|
+
}
|
|
203
303
|
sendSnapshot() {
|
|
204
304
|
this.flushLive();
|
|
205
305
|
const { transcript, truncated, omittedBefore } = this.capTranscript(this.entries, this.paired ? SNAPSHOT_MAX_BYTES_PAIRED : SNAPSHOT_MAX_BYTES);
|
|
206
306
|
this.send("snapshot", this.sessionId, {
|
|
207
307
|
transcript, activity: this.activity, status: { ctxPct: this.ctxPct, route: this.route, ...(this.tokens != null ? { tokens: this.tokens } : {}) },
|
|
308
|
+
...(this.epoch != null ? { epoch: this.epoch } : {}), // RC v2 A2: the reliable place to stamp epoch (welcome fires pre-attach)
|
|
208
309
|
...(truncated ? { truncated: true, omittedBefore } : {}),
|
|
209
310
|
...(this.capabilities ? { capabilities: this.capabilities } : {}), // absent until the shell's first setCapabilities() call; already capped by capCapabilities() in setCapabilities()
|
|
210
311
|
}, this.seq);
|
|
@@ -143,6 +143,7 @@ async function installCompanion(name) {
|
|
|
143
143
|
const script = new URL("../../scripts/setup-services.sh", import.meta.url).pathname;
|
|
144
144
|
if (!(await fileExists(script)))
|
|
145
145
|
return;
|
|
146
|
+
// owned-exempt: installs a SHARED launchd service (opt-in KODE_AUTO_INSTALL_SERVICES) that must outlive this session
|
|
146
147
|
const child = spawn("bash", [script, name], { detached: true, stdio: "ignore" });
|
|
147
148
|
child.unref?.();
|
|
148
149
|
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { killOwnedChildren, killOwnedChildrenSync, removePidfile } from "./util/owned-children.js";
|
|
2
|
+
export const asEndReason = (r) => (r === "quit" || r === "error" ? r : "interrupted");
|
|
3
|
+
export function installProcessTeardown(t, d) {
|
|
4
|
+
t.add("session-end", (r) => d.recordEnd(asEndReason(r)), { order: 10 }); // first: record before anything is killed
|
|
5
|
+
t.add("shells", () => d.disposeShells(), { order: 80 });
|
|
6
|
+
t.add("browser", () => d.disposeBrowser(), { order: 81 });
|
|
7
|
+
// The sweep: whatever this process spawned and still owns (background jobs, MCP servers, Chrome, shells) — waited for, then SIGKILLed.
|
|
8
|
+
t.add("owned-children", () => killOwnedChildren().then(() => undefined), { sync: () => { killOwnedChildrenSync(); }, order: 90 });
|
|
9
|
+
t.add("telemetry-flush", () => d.flushTelemetry(), { sync: () => d.flushTelemetrySync(), order: 95 });
|
|
10
|
+
t.add("pidfile", () => removePidfile(), { order: 99 });
|
|
11
|
+
}
|
package/dist/session.js
CHANGED
|
@@ -46,6 +46,25 @@ export function thinkDirective(mode) {
|
|
|
46
46
|
`through the whole problem, surface assumptions, weigh alternatives and edge cases, and check your ` +
|
|
47
47
|
`own work — then give the answer. Depth over speed for this turn.`;
|
|
48
48
|
}
|
|
49
|
+
/** Render the per-turn BUDGET block that makes the model self-pace (pure, so it's unit-testable). Each line
|
|
50
|
+
* is omitted when its value is unset/zero; returns "" when nothing is known. See Session.budgetDirective. */
|
|
51
|
+
export function renderBudgetBlock(b) {
|
|
52
|
+
const k = (n) => `${Math.round(n / 1000)}k`;
|
|
53
|
+
const lines = [];
|
|
54
|
+
if (b.ctxWindow && b.ctxWindow > 0) {
|
|
55
|
+
const ceil = b.ceilingTokens && b.ceilingTokens > 0 ? ` — the engine auto-compacts near ~${k(b.ceilingTokens)}` : "";
|
|
56
|
+
lines.push(`- Context window: ~${k(b.ctxWindow)} tokens${ceil}.`);
|
|
57
|
+
}
|
|
58
|
+
if (b.wallClockMs && b.wallClockMs > 0) {
|
|
59
|
+
lines.push(`- This turn's time budget: ~${Math.round(b.wallClockMs / 1000)}s of wall-clock (a crawling turn is wrapped at the limit).`);
|
|
60
|
+
}
|
|
61
|
+
if (b.sessionTokens && b.sessionTokens > 0) {
|
|
62
|
+
lines.push(`- Session spent so far: ~${k(b.sessionTokens)} tokens.`);
|
|
63
|
+
}
|
|
64
|
+
if (!lines.length)
|
|
65
|
+
return "";
|
|
66
|
+
return `\n\n## BUDGET — pace yourself\nYou run under a bounded budget. The engine auto-compacts and wraps a crawling turn, but don't rely on it:\n${lines.join("\n")}\nKeep tool results LEAN (fetch fewer items, narrow queries, one thing at a time), converge toward the deliverable instead of exploring indefinitely, and if a turn is clearly dragging — long wall-clock, big context, round after round of the same tool — SUMMARIZE what you have and stop or hand back rather than spinning.`;
|
|
67
|
+
}
|
|
49
68
|
// The `spawn_agent` tool — a thin pass-through to the shell's delegate handler. The handler owns the
|
|
50
69
|
// policy (cap) and the reply text; the tool just guards against an empty task. safe:false so it's an
|
|
51
70
|
// action (gated when permissions are on), never run speculatively in the safe-parallel batch.
|
|
@@ -300,7 +319,7 @@ export class Session {
|
|
|
300
319
|
this.modelId = DEFAULT_MODEL_ID; // unavailable at startup → quiet fallback
|
|
301
320
|
}
|
|
302
321
|
this.systemPrompt = cfg.systemPrompt;
|
|
303
|
-
this.maxTokens = cfg.maxTokens ?? 2048
|
|
322
|
+
this.maxTokens = cfg.maxTokens ?? 32768; // == settings DEFAULTS.maxTokens (session-defaults.test.mts locks the pair); ACP/headless callers that omit cfg used to silently get a tight 2048 cap. clampMaxTokens still trims to the live window.
|
|
304
323
|
this.maxTurnTokens = cfg.maxTurnTokens;
|
|
305
324
|
this.maxTurnWallClockMs = cfg.maxTurnWallClockMs;
|
|
306
325
|
this.maxRounds = cfg.maxRounds;
|
|
@@ -357,9 +376,30 @@ export class Session {
|
|
|
357
376
|
* ultrathink adds the exhaustive push on top. */
|
|
358
377
|
sysWithThink() {
|
|
359
378
|
const base = this.sys();
|
|
360
|
-
const
|
|
379
|
+
const think = thinkDirective(this.thinkMode);
|
|
380
|
+
const budget = this.budgetDirective();
|
|
381
|
+
const push = `${think}${budget}`;
|
|
361
382
|
return push ? (base ?? "") + push : base;
|
|
362
383
|
}
|
|
384
|
+
/** Make the model BUDGET-AWARE: a per-turn block stating its context window, the auto-compaction ceiling,
|
|
385
|
+
* this turn's wall-clock budget, and session spend so far, plus a self-pacing policy. The engine already
|
|
386
|
+
* acts ON the model (auto-compaction, the wall-clock turn brake, tool-result truncation), but the model
|
|
387
|
+
* never SAW the numbers, so it couldn't pace itself — it would explore until the hard stop. Surfacing the
|
|
388
|
+
* budget here lets it converge on its own. Numbers are cheap to read (endpoint ctx limit + the configured
|
|
389
|
+
* ceilings + the running session total); any unset field is simply omitted. */
|
|
390
|
+
budgetDirective() {
|
|
391
|
+
let ctxWindow = 0;
|
|
392
|
+
try {
|
|
393
|
+
ctxWindow = this.inner.ctxLimit();
|
|
394
|
+
}
|
|
395
|
+
catch { /* endpoint not ready — skip the ctx line */ }
|
|
396
|
+
return renderBudgetBlock({
|
|
397
|
+
ctxWindow,
|
|
398
|
+
ceilingTokens: this.compactionCeilingTokens,
|
|
399
|
+
wallClockMs: this.maxTurnWallClockMs,
|
|
400
|
+
sessionTokens: this.sessionTokensTotal,
|
|
401
|
+
});
|
|
402
|
+
}
|
|
363
403
|
/** Compose the tool executor: local tools + MCP (composite) with the permission/audit layer on top.
|
|
364
404
|
* withPermissions returns the composite UNCHANGED when the policy is inert (bypass) — zero overhead.
|
|
365
405
|
* In plan mode a read-only gated policy (no approver → mutating tools fail-safe deny) overrides the
|
package/dist/telemetry/events.js
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
const nodeImport = (m) => import(/* @vite-ignore */ m);
|
|
12
12
|
// redact is pure regex + node-free — the static import keeps this module bundle-safe (GW-10 graph).
|
|
13
13
|
import { redactSecrets } from "../engine/redact.js";
|
|
14
|
+
import { defaultIngest } from "./ingest.js";
|
|
14
15
|
export const EVENT_V = 1;
|
|
15
16
|
/** The machine-wide audit file: an explicit KODE_EVENTS_FILE / KODE_AUDIT_FILE, else `$KODE_HOME/events.jsonl`,
|
|
16
17
|
* else `~/.axe/operator/events.jsonl` (unexpanded `~/`). Deliberately NOT profile-scoped: one audit trail per
|
|
@@ -19,6 +20,13 @@ export function defaultEventsFile() {
|
|
|
19
20
|
const e = process.env;
|
|
20
21
|
return e.KODE_EVENTS_FILE || e.KODE_AUDIT_FILE || (e.KODE_HOME ? e.KODE_HOME + "/events.jsonl" : "~/.axe/operator/events.jsonl");
|
|
21
22
|
}
|
|
23
|
+
/** uuid v4 — the native one where there is one, a Math.random fallback for a JSCore host without `crypto`. */
|
|
24
|
+
export function newEid() {
|
|
25
|
+
const c = globalThis.crypto;
|
|
26
|
+
if (c?.randomUUID)
|
|
27
|
+
return c.randomUUID();
|
|
28
|
+
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (ch) => { const r = (Math.random() * 16) | 0; return (ch === "x" ? r : (r & 0x3) | 0x8).toString(16); });
|
|
29
|
+
}
|
|
22
30
|
const DEFAULT_AUDIT_MAX_BYTES = 64 * 1024 * 1024;
|
|
23
31
|
const DEFAULT_AUDIT_KEEP = 20;
|
|
24
32
|
const envPosInt = (name, fallback) => {
|
|
@@ -33,11 +41,16 @@ const envPosInt = (name, fallback) => {
|
|
|
33
41
|
* line's own body). Editing, deleting or reordering a line breaks `operator audit verify`. It also rotates by
|
|
34
42
|
* size into `<dir>/audit/` so the log cannot grow without bound. Honest limit: the chain is unkeyed, so
|
|
35
43
|
* someone who can write the file AND recompute from the edit point can forge it — the append-only remote copy
|
|
36
|
-
* (KODE_TELEMETRY_URL / a SIEM forwarder) is the anchor, and the sandbox keeps the agent away from the file.
|
|
44
|
+
* (KODE_TELEMETRY_URL / a SIEM forwarder) is the anchor, and the sandbox keeps the agent away from the file.
|
|
45
|
+
*
|
|
46
|
+
* Independently of both, every event is offered to the central ingest (telemetry/ingest.ts): while an account is
|
|
47
|
+
* signed in it projects session/tool/turn events onto the ledger wire shape and delivers them batched, Bearer-authed,
|
|
48
|
+
* with a disk outbox. KODE_TELEMETRY_URL above is unchanged — it is the dashboard's raw-envelope feed. */
|
|
37
49
|
export class EventSink {
|
|
38
50
|
file;
|
|
39
51
|
url;
|
|
40
52
|
onEvent;
|
|
53
|
+
ingest;
|
|
41
54
|
subscribers = new Set();
|
|
42
55
|
lastWrite = Promise.resolve(); // chained so appends land in emit order (an audit log must be ordered)
|
|
43
56
|
cid = "";
|
|
@@ -46,6 +59,8 @@ export class EventSink {
|
|
|
46
59
|
sinceStat = Number.POSITIVE_INFINITY; // stat the file on the first write, then every `rotateEvery`
|
|
47
60
|
rotations = 0;
|
|
48
61
|
rotateEvery;
|
|
62
|
+
/** `ingest`: the central session-tracking poster events are also fed to (default: the process-wide one, a no-op while
|
|
63
|
+
* signed out); pass `null` for a sink that must stay local-only. */
|
|
49
64
|
constructor(opts = {}) {
|
|
50
65
|
this.file = opts.file ?? defaultEventsFile();
|
|
51
66
|
this.rotateEvery = opts.rotateEvery ?? 50;
|
|
@@ -54,12 +69,13 @@ export class EventSink {
|
|
|
54
69
|
// not a KODE_TELEMETRY_URL backend), same pattern as the bg-agents host bridge. A native/web host sets
|
|
55
70
|
// this to marshal each event into its own store and render the control-plane surface.
|
|
56
71
|
this.onEvent = opts.onEvent;
|
|
72
|
+
this.ingest = opts.ingest === undefined ? defaultIngest() : opts.ingest;
|
|
57
73
|
}
|
|
58
74
|
subscribe(fn) { this.subscribers.add(fn); }
|
|
59
75
|
unsubscribe(fn) { this.subscribers.delete(fn); }
|
|
60
76
|
/** Fill in envelope boilerplate and dispatch. Callers pass kind + the matching payload + actor. */
|
|
61
77
|
emit(e) {
|
|
62
|
-
const full = { v: EVENT_V, ts: new Date().toISOString(), ...e };
|
|
78
|
+
const full = { v: EVENT_V, ts: new Date().toISOString(), eid: newEid(), ...e };
|
|
63
79
|
// In-process listener first (synchronous, never throws out) so a host callback sees every event even
|
|
64
80
|
// where fs/HTTP are absent (mobile). Then fire-and-forget the file + HTTP sinks off the hot path.
|
|
65
81
|
try {
|
|
@@ -74,6 +90,10 @@ export class EventSink {
|
|
|
74
90
|
}
|
|
75
91
|
this.lastWrite = this.lastWrite.then(() => this.write(full)); // serialized: ordered append, awaitable via flushed()
|
|
76
92
|
void this.post(full);
|
|
93
|
+
try {
|
|
94
|
+
this.ingest?.push(full);
|
|
95
|
+
}
|
|
96
|
+
catch { /* the central poster must never break a turn */ }
|
|
77
97
|
}
|
|
78
98
|
/** Resolves once all queued file appends have landed. The app never awaits this (the sink is
|
|
79
99
|
* best-effort, off the hot path); it makes the JSONL deterministically testable without sleeping. */
|