ace-wake 0.4.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,276 +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
-
7
- const execute = promisify(execFile);
8
- export const EYES_BINDING = "ace-wake-eyes-binding";
9
-
10
- // Birth identity is immutable for this process. Probe once at session binding,
11
- // never during observation polling. Darwin uses the same native libproc owner
12
- // as the Ruby readiness reader; second-resolution ps timestamps are insufficient.
13
- let ownIdentity;
14
- export function eyesProcessIdentity() {
15
- if (ownIdentity === undefined) ownIdentity = readEyesProcessIdentity();
16
- return ownIdentity;
17
- }
18
-
19
- export function readEyesProcessIdentity({ platform = process.platform, pid = process.pid,
20
- readFile = fs.readFileSync, run = execFileSync } = {}) {
21
- try {
22
- if (platform === "darwin") {
23
- const birth = run("ruby", ["-r", "ace/runtime/molecules/process_identity", "-e",
24
- "print Ace::Runtime::Molecules::ProcessIdentity.new.native_birth(Integer(ARGV.fetch(0)))", String(pid)],
25
- { encoding: "utf8", timeout: 2000, killSignal: "SIGKILL", maxBuffer: 1024, stdio: ["ignore", "pipe", "pipe"] }).trim();
26
- return /^darwin:[1-9][0-9]*:[0-9]{1,6}$/.test(birth) ? { pid, startedAt: birth } : null;
27
- }
28
- if (platform !== "linux") return null;
29
- const stat = readFile(`/proc/${pid}/stat`, "utf8");
30
- const end = stat.lastIndexOf(") ");
31
- if (end < 0) return null;
32
- const ticks = stat.slice(end + 2).trim().split(/\s+/)[19];
33
- const boot = readFile("/proc/sys/kernel/random/boot_id", "utf8").trim();
34
- if (!/^[1-9][0-9]*$/.test(ticks) || !/^[0-9a-f-]{36}$/.test(boot)) return null;
35
- return { pid, startedAt: `linux:${boot}:${ticks}` };
36
- } catch { return null; }
37
- }
38
-
39
- /** Existing native sync owns canonical import; HITL owns event projection.
40
- * No Ruby parsing, private text, shell command strings or model work here. */
41
- export async function observeHitl(cwd, config) {
42
- const options = { cwd, timeout: config.timeoutMs, maxBuffer: 1024 * 1024, encoding: "utf8" };
43
- for (const source of config.syncRoutes) {
44
- // One source per project: each entry names the project hitl config and,
45
- // when several hermes_native routes exist there, the route to reconcile.
46
- const argv = ["sync", "--config", source.config];
47
- if (source.route !== undefined) argv.push("--route", source.route);
48
- const { stdout } = await execute("ace-hitl-hermes", argv, options);
49
- const result = JSON.parse(stdout);
50
- if (!Array.isArray(result.errors) || result.errors.length) throw new Error("Native synchronization incomplete");
51
- }
52
- const { stdout } = await execute("ace-overseer", ["observe", "--owner", config.recipient, "--scope", config.scope, "--limit", String(config.maxEvents)], options);
53
- const result = JSON.parse(stdout);
54
- if (!result?.sources || typeof result.sources !== "object" || Array.isArray(result.sources) ||
55
- Object.keys(result.sources).length === 0) throw new Error("Observation source health is missing");
56
- return result;
57
- }
58
-
59
- export async function processReports(cwd, config, signal) {
60
- const { stdout } = await execute("ace-overseer", ["process-reports", "--json",
61
- "--owner", config.recipient, "--scope", config.scope],
62
- { cwd, signal, maxBuffer: 8 * 1024 * 1024, encoding: "utf8" });
63
- const result = JSON.parse(stdout);
64
- if (!Array.isArray(result?.outcomes) || result.dry_run !== false)
65
- throw new Error("Invalid report-processing receipt");
66
- return result;
67
- }
68
-
69
- export function registerEyes(pi, { observe = observeHitl, processReports: processReportOwner = processReports, env = process.env, now = Date.now,
70
- schedule = (fn, ms) => setInterval(fn, ms), cancel = clearInterval, processIdentity = eyesProcessIdentity } = {}) {
71
- let eyes, timer, attempt, observedSources, observedAt, bindingGeneration = 0, compacting = false, running = false, arming = false;
72
- const clearEvidence = () => { observedSources = undefined; observedAt = undefined; };
73
- const stopTimer = () => { if (timer !== undefined) cancel(timer); timer = undefined; };
74
- function arm() {
75
- stopTimer();
76
- if (eyes?.s.enabled && !eyes.s.retired && !eyes.s.breaker) {
77
- timer = schedule(() => { void eyes.tick({ scheduled: true }); },
78
- eyes.s.config.intervalSeconds * 1000);
79
- timer?.unref?.();
80
- }
81
- }
82
- const bind = async (ctx) => {
83
- const generation = ++bindingGeneration;
84
- stopTimer(); eyes?.dispose(); attempt = undefined; clearEvidence(); compacting = false; running = false;
85
- const entries = ctx.sessionManager.getBranch();
86
- const snapshot = [...entries].reverse().find((e) => e.type === "custom" && e.customType === EYES_ENTRY)?.data;
87
- const ownerCwd = path.resolve(ctx.cwd);
88
- if (snapshot?.ownerCwd && snapshot.ownerCwd !== ownerCwd) {
89
- eyes = undefined;
90
- ctx.ui?.setStatus?.("ace-eyes", "eyes blocked: session belongs to another project cwd");
91
- throw new Error("Eyes project owner mismatch; preserve this actor and use its original project session");
92
- }
93
- const identity = processIdentity();
94
- pi.appendEntry(EYES_BINDING, { ownerCwd, process: identity });
95
- eyes = new Eyes({ snapshot, now,
96
- save: (data) => {
97
- const entries = observedSources && typeof observedSources === "object" && !Array.isArray(observedSources) ? Object.entries(observedSources) : [];
98
- const valid = entries.length > 0 && entries.length <= 64 && entries.every(([name, source]) =>
99
- /^[a-zA-Z0-9_.:-]{1,128}$/.test(name) && source && ["ok", "degraded"].includes(source.status));
100
- const sources = valid ? Object.fromEntries(entries.map(([name, source]) => [name, source.status]).sort()) : {};
101
- pi.appendEntry(EYES_ENTRY, { ...data, ownerCwd, observerEvidence: {
102
- process: identity, observedAt: observedAt ?? null, sources
103
- } });
104
- },
105
- status: (state) => {
106
- 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}`);
107
- if (state.breaker || state.retired) stopTimer();
108
- },
109
- observe: (config) => observe(ctx.cwd, config),
110
- // A result is evidence only after Eyes validated it and confirmed that
111
- // the observer generation is still current.
112
- onObserved: (result) => {
113
- if (generation === bindingGeneration) { observedSources = result.sources; observedAt = now(); }
114
- },
115
- onObservationUnavailable: () => {
116
- if (generation === bindingGeneration) clearEvidence();
117
- },
118
- // Do not queue a follow-up while the current turn can still handle and
119
- // acknowledge the same revision. Polling retains it until the agent is
120
- // idle; already handled changes then require no extra model turn. Unlike
121
- // eyes revisions, loop/watch messages cannot be acknowledged this way.
122
- canDeliver: () => !arming && !compacting && !running && ctx.isIdle() && !ctx.hasPendingMessages(),
123
- deliveryStatus: () => {
124
- if (attempt?.accepted) return "accepted";
125
- // sendUserMessage is a void wrapper. Busy/queued is uncertain, not
126
- // acceptance or rejection. Idle without confirmation is uncertain:
127
- // async input/auth preflight may still be running, so never blind-retry.
128
- return compacting || !ctx.isIdle() || ctx.hasPendingMessages() ? "waiting" : "uncertain";
129
- },
130
- deliver: async (batch) => {
131
- if (!ctx.model) return false;
132
- const text = `[ace-eyes] Pending task/assignment/HITL/deadline revisions: ${JSON.stringify(batch)}. ` +
133
- "Read the original state owners. For reports use ace_eyes action process-reports; it accepts, continues and acknowledges exact completed revisions. " +
134
- "Reconcile uncertain effects; never repeat external actions on wake alone. For other event types, after handling each exact revision, " +
135
- "acknowledge with the ace_eyes tool (action ack, key, revision). Settlement alone is not acknowledgement.";
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
- return submitted !== false;
144
- } });
145
- const configPath = env.ACE_OVERSEER_EYES_CONFIG;
146
- if (configPath) {
147
- const expected = path.join(ownerCwd, ".ace-local/overseer/eyes.json");
148
- if (path.resolve(configPath) !== expected) throw new Error("Eyes config does not belong to this coordinator root");
149
- eyes.start(JSON.parse(fs.readFileSync(configPath, "utf8")));
150
- }
151
- arm();
152
- if (eyes.s.enabled && configPath) {
153
- arming = true;
154
- try { await eyes.tick(); } finally { arming = false; }
155
- } else if (eyes.s.enabled) void eyes.tick();
156
- };
157
- pi.on("session_start", async (_event, ctx) => bind(ctx));
158
- pi.on("session_tree", async (_event, ctx) => bind(ctx));
159
- pi.on("agent_start", async () => { running = true; });
160
- pi.on("agent_settled", async () => { running = false; eyes?.persist(); });
161
- pi.on("message_start", async (event) => {
162
- if (event.message?.role !== "user" || !attempt) return;
163
- const text = typeof event.message.content === "string" ? event.message.content :
164
- (event.message.content || []).filter(part => part.type === "text").map(part => part.text).join("");
165
- if (text === attempt.text) attempt.accepted = true;
166
- });
167
- pi.on("session_before_compact", async (event) => { if (event.reason === "manual") compacting = true; });
168
- pi.on("session_compact", async () => { compacting = false; eyes?.persist(); });
169
- pi.on("session_compact_failed", async () => { compacting = false; });
170
- pi.on("session_shutdown", async () => {
171
- bindingGeneration++; stopTimer(); clearEvidence();
172
- eyes?.persist(); eyes?.dispose(); eyes = undefined;
173
- });
174
- pi.on("message_end", async (event) => {
175
- const message = event.message;
176
- if (message?.role === "assistant" && message.stopReason === "error") eyes?.quota(message.errorMessage);
177
- });
178
- pi.registerTool?.({
179
- name: "ace_eyes", label: "Eyes observation", description: "Start standing observation with an existing config file, read pending semantic events or acknowledge an exact handled revision. 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 identity and revision; cancel when no longer active.",
180
- parameters: { type: "object", properties: {
181
- action: { type: "string", enum: ["start", "status", "process-reports", "ack", "deadline", "cancel"] },
182
- configPath: { type: "string" },
183
- key: { type: "string" }, revision: { type: "string" },
184
- 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." }
185
- }, required: ["action"], additionalProperties: false },
186
- execute: async (_id, args, _signal, _onUpdate, ctx) => {
187
- if (!eyes) {
188
- if (!ctx) throw new Error("Eyes session not initialized");
189
- await bind(ctx);
190
- }
191
- let processing;
192
- if (args.action === "start") {
193
- if (!ctx || typeof args.configPath !== "string" || !args.configPath.trim()) {
194
- throw new Error("Eyes start requires configPath and the current session context");
195
- }
196
- const config = JSON.parse(fs.readFileSync(path.resolve(ctx.cwd, args.configPath), "utf8"));
197
- const current = eyes, generation = bindingGeneration;
198
- clearEvidence(); current.start(config); arm();
199
- // Observe now, but do not enqueue a redundant model turn inside the
200
- // caller's turn. Pending revisions are returned to the caller below.
201
- arming = true;
202
- try { await current.tick(); } finally { if (current === eyes && generation === bindingGeneration) arming = false; }
203
- if (current !== eyes || generation !== bindingGeneration) throw new Error("Eyes session changed during start");
204
- }
205
- else if (args.action === "process-reports") {
206
- if (!ctx || !eyes.s.enabled) throw new Error("Report processing requires active eyes in this session");
207
- const sources = observedSources && Object.values(observedSources);
208
- const config = eyes.s.config;
209
- const interval = config.intervalSeconds * 1000;
210
- const cadence = Math.ceil(3600000 / (config.maxObservationsPerHour * interval)) * interval;
211
- if (eyes.s.breaker || eyes.s.observationUnavailable || !sources?.length ||
212
- sources.some(source => source.status !== "ok") || observedAt === undefined ||
213
- now() - observedAt > cadence + config.timeoutMs)
214
- throw new Error("Report processing blocked: required observation is unavailable, degraded or stale");
215
- const current = eyes, generation = bindingGeneration;
216
- processing = await processReportOwner(ctx.cwd, current.s.config, _signal);
217
- if (current !== eyes || generation !== bindingGeneration)
218
- throw new Error("Eyes session changed during report processing; retained receipts require reconciliation");
219
- if (!Array.isArray(processing?.outcomes) || processing.dry_run !== false)
220
- throw new Error("Invalid report-processing receipt");
221
- for (const receipt of processing.outcomes) {
222
- if (receipt.acknowledge !== true || receipt.accepted !== true || receipt.cleanup !== "complete") continue;
223
- if (current.s.pending[receipt.key]?.revision === receipt.revision || current.sent.get(receipt.key) === receipt.revision)
224
- current.ack(receipt.key, receipt.revision);
225
- }
226
- }
227
- else if (args.action === "ack") eyes.ack(args.key, args.revision);
228
- else if (args.action === "deadline") eyes.deadline(args.key, args.at, args.revision);
229
- else if (args.action === "cancel") eyes.cancelDeadline(args.key);
230
- else if (args.action !== "status") throw new Error("Unknown eyes action");
231
- // Do not send a second wake from inside the running model turn. The next
232
- // observation delivers remaining coalesced revisions through the same owner.
233
- const details = { ...eyes.summary(), ...(processing ? { processing } : {}), sources: observedSources, pending: eyes.s.pending, deadlines: eyes.s.deadlines };
234
- return { content: [{ type: "text", text: JSON.stringify(details) }], details };
235
- }
236
- });
237
- pi.registerCommand("eyes", { description: "Event-driven HITL observation: start CONFIG | status | ack KEY REV | deadline NAME REVISION EPOCH_MS | cancel NAME | resume quota-verified | retire",
238
- handler: async (args, ctx) => {
239
- try {
240
- if (!eyes) await bind(ctx);
241
- const [command, a, b, ...rest] = args.trim().split(/\s+/);
242
- if (rest.length && command !== "deadline") throw new Error("Too many arguments");
243
- switch (command) {
244
- case "start": {
245
- if (!a || b) throw new Error("Use eyes start CONFIG_JSON");
246
- const config = JSON.parse(fs.readFileSync(path.resolve(ctx.cwd, a), "utf8"));
247
- const current = eyes, generation = bindingGeneration;
248
- clearEvidence(); current.start(config); arm(); await current.tick();
249
- if (current !== eyes || generation !== bindingGeneration) throw new Error("Eyes session changed during start");
250
- break;
251
- }
252
- case "status": ctx.ui?.notify?.(JSON.stringify({ ...eyes.summary(), pending: eyes.s.pending, deadlines: eyes.s.deadlines }), "info"); break;
253
- case "ack": eyes.ack(a, b); await eyes.tick(); break;
254
- case "deadline":
255
- if (rest.length !== 1) throw new Error("Deadline requires operation identity, revision and epoch milliseconds");
256
- eyes.deadline(a, Number(rest[0]), b); await eyes.tick(); break;
257
- case "cancel": eyes.cancelDeadline(a); break;
258
- case "resume":
259
- if (a !== "quota-verified" || b) throw new Error("Explicit owner verification required: eyes resume quota-verified");
260
- {
261
- const current = eyes, generation = bindingGeneration;
262
- clearEvidence(); await current.resume();
263
- if (current !== eyes || generation !== bindingGeneration) throw new Error("Eyes session changed during resume");
264
- arm();
265
- }
266
- break;
267
- case "retire": eyes.retire(); stopTimer(); break;
268
- default: throw new Error("Unknown eyes command; use start, status, ack, deadline, cancel, resume or retire");
269
- }
270
- } catch (error) {
271
- // Never echo process stdout/stderr: a failed native sync may carry private data.
272
- ctx.ui?.notify?.(`Eyes operation refused (${error.name}); check configuration or /eyes status`, "error");
273
- }
274
- } });
275
- return { active: () => Boolean(eyes?.s.enabled || eyes?.s.retired) };
276
- }