@0perator/operator 0.2.0 → 0.2.1
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 +4 -3
- package/dist/auth/commands.js +7 -3
- package/dist/auth/identity.js +1 -0
- package/dist/auth/staff.js +55 -0
- package/dist/autonomy/delegate-mode.js +2 -2
- package/dist/autonomy/delegate.js +41 -14
- package/dist/autonomy/headless.js +7 -4
- package/dist/autonomy/index.js +2 -4
- package/dist/autonomy/session-factory.js +11 -12
- package/dist/autonomy/subagent-model.js +17 -7
- package/dist/background/capacity.js +136 -0
- package/dist/background/evidence.js +42 -0
- package/dist/background/index.js +311 -44
- package/dist/background/lane-phase.js +60 -0
- package/dist/background/lane-summary.js +151 -0
- package/dist/background/notices.js +12 -3
- package/dist/background/synthesis.js +25 -0
- package/dist/bus/inbox.js +150 -6
- package/dist/cli.js +191 -96
- package/dist/config/features.js +3 -3
- package/dist/config/persona.js +29 -3
- package/dist/config/settings.js +261 -20
- package/dist/config/staff-prompt.js +12 -0
- package/dist/engine/agent.js +51 -40
- package/dist/engine/aurora.js +36 -4
- package/dist/engine/batch-scheduler.js +4 -13
- package/dist/engine/compaction.js +1 -1
- package/dist/engine/continuation.js +30 -32
- package/dist/engine/decision-points.js +2 -3
- package/dist/engine/fanout.js +16 -0
- package/dist/engine/loop-guard.js +26 -83
- package/dist/engine/messages.js +2 -2
- package/dist/engine/moa.js +16 -1
- package/dist/engine/native-vision-node.js +72 -0
- package/dist/engine/native-vision.js +103 -0
- package/dist/engine/verify-gate.js +37 -7
- package/dist/gateway-cli.js +14 -3
- package/dist/memory/live-progress.js +4 -5
- package/dist/moa/codeact-lane.js +98 -0
- package/dist/moa/codeact-sandbox.js +409 -0
- package/dist/moa/codeact.js +140 -0
- package/dist/permissions/artifact-visibility.js +10 -0
- package/dist/permissions/tier.js +4 -2
- package/dist/products/craft.js +2 -2
- package/dist/remote/grants.js +119 -0
- package/dist/remote/host.js +33 -5
- package/dist/router/models.js +24 -14
- package/dist/selfimprove/index.js +8 -6
- package/dist/services/preflight.js +35 -91
- package/dist/session.js +127 -41
- package/dist/skills/install-guard.js +68 -0
- package/dist/skills/install.js +67 -0
- package/dist/toolchain/manifest.json +13 -13
- package/dist/tools/background-result.js +1 -1
- package/dist/tools/classes.js +103 -0
- package/dist/tools/contract.js +1 -1
- package/dist/tools/craft.js +13 -2
- package/dist/tools/executor.js +25 -15
- package/dist/tools/generation-gateway.js +94 -0
- package/dist/tools/registry.js +83 -152
- package/dist/ui/App.js +15 -4
- package/dist/ui/BgPanel.js +15 -10
- package/dist/ui/Header.js +1 -6
- package/dist/ui/StatusRule.js +18 -7
- package/dist/ui/ToolStep.js +3 -3
- package/dist/ui/Transcript.js +36 -14
- package/dist/ui/batchLine.js +4 -4
- package/dist/ui/editdiff.js +2 -4
- package/dist/ui/format.js +4 -20
- package/dist/ui/liveTools.js +3 -3
- package/dist/ui/opsMode.js +20 -0
- package/dist/ui/types.js +0 -2
- package/dist/update-check.js +17 -6
- package/package.json +1 -1
- package/dist/tools/mutating.js +0 -15
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// The lane's "what is it doing" line, in plain words, from real signals only: the running tool and its key argument, the
|
|
2
|
+
// plan step it marked in progress, and the stream phase with its progress. Never the backend (that explains a wait, so it
|
|
3
|
+
// lives in the queued reason and /agents <id>), never a full command line, and redacted before it reaches the TUI. Pure.
|
|
4
|
+
import { redactSecrets } from "../engine/redact.js";
|
|
5
|
+
import { fmtElapsed, fmtTok } from "../ui/format.js";
|
|
6
|
+
import { FILE_READ, LOCAL_SEARCH, PLAN_TOOLS, SHELL_ANY, WEB_FETCH, WEB_SEARCH } from "../tools/classes.js";
|
|
7
|
+
/** Fits one lane line at 100 columns beside the name, round, elapsed and tokens. */
|
|
8
|
+
export const SUMMARY_MAX = 56;
|
|
9
|
+
const WRITES = { file_write: "writing", file_create: "writing", write_file: "writing", file_edit: "editing", edit_file: "editing", multi_edit: "editing", apply_patch: "patching", notebook_edit: "editing" };
|
|
10
|
+
const str = (v) => (typeof v === "string" && v.trim() ? v.replace(/\s+/g, " ").trim() : undefined);
|
|
11
|
+
const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : typeof v === "string" && /^\d+$/.test(v) ? Number(v) : undefined);
|
|
12
|
+
const base = (p) => p.replace(/[/\\]+$/, "").split(/[/\\]/).pop() || p;
|
|
13
|
+
const quoted = (s, n = 28) => `"${s.length > n ? `${s.slice(0, n - 1)}…` : s}"`;
|
|
14
|
+
/** Trim to `max` cells with a clean "…" (never mid-surrogate). */
|
|
15
|
+
export function clip(s, max = SUMMARY_MAX) {
|
|
16
|
+
const chars = [...s];
|
|
17
|
+
return chars.length <= max ? s : `${chars.slice(0, max - 1).join("").trimEnd()}…`;
|
|
18
|
+
}
|
|
19
|
+
function lineWindow(args) {
|
|
20
|
+
const start = num(args.start_line) ?? num(args.offset) ?? num(args.line);
|
|
21
|
+
const end = num(args.end_line) ?? (start !== undefined && num(args.limit) !== undefined ? start + num(args.limit) - 1 : undefined);
|
|
22
|
+
if (start === undefined)
|
|
23
|
+
return num(args.limit) !== undefined ? `lines 1–${num(args.limit)}` : undefined;
|
|
24
|
+
return end !== undefined ? `lines ${start}–${end}` : `from line ${start}`;
|
|
25
|
+
}
|
|
26
|
+
const WRAPPERS = new Set(["sudo", "nice", "time", "env", "nohup", "exec"]);
|
|
27
|
+
/** The program a command runs, without its arguments: env assignments and `cd …&&` are skipped, a path is cut to its name. */
|
|
28
|
+
export function commandWord(cmd) {
|
|
29
|
+
const words = cmd.trim().split(/\s+/).filter(Boolean);
|
|
30
|
+
for (let i = 0; i < words.length; i++) {
|
|
31
|
+
const w = words[i];
|
|
32
|
+
if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(w) || WRAPPERS.has(w) || /^-/.test(w) || /^\d+$/.test(w))
|
|
33
|
+
continue;
|
|
34
|
+
if (w === "cd") {
|
|
35
|
+
while (i < words.length && !/^(&&|;)$/.test(words[i]) && !/;$/.test(words[i]))
|
|
36
|
+
i++;
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
if (/^(&&|;|\|\|)$/.test(w))
|
|
40
|
+
continue;
|
|
41
|
+
return base(w).replace(/[^\w.+-]/g, "") || undefined;
|
|
42
|
+
}
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
/** One tool call in plain words: "reading digest.md (lines 1–900)", "searching the repo for "relayClient"". */
|
|
46
|
+
export function toolSummary(name, args = {}) {
|
|
47
|
+
const path = str(args.path) ?? str(args.file_path) ?? str(args.file) ?? (Array.isArray(args.paths) ? str(args.paths[0]) : undefined);
|
|
48
|
+
if (FILE_READ.has(name)) {
|
|
49
|
+
const more = Array.isArray(args.paths) && args.paths.length > 1 ? ` +${args.paths.length - 1}` : "";
|
|
50
|
+
const win = lineWindow(args);
|
|
51
|
+
return path ? `reading ${base(path)}${more}${win ? ` (${win})` : ""}` : "reading files";
|
|
52
|
+
}
|
|
53
|
+
if (LOCAL_SEARCH.has(name)) {
|
|
54
|
+
const q = str(args.pattern) ?? str(args.query) ?? str(args.glob) ?? str(args.name);
|
|
55
|
+
return q ? `searching the repo for ${quoted(q)}` : "searching the repo";
|
|
56
|
+
}
|
|
57
|
+
if (WEB_SEARCH.has(name)) {
|
|
58
|
+
const q = str(args.query);
|
|
59
|
+
return q ? `searching the web for ${quoted(q)}` : "searching the web";
|
|
60
|
+
}
|
|
61
|
+
if (WEB_FETCH.has(name)) {
|
|
62
|
+
const u = str(args.url);
|
|
63
|
+
let host;
|
|
64
|
+
try {
|
|
65
|
+
host = u ? new URL(u).hostname : undefined;
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
host = undefined;
|
|
69
|
+
}
|
|
70
|
+
return host ? `fetching ${host}` : "browsing";
|
|
71
|
+
}
|
|
72
|
+
if (SHELL_ANY.has(name)) {
|
|
73
|
+
const d = str(args.description);
|
|
74
|
+
if (d)
|
|
75
|
+
return d.charAt(0).toLowerCase() + d.slice(1);
|
|
76
|
+
const w = str(args.command) ? commandWord(String(args.command)) : undefined;
|
|
77
|
+
return w ? `running ${w}` : "running a command";
|
|
78
|
+
}
|
|
79
|
+
if (WRITES[name])
|
|
80
|
+
return path ? `${WRITES[name]} ${base(path)}` : `${WRITES[name]} a file`;
|
|
81
|
+
if (PLAN_TOOLS.has(name))
|
|
82
|
+
return "updating its plan";
|
|
83
|
+
if (name === "message_agent")
|
|
84
|
+
return "messaging another agent";
|
|
85
|
+
if (name === "codeact_run")
|
|
86
|
+
return `running one ${str(args.language) ? `${str(args.language)} ` : ""}program over its targets`;
|
|
87
|
+
return name.replace(/_/g, " ");
|
|
88
|
+
}
|
|
89
|
+
/** The step a task_update put in progress, read from the tool's own result ("[>] #3 Check relay callers"). */
|
|
90
|
+
export function planStepFrom(args, result) {
|
|
91
|
+
if (args.status !== "in_progress")
|
|
92
|
+
return undefined;
|
|
93
|
+
const id = num(args.id);
|
|
94
|
+
const line = result.split("\n").find((l) => l.startsWith("[>]") && (id === undefined || l.startsWith(`[>] #${id} `)));
|
|
95
|
+
return line ? str(line.replace(/^\[>\]\s*#\d+\s*/, "")) : undefined;
|
|
96
|
+
}
|
|
97
|
+
/** The first clause of the agent's own progress line ("Checking the relay callers, then…" → "checking the relay callers"). */
|
|
98
|
+
function firstClause(s) {
|
|
99
|
+
const c = s?.split(/[.;:!?](?=\s|$)|,\s|\s—\s|\s-\s/)[0]?.trim();
|
|
100
|
+
return c ? c.charAt(0).toLowerCase() + c.slice(1) : undefined;
|
|
101
|
+
}
|
|
102
|
+
function poolBusy(reason) {
|
|
103
|
+
const m = reason ? /(\d+)\/(\d+) busy/.exec(reason) : null;
|
|
104
|
+
return m ? `pool ${m[1]}/${m[2]} busy` : undefined;
|
|
105
|
+
}
|
|
106
|
+
/** What the lane is doing now, short and redacted. Falls back to the agent's progress line, then "starting". */
|
|
107
|
+
export function laneSummary(a, now) {
|
|
108
|
+
const p = a.phase;
|
|
109
|
+
const step = a.planStep ? clip(a.planStep, 30) : undefined;
|
|
110
|
+
const t = p ? fmtElapsed(now - p.since) : "";
|
|
111
|
+
let s;
|
|
112
|
+
switch (p?.kind) {
|
|
113
|
+
case "queued":
|
|
114
|
+
case "slot": {
|
|
115
|
+
const busy = p.kind === "queued" ? poolBusy(a.queueReason) : p.holder ? `held by ${p.holder}` : undefined;
|
|
116
|
+
s = `waiting for a free model slot${busy ? ` (${busy})` : ""}`;
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
119
|
+
case "sent":
|
|
120
|
+
s = `${step ?? "waiting for the model"} (sent ${t} ago)`;
|
|
121
|
+
break;
|
|
122
|
+
case "reading": {
|
|
123
|
+
const fresh = Math.max(1, p.total - p.cached);
|
|
124
|
+
const pct = Math.min(100, Math.round((Math.max(0, p.processed - p.cached) / fresh) * 100));
|
|
125
|
+
s = `${step ? `${step}: ` : ""}reading its context (${fmtTok(fresh)} tok, ${pct}%)`;
|
|
126
|
+
break;
|
|
127
|
+
}
|
|
128
|
+
case "thinking":
|
|
129
|
+
case "writing": {
|
|
130
|
+
const n = p.tokens - p.startTokens;
|
|
131
|
+
const what = step ?? firstClause(a.progress) ?? p.kind;
|
|
132
|
+
s = `${what}${n > 0 ? ` (${fmtTok(n)} tok)` : ""}`;
|
|
133
|
+
break;
|
|
134
|
+
}
|
|
135
|
+
case "tool": {
|
|
136
|
+
const d = `${a.doing ?? p.name.replace(/_/g, " ")}${p.count > 1 ? ` +${p.count - 1}` : ""}`;
|
|
137
|
+
s = d.endsWith(")") ? `${d.slice(0, -1)}, ${t})` : `${d} (${t})`;
|
|
138
|
+
break;
|
|
139
|
+
}
|
|
140
|
+
case "between":
|
|
141
|
+
s = step ?? "between rounds";
|
|
142
|
+
break;
|
|
143
|
+
}
|
|
144
|
+
s ??= firstClause(a.progress) ?? (a.steps?.length ? a.steps[a.steps.length - 1].name.replace(/_/g, " ") : undefined) ?? "starting";
|
|
145
|
+
// The trailing "(…)" carries the live numbers: keep it whole and cut the words before it.
|
|
146
|
+
const red = redactSecrets(s);
|
|
147
|
+
const tail = /\s(\([^()]*\))$/.exec(red);
|
|
148
|
+
if (!tail || [...red].length <= SUMMARY_MAX)
|
|
149
|
+
return clip(red);
|
|
150
|
+
return `${clip(red.slice(0, tail.index), SUMMARY_MAX - [...tail[1]].length - 1)} ${tail[1]}`;
|
|
151
|
+
}
|
|
@@ -10,6 +10,10 @@ const REPORT_CHARS = 8000; // the spawn brief asks for a ~1-2k token report; a r
|
|
|
10
10
|
// report on blank lines and print each paragraph — the model's instructions included — as its own "⤷" line.
|
|
11
11
|
const reports = [];
|
|
12
12
|
const listeners = new Set();
|
|
13
|
+
let gate = () => ({ ready: true, missing: "" });
|
|
14
|
+
export function setReportGate(fn) {
|
|
15
|
+
gate = fn ?? (() => ({ ready: true, missing: "" }));
|
|
16
|
+
}
|
|
13
17
|
const clip = (s, n) => s.length <= n ? s : s.slice(0, n) + `\n… [report clipped at ${n} chars — re-run the sub-agent with a tighter deliverable if the rest matters]`;
|
|
14
18
|
const who = (a) => `${a.name ? `${a.name} (${a.title ?? "sub-agent"}, ${a.id})` : `sub-agent ${a.id}`} — ${a.label}`;
|
|
15
19
|
/** The notice the model reads when a sub-agent finishes: who, what it changed, its report — and what to do with it.
|
|
@@ -38,7 +42,7 @@ export function ownerLine(agent, result) {
|
|
|
38
42
|
}
|
|
39
43
|
/** Queue a stuck notice for the next turn and wake the shell (same channel as a finished report). */
|
|
40
44
|
export function queueAgentNotice(text, owner = "a sub-agent notice") {
|
|
41
|
-
reports.push({ text, owner });
|
|
45
|
+
reports.push({ text, owner, kind: "notice" });
|
|
42
46
|
for (const fn of listeners) {
|
|
43
47
|
try {
|
|
44
48
|
fn();
|
|
@@ -48,7 +52,7 @@ export function queueAgentNotice(text, owner = "a sub-agent notice") {
|
|
|
48
52
|
}
|
|
49
53
|
/** Queue a finished agent's report for the next turn and tell the shell (which wakes an idle session). */
|
|
50
54
|
export function queueAgentReport(agent, result) {
|
|
51
|
-
reports.push({ text: formatAgentReport(agent, result), owner: ownerLine(agent, result) });
|
|
55
|
+
reports.push({ text: formatAgentReport(agent, result), owner: ownerLine(agent, result), kind: "report" });
|
|
52
56
|
for (const fn of listeners) {
|
|
53
57
|
try {
|
|
54
58
|
fn();
|
|
@@ -59,10 +63,15 @@ export function queueAgentReport(agent, result) {
|
|
|
59
63
|
export function pendingAgentReports() {
|
|
60
64
|
return reports.length;
|
|
61
65
|
}
|
|
66
|
+
/** Whether queued reports should wake the session now: any notice, or reports once the synthesis gate is ready. */
|
|
67
|
+
export function agentReportsDue() {
|
|
68
|
+
return reports.some((r) => r.kind === "notice") || (reports.length > 0 && gate().ready);
|
|
69
|
+
}
|
|
62
70
|
/** Take every queued report: the model's text (joined, byte-identical to what it always was) and the owner lines. */
|
|
63
71
|
export function drainAgentNotices() {
|
|
64
72
|
const taken = reports.splice(0);
|
|
65
|
-
|
|
73
|
+
const missing = taken.some((r) => r.kind === "report") ? gate().missing : "";
|
|
74
|
+
return { text: [...taken.map((r) => r.text), ...(missing ? [missing] : [])].join("\n\n"), owners: taken.map((r) => r.owner) };
|
|
66
75
|
}
|
|
67
76
|
/** Take every queued report (joined), or "" when none. Called at the start of a turn. */
|
|
68
77
|
export function drainAgentReports() {
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { fmtElapsed } from "../ui/format.js";
|
|
2
|
+
const live = (a) => a.status === "working" || a.status === "queued";
|
|
3
|
+
export function synthesisState(agents, now) {
|
|
4
|
+
const running = agents.filter(live);
|
|
5
|
+
const waitingOn = running.filter((a) => a.optional !== true).map((a) => a.name ?? a.id);
|
|
6
|
+
const missing = running.filter((a) => a.optional === true).map((a) => ({
|
|
7
|
+
name: a.name ?? a.id,
|
|
8
|
+
reason: a.deadlineAt !== undefined && now > a.deadlineAt ? `optional, ${fmtElapsed(now - a.deadlineAt)} past its deadline` : "optional, still running",
|
|
9
|
+
}));
|
|
10
|
+
return { ready: waitingOn.length === 0, waitingOn, missing };
|
|
11
|
+
}
|
|
12
|
+
/** The line the parent reads with the reports it synthesizes from. "" when nothing is missing. */
|
|
13
|
+
export function missingLine(missing) {
|
|
14
|
+
if (!missing.length)
|
|
15
|
+
return "";
|
|
16
|
+
return `[system notice] missing: ${missing.map((m) => `${m.name} (${m.reason})`).join(", ")}. Synthesize from the reports you have ` +
|
|
17
|
+
`and say what is missing; a late report arrives on its own if it finishes — do not wait or poll for it.`;
|
|
18
|
+
}
|
|
19
|
+
/** The lane's deadline words: "4m 10s left", "overdue 1m 2s". Undefined without a deadline. */
|
|
20
|
+
export function deadlineText(a, now) {
|
|
21
|
+
if (a.deadlineAt === undefined)
|
|
22
|
+
return undefined;
|
|
23
|
+
const left = a.deadlineAt - now;
|
|
24
|
+
return left >= 0 ? `⏱ ${fmtElapsed(left)} left` : `⏱ overdue ${fmtElapsed(-left)}${a.optional ? " (not waited on)" : ""}`;
|
|
25
|
+
}
|
package/dist/bus/inbox.js
CHANGED
|
@@ -6,9 +6,11 @@
|
|
|
6
6
|
//
|
|
7
7
|
// SECURITY: a bus message is DATA written by another agent — untrusted input. The UI surfaces it to the
|
|
8
8
|
// operator; nothing here executes message contents.
|
|
9
|
-
import { readdirSync, readFileSync, renameSync, mkdirSync, existsSync } from "node:fs";
|
|
10
|
-
import {
|
|
9
|
+
import { readdirSync, readFileSync, renameSync, mkdirSync, existsSync, writeFileSync, realpathSync } from "node:fs";
|
|
10
|
+
import { randomUUID } from "node:crypto";
|
|
11
|
+
import { isAbsolute, join, sep } from "node:path";
|
|
11
12
|
import { homedir, hostname } from "node:os";
|
|
13
|
+
import { redactSecrets } from "../engine/redact.js";
|
|
12
14
|
/** The bus state root — mirrors the switchboard CLI's SWITCHBOARD_DIR. Neutral default (~/.switchboard) so
|
|
13
15
|
* this works on any box/surface, not just the AXE fleet; the env var repoints it wherever the bus lives. */
|
|
14
16
|
export function busDir() {
|
|
@@ -63,13 +65,19 @@ export function pollBus(agent = selfAgent(), opts = {}) {
|
|
|
63
65
|
* allowlist). PURE + tested — the cli.tsx poller calls this, then routes the text to the submit/queue path.
|
|
64
66
|
* Contract: a rendered bus message is only displayed; THIS is what puts a peer message into the model's context
|
|
65
67
|
* as an actionable turn. `allow` unset/empty = any sender wakes; otherwise only senders in the list. */
|
|
66
|
-
export function buildMentorWake(incoming, allow) {
|
|
67
|
-
const toWake = allow && allow.length ? incoming.filter((m) => allow.includes(m.from)) : incoming;
|
|
68
|
+
export function buildMentorWake(incoming, allow, rootPolicy) {
|
|
69
|
+
const toWake = (allow && allow.length ? incoming.filter((m) => allow.includes(m.from)) : incoming).filter((m) => !isAutoReport(m));
|
|
68
70
|
if (!toWake.length)
|
|
69
71
|
return null;
|
|
70
|
-
|
|
72
|
+
const dir = rootPolicy ? wakeWorkdir(toWake, rootPolicy) : null;
|
|
73
|
+
const frame = `[mentor-wake] ${toWake.length} new bus message(s) arrived — review and act on them now:\n\n` +
|
|
71
74
|
toWake.map((m) => `--- from ${m.from}${m.subject ? ` · ${m.subject}` : ""} (${m.ts}) ---\n${m.body}`).join("\n\n") +
|
|
72
|
-
`\n\
|
|
75
|
+
(dir ? `\n\nThe harness set this turn's working directory to ${dir} (the brief's worktree): relative paths and shell commands resolve there for this turn only, then the session returns to its own folder.` : "") +
|
|
76
|
+
`\n\n${replyProtocol([...new Set(toWake.map((m) => m.from))])}`;
|
|
77
|
+
wakeRegistry.set(frame, { msgs: toWake, dir });
|
|
78
|
+
while (wakeRegistry.size > WAKE_REGISTRY_MAX)
|
|
79
|
+
wakeRegistry.delete(wakeRegistry.keys().next().value);
|
|
80
|
+
return frame;
|
|
73
81
|
}
|
|
74
82
|
/** The reply contract a woken turn owes its sender, spelled out in the frame itself. The sender is another agent
|
|
75
83
|
* on the bus and cannot see this screen: a turn that works in silence is invisible to the teacher, and the plan
|
|
@@ -127,3 +135,139 @@ export function pollSent(agent = selfAgent(), opts = {}) {
|
|
|
127
135
|
}
|
|
128
136
|
return out;
|
|
129
137
|
}
|
|
138
|
+
// ── Report delivery: a woken turn's answer reaches its sender ────────────────────────────────────────────────────
|
|
139
|
+
// replyProtocol asks the turn to send a report; nothing checked it, so a turn that ended without one left the sender
|
|
140
|
+
// with nothing (11/24: four D6 turns, zero replies). Claude Code returns a sub-agent's final message to its parent and
|
|
141
|
+
// `codex exec -o` writes the last message for its caller; the bus counterpart is below: at the end of a mentor-wake
|
|
142
|
+
// turn, each sender that got nothing from this agent during the turn receives the turn's final answer, marked
|
|
143
|
+
// auto-delivered. A turn that did reply is left alone.
|
|
144
|
+
/** The senders a `[mentor-wake]` frame came from (its `--- from <name>[ · subject] (<ts>) ---` headers), in order. */
|
|
145
|
+
/** The bus messages a wake frame was built from, recorded when the harness built it. The senders a woken turn
|
|
146
|
+
* owes a report come from here, never from the frame's text: a message body can contain a line that looks like a
|
|
147
|
+
* "--- from X ---" header. */
|
|
148
|
+
const wakeRegistry = new Map();
|
|
149
|
+
const WAKE_REGISTRY_MAX = 64;
|
|
150
|
+
function wakeEntry(turnText) {
|
|
151
|
+
for (const [frame, e] of wakeRegistry)
|
|
152
|
+
if (turnText === frame || turnText.endsWith(frame))
|
|
153
|
+
return e;
|
|
154
|
+
return undefined;
|
|
155
|
+
}
|
|
156
|
+
/** The messages behind the wake frame in this turn's text (a job notice may be prepended), or [] for any other turn. */
|
|
157
|
+
export function wakeMessages(turnText) {
|
|
158
|
+
return wakeEntry(turnText)?.msgs ?? [];
|
|
159
|
+
}
|
|
160
|
+
/** The working directory the harness chose for this wake turn (wakeWorkdir), or null. Read from the registry, never
|
|
161
|
+
* from the frame's text: a message body cannot set it. */
|
|
162
|
+
export function wakeRoot(turnText) {
|
|
163
|
+
return wakeEntry(turnText)?.dir ?? null;
|
|
164
|
+
}
|
|
165
|
+
const realDir = (p) => { try {
|
|
166
|
+
return realpathSync(p);
|
|
167
|
+
}
|
|
168
|
+
catch {
|
|
169
|
+
return null;
|
|
170
|
+
} };
|
|
171
|
+
const isCheckoutTop = (dir) => existsSync(join(dir, ".git"));
|
|
172
|
+
/** The one working directory a batch of wake messages names in its refs (`worktree`, else `cwd`), or null. It must be
|
|
173
|
+
* the same across the batch, absolute, and after realpath a git checkout's top folder inside one of the policy's
|
|
174
|
+
* roots — never `/`, $HOME, ~/.ssh or a root itself. The bus counterpart of Codex `--cd` and Claude Code's worktree
|
|
175
|
+
* isolation for a delegated agent. */
|
|
176
|
+
export function wakeWorkdir(msgs, policy, isTop = isCheckoutTop) {
|
|
177
|
+
const dirs = new Set();
|
|
178
|
+
for (const m of msgs) {
|
|
179
|
+
const v = m.refs?.worktree ?? m.refs?.cwd;
|
|
180
|
+
if (typeof v === "string" && v.trim())
|
|
181
|
+
dirs.add(v.trim().replace(/\/+$/, ""));
|
|
182
|
+
}
|
|
183
|
+
if (dirs.size !== 1)
|
|
184
|
+
return null;
|
|
185
|
+
const [named] = [...dirs];
|
|
186
|
+
if (!named || !isAbsolute(named))
|
|
187
|
+
return null;
|
|
188
|
+
const dir = realDir(named);
|
|
189
|
+
if (!dir || !isTop(dir))
|
|
190
|
+
return null;
|
|
191
|
+
const inside = policy.roots.map(realDir).some((r) => r && dir !== r && dir.startsWith(r.endsWith(sep) ? r : r + sep));
|
|
192
|
+
return inside ? dir : null;
|
|
193
|
+
}
|
|
194
|
+
/** An auto-delivered report: delivered to the inbox like any message but never wakes a turn, so two Operators
|
|
195
|
+
* can't answer each other's auto-reports forever. */
|
|
196
|
+
export function isAutoReport(m) {
|
|
197
|
+
return m.meta?.auto === true;
|
|
198
|
+
}
|
|
199
|
+
/** Whether `agent` already sent `to` this answer since `sinceMs` (the model replied itself, or quoted its final
|
|
200
|
+
* answer). A plan or progress message to the sender does not count: only the final answer closes the loop. */
|
|
201
|
+
export function reportedTo(agent, to, sinceMs, answer) {
|
|
202
|
+
const probe = answer.replace(/\s+/g, " ").trim().slice(0, 200);
|
|
203
|
+
for (const dir of [sentOf(agent), sentReadOf(agent)]) {
|
|
204
|
+
if (!existsSync(dir))
|
|
205
|
+
continue;
|
|
206
|
+
let files;
|
|
207
|
+
try {
|
|
208
|
+
files = readdirSync(dir).filter((f) => f.endsWith(".json") && !f.startsWith(".tmp-"));
|
|
209
|
+
}
|
|
210
|
+
catch {
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
for (const f of files) {
|
|
214
|
+
const stamp = Number(f.split("-")[0]);
|
|
215
|
+
if (Number.isFinite(stamp) && stamp && stamp < sinceMs)
|
|
216
|
+
continue; // the file name leads with its send time (ms)
|
|
217
|
+
try {
|
|
218
|
+
const m = JSON.parse(readFileSync(join(dir, f), "utf8"));
|
|
219
|
+
if (m.to === to && Date.parse(m.ts) >= sinceMs && m.body.replace(/\s+/g, " ").includes(probe))
|
|
220
|
+
return true;
|
|
221
|
+
}
|
|
222
|
+
catch { /* skip corrupt */ }
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return false;
|
|
226
|
+
}
|
|
227
|
+
export function busSend(from, to, body, opts = {}) {
|
|
228
|
+
const id = randomUUID();
|
|
229
|
+
const msg = { id, from, to, ts: new Date().toISOString(), subject: opts.subject ?? null, thread: opts.thread ?? null, body, ...(opts.auto ? { meta: { auto: true } } : {}) };
|
|
230
|
+
const name = `${String(Date.now()).padStart(15, "0")}-${id.slice(0, 8)}.json`;
|
|
231
|
+
for (const dir of [inboxOf(to), sentOf(from)]) {
|
|
232
|
+
mkdirSync(dir, { recursive: true });
|
|
233
|
+
const tmp = join(dir, `.tmp-${name}`);
|
|
234
|
+
writeFileSync(tmp, JSON.stringify(msg), { mode: 0o600 });
|
|
235
|
+
renameSync(tmp, join(dir, name));
|
|
236
|
+
}
|
|
237
|
+
return id;
|
|
238
|
+
}
|
|
239
|
+
export const AUTO_REPORT_MAX = 8_000;
|
|
240
|
+
/** Who a woken turn owes a report, with the thread to answer in (the sender's last message's). */
|
|
241
|
+
function owed(turnText, agent) {
|
|
242
|
+
const last = new Map();
|
|
243
|
+
for (const m of wakeMessages(turnText))
|
|
244
|
+
if (m.from !== agent)
|
|
245
|
+
last.set(m.from, m);
|
|
246
|
+
return [...last.values()].map((m) => ({ to: m.from, thread: m.thread ?? m.id }));
|
|
247
|
+
}
|
|
248
|
+
/** A woken turn ended without sending its final answer to a sender: the harness delivers it (Claude Code returns a
|
|
249
|
+
* sub-agent's final message to its parent; `codex exec -o` writes it for the caller). One sender gets the answer;
|
|
250
|
+
* when one turn answered several senders, each gets a short note instead, so one agent's report never goes to
|
|
251
|
+
* another. Secrets are redacted and the message is tagged auto, so it never wakes the receiver. */
|
|
252
|
+
export function autoDeliverReport(turnText, finalAnswer, sinceMs, agent = selfAgent()) {
|
|
253
|
+
const answer = redactSecrets(finalAnswer.trim());
|
|
254
|
+
if (!answer)
|
|
255
|
+
return [];
|
|
256
|
+
const due = owed(turnText, agent).filter((o) => !reportedTo(agent, o.to, sinceMs, answer));
|
|
257
|
+
const shared = owed(turnText, agent).length > 1;
|
|
258
|
+
for (const o of due) {
|
|
259
|
+
const body = shared
|
|
260
|
+
? `Auto-delivered by Operator's harness: one turn handled messages from several agents and ended without a report to you. Its answer is not forwarded to keep reports separate; ask ${agent} or its owner for your part.`
|
|
261
|
+
: `Auto-delivered by Operator's harness: this turn ended without a report to you, so its final answer follows.\n\n${answer.length > AUTO_REPORT_MAX ? `${answer.slice(0, AUTO_REPORT_MAX)}\n… (cut at ${AUTO_REPORT_MAX} characters)` : answer}`;
|
|
262
|
+
busSend(agent, o.to, body, { subject: "Report (auto-delivered)", thread: o.thread, auto: true });
|
|
263
|
+
}
|
|
264
|
+
return due.map((o) => o.to);
|
|
265
|
+
}
|
|
266
|
+
/** A woken turn was interrupted or failed: its senders get a short note instead of silence. */
|
|
267
|
+
export function autoDeliverFailure(turnText, reason, agent = selfAgent()) {
|
|
268
|
+
const due = owed(turnText, agent);
|
|
269
|
+
for (const o of due) {
|
|
270
|
+
busSend(agent, o.to, `Auto-delivered by Operator's harness: the turn that took your message was ${reason} before it finished. No report was produced; resend the task if it is still needed.`, { subject: `Report (${reason})`, thread: o.thread, auto: true });
|
|
271
|
+
}
|
|
272
|
+
return due.map((o) => o.to);
|
|
273
|
+
}
|