Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

monitors: watching an already-exited (#393)

Regan Bell6dd77b8587e3
diff --git a/scripts/monitor-smoke.ts b/scripts/monitor-smoke.ts
index 0ba165240..996e1e923 100644
--- a/scripts/monitor-smoke.ts
+++ b/scripts/monitor-smoke.ts
@@ -8,7 +8,7 @@ import { scopeId, type TurnRequest, type TurnResult } from "../src/types.ts";
import { createMemoryProcessRegistry } from "../src/processes/process-registry.ts";
import { createBackgroundBroker } from "../src/connectors/background-exec-broker.ts";
import { createMonitorStore } from "../src/monitors/monitor-store.ts";
-import { createMonitorBroker } from "../src/monitors/monitor-broker.ts";
+import { createMonitorBroker, readBackgroundOutputTail } from "../src/monitors/monitor-broker.ts";
import { createMonitorPoller } from "../src/monitors/monitor-poller.ts";
import { createDeliveryStore } from "../src/delivery/delivery-store.ts";
import { createIdempotencyStore } from "../src/idempotency/idempotency-store.ts";
@@ -64,9 +64,22 @@ const registry = createMemoryProcessRegistry();
const monitors = createMonitorStore();
const deliveries = createDeliveryStore();
const broker = createBackgroundBroker({ sandbox: sb, registry, scopeId: scope, pollMs: 4000, ttlMaxMs: 60 * 60_000 });
+let h: Awaited<ReturnType<typeof sb.provision>> | undefined;
const monitorBroker = createMonitorBroker({
store: monitors,
registry,
+ readOutputTail: async (processId, maxBytes) => {
+ if (!h) return { outputTail: "" };
+ const handle = h;
+ return readBackgroundOutputTail(maxBytes, async (cursor, readMaxBytes) => {
+ const read = await broker.poll(handle, processId, { sinceCursor: cursor, maxBytes: readMaxBytes, waitMs: 0 });
+ return {
+ chunks: read.chunks,
+ cursor: read.cursor,
+ ...(read.status.state === "exited" ? { exitCode: read.status.code } : {}),
+ };
+ });
+ },
scopeId: scope,
owner,
ownerScopeId: scope,
@@ -97,7 +110,6 @@ const poller = createMonitorPoller({
},
});
-let h: Awaited<ReturnType<typeof sb.provision>> | undefined;
try {
console.log(`[${ts()}] provisioning sprite for`, scope, "…");
h = await sb.provision([{ scopeId: scope, mountPath: "", mode: "rw" }]);
@@ -117,6 +129,7 @@ try {
instructions: "Briefly tell the user how the diffusion-model download/generation is going.",
sinceCursor: s.cursor,
});
+ if ("completed" in w) throw new Error(`job already ${w.registryStatus} before watch could be armed`);
ok(!w.reattached, `watch armed (monitor ${w.monitorId}, expires ${new Date(w.expiresAt).toISOString()})`);
console.log(`[${ts()}] polling every 10s until the exit wake (cap 35min) …`);
diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.ts
index cadd8abae..ea4380979 100644
--- a/src/core/orchestrator.ts
+++ b/src/core/orchestrator.ts
@@ -25,7 +25,7 @@ import type { GapPhase, LeaseAttempt, SessionStore } from "../sessions/session-s
import { isOverheardEntry } from "../sessions/session-store.ts";
import { supportsProcessSessions, supportsScopeProfile } from "../sandbox/sandbox.ts";
import { createBackgroundBroker } from "../connectors/background-exec-broker.ts";
-import { createMonitorBroker } from "../monitors/monitor-broker.ts";
+import { createMonitorBroker, readBackgroundOutputTail } from "../monitors/monitor-broker.ts";
import { isPollSurface, isSilentPollReply } from "../triggers/run-trigger.ts";
import { envKey } from "../credentials/connector-token.ts";
import { renderKeychainManifest, type MaterializedEnvCred } from "../credentials/keychain.ts";
@@ -1569,11 +1569,30 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
})
: undefined;
+ const readOutputTail = backgroundBroker
+ ? async (processId: string, maxBytes: number) => {
+ const handle = await provision();
+ return readBackgroundOutputTail(maxBytes, async (cursor, readMaxBytes) => {
+ const read = await backgroundBroker.poll(handle, processId, {
+ sinceCursor: cursor,
+ maxBytes: readMaxBytes,
+ waitMs: 0,
+ });
+ return {
+ chunks: read.chunks,
+ cursor: read.cursor,
+ ...(read.status.state === "exited" ? { exitCode: read.status.code } : {}),
+ };
+ });
+ }
+ : undefined;
+
const monitorBroker =
deps.monitors && deps.processes && supportsProcessSessions(deps.sandbox)
? createMonitorBroker({
store: deps.monitors,
registry: deps.processes,
+ readOutputTail: readOutputTail ?? (async () => ({ outputTail: "" })),
scopeId: memoryScopeId,
owner: actor.id,
ownerScopeId: scopeId,
diff --git a/src/harness/pi-tools.ts b/src/harness/pi-tools.ts
index 778772611..0e5988994 100644
--- a/src/harness/pi-tools.ts
+++ b/src/harness/pi-tools.ts
@@ -1209,6 +1209,20 @@ export function createPiTools(ref: ToolContextRef, opts?: PiToolsOptions): ToolD
...(params.pattern !== undefined ? { pattern: params.pattern } : {}),
...(params.since_cursor !== undefined ? { sinceCursor: params.since_cursor } : {}),
});
+ if ("completed" in r) {
+ const status = `${r.registryStatus}${r.exitCode !== undefined ? ` (code ${r.exitCode})` : ""}`;
+ const result = r.outputTail
+ ? `job already ${status} — no watch armed; here is the tail of its output:\n${r.outputTail}`
+ : `job already ${status} — no watch armed; it produced no output.`;
+ return recordResult(
+ callId,
+ { tool: "background", ...r },
+ {
+ content: [{ type: "text" as const, text: result }],
+ details: r,
+ },
+ );
+ }
const trigger = params.pattern ? `new output matching /${params.pattern}/` : "new output";
return recordResult(
callId,
diff --git a/src/monitors/monitor-broker.ts b/src/monitors/monitor-broker.ts
index 08e7251d2..9bc1df38c 100644
--- a/src/monitors/monitor-broker.ts
+++ b/src/monitors/monitor-broker.ts
@@ -1,14 +1,31 @@
import type { Destination, Monitor, ScopeId } from "../types.ts";
import type { MonitorStore } from "./monitor-store.ts";
-import type { ProcessRegistry } from "../processes/process-registry.ts";
+import type { ProcessRegistry, ProcessStatus } from "../processes/process-registry.ts";
-export interface BackgroundWatchResult {
+export interface BackgroundWatchArmedResult {
monitorId: string;
processId: string;
reattached: boolean;
expiresAt: number;
}
+interface BackgroundWatchCompletedResult {
+ processId: string;
+ completed: true;
+ registryStatus: ProcessStatus;
+ exitCode?: number;
+ outputTail: string;
+ cursor?: number;
+}
+
+export type BackgroundWatchResult = BackgroundWatchArmedResult | BackgroundWatchCompletedResult;
+
+export interface BackgroundOutputTail {
+ outputTail: string;
+ cursor?: number;
+ exitCode?: number;
+}
+
export interface BackgroundUnwatchResult {
monitorId: string;
removed: boolean;
@@ -25,6 +42,33 @@ export interface MonitorBroker {
const EXPIRY_GRACE_MS = 5 * 60_000;
const MAX_PATTERN_CHARS = 256;
+const WATCH_COMPLETED_TAIL_BYTES = 4 * 1024;
+
+export async function readBackgroundOutputTail(
+ maxBytes: number,
+ readNext: (cursor: number, maxBytes: number) => Promise<{ chunks: string; cursor: number; exitCode?: number }>,
+): Promise<BackgroundOutputTail> {
+ let cursor = 0;
+ let outputTail = "";
+ let exitCode: number | undefined;
+ for (;;) {
+ const read = await readNext(cursor, maxBytes);
+ if (read.exitCode !== undefined) exitCode = read.exitCode;
+ if (read.chunks) {
+ const bytes = Buffer.from(outputTail + read.chunks);
+ outputTail =
+ bytes.length > maxBytes ? bytes.subarray(bytes.length - maxBytes).toString("utf8") : bytes.toString("utf8");
+ }
+ if (!read.chunks || read.cursor === cursor) {
+ return {
+ outputTail,
+ cursor: read.cursor,
+ ...(exitCode !== undefined ? { exitCode } : {}),
+ };
+ }
+ cursor = read.cursor;
+ }
+}
export function compileMonitorPattern(pattern: string): (line: string) => boolean {
if (!pattern || pattern.length > MAX_PATTERN_CHARS)
@@ -52,6 +96,7 @@ export function compileMonitorPattern(pattern: string): (line: string) => boolea
export interface MonitorBrokerDeps {
store: MonitorStore;
registry: ProcessRegistry;
+ readOutputTail(processId: string, maxBytes: number): Promise<BackgroundOutputTail>;
scopeId: string;
owner: string;
ownerScopeId: ScopeId;
@@ -69,7 +114,15 @@ export function createMonitorBroker(deps: MonitorBrokerDeps): MonitorBroker {
throw new Error("no such background job to watch");
}
if (rec.status !== "running") {
- throw new Error(`background job already ${rec.status} — nothing left to watch`);
+ const tail = await deps.readOutputTail(processId, WATCH_COMPLETED_TAIL_BYTES);
+ return {
+ processId,
+ completed: true,
+ registryStatus: rec.status,
+ ...(tail.exitCode !== undefined ? { exitCode: tail.exitCode } : {}),
+ outputTail: tail.outputTail,
+ ...(tail.cursor !== undefined ? { cursor: tail.cursor } : {}),
+ };
}
if (opts?.pattern !== undefined) {
try {
diff --git a/test/monitor-broker.test.ts b/test/monitor-broker.test.ts
index c6eec7d67..1a27949c2 100644
--- a/test/monitor-broker.test.ts
+++ b/test/monitor-broker.test.ts
@@ -1,13 +1,20 @@
import { test } from "node:test";
import assert from "node:assert/strict";
-import { createMonitorBroker } from "../src/monitors/monitor-broker.ts";
+import { createMonitorBroker, readBackgroundOutputTail } from "../src/monitors/monitor-broker.ts";
+import type { BackgroundWatchArmedResult, BackgroundWatchResult } from "../src/monitors/monitor-broker.ts";
import { createMonitorStore } from "../src/monitors/monitor-store.ts";
import { createMemoryProcessRegistry } from "../src/processes/process-registry.ts";
import { scopeId } from "../src/types.ts";
const SCOPE = "personal:U1";
+type ReadOutputTail = Parameters<typeof createMonitorBroker>[0]["readOutputTail"];
-async function harness() {
+function armed(r: BackgroundWatchResult): BackgroundWatchArmedResult {
+ if ("completed" in r) assert.fail("expected watch to arm a monitor");
+ return r;
+}
+
+async function harness(readOutputTail: ReadOutputTail = async () => ({ outputTail: "" })) {
const store = createMonitorStore();
const registry = createMemoryProcessRegistry();
const rec = await registry.register({
@@ -20,6 +27,7 @@ async function harness() {
const broker = createMonitorBroker({
store,
registry,
+ readOutputTail,
scopeId: SCOPE,
owner: "U1",
ownerScopeId: scopeId("personal", "U1"),
@@ -32,7 +40,7 @@ async function harness() {
test("watch arms a monitor inheriting the turn's owner, scope, thread, and destination", async () => {
const { broker, store, rec } = await harness();
- const r = await broker.watch("p-1", { instructions: "summarize failures", pattern: "FAIL", sinceCursor: 7 });
+ const r = armed(await broker.watch("p-1", { instructions: "summarize failures", pattern: "FAIL", sinceCursor: 7 }));
assert.equal(r.reattached, false);
assert.equal(r.expiresAt, rec.expiresAt + 1000);
const m = await store.get(r.monitorId);
@@ -48,8 +56,8 @@ test("watch arms a monitor inheriting the turn's owner, scope, thread, and desti
test("watching the same job in the same thread twice reattaches instead of double-arming", async () => {
const { broker, store } = await harness();
- const first = await broker.watch("p-1");
- const second = await broker.watch("p-1");
+ const first = armed(await broker.watch("p-1"));
+ const second = armed(await broker.watch("p-1"));
assert.equal(second.reattached, true);
assert.equal(second.monitorId, first.monitorId);
assert.equal((await store.list()).length, 1);
@@ -57,9 +65,9 @@ test("watching the same job in the same thread twice reattaches instead of doubl
test("a repeat watch re-arms with the new settings instead of silently keeping stale ones", async () => {
const { broker, store } = await harness();
- const first = await broker.watch("p-1", { pattern: "FAIL", instructions: "old", sinceCursor: 5 });
+ const first = armed(await broker.watch("p-1", { pattern: "FAIL", instructions: "old", sinceCursor: 5 }));
await store.advance(first.monitorId, { cursor: 9, tail: "partial" });
- const second = await broker.watch("p-1", { pattern: "ERROR", instructions: "new", sinceCursor: 20 });
+ const second = armed(await broker.watch("p-1", { pattern: "ERROR", instructions: "new", sinceCursor: 20 }));
assert.equal(second.reattached, true);
const m = await store.get(first.monitorId);
assert.equal(m?.pattern, "ERROR");
@@ -74,7 +82,7 @@ test("a repeat watch re-arms with the new settings instead of silently keeping s
assert.equal(after?.cursor, 30);
});
-test("watch refuses a job from another scope, an unknown job, and an exited job", async () => {
+test("watch refuses a job from another scope and an unknown job", async () => {
const { broker, registry } = await harness();
await registry.register({
processId: "p-other",
@@ -85,8 +93,59 @@ test("watch refuses a job from another scope, an unknown job, and an exited job"
});
await assert.rejects(() => broker.watch("p-other"), /no such background job/);
await assert.rejects(() => broker.watch("p-missing"), /no such background job/);
+});
+
+test("watch on an exited job with output returns its final tail without arming a monitor", async () => {
+ const calls: Array<{ processId: string; maxBytes: number }> = [];
+ const { broker, registry, store } = await harness(async (processId, maxBytes) => {
+ calls.push({ processId, maxBytes });
+ return { outputTail: "last lines\nfinished\n", cursor: 8192, exitCode: 0 };
+ });
+ await registry.markStatus("p-1", "exited");
+
+ const r = await broker.watch("p-1");
+
+ assert.deepEqual(r, {
+ processId: "p-1",
+ completed: true,
+ registryStatus: "exited",
+ exitCode: 0,
+ outputTail: "last lines\nfinished\n",
+ cursor: 8192,
+ });
+ assert.deepEqual(calls, [{ processId: "p-1", maxBytes: 4096 }]);
+ assert.equal((await store.list()).length, 0);
+});
+
+test("watch on an exited job with no output returns success without arming a monitor", async () => {
+ const { broker, registry, store } = await harness(async () => ({ outputTail: "", cursor: 0 }));
await registry.markStatus("p-1", "exited");
- await assert.rejects(() => broker.watch("p-1"), /already exited/);
+
+ const r = await broker.watch("p-1");
+
+ assert.deepEqual(r, {
+ processId: "p-1",
+ completed: true,
+ registryStatus: "exited",
+ outputTail: "",
+ cursor: 0,
+ });
+ assert.equal((await store.list()).length, 0);
+});
+
+test("readBackgroundOutputTail scans output and keeps the final bytes", async () => {
+ const output = "abcdefghij";
+
+ const r = await readBackgroundOutputTail(5, async (cursor, maxBytes) => {
+ const next = Math.min(output.length, cursor + maxBytes);
+ return {
+ chunks: output.slice(cursor, next),
+ cursor: next,
+ ...(next === output.length ? { exitCode: 0 } : {}),
+ };
+ });
+
+ assert.deepEqual(r, { outputTail: "fghij", cursor: 10, exitCode: 0 });
});
test("watch rejects an invalid regex pattern up front", async () => {
@@ -99,7 +158,7 @@ test("watch rejects an invalid regex pattern up front", async () => {
test("unwatch removes own monitors only", async () => {
const { broker, store } = await harness();
- const r = await broker.watch("p-1");
+ const r = armed(await broker.watch("p-1"));
const other = await store.create({
owner: "U2",
createdBy: "U2",
diff --git a/test/pi-tools.test.ts b/test/pi-tools.test.ts
index 5e99d0f80..a3fca52ad 100644
--- a/test/pi-tools.test.ts
+++ b/test/pi-tools.test.ts
@@ -1302,6 +1302,39 @@ test("background dispatches each action and emits tool_call/tool_result", async
assert.equal(bg.length, 10);
});
+test("background watch reports an already exited job as a successful tail result", async () => {
+ const textOf = (r: unknown): string => (r as { content: Array<{ text: string }> }).content[0]?.text ?? "";
+ const emitted: Emitted[] = [];
+ const ref: ToolContextRef = {
+ current: {
+ ...fakeToolContext(),
+ async backgroundWatch(processId) {
+ return {
+ processId,
+ completed: true,
+ registryStatus: "exited",
+ exitCode: 0,
+ outputTail: "final line\n",
+ cursor: 42,
+ };
+ },
+ },
+ emit: (e) => {
+ emitted.push(e as Emitted);
+ },
+ scopeLabel: "personal:U1",
+ };
+ const background = createPiTools(ref).find((t) => t.name === "background");
+
+ const watched = textOf(await call(background, { action: "watch", process_id: "bg-1" }));
+
+ assert.match(watched, /job already exited \(code 0\) — no watch armed; here is the tail of its output:/);
+ assert.match(watched, /final line/);
+ const result = emitted.find((e) => e.type === "tool_result")!.payload;
+ assert.equal(result.completed, true);
+ assert.equal(result.error, undefined);
+});
+
test("background per-action validation returns a crisp [error] instead of throwing", async () => {
const textOf = (r: unknown): string => (r as { content: Array<{ text: string }> }).content[0]?.text ?? "";
const background = createPiTools({ current: fakeToolContext() }).find((t) => t.name === "background");