ace-wake 0.5.0 → 0.6.0

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.
@@ -1,332 +0,0 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
3
- import { execFile, execFileSync } from "node:child_process";
4
- import { promisify } from "node:util";
5
- import { Eyes, EYES_ENTRY } from "./eyes.js";
6
- import { clip, renderWake, renderStatus, renderProcessing, wakePresentation, statusPresentation, processingPresentation } from "./eyes-digest.js";
7
-
8
- const execute = promisify(execFile);
9
- export const EYES_BINDING = "ace-wake-eyes-binding";
10
-
11
- // Birth identity is immutable for this process. Probe once at session binding,
12
- // never during observation polling. Darwin uses the same native libproc owner
13
- // as the Ruby readiness reader; second-resolution ps timestamps are insufficient.
14
- let ownIdentity;
15
- export function eyesProcessIdentity() {
16
- if (ownIdentity === undefined) ownIdentity = readEyesProcessIdentity();
17
- return ownIdentity;
18
- }
19
-
20
- export function readEyesProcessIdentity({ platform = process.platform, pid = process.pid,
21
- readFile = fs.readFileSync, run = execFileSync } = {}) {
22
- try {
23
- if (platform === "darwin") {
24
- const birth = run("ruby", ["-r", "ace/runtime/molecules/process_identity", "-e",
25
- "print Ace::Runtime::Molecules::ProcessIdentity.new.native_birth(Integer(ARGV.fetch(0)))", String(pid)],
26
- { encoding: "utf8", timeout: 2000, killSignal: "SIGKILL", maxBuffer: 1024, stdio: ["ignore", "pipe", "pipe"] }).trim();
27
- return /^darwin:[1-9][0-9]*:[0-9]{1,6}$/.test(birth) ? { pid, startedAt: birth } : null;
28
- }
29
- if (platform !== "linux") return null;
30
- const stat = readFile(`/proc/${pid}/stat`, "utf8");
31
- const end = stat.lastIndexOf(") ");
32
- if (end < 0) return null;
33
- const ticks = stat.slice(end + 2).trim().split(/\s+/)[19];
34
- const boot = readFile("/proc/sys/kernel/random/boot_id", "utf8").trim();
35
- if (!/^[1-9][0-9]*$/.test(ticks) || !/^[0-9a-f-]{36}$/.test(boot)) return null;
36
- return { pid, startedAt: `linux:${boot}:${ticks}` };
37
- } catch { return null; }
38
- }
39
-
40
- /** Existing native sync owns canonical import; HITL owns event projection.
41
- * No Ruby parsing, private text, shell command strings or model work here. */
42
- export async function observeHitl(cwd, config) {
43
- const options = { cwd, timeout: config.timeoutMs, maxBuffer: 1024 * 1024, encoding: "utf8" };
44
- for (const source of config.syncRoutes) {
45
- // One source per project: each entry names the project hitl config and,
46
- // when several hermes_native routes exist there, the route to reconcile.
47
- const argv = ["sync", "--config", source.config];
48
- if (source.route !== undefined) argv.push("--route", source.route);
49
- const { stdout } = await execute("ace-hitl-hermes", argv, options);
50
- const result = JSON.parse(stdout);
51
- if (!Array.isArray(result.errors) || result.errors.length) throw new Error("Native synchronization incomplete");
52
- }
53
- const { stdout } = await execute("ace-overseer", ["observe", "--owner", config.recipient, "--scope", config.scope, "--limit", String(config.maxEvents)], options);
54
- const result = JSON.parse(stdout);
55
- if (!result?.sources || typeof result.sources !== "object" || Array.isArray(result.sources) ||
56
- Object.keys(result.sources).length === 0) throw new Error("Observation source health is missing");
57
- return result;
58
- }
59
-
60
- export async function processReports(cwd, config, signal) {
61
- const { stdout } = await execute("ace-overseer", ["process-reports", "--json",
62
- "--owner", config.recipient, "--scope", config.scope],
63
- { cwd, signal, maxBuffer: 8 * 1024 * 1024, encoding: "utf8" });
64
- const result = JSON.parse(stdout);
65
- if (!Array.isArray(result?.outcomes) || result.dry_run !== false)
66
- throw new Error("Invalid report-processing receipt");
67
- return result;
68
- }
69
-
70
- export function registerEyes(pi, { observe = observeHitl, processReports: processReportOwner = processReports, env = process.env, now = Date.now,
71
- schedule = (fn, ms) => setInterval(fn, ms), cancel = clearInterval, processIdentity = eyesProcessIdentity } = {}) {
72
- let eyes, timer, attempt, observedSources, observedAt, bindingGeneration = 0, compacting = false, running = false, arming = false;
73
- const clearEvidence = () => { observedSources = undefined; observedAt = undefined; };
74
- const stopTimer = () => { if (timer !== undefined) cancel(timer); timer = undefined; };
75
- function arm() {
76
- stopTimer();
77
- if (eyes?.s.enabled && !eyes.s.retired && !eyes.s.breaker) {
78
- timer = schedule(() => { void eyes.tick({ scheduled: true }); },
79
- eyes.s.config.intervalSeconds * 1000);
80
- timer?.unref?.();
81
- }
82
- }
83
- const bind = async (ctx) => {
84
- const generation = ++bindingGeneration;
85
- stopTimer(); eyes?.dispose(); attempt = undefined; clearEvidence(); compacting = false; running = false;
86
- const entries = ctx.sessionManager.getBranch();
87
- const snapshot = [...entries].reverse().find((e) => e.type === "custom" && e.customType === EYES_ENTRY)?.data;
88
- const ownerCwd = path.resolve(ctx.cwd);
89
- if (snapshot?.ownerCwd && snapshot.ownerCwd !== ownerCwd) {
90
- eyes = undefined;
91
- ctx.ui?.setStatus?.("ace-eyes", "eyes blocked: session belongs to another project cwd");
92
- throw new Error("Eyes project owner mismatch; preserve this actor and use its original project session");
93
- }
94
- const identity = processIdentity();
95
- pi.appendEntry(EYES_BINDING, { ownerCwd, process: identity });
96
- eyes = new Eyes({ snapshot, now,
97
- save: (data) => {
98
- const entries = observedSources && typeof observedSources === "object" && !Array.isArray(observedSources) ? Object.entries(observedSources) : [];
99
- const valid = entries.length > 0 && entries.length <= 64 && entries.every(([name, source]) =>
100
- /^[a-zA-Z0-9_.:-]{1,128}$/.test(name) && source && ["ok", "degraded"].includes(source.status));
101
- const sources = valid ? Object.fromEntries(entries.map(([name, source]) => [name, source.status]).sort()) : {};
102
- pi.appendEntry(EYES_ENTRY, { ...data, ownerCwd, observerEvidence: {
103
- process: identity, observedAt: observedAt ?? null, sources
104
- } });
105
- },
106
- status: (state) => {
107
- ctx.ui?.setStatus?.("ace-eyes", `eyes ${state.retired ? "retired" : state.breaker?.reason || (state.observationUnavailable ? "observation-unavailable" : state.wakeLimitedUntil && state.pending ? `wake-limited until ${new Date(state.wakeLimitedUntil).toISOString()}` : state.enabled ? "observing" : "off")} pending:${state.pending}`);
108
- if (state.breaker || state.retired) stopTimer();
109
- },
110
- observe: (config) => observe(ctx.cwd, config),
111
- // A result is evidence only after Eyes validated it and confirmed that
112
- // the observer generation is still current.
113
- onObserved: (result) => {
114
- if (generation === bindingGeneration) { observedSources = result.sources; observedAt = now(); }
115
- },
116
- onObservationUnavailable: () => {
117
- if (generation === bindingGeneration) clearEvidence();
118
- },
119
- // Do not queue a follow-up while the current turn can still handle and
120
- // acknowledge the same revision. Polling retains it until the agent is
121
- // idle; already handled changes then require no extra model turn. Unlike
122
- // eyes revisions, loop/watch messages cannot be acknowledged this way.
123
- canDeliver: () => !arming && !compacting && !running && ctx.isIdle() && !ctx.hasPendingMessages(),
124
- deliveryStatus: () => {
125
- if (attempt?.accepted) return "accepted";
126
- // sendUserMessage is a void wrapper. Busy/queued is uncertain, not
127
- // acceptance or rejection. Idle without confirmation is uncertain:
128
- // async input/auth preflight may still be running, so never blind-retry.
129
- return compacting || !ctx.isIdle() || ctx.hasPendingMessages() ? "waiting" : "uncertain";
130
- },
131
- deliver: async (batch) => {
132
- if (!ctx.model) return false;
133
- const omitted = Math.max(0, Object.keys(eyes.s.pending).length - batch.length);
134
- const presented = wakePresentation(batch, omitted);
135
- const text = renderWake(batch, omitted);
136
- const previous = attempt;
137
- attempt = { text, accepted: false };
138
- const result = pi.sendUserMessage(text, { deliverAs: "followUp" });
139
- // Some hosts expose a promise, the standard ExtensionAPI exposes void.
140
- // Neither completion nor void is proof of message consumption.
141
- const submitted = await result;
142
- if (submitted === false) attempt = previous;
143
- else eyes.markPresented(presented);
144
- return submitted !== false;
145
- } });
146
- const configPath = env.ACE_OVERSEER_EYES_CONFIG;
147
- if (configPath) {
148
- const expected = path.join(ownerCwd, ".ace-local/overseer/eyes.json");
149
- if (path.resolve(configPath) !== expected) throw new Error("Eyes config does not belong to this coordinator root");
150
- eyes.start(JSON.parse(fs.readFileSync(configPath, "utf8")));
151
- }
152
- arm();
153
- if (eyes.s.enabled && configPath) {
154
- arming = true;
155
- try { await eyes.tick(); } finally { arming = false; }
156
- } else if (eyes.s.enabled) void eyes.tick();
157
- };
158
- pi.on("session_start", async (_event, ctx) => bind(ctx));
159
- pi.on("session_tree", async (_event, ctx) => bind(ctx));
160
- pi.on("agent_start", async () => { running = true; });
161
- pi.on("agent_settled", async () => { running = false; eyes?.persist(); });
162
- pi.on("message_start", async (event) => {
163
- if (event.message?.role !== "user" || !attempt) return;
164
- const text = typeof event.message.content === "string" ? event.message.content :
165
- (event.message.content || []).filter(part => part.type === "text").map(part => part.text).join("");
166
- if (text === attempt.text) attempt.accepted = true;
167
- });
168
- pi.on("session_before_compact", async (event) => { if (event.reason === "manual") compacting = true; });
169
- pi.on("session_compact", async () => { compacting = false; eyes?.persist(); });
170
- pi.on("session_compact_failed", async () => { compacting = false; });
171
- pi.on("session_shutdown", async () => {
172
- bindingGeneration++; stopTimer(); clearEvidence();
173
- eyes?.persist(); eyes?.dispose(); eyes = undefined;
174
- });
175
- pi.on("message_end", async (event) => {
176
- const message = event.message;
177
- if (message?.role === "assistant" && message.stopReason === "error") eyes?.quota(message.errorMessage);
178
- });
179
- // Shared by the ace_eyes tool and the /eyes command: both close over this
180
- // registerEyes scope (eyes, observedSources). Only MODEL-visible renders
181
- // (the tool's status result) record presented revisions; an operator
182
- // notification must never authorize a model acknowledgement.
183
- const statusSnapshot = () => ({
184
- summary: eyes.summary(), sources: observedSources,
185
- pending: Object.entries(eyes.s.pending), deadlines: Object.keys(eyes.s.deadlines).length,
186
- });
187
- const statusText = (filter) => renderStatus(statusSnapshot(), { filter });
188
- const presentStatus = (filter) => {
189
- const snapshot = statusSnapshot();
190
- eyes.markPresented(statusPresentation(snapshot, { filter }));
191
- return renderStatus(snapshot, { filter });
192
- };
193
- pi.registerTool?.({
194
- name: "ace_eyes", label: "Eyes observation", description: "Start standing observation with an existing config file, read a compact digest of pending semantic events, or acknowledge one exactly handled event by its short id. Acks are held to the revision presented this session by wake or status; a stale id acknowledges its presented revision and keeps any newer unseen revision pending. Action process-reports invokes the existing report owner and acknowledges only its completed exact revisions; other events require explicit ack. Does not reset quota. Deadlines require an operation id and revision; cancel when no longer active.",
195
- parameters: { type: "object", properties: {
196
- action: { type: "string", enum: ["start", "status", "process-reports", "ack", "deadline", "cancel"] },
197
- configPath: { type: "string" },
198
- id: { type: "string", description: "Short event id from ace_eyes status (for ack); for deadline/cancel pass the bare operation name" },
199
- filter: { type: "string", description: "Optional status filter: event kind or id substring" },
200
- revision: { type: "string", description: "Deadline operation revision (deadline action)" },
201
- at: { type: "integer", description: "Absolute Unix epoch timestamp in milliseconds, NOT a duration. For five minutes from now use the current epoch milliseconds plus 300000; a past timestamp is immediately due." }
202
- }, required: ["action"], additionalProperties: false },
203
- execute: async (_id, args, _signal, _onUpdate, ctx) => {
204
- if (!eyes) {
205
- if (!ctx) throw new Error("Eyes session not initialized");
206
- await bind(ctx);
207
- }
208
- // Tool metadata mirrors bounded scalars only: no per-event keys,
209
- // revisions, deadlines map or receipt timings reach the model.
210
- const boundedDetails = (receipt) => ({
211
- ...eyes.summary(),
212
- ...(observedSources ? { sources: Object.fromEntries(Object.entries(observedSources)
213
- .map(([name, source]) => [name, source?.status])) } : {}),
214
- ...(receipt ? { processing: {
215
- counts: receipt.counts,
216
- acknowledged: receipt.outcomes.filter((row) =>
217
- row.acknowledge === true && row.accepted === true && row.cleanup === "complete").length,
218
- } } : {}),
219
- });
220
- let processing;
221
- let text;
222
- if (args.action === "start") {
223
- if (!ctx || typeof args.configPath !== "string" || !args.configPath.trim()) {
224
- throw new Error("Eyes start requires configPath and the current session context");
225
- }
226
- const config = JSON.parse(fs.readFileSync(path.resolve(ctx.cwd, args.configPath), "utf8"));
227
- const current = eyes, generation = bindingGeneration;
228
- clearEvidence(); current.start(config); arm();
229
- // Observe now, but do not enqueue a redundant model turn inside the
230
- // caller's turn. Pending revisions are returned to the caller below.
231
- arming = true;
232
- try { await current.tick(); } finally { if (current === eyes && generation === bindingGeneration) arming = false; }
233
- if (current !== eyes || generation !== bindingGeneration) throw new Error("Eyes session changed during start");
234
- }
235
- else if (args.action === "process-reports") {
236
- if (!ctx || !eyes.s.enabled) throw new Error("Report processing requires active eyes in this session");
237
- const sources = observedSources && Object.values(observedSources);
238
- const config = eyes.s.config;
239
- const interval = config.intervalSeconds * 1000;
240
- const cadence = Math.ceil(3600000 / (config.maxObservationsPerHour * interval)) * interval;
241
- if (eyes.s.breaker || eyes.s.observationUnavailable || !sources?.length ||
242
- sources.some(source => source.status !== "ok") || observedAt === undefined ||
243
- now() - observedAt > cadence + config.timeoutMs)
244
- throw new Error("Report processing blocked: required observation is unavailable, degraded or stale");
245
- const current = eyes, generation = bindingGeneration;
246
- processing = await processReportOwner(ctx.cwd, current.s.config, _signal);
247
- if (current !== eyes || generation !== bindingGeneration)
248
- throw new Error("Eyes session changed during report processing; retained receipts require reconciliation");
249
- if (!Array.isArray(processing?.outcomes) || processing.dry_run !== false)
250
- throw new Error("Invalid report-processing receipt");
251
- for (const receipt of processing.outcomes) {
252
- if (receipt.acknowledge !== true || receipt.accepted !== true || receipt.cleanup !== "complete") continue;
253
- if (current.s.pending[receipt.key]?.revision === receipt.revision || current.sent.get(receipt.key) === receipt.revision)
254
- current.ack(receipt.key, receipt.revision);
255
- }
256
- }
257
- else if (args.action === "ack") {
258
- const entry = eyes.ackByRef(args.id);
259
- const staleNote = entry?.stale ? " at the presented revision; a newer revision is pending and will re-report" : "";
260
- text = `acknowledged ${clip(entry?.ref ?? args.id, 64)}${staleNote}; ${Object.keys(eyes.s.pending).length} pending change(s) remain`;
261
- }
262
- else if (args.action === "deadline") {
263
- if (typeof args.id !== "string" || !args.id.trim()) throw new Error("Deadline requires an operation id");
264
- eyes.deadline(args.id, args.at, args.revision);
265
- text = `deadline ${args.id} registered for ${new Date(args.at).toISOString()}`;
266
- }
267
- else if (args.action === "cancel") {
268
- if (typeof args.id !== "string" || !args.id.trim()) throw new Error("Cancel requires an operation id");
269
- eyes.cancelDeadline(args.id);
270
- text = `deadline ${args.id} cancelled`;
271
- }
272
- else if (args.action !== "status") throw new Error("Unknown eyes action");
273
- // Do not send a second wake from inside the running model turn. The next
274
- // observation delivers remaining coalesced revisions through the same owner.
275
- if (args.action === "process-reports") {
276
- // The receipt digest is the model-visible surface here: only its
277
- // rendered rows — bound to still-pending exact revisions — become
278
- // presented. An event the receipt does not name still requires a
279
- // visible status or wake before it can be acknowledged.
280
- eyes.markReceiptPresented(processingPresentation(processing));
281
- text = renderProcessing(processing, Object.keys(eyes.s.pending).length);
282
- } else if (text === undefined) text = presentStatus(args.filter);
283
- return { content: [{ type: "text", text }], details: boundedDetails(processing) };
284
- }
285
- });
286
- pi.registerCommand("eyes", { description: "Event-driven HITL observation: start CONFIG | status [FILTER] | ack ID | deadline NAME REVISION EPOCH_MS | cancel NAME | resume quota-verified | retire",
287
- handler: async (args, ctx) => {
288
- try {
289
- if (!eyes) await bind(ctx);
290
- const [command, a, b, ...rest] = args.trim().split(/\s+/);
291
- if (rest.length && command !== "deadline") throw new Error("Too many arguments");
292
- switch (command) {
293
- case "start": {
294
- if (!a || b) throw new Error("Use eyes start CONFIG_JSON");
295
- const config = JSON.parse(fs.readFileSync(path.resolve(ctx.cwd, a), "utf8"));
296
- const current = eyes, generation = bindingGeneration;
297
- clearEvidence(); current.start(config); arm(); await current.tick();
298
- if (current !== eyes || generation !== bindingGeneration) throw new Error("Eyes session changed during start");
299
- break;
300
- }
301
- case "status": ctx.ui?.notify?.(statusText(a), "info"); break;
302
- case "ack": {
303
- // Operator authority: the human just viewed /eyes status and is
304
- // acknowledging the current revision themselves.
305
- const entry = eyes.ackByRef(a, { presentationRequired: false });
306
- const staleNote = entry?.stale ? " at the presented revision; a newer revision is pending and will re-report" : "";
307
- ctx.ui?.notify?.(`acknowledged ${clip(entry?.ref ?? a, 64)}${staleNote}; ${Object.keys(eyes.s.pending).length} pending change(s) remain`, "info");
308
- await eyes.tick(); break;
309
- }
310
- case "deadline":
311
- if (rest.length !== 1) throw new Error("Deadline requires operation identity, revision and epoch milliseconds");
312
- eyes.deadline(a, Number(rest[0]), b); await eyes.tick(); break;
313
- case "cancel": eyes.cancelDeadline(a); break;
314
- case "resume":
315
- if (a !== "quota-verified" || b) throw new Error("Explicit owner verification required: eyes resume quota-verified");
316
- {
317
- const current = eyes, generation = bindingGeneration;
318
- clearEvidence(); await current.resume();
319
- if (current !== eyes || generation !== bindingGeneration) throw new Error("Eyes session changed during resume");
320
- arm();
321
- }
322
- break;
323
- case "retire": eyes.retire(); stopTimer(); break;
324
- default: throw new Error("Unknown eyes command; use start, status, ack, deadline, cancel, resume or retire");
325
- }
326
- } catch (error) {
327
- // Never echo process stdout/stderr: a failed native sync may carry private data.
328
- ctx.ui?.notify?.(`Eyes operation refused (${error.name}); check configuration or /eyes status`, "error");
329
- }
330
- } });
331
- return { active: () => Boolean(eyes?.s.enabled || eyes?.s.retired) };
332
- }