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,457 +1,193 @@
1
- // ace-wake — in-process loop and file-watch wakes for Pi agents.
2
- //
3
- // Named /loop timers and /watch file subscriptions queue a bounded wake
4
- // message to the agent through sendUserMessage only. The agent decides what
5
- // to do after waking; the extension never executes tasks and never depends on
6
- // cron, systemd, or any external heartbeat service. While the agent is busy a
7
- // wake is queued as a follow-up instead of interrupting an in-flight tool
8
- // operation. Definitions persist as session entries, survive compaction, and
9
- // reconcile exactly once per session start, reload, or branch switch.
10
- //
11
- // Commands:
12
- // /loop add NAME --interval SECONDS --message TEXT
13
- // /loop list
14
- // /loop remove NAME
15
- // /watch add NAME --path PATH --message TEXT
16
- // /watch list
17
- // /watch remove NAME
1
+ // Pi is an adapter to the installed ace-watch contract. It owns no wake state.
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { execFile, spawn } from "node:child_process";
5
+ import { promisify } from "node:util";
6
+ const execute = promisify(execFile);
18
7
 
19
- import { clearInterval, setInterval } from "node:timers";
20
- import * as nodePath from "node:path";
21
-
22
- import { registerEyes } from "./wake/eyes-runtime.js";
23
- import { WakeDispatcher } from "./wake/wake-dispatcher.js";
24
- import { parseWakeCommand } from "./wake/wake-command-parser.js";
25
- import { createLoopPort } from "./wake/loop-subscription.js";
26
- import { createWatchPort, nodeReadFn, nodeStatFn, nodeStatfsFn, nodeWatchFactory } from "./wake/watch-subscription.js";
27
- import { armPendingAskWatches, requestsDirFor } from "./wake/ask-bridge.js";
28
- import {
29
- SESSION_ENTRY_TYPE,
30
- WakeError,
31
- boundMessage,
32
- } from "./wake/types.js";
33
- import { WakeRegistry } from "./wake/wake-registry.js";
34
-
35
- const STATUS_KEY = "ace-wake";
36
-
37
- /**
38
- * Extension factory. Pi calls it as `factory(pi)`; the optional second
39
- * argument exists so tests can inject deterministic clock, watcher, and
40
- * stat ports. Production defaults are real Node timers and fs.
41
- *
42
- * All mutable state lives inside this factory closure: one extension runtime
43
- * (one pi process, or one SDK session) owns exactly one state slot, and
44
- * multiple runtimes in one process never share state.
45
- *
46
- * @param {object} pi ExtensionAPI surface provided by Pi.
47
- * @param {object} [ports] Injectable host ports for deterministic tests.
48
- */
49
8
  export default function (pi, ports = {}) {
50
- /** @type {{registry: WakeRegistry} | undefined} */
51
- let runtime;
52
-
53
- /** The ask bridge's own watch port (one per session, replaced on re-bind). */
54
- let askBridgePort;
55
-
56
- let eyes;
57
- const getRuntime = () => runtime;
58
- const bindRuntime = (ctx) => {
59
- runtime?.registry.dispose();
60
- askBridgePort?.stopAll();
61
- runtime = { registry: createRegistry(pi, ctx, ports) };
62
- runtime.registry.reconcile();
63
- askBridgePort = startAskBridge(ctx, ports, runtime.registry);
64
- };
65
-
66
- // Eyes and user subscriptions coexist by contract (8xs.t.pu0.2):
67
- // eyes owns STANDING observation of canonical HITL events, the
68
- // registry owns /loop timers and /watch file subscriptions, and both
69
- // deliver through the same sendUserMessage infrastructure. Eyes never
70
- // rejects /watch (or /loop) add and never removes an active
71
- // subscription — there is no competing observation ownership here.
72
- pi.registerCommand("loop", {
73
- description: "Manage named timer loops that wake this agent (add | list | remove)",
74
- handler: async (args, ctx) => {
75
- await handleCommand(ctx, "loop", args, getRuntime, bindRuntime);
76
- },
77
- });
78
-
79
- pi.registerCommand("watch", {
80
- description: "Manage named file watches that wake this agent (add | list | remove)",
81
- handler: async (args, ctx) => {
82
- await handleCommand(ctx, "watch", args, getRuntime, bindRuntime);
83
- },
84
- });
85
-
86
- // session_start covers startup, reload, resume, fork, and new sessions;
87
- // session_tree covers branch switches. Reconciliation is idempotent, so a
88
- // reload re-registers each configured subscription exactly once.
89
- pi.on("session_start", async (_event, ctx) => {
90
- bindRuntime(ctx);
91
- });
92
- pi.on("session_tree", async (_event, ctx) => {
93
- bindRuntime(ctx);
94
- });
95
-
96
- eyes = registerEyes(pi, ports.eyes);
97
-
98
- // A run has begun: wakes dispatched concurrently during the idle-to-running
99
- // transition can now enter the follow-up queue safely, so the registry
100
- // drains anything it serialized.
101
- pi.on("agent_start", async () => {
102
- runtime?.registry.noteRunStarted();
103
- });
104
-
105
- // The agent consumed every queued continuation; same-source wakes may
106
- // deliver again. Watches whose change was absorbed by a pending wake are
107
- // re-checked so no change is lost without a new filesystem event.
108
- pi.on("agent_settled", async () => {
109
- runtime?.registry.settleAll();
110
- });
111
-
112
- // Manual compaction rejects sendUserMessage asynchronously (before, during,
113
- // and briefly after the compaction events) and never emits agent_settled:
114
- // wakes are retained while it runs and flushed once the context is actually
115
- // idle again. Automatic compaction happens inside a run whose pending wakes
116
- // stay legitimately queued, so it is left untouched.
117
- pi.on("session_before_compact", async (event) => {
118
- if (event.reason === "manual") {
119
- runtime?.registry.pauseDelivery();
120
- }
121
- });
122
- pi.on("session_compact", async (event, ctx) => {
123
- if (event.reason === "manual") {
124
- runtime?.registry.resumeDelivery();
125
- scheduleManualCompactionFlush(ctx);
126
- }
127
- });
128
- pi.on("session_compact_failed", async (event, ctx) => {
129
- if (event.reason === "manual") {
130
- runtime?.registry.resumeDelivery();
131
- scheduleManualCompactionFlush(ctx);
9
+ let current, generation = 0;
10
+ const env = ports.env ?? process.env;
11
+ const executable = ports.executable ?? env.ACE_WATCH_EXECUTABLE ?? "ace-watch";
12
+ const runCLI = ports.runCLI ?? (async (argv, { cwd, input }) => {
13
+ if (input === undefined) {
14
+ const { stdout } = await execute(executable, argv, { cwd, timeout: 130000, maxBuffer: 16 * 1024 * 1024 });
15
+ return JSON.parse(stdout);
132
16
  }
17
+ return new Promise((resolve, reject) => {
18
+ const child = execFile(executable, argv, { cwd, timeout: 130000, maxBuffer: 16 * 1024 * 1024 },
19
+ (error, stdout) => { if (error) reject(new Error("ace-watch state import refused")); else {
20
+ try { resolve(JSON.parse(stdout)); } catch { reject(new Error("Invalid ace-watch response")); }
21
+ } });
22
+ child.stdin.end(JSON.stringify(input));
23
+ });
133
24
  });
134
-
135
- pi.on("session_shutdown", async () => {
136
- runtime?.registry.dispose();
137
- runtime = undefined;
138
- askBridgePort?.stopAll();
139
- askBridgePort = undefined;
140
- });
141
-
142
- /**
143
- * Poll until the host context is genuinely idle (no run, no compaction) and
144
- * then flush retained wakes. A single deferred callback is not enough: other
145
- * session_compact handlers may await asynchronous work while Pi still rejects
146
- * prompts. Bounded polling covers the idle-after-compaction case; a run that
147
- * continues after compaction flushes via agent_settled instead.
148
- */
149
- function scheduleManualCompactionFlush(ctx) {
150
- const pollMs = 100;
151
- // Bound the poll to the session that scheduled it: a rebind or shutdown
152
- // replaces the registry, and the old poll must not flush the new one.
153
- const registry = runtime.registry;
154
- const attempt = () => {
155
- if (runtime?.registry !== registry) {
156
- return;
25
+ const startRunner = ports.startRunner ?? ((argv, options) => spawn(executable, argv,
26
+ { cwd: options.cwd, stdio: ["pipe", "pipe", "pipe"] }));
27
+ const notify = (ctx, text, kind = "info") => ctx.ui?.notify?.(text, kind);
28
+ const busy = scope => scope.running || scope.compacting || !scope.ctx.model ||
29
+ !scope.ctx.isIdle() || scope.ctx.hasPendingMessages();
30
+ const queueBusy = scope => scope.compacting || !scope.ctx.model ||
31
+ (!scope.running && (!scope.ctx.isIdle() || scope.ctx.hasPendingMessages()));
32
+ function invoke(scope, args, { operator = false, present = false, input } = {}) {
33
+ const target = operator ? scope.operator : scope.target;
34
+ const argv = ["--actor", scope.actor, "--target", target, "--json", ...(present ? ["--present"] : []), ...args];
35
+ const result = scope.queue.then(() => runCLI(argv, { cwd: scope.ctx.cwd, input }));
36
+ scope.queue = result.catch(() => {});
37
+ return result.then(value => {
38
+ if (value?.schema !== "ace.watch.result/v1") throw new Error("Incompatible ace-watch CLI; install the matching runtime");
39
+ return value;
40
+ });
41
+ }
42
+ async function readiness(scope) {
43
+ if (scope !== current) return;
44
+ const mode = busy(scope) ? (scope.running && !queueBusy(scope) ? "active" : "busy") : "ready";
45
+ if (scope.lastReadiness === mode) return;
46
+ await invoke(scope, ["delivery", mode]);
47
+ scope.lastReadiness = mode;
48
+ }
49
+ async function deliver(scope, result) {
50
+ for (const event of result.events ?? []) {
51
+ if (scope !== current || (event.kind === "eyes" ? busy(scope) : queueBusy(scope))) {
52
+ await invoke(scope, ["delivery", "reject", event.id]); await readiness(scope); continue;
157
53
  }
158
- let idle;
54
+ scope.attempts.set(event.text, event.id);
159
55
  try {
160
- idle = ctx.isIdle();
56
+ const accepted = await pi.sendUserMessage(event.text, { deliverAs: "followUp" });
57
+ if (accepted === false) {
58
+ scope.attempts.delete(event.text); await invoke(scope, ["delivery", "reject", event.id]);
59
+ }
161
60
  } catch {
162
- return; // Stale context: session_start rebinds.
163
- }
164
- if (idle) {
165
- registry.completeResume();
166
- return;
61
+ await invoke(scope, ["delivery", "uncertain"]);
62
+ notify(scope.ctx, "Wake delivery uncertain; inspect ace-watch eyes status and reconcile before resume", "error");
167
63
  }
168
- const timer = setTimeout(attempt, pollMs);
64
+ }
65
+ }
66
+ async function stop(scope) {
67
+ if (!scope) return;
68
+ clearInterval(scope.readinessTimer);
69
+ scope.child?.stdin?.end();
70
+ if (scope.child) await new Promise(resolve => {
71
+ const timer = setTimeout(() => { scope.child.kill("SIGTERM"); resolve(); }, 3000);
169
72
  timer.unref?.();
170
- };
171
- attempt();
73
+ scope.child.once("exit", () => { clearTimeout(timer); resolve(); });
74
+ if (scope.child.exitCode !== null && scope.child.exitCode !== undefined) { clearTimeout(timer); resolve(); }
75
+ });
76
+ await scope.queue;
172
77
  }
173
- }
174
-
175
- /**
176
- * The ask bridge: consume `ace-hitl ask` wake requests without any agent
177
- * turn activity. The bridge owns a small watch port anchored on the
178
- * session's wake-request folder — or, while that folder does not exist yet
179
- * (a fresh worktree; the first `ask` creates it), on its nearest existing
180
- * ancestor, promoted to the real folder as soon as it appears. Its
181
- * reconcile passes (registration, the delayed registration-gap reconcile,
182
- * folder events — and the poll fallback on unreliable mounts) arm one
183
- * scoped `ask-<case id>` watch per pending request through the registry,
184
- * which owns delivery, coalescing, and persistence for the wakes.
185
- *
186
- * @param {object} ctx Session context (cwd selects the request folder).
187
- * @param {object} ports Injectable host ports (same surface as the registry).
188
- * @param {WakeRegistry} registry
189
- * @returns {{stopAll: () => void}}
190
- */
191
- function startAskBridge(ctx, ports, registry) {
192
- const requestsDir = requestsDirFor(ctx.cwd);
193
- const statFn = ports.statFn ?? nodeStatFn;
194
- const armPass = () => {
195
- try {
196
- armPendingAskWatches({ requestsDir, registry });
197
- } catch {
198
- // Arming must never break the extension host.
199
- }
200
- };
201
- const bridgePort = createWatchPort({
202
- watchFactory: ports.watchFactory ?? nodeWatchFactory,
203
- statFn,
204
- statfsFn: ports.statfsFn ?? nodeStatfsFn,
205
- pollIntervalMs: ports.pollIntervalMs,
206
- baseDir: ctx.cwd,
207
- });
208
- let anchoredTo;
209
- const promote = () => {
210
- if (anchoredTo === requestsDir) {
211
- return;
212
- }
213
- try {
214
- statFn(requestsDir);
215
- } catch {
216
- return; // Still absent: the ancestor anchor remains the channel.
217
- }
218
- bridgePort.stop("__ace_ask_requests");
219
- startAnchor();
220
- // Mirror the registration-gap posture: a request landing between the
221
- // anchor switch and the new watcher's effectiveness re-arms once.
222
- armPass();
223
- };
224
- const onEvent = () => {
225
- armPass();
226
- promote();
227
- return { delivered: true };
228
- };
229
- function startAnchor() {
230
- let candidate = requestsDir;
231
- let attempts = 0;
232
- for (;;) {
233
- try {
234
- statFn(candidate);
235
- break;
236
- } catch {
237
- if (attempts >= 6 || candidate === nodePath.dirname(candidate)) {
238
- return false; // Nothing watchable (synthetic host): arm pass only.
239
- }
240
- attempts += 1;
241
- candidate = nodePath.dirname(candidate);
78
+ async function bind(ctx) {
79
+ const ticket = ++generation;
80
+ const old = current; current = undefined; await stop(old);
81
+ if (ticket !== generation) return;
82
+ const session = ctx.sessionManager.getSessionId?.() ?? `pid-${process.pid}`;
83
+ const configPath = env.ACE_OVERSEER_EYES_CONFIG;
84
+ if (configPath && path.resolve(configPath) !== path.join(path.resolve(ctx.cwd), ".ace-local/overseer/eyes.json"))
85
+ throw new Error("Eyes configuration belongs to another coordinator root");
86
+ const config = configPath ? JSON.parse(fs.readFileSync(configPath, "utf8")) : undefined;
87
+ const actor = config?.recipient ?? `pi-${session}`;
88
+ const scope = { ctx, actor, target: `pi:${session}`, operator: `operator:${session}`,
89
+ queue: Promise.resolve(), attempts: new Map(), running: false, compacting: false };
90
+ current = scope;
91
+ const branch = ctx.sessionManager.getBranch();
92
+ const legacy = kind => [...branch].reverse().find(entry => entry.type === "custom" && entry.customType === kind)?.data;
93
+ await invoke(scope, ["state", "import"], { input: {session, eyes: legacy("ace-wake-eyes"), subscriptions: legacy("ace-wake")} });
94
+ const bound = await invoke(scope, ["delivery", "ready", "--pid", String(process.pid)]);
95
+ await invoke(scope, ["delivery", "busy"]);
96
+ const processBinding = bound.binding && { pid: bound.binding.pid, startedAt: bound.binding.started_at };
97
+ pi.appendEntry("ace-wake-eyes-binding", { ownerCwd: path.resolve(ctx.cwd), process: processBinding,
98
+ actor, statePath: bound.state_path, target: scope.target });
99
+ if (configPath) await invoke(scope, ["eyes", "start", "--config", configPath]);
100
+ if (ticket !== generation) return;
101
+ const child = startRunner(["--actor", actor, "--target", scope.target, "--json", "run", "--attached"], { cwd: ctx.cwd });
102
+ scope.child = child;
103
+ let buffer = "";
104
+ child.stdout.setEncoding("utf8");
105
+ child.stdout.on("data", chunk => {
106
+ buffer += chunk;
107
+ if (buffer.length > 4 * 1024 * 1024) { child.kill("SIGTERM"); return; }
108
+ let end;
109
+ while ((end = buffer.indexOf("\n")) >= 0) {
110
+ const line = buffer.slice(0, end); buffer = buffer.slice(end + 1);
111
+ try { void deliver(scope, JSON.parse(line)).catch(() => {}); }
112
+ catch { notify(ctx, "Invalid ace-watch runner output", "error"); }
242
113
  }
243
- }
244
- try {
245
- bridgePort.start(
246
- { kind: "watch", name: "__ace_ask_requests", path: candidate, message: "" },
247
- onEvent,
248
- );
249
- anchoredTo = candidate;
250
- return true;
251
- } catch {
252
- return false;
253
- }
114
+ });
115
+ child.stderr.on("data", () => {
116
+ if (scope === current) ctx.ui?.setStatus?.("ace-eyes", "wake source degraded; inspect ace-watch status");
117
+ });
118
+ child.on("error", () => notify(ctx, "ace-watch unavailable; install the matching ace-wake gem", "error"));
119
+ child.on("exit", () => { if (scope === current) ctx.ui?.setStatus?.("ace-eyes", "wake runner stopped"); });
120
+ await readiness(scope);
121
+ // Local capability/idle transitions need no model turn. Only a changed
122
+ // readiness value calls the CLI; unchanged ticks perform no subprocess IO.
123
+ scope.readinessTimer = setInterval(() => { void readiness(scope).catch(() => {}); }, 1000);
124
+ scope.readinessTimer.unref?.();
254
125
  }
255
- startAnchor();
256
- // Requests that landed while the session was down arm at startup; the
257
- // port's registration-gap reconcile covers the arming race.
258
- armPass();
259
- return bridgePort;
260
- }
261
-
262
- function createRegistry(pi, ctx, ports) {
263
- const dispatcher = new WakeDispatcher({
264
- deliver: (sourceKey, text) => deliverWake(pi, ctx, sourceKey, text),
126
+ async function ensure(ctx) { if (!current) await bind(ctx); return current; }
127
+ for (const event of ["session_start", "session_tree"]) pi.on(event, async (_event, ctx) => {
128
+ try { await bind(ctx); }
129
+ catch { notify(ctx, "Wake initialization refused; inspect installed ace-watch and actor state", "error"); }
130
+ });
131
+ pi.on("session_shutdown", async () => { generation++; const old = current; current = undefined; await stop(old); });
132
+ pi.on("agent_start", async () => { if (current) { current.running = true; await readiness(current); } });
133
+ pi.on("agent_settled", async () => {
134
+ const scope = current; if (!scope) return;
135
+ scope.running = false; await invoke(scope, ["delivery", "settle"]); scope.lastReadiness = undefined; await readiness(scope);
136
+ });
137
+ pi.on("message_start", async event => {
138
+ const scope = current; if (!scope || event.message?.role !== "user") return;
139
+ const content = event.message.content;
140
+ const text = typeof content === "string" ? content : (content ?? []).filter(row => row.type === "text").map(row => row.text).join("");
141
+ const id = scope.attempts.get(text);
142
+ if (id) { scope.attempts.delete(text); await invoke(scope, ["delivery", "confirm", id]); }
143
+ });
144
+ pi.on("session_before_compact", async event => {
145
+ if (event.reason === "manual" && current) { current.compacting = true; await invoke(current, ["delivery", "suspend"]); }
265
146
  });
266
- /** The registry is created after its watch port, so deactivation hooks go
267
- * through this holder once it exists. */
268
- let registry;
269
- const built = new WakeRegistry({
270
- loops: createLoopPort({
271
- setIntervalFn: ports.setIntervalFn ?? ((callback, ms) => setInterval(callback, ms)),
272
- clearIntervalFn: ports.clearIntervalFn ?? ((handle) => clearInterval(handle)),
273
- }),
274
- watches: createWatchPort({
275
- watchFactory: ports.watchFactory ?? nodeWatchFactory,
276
- statFn: ports.statFn ?? nodeStatFn,
277
- readFn: ports.readFn ?? nodeReadFn,
278
- // Mount classifier for the poll fallback (virtiofs/fuse targets are
279
- // deaf to fs.watch and reconcile on a timer instead); injectable for
280
- // deterministic tests.
281
- statfsFn: ports.statfsFn ?? nodeStatfsFn,
282
- pollIntervalMs: ports.pollIntervalMs,
283
- baseDir: ctx.cwd,
284
- // The report-inbox watch covers every linked worktree's
285
- // .ace-local/hitl by default (the same git worktree discovery
286
- // ace-hitl's list uses); injectable for deterministic tests.
287
- resolveTargets: ports.resolveTargets,
288
- scheduleReconcile: ports.scheduleReconcile,
289
- onDeactivate: () => registry?.refreshStatus(),
290
- }),
291
- state: sessionStatePort(pi, ctx),
292
- status: statusPort(ctx),
293
- dispatcher,
294
- dispatchRecoveryMs: ports.dispatchRecoveryMs,
295
- isHostQueued: () => {
147
+ for (const event of ["session_compact", "session_compact_failed"]) pi.on(event, async () => {
148
+ if (current) { current.compacting = false; await invoke(current, ["delivery", "settle"]); current.lastReadiness = undefined; await readiness(current); }
149
+ });
150
+ pi.on("message_end", async event => {
151
+ if (current && event.message?.role === "assistant" && event.message.stopReason === "error")
152
+ await invoke(current, ["delivery", "quota", "--message", String(event.message.errorMessage ?? "")]);
153
+ });
154
+ for (const kind of ["loop", "watch", "eyes"]) pi.registerCommand(kind, {
155
+ description: `Operate ${kind} through ace-watch; see ace-watch --help`,
156
+ handler: async (raw, ctx) => {
296
157
  try {
297
- return ctx.hasPendingMessages();
298
- } catch {
299
- return true;
300
- }
301
- },
302
- isHostIdle: () => {
303
- try {
304
- return ctx.isIdle();
305
- } catch {
306
- return false;
307
- }
158
+ const scope = await ensure(ctx);
159
+ const resume = kind === "eyes" && /^\s*resume(?:\s|$)/.test(raw);
160
+ const result = await invoke(scope, [kind, "--command-string", raw], { operator: !resume, present: !resume });
161
+ if (resume && result.events.length) await deliver(scope, result);
162
+ else notify(ctx, result.text);
163
+ } catch { notify(ctx, `${kind} refused; inspect ace-watch status or ace-watch --help`, "error"); }
308
164
  },
309
165
  });
310
- registry = built;
311
- return built;
312
- }
313
-
314
- /**
315
- * Queue-only delivery, always as a queued follow-up. Pi runs a follow-up
316
- * immediately when nothing is in flight and queues it behind any active run
317
- * otherwise, so no window — between runs, during a tool, or while earlier
318
- * wakes are queued — can drop a wake or interrupt an in-flight operation.
319
- * The complete rendered message (source prefix included) is bounded.
320
- */
321
- function deliverWake(pi, ctx, sourceKey, text) {
322
- const message = boundMessage(`[ace-wake ${sourceKey}] ${text}`);
323
- try {
324
- // Known synchronous preflight: without a selected model Pi rejects the
325
- // prompt asynchronously and no lifecycle event ever acknowledges it, so
326
- // the wake is refused here and the next tick re-attempts instead of
327
- // coalescing behind a stranded pending marker.
328
- if (!ctx.model) {
329
- return false;
330
- }
331
- pi.sendUserMessage(message, { deliverAs: "followUp" });
332
- return true;
333
- } catch {
334
- // A stale context (session replaced/reloaded) or a rejecting host must
335
- // not crash the timer callback; the next session_start rebinds.
336
- return false;
337
- }
338
- }
339
-
340
- function sessionStatePort(pi, ctx) {
341
- return {
342
- load() {
343
- let snapshot;
344
- for (const entry of ctx.sessionManager.getBranch()) {
345
- if (entry.type === "custom" && entry.customType === SESSION_ENTRY_TYPE && entry.data) {
346
- snapshot = entry.data;
347
- }
348
- }
349
- // getBranch() returns the stored entries themselves; cloning keeps
350
- // registry mutations from rewriting historical session entries, which
351
- // would leak later edits back into branched-away history.
352
- return snapshot ? structuredClone(snapshot) : { loops: [], watches: [] };
353
- },
354
- save(snapshot) {
355
- pi.appendEntry(SESSION_ENTRY_TYPE, snapshot);
356
- },
357
- };
358
- }
359
-
360
- function statusPort(ctx) {
361
- return {
362
- render(entries) {
166
+ pi.registerTool?.({ name: "ace_eyes", label: "Eyes observation",
167
+ description: "Operate the installed ace-watch Eyes owner. Status is compact. ACK uses only revisions presented to this model session. Observation starts no model.",
168
+ parameters: { type: "object", properties: {
169
+ action: { type: "string", enum: ["start", "observe", "status", "ack", "process-reports", "deadline", "cancel", "resume", "retire"] },
170
+ configPath: { type: "string" }, id: { type: "string" }, filter: { type: "string" },
171
+ revision: { type: "string" }, at: { type: "integer" }, quotaVerified: { type: "boolean" },
172
+ }, required: ["action"], additionalProperties: false },
173
+ execute: async (_id, args, _signal, _onUpdate, ctx) => {
174
+ const scope = await ensure(ctx);
175
+ const argv = ["eyes", args.action];
176
+ if (args.action === "start") argv.push("--config", args.configPath ?? "");
177
+ if (["ack", "cancel"].includes(args.action)) argv.push(args.id ?? "");
178
+ if (args.action === "status" && args.filter) argv.push(args.filter);
179
+ if (args.action === "deadline") argv.push(args.id ?? "", args.revision ?? "", String(args.at));
180
+ if (args.action === "resume" && args.quotaVerified) argv.push("--quota-verified");
181
+ let result;
363
182
  try {
364
- // Every context access — including hasUI — throws once the context
365
- // is stale after session replacement, reload, or disposal.
366
- if (!ctx.hasUI) {
367
- return;
368
- }
369
- if (entries.length === 0) {
370
- ctx.ui.setStatus(STATUS_KEY, undefined);
371
- return;
372
- }
373
- const parts = entries.map((entry) => {
374
- const state = entry.error ? " error" : entry.pending ? " pending" : "";
375
- return `${entry.kind} ${entry.name}${state} ${entry.detail}`;
376
- });
377
- ctx.ui.setStatus(STATUS_KEY, parts.join(" | "));
378
- } catch {
379
- // Stale context: skip the render; the next session_start rebinds.
380
- }
183
+ result = await invoke(scope, argv, { present: true });
184
+ } catch { throw new Error("Eyes operation refused; inspect ace-watch eyes status and its existing owner"); }
185
+ return { content: [{ type: "text", text: result.text }], details: {
186
+ ...result.summary,
187
+ sourceHealth: { ok: Object.values(result.sources ?? {}).filter(row => row.status === "ok").length,
188
+ degraded: Object.values(result.sources ?? {}).filter(row => row.status !== "ok").length },
189
+ ...(result.processing ? { processing: result.processing } : {}),
190
+ } };
381
191
  },
382
- };
383
- }
384
-
385
- async function handleCommand(ctx, kind, args, getRuntime, bindRuntime) {
386
- try {
387
- if (!getRuntime()) {
388
- bindRuntime(ctx);
389
- }
390
- const registry = getRuntime().registry;
391
- const parsed = parseWakeCommand(kind, args);
392
- switch (parsed.subcommand) {
393
- case "add":
394
- addSubscription(registry, kind, parsed);
395
- notify(ctx, `${kind} "${parsed.name}" added`, "info");
396
- break;
397
- case "list":
398
- notify(ctx, formatList(kind, registry.list()), "info");
399
- break;
400
- case "remove":
401
- removeSubscription(registry, kind, parsed.name);
402
- notify(ctx, `${kind} "${parsed.name}" removed; no further wakes will fire`, "info");
403
- break;
404
- default:
405
- throw new WakeError(`unknown ${kind} subcommand: ${parsed.subcommand}`);
406
- }
407
- } catch (error) {
408
- notify(ctx, error instanceof WakeError ? error.message : `${kind} failed: ${error.message}`, "error");
409
- }
410
- }
411
-
412
- function addSubscription(registry, kind, parsed) {
413
- if (kind === "loop") {
414
- registry.addLoop({
415
- name: parsed.name,
416
- intervalSeconds: parsed.flags.interval,
417
- message: parsed.message,
418
- });
419
- return;
420
- }
421
- registry.addWatch({
422
- name: parsed.name,
423
- path: parsed.flags.path,
424
- message: parsed.message,
425
192
  });
426
193
  }
427
-
428
- function removeSubscription(registry, kind, name) {
429
- if (kind === "loop") {
430
- registry.removeLoop(name);
431
- return;
432
- }
433
- registry.removeWatch(name);
434
- }
435
-
436
- /**
437
- * @returns {string}
438
- */
439
- function formatList(kind, entries) {
440
- const plural = kind === "watch" ? "watches" : `${kind}s`;
441
- const scoped = entries.filter((entry) => entry.kind === kind);
442
- if (scoped.length === 0) {
443
- return `no ${plural} configured`;
444
- }
445
- return scoped
446
- .map((entry) => {
447
- const state = entry.error ? ` ERROR: ${entry.error}` : entry.pending ? " (wake pending)" : "";
448
- return `${entry.name} — ${entry.detail}${state}`;
449
- })
450
- .join("\n");
451
- }
452
-
453
- function notify(ctx, message, type) {
454
- if (ctx.hasUI) {
455
- ctx.ui.notify(message, type);
456
- }
457
- }