@stage-labs/metro 0.1.0-beta.277 → 0.1.0-beta.279
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/dist/automation.js +56 -0
- package/dist/cli.js +9 -0
- package/package.json +1 -1
- package/runtime/marketplace/plugin/.claude-plugin/plugin.json +1 -1
- package/runtime/node_modules/@metro-labs/core/package.json +2 -0
- package/runtime/node_modules/@metro-labs/core/src/automation-files.ts +216 -0
- package/runtime/node_modules/@metro-labs/core/src/automation-store.ts +171 -0
- package/runtime/node_modules/@metro-labs/core/src/automation-types.ts +141 -0
- package/runtime/node_modules/@metro-labs/daemon/src/boot/boot.ts +1 -0
- package/runtime/node_modules/@metro-labs/daemon/src/stations/runtime-deps.ts +43 -6
- package/runtime/node_modules/@metro-labs/whatsapp/src/client-history.ts +1 -1
- package/runtime/runtime.json +1 -1
- package/runtime/sdk-runner/node_modules/@metro-labs/core/package.json +2 -0
- package/runtime/sdk-runner/node_modules/@metro-labs/core/src/automation-files.ts +216 -0
- package/runtime/sdk-runner/node_modules/@metro-labs/core/src/automation-store.ts +171 -0
- package/runtime/sdk-runner/node_modules/@metro-labs/core/src/automation-types.ts +141 -0
- package/runtime/sdk-runner/runner.json +1 -1
- package/runtime/sdk-runner/src/app.ts +4 -1
- package/runtime/sdk-runner/src/automation-cli.ts +10 -0
- package/runtime/sdk-runner/src/automation-command.ts +151 -0
- package/runtime/sdk-runner/src/automation.ts +145 -0
- package/runtime/sdk-runner/src/inbox.ts +9 -1
- package/runtime/sdk-runner/src/rules.ts +1 -0
- package/runtime/sdk-runner/src/runner.ts +18 -1
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { AutomationStore } from '@metro-labs/core/automation-store';
|
|
2
|
+
import { automationCommandFailure, automationRoot, runAutomationCommand } from './automation-command.js';
|
|
3
|
+
|
|
4
|
+
try {
|
|
5
|
+
const result = await runAutomationCommand(process.argv.slice(2), { store: new AutomationStore(automationRoot()) });
|
|
6
|
+
process.stdout.write(`${JSON.stringify(result)}\n`);
|
|
7
|
+
} catch (err) {
|
|
8
|
+
process.stderr.write(`metro task: ${automationCommandFailure(err)}\n`);
|
|
9
|
+
process.exitCode = 1;
|
|
10
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from 'node:fs';
|
|
2
|
+
import { dirname, join, resolve } from 'node:path';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { AutomationError, automationRequest, assertRoutine, AUTOMATION_PROMPT_MAX } from '@metro-labs/core/automation-types';
|
|
6
|
+
import type { AutomationRequest } from '@metro-labs/core/automation-types';
|
|
7
|
+
import type { AutomationStore } from '@metro-labs/core/automation-store';
|
|
8
|
+
|
|
9
|
+
const HOUR_MS = 3_600_000;
|
|
10
|
+
const SLOT_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/;
|
|
11
|
+
|
|
12
|
+
export class AutomationCommandError extends Error {}
|
|
13
|
+
|
|
14
|
+
export interface AutomationCommandDeps {
|
|
15
|
+
store: Pick<AutomationStore, 'validate' | 'submit' | 'requests' | 'statuses' | 'finish'>;
|
|
16
|
+
now?: () => number;
|
|
17
|
+
readPrompt?: (path: string) => string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function automationShellCommand(args: readonly string[], runtime: { executable?: string; entry?: string } = {}): string {
|
|
21
|
+
const executable = runtime.executable ?? process.execPath;
|
|
22
|
+
const entry = runtime.entry ?? fileURLToPath(new URL('./automation-cli.ts', import.meta.url));
|
|
23
|
+
const quoted = [executable, '--no-install', entry, ...args].map((value) => `'${value.replaceAll("'", "'\\''")}'`);
|
|
24
|
+
return `BUN_RUNTIME_TRANSPILER_CACHE_PATH=0 ${quoted.join(' ')}`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function automationRoot(env: NodeJS.ProcessEnv = process.env): string {
|
|
28
|
+
const home = env.HOME?.trim() ?? '';
|
|
29
|
+
const state = env.METRO_RUNNER_STATE?.trim() ?? '';
|
|
30
|
+
const path = state === '' ? join(home === '' ? homedir() : home, '.metro', 'agent-session.json') : state;
|
|
31
|
+
return join(dirname(path), 'automation');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function regularPromptPath(path: string): string {
|
|
35
|
+
const full = resolve(path);
|
|
36
|
+
let at = full;
|
|
37
|
+
for (;;) {
|
|
38
|
+
const stat = lstatSync(at);
|
|
39
|
+
if (stat.isSymbolicLink() || (at !== full && !stat.isDirectory()))
|
|
40
|
+
throw new AutomationCommandError('prompt file must not use symbolic links');
|
|
41
|
+
const parent = dirname(at);
|
|
42
|
+
if (parent === at) return full;
|
|
43
|
+
at = parent;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function readAutomationPrompt(path: string): string {
|
|
48
|
+
let fd: number | undefined;
|
|
49
|
+
try {
|
|
50
|
+
fd = openSync(regularPromptPath(path), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
51
|
+
const stat = fstatSync(fd);
|
|
52
|
+
if (!stat.isFile() || stat.size > AUTOMATION_PROMPT_MAX)
|
|
53
|
+
throw new AutomationCommandError('prompt must be a regular UTF-8 file of at most 64 KiB');
|
|
54
|
+
const buffer = Buffer.alloc(AUTOMATION_PROMPT_MAX + 1);
|
|
55
|
+
let size = 0;
|
|
56
|
+
while (size < buffer.length) {
|
|
57
|
+
const read = readSync(fd, buffer, size, buffer.length - size, size);
|
|
58
|
+
if (read === 0) break;
|
|
59
|
+
size += read;
|
|
60
|
+
}
|
|
61
|
+
if (size > AUTOMATION_PROMPT_MAX)
|
|
62
|
+
throw new AutomationCommandError('prompt must be a regular UTF-8 file of at most 64 KiB');
|
|
63
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(0, size));
|
|
64
|
+
} catch (err) {
|
|
65
|
+
if (err instanceof AutomationCommandError) throw err;
|
|
66
|
+
throw new AutomationCommandError('cannot read prompt as a regular UTF-8 file without symbolic links');
|
|
67
|
+
} finally {
|
|
68
|
+
if (fd !== undefined) closeSync(fd);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function slotTime(text: string): number {
|
|
73
|
+
const slot = Date.parse(text);
|
|
74
|
+
if (!SLOT_RE.test(text) || !Number.isFinite(slot) || new Date(slot).toISOString() !== text.replace(/:([0-9]{2})Z$/, ':$1.000Z'))
|
|
75
|
+
throw new AutomationCommandError('--slot must be a valid UTC ISO timestamp ending in Z');
|
|
76
|
+
return slot;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function submitFlags(flags: string[]): { slot: number | undefined; dryRun: boolean } {
|
|
80
|
+
let slot: number | undefined;
|
|
81
|
+
let dryRun = false;
|
|
82
|
+
for (let i = 0; i < flags.length; i += 1) {
|
|
83
|
+
const flag = flags[i];
|
|
84
|
+
const value = flags[i + 1];
|
|
85
|
+
if (flag === '--dry-run' && !dryRun) dryRun = true;
|
|
86
|
+
else if (flag === '--slot' && slot === undefined && value !== undefined) {
|
|
87
|
+
slot = slotTime(value);
|
|
88
|
+
i += 1;
|
|
89
|
+
} else throw new AutomationCommandError('invalid or repeated submit option');
|
|
90
|
+
}
|
|
91
|
+
return { slot, dryRun };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function submitOptions(args: string[], now: number): { routine: string; path: string; slot: number; dryRun: boolean } {
|
|
95
|
+
const [routine, path, ...flags] = args;
|
|
96
|
+
if (routine === undefined || path === undefined || path.startsWith('--'))
|
|
97
|
+
throw new AutomationCommandError('submit needs <routine> <prompt-file> [--slot <UTC ISO timestamp>] [--dry-run]');
|
|
98
|
+
assertRoutine(routine);
|
|
99
|
+
const { slot, dryRun } = submitFlags(flags);
|
|
100
|
+
return { routine, path, slot: slot ?? Math.floor(now / HOUR_MS) * HOUR_MS, dryRun };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function metadata(request: AutomationRequest): Omit<AutomationRequest, 'prompt' | 'digest'> {
|
|
104
|
+
return { version: 1, routine: request.routine, slot: request.slot, uuid: request.uuid, createdAt: request.createdAt };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function submitTask(args: string[], deps: AutomationCommandDeps): object {
|
|
108
|
+
const now = (deps.now ?? Date.now)();
|
|
109
|
+
const { routine, path, slot, dryRun } = submitOptions(args, now);
|
|
110
|
+
const prompt = (deps.readPrompt ?? readAutomationPrompt)(path);
|
|
111
|
+
const request = automationRequest(routine, slot, prompt, now);
|
|
112
|
+
deps.store.validate();
|
|
113
|
+
if (dryRun) return { status: 'validated', queued: false, dryRun: true, ...metadata(request) };
|
|
114
|
+
const saved = deps.store.submit(routine, slot, prompt);
|
|
115
|
+
const state = deps.store.statuses().find((status) => status.uuid === saved.uuid)?.state ?? 'pending';
|
|
116
|
+
return { status: 'accepted', queued: state === 'pending', state, ...metadata(saved) };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function taskStatus(args: string[], deps: AutomationCommandDeps): object {
|
|
120
|
+
if (args.length > 1) throw new AutomationCommandError('status accepts only an optional routine');
|
|
121
|
+
const routine = args[0];
|
|
122
|
+
if (routine !== undefined) assertRoutine(routine);
|
|
123
|
+
deps.store.validate();
|
|
124
|
+
const statuses = new Map(deps.store.statuses().map((status) => [status.uuid, status]));
|
|
125
|
+
const tasks = deps.store.requests().filter((request) => routine === undefined || request.routine === routine).map((request) => {
|
|
126
|
+
const status = statuses.get(request.uuid);
|
|
127
|
+
return { ...metadata(request), state: status?.state ?? 'pending', token: status?.token ?? null, updatedAt: status?.updatedAt ?? null, ...(status?.detail === undefined ? {} : { detail: status.detail }) };
|
|
128
|
+
});
|
|
129
|
+
return { tasks };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function finishTask(args: string[], deps: AutomationCommandDeps): object {
|
|
133
|
+
const [uuid, token, outcome] = args;
|
|
134
|
+
if (args.length !== 3 || uuid === undefined || token === undefined || (outcome !== 'completed' && outcome !== 'blocked'))
|
|
135
|
+
throw new AutomationCommandError('finish needs <uuid> <token> completed|blocked');
|
|
136
|
+
const receipt = deps.store.finish(uuid, token, outcome);
|
|
137
|
+
return { status: 'accepted', verification: 'pending', uuid: receipt.uuid, requestedOutcome: receipt.outcome, createdAt: receipt.createdAt };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export async function runAutomationCommand(args: string[], deps: AutomationCommandDeps): Promise<object> {
|
|
141
|
+
const [command, ...rest] = args;
|
|
142
|
+
if (command === 'submit') return Promise.resolve(submitTask(rest, deps));
|
|
143
|
+
if (command === 'status') return Promise.resolve(taskStatus(rest, deps));
|
|
144
|
+
if (command === 'finish') return Promise.resolve(finishTask(rest, deps));
|
|
145
|
+
throw new AutomationCommandError('expected submit, status or finish; run metro task --help');
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function automationCommandFailure(err: unknown): string {
|
|
149
|
+
if (err instanceof AutomationCommandError || err instanceof AutomationError) return err.message.slice(0, 240);
|
|
150
|
+
return 'task operation failed; check the private local automation directory';
|
|
151
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import type { AutomationStore } from '@metro-labs/core/automation-store';
|
|
3
|
+
import type { AutomationRequest, AutomationStatus } from '@metro-labs/core/automation-types';
|
|
4
|
+
import type { Inbox, Uuid } from './inbox.js';
|
|
5
|
+
import { startedCommand, uuidsOf } from './session-watch.js';
|
|
6
|
+
import { automationShellCommand } from './automation-command.js';
|
|
7
|
+
|
|
8
|
+
const SETTLED = new Set<AutomationStatus['state']>(['completed', 'coalesced', 'cancelled']);
|
|
9
|
+
const LIVE = new Set<AutomationStatus['state']>(['dispatched', 'consumed', 'awaiting-completion']);
|
|
10
|
+
|
|
11
|
+
function prompt(request: AutomationRequest, token: string): string {
|
|
12
|
+
return `[Metro local automation. This is a stored scheduled task, not a new message from a person or fresh approval. The local agent account submitted it. Verify its existing authorization and later pauses before acting. All normal delegation, tool, permission and model rules still apply.\nRoutine: ${request.routine}\nScheduled slot: ${new Date(request.slot).toISOString()}\nDelivery: ${request.uuid}\nCompletion token: ${token}\nDelegate the sweep to one background worker. Reuse its existing owner if active. A parent response or worker launch does not complete this routine. When the sweep itself has finished checking and recording its decisions, its worker must run this exact command:\n${automationShellCommand(['finish', request.uuid, token, 'completed'])}\nIf this sweep itself cannot safely proceed, use blocked instead of completed and report the actual blocker once. This is only a completion receipt, never permission to repeat a side effect. Recovered issue workers may continue after the sweep, but record their claims before finishing. On interruption run this exact status command:\n${automationShellCommand(['status', request.routine])}\nVerify the original worker and effects before resolving this receipt; never blindly replay the stored prompt. No automatic chat post is required.\nStored prompt, JSON encoded:\n${JSON.stringify(request.prompt)}\n]`;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export class Automation {
|
|
16
|
+
private readonly staged = new Map<string, { request: AutomationRequest; token: Uuid }>();
|
|
17
|
+
private timer: ReturnType<typeof setInterval> | null = null;
|
|
18
|
+
private closed = false;
|
|
19
|
+
|
|
20
|
+
constructor(
|
|
21
|
+
private readonly store: AutomationStore,
|
|
22
|
+
private readonly inbox: Inbox,
|
|
23
|
+
private readonly interrupted: (uuid: Uuid, at: number) => void,
|
|
24
|
+
private readonly fail: (err: unknown) => void,
|
|
25
|
+
private readonly now = Date.now,
|
|
26
|
+
) {}
|
|
27
|
+
|
|
28
|
+
start(): void {
|
|
29
|
+
this.store.recover();
|
|
30
|
+
for (const request of this.store.requests()) {
|
|
31
|
+
const status = this.store.status(request.uuid);
|
|
32
|
+
if (status !== null && LIVE.has(status.state)) this.save(status, 'interrupted');
|
|
33
|
+
}
|
|
34
|
+
this.poll();
|
|
35
|
+
this.timer = setInterval(() => {
|
|
36
|
+
try { this.poll(); } catch (err) { this.fail(err); }
|
|
37
|
+
}, 5_000);
|
|
38
|
+
this.timer.unref();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
poll(): void {
|
|
42
|
+
if (this.closed) return;
|
|
43
|
+
this.resolve();
|
|
44
|
+
const requests = this.store.requests();
|
|
45
|
+
const statuses = new Map(this.store.statuses().map((status) => [status.uuid, status]));
|
|
46
|
+
for (const request of requests) {
|
|
47
|
+
const status = statuses.get(request.uuid);
|
|
48
|
+
if (status !== undefined && (status.state === 'interrupted' || status.state === 'failed')) this.interrupted(request.uuid, request.createdAt);
|
|
49
|
+
}
|
|
50
|
+
this.admit(requests, statuses);
|
|
51
|
+
this.store.prune();
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
dispatched(uuid: string | undefined): void {
|
|
55
|
+
if (uuid === undefined) return;
|
|
56
|
+
const item = this.staged.get(uuid);
|
|
57
|
+
if (item === undefined) return;
|
|
58
|
+
try {
|
|
59
|
+
this.store.saveStatus({ uuid: item.request.uuid, token: item.token, state: 'dispatched', updatedAt: this.now() });
|
|
60
|
+
this.staged.delete(uuid);
|
|
61
|
+
} catch (err) {
|
|
62
|
+
this.fail(err);
|
|
63
|
+
throw err;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
observe(m: Record<string, unknown>): void {
|
|
68
|
+
if (this.closed || (m.parent_tool_use_id !== undefined && m.parent_tool_use_id !== null)) return;
|
|
69
|
+
const started = startedCommand(m);
|
|
70
|
+
const ids = new Set([...(uuidsOf(m) ?? []), ...(started === null ? [] : [started])]);
|
|
71
|
+
if (ids.size === 0) return;
|
|
72
|
+
for (const request of this.store.requests()) {
|
|
73
|
+
if (!ids.has(request.uuid)) continue;
|
|
74
|
+
const status = this.store.status(request.uuid);
|
|
75
|
+
if (status !== null) this.observeStatus(status, m);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
private observeStatus(status: AutomationStatus, m: Record<string, unknown>): void {
|
|
80
|
+
if (!LIVE.has(status.state)) return;
|
|
81
|
+
if (m.type === 'result') this.save(status, m.is_error !== true && m.subtype === 'success' ? 'awaiting-completion' : 'failed');
|
|
82
|
+
else if (status.state === 'dispatched') this.save(status, 'consumed');
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
close(cancel = false): void {
|
|
86
|
+
if (this.closed && !cancel) return;
|
|
87
|
+
this.closed = true;
|
|
88
|
+
if (this.timer !== null) clearInterval(this.timer);
|
|
89
|
+
this.timer = null;
|
|
90
|
+
if (!cancel) return;
|
|
91
|
+
this.resolve();
|
|
92
|
+
for (const request of this.store.requests()) {
|
|
93
|
+
const status = this.store.status(request.uuid);
|
|
94
|
+
if (status !== null && LIVE.has(status.state)) this.save(status, 'cancelled');
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
private save(status: AutomationStatus, state: AutomationStatus['state']): void {
|
|
99
|
+
this.store.saveStatus({ ...status, state, updatedAt: this.now() });
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
private resolve(): void {
|
|
103
|
+
const statuses = new Map(this.store.statuses().map((status) => [status.uuid, status]));
|
|
104
|
+
for (const receipt of this.store.resolutions()) {
|
|
105
|
+
const status = statuses.get(receipt.uuid);
|
|
106
|
+
if (status === undefined || status.token !== receipt.token) throw new Error('A local automation completion receipt does not match its dispatched task.');
|
|
107
|
+
if (SETTLED.has(status.state)) continue;
|
|
108
|
+
const state = receipt.outcome === 'completed' ? 'completed' : 'failed';
|
|
109
|
+
if (status.state === state) continue;
|
|
110
|
+
this.save(status, state);
|
|
111
|
+
statuses.set(receipt.uuid, { ...status, state });
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
private admit(requests: AutomationRequest[], statuses: ReadonlyMap<string, AutomationStatus>): void {
|
|
116
|
+
const routines = new Map<string, AutomationRequest[]>();
|
|
117
|
+
for (const request of requests) {
|
|
118
|
+
const list = routines.get(request.routine) ?? [];
|
|
119
|
+
list.push(request);
|
|
120
|
+
routines.set(request.routine, list);
|
|
121
|
+
}
|
|
122
|
+
for (const list of routines.values()) {
|
|
123
|
+
if (list.some((request) => this.staged.has(request.uuid))) continue;
|
|
124
|
+
if (list.some((request) => {
|
|
125
|
+
const status = statuses.get(request.uuid);
|
|
126
|
+
return status !== undefined && !SETTLED.has(status.state);
|
|
127
|
+
})) continue;
|
|
128
|
+
const latest = this.coalesce(list, statuses);
|
|
129
|
+
if (latest === null || this.inbox.pending > 0) continue;
|
|
130
|
+
const token = randomUUID();
|
|
131
|
+
this.staged.set(latest.uuid, { request: latest, token });
|
|
132
|
+
this.inbox.automation(prompt(latest, token), latest.uuid, latest.createdAt);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
private coalesce(list: AutomationRequest[], statuses: ReadonlyMap<string, AutomationStatus>): AutomationRequest | null {
|
|
137
|
+
const pending = list.filter((request) => !statuses.has(request.uuid) && request.slot <= this.now()).sort((a, b) => b.slot - a.slot);
|
|
138
|
+
const latest = pending.shift();
|
|
139
|
+
if (latest === undefined) return null;
|
|
140
|
+
const watermark = Math.max(...list.filter((request) => statuses.has(request.uuid)).map((request) => request.slot));
|
|
141
|
+
if (latest.slot <= watermark) pending.push(latest);
|
|
142
|
+
for (const request of pending) this.store.saveStatus({ uuid: request.uuid, token: randomUUID(), state: 'coalesced', updatedAt: this.now() });
|
|
143
|
+
return latest.slot <= watermark ? null : latest;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
@@ -53,13 +53,21 @@ export class Inbox implements AsyncIterable<SDKUserMessage> {
|
|
|
53
53
|
}
|
|
54
54
|
|
|
55
55
|
push(kind: InputKind, text: string, _priority?: Priority, uuid: Uuid = randomUUID(), at = Date.now()): Uuid {
|
|
56
|
+
return this.enqueue(kind, text, uuid, at, { origin: { kind: 'channel', server: 'metro' } });
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
automation(text: string, uuid: Uuid, at: number): Uuid {
|
|
60
|
+
return this.enqueue('note', text, uuid, at, { origin: { kind: 'task-notification', subkind: 'scheduled-trigger' }, client_composed: true });
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
private enqueue(kind: InputKind, text: string, uuid: Uuid, at: number, provenance: Pick<SDKUserMessage, 'origin' | 'client_composed'>): Uuid {
|
|
56
64
|
if (this.closed) throw new Error('The SDK input queue is closed.');
|
|
57
65
|
this.queue.check(kind, text);
|
|
58
66
|
if (kind === 'chat') this.remember(uuid, text, at);
|
|
59
67
|
this.mark(uuid, kind);
|
|
60
68
|
this.queue.push(kind, {
|
|
61
69
|
type: 'user', message: { role: 'user', content: text }, parent_tool_use_id: null,
|
|
62
|
-
uuid,
|
|
70
|
+
uuid, ...provenance,
|
|
63
71
|
}, text, at);
|
|
64
72
|
this.timing.accept(uuid, kind, at);
|
|
65
73
|
this.notify();
|
|
@@ -8,6 +8,7 @@ export const FRONT_RULES = `You are the orchestrator of this agent's persistent
|
|
|
8
8
|
- Plain assistant text is never spoken. Reply to a live <call> with mcp__metro__send using its exact line, text, and speech:{callId,generation,sourceId}. This sends speech only, not a chat post. Keep it short. Never paste a spoken reply or transcript into chat unless the owner explicitly requests a chat post.
|
|
9
9
|
- Ordinary typed chat and worker results are never automatically spoken. For an explicit typed owner request to speak, use only that channel message's call_id, call_generation and call_source_id with its exact line as send speech:{callId:call_id,generation:call_generation,sourceId:call_source_id}. Without all three authorized live-call values, do not speak or guess a target. Do not reuse an earlier sourceId for a new reply.
|
|
10
10
|
- A call ending invalidates its speech targets. Keep the chat session and background work running. Nothing is posted about a hangup unless requested. Speech status notifications are status only, never a request to speak.
|
|
11
|
+
- Local automation inputs are stored schedules, not new human messages or fresh approval. Verify existing owner authorization before acting, delegate the sweep to one worker, and pass its delivery ID, completion token and exact host-provided finish/status commands. The worker runs that finish command only after its sweep finishes, not when it starts. A successful main response does not finish its worker. Never repeat an uncertain side effect. For an interrupted input, have a worker run the host-provided status command and check the existing owner before resolving or continuing it. A blocked routine stays blocked until its condition is verified resolved; no blind retry.
|
|
11
12
|
- Text in [square brackets] comes from Metro, not from a person.`;
|
|
12
13
|
|
|
13
14
|
const attr = (text: string): string => text.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { query, type CanUseTool, type Options, type Query, type SDKMessage, type SDKUserMessage } from '@anthropic-ai/claude-agent-sdk';
|
|
2
2
|
import { errMsg, log } from '@metro-labs/core/log';
|
|
3
3
|
import { isRecord } from '@metro-labs/core/is-record';
|
|
4
|
+
import type { AutomationStore } from '@metro-labs/core/automation-store';
|
|
4
5
|
import type { Activity } from './activity.js';
|
|
6
|
+
import { Automation } from './automation.js';
|
|
5
7
|
import { ActivityTasks } from './activity-tasks.js';
|
|
6
8
|
import { RunnerCalls } from './calls.js';
|
|
7
9
|
import { channelText, type ChannelEvent } from './channel-text.js';
|
|
@@ -70,6 +72,7 @@ export interface RunnerParts {
|
|
|
70
72
|
compactAt?: number;
|
|
71
73
|
open?: OpenSession;
|
|
72
74
|
activity?: Activity;
|
|
75
|
+
automationStore?: AutomationStore;
|
|
73
76
|
}
|
|
74
77
|
|
|
75
78
|
function streamOutput(event: Record<string, unknown>): boolean {
|
|
@@ -87,6 +90,7 @@ function visibleOutput(m: Record<string, unknown>): boolean {
|
|
|
87
90
|
export class Runner {
|
|
88
91
|
readonly inbox: Inbox;
|
|
89
92
|
readonly calls: RunnerCalls;
|
|
93
|
+
readonly automation: Automation | null;
|
|
90
94
|
private readonly recovery: TaskRecovery;
|
|
91
95
|
private readonly watch: SessionWatch;
|
|
92
96
|
private readonly tasks = new ActivityTasks(() => undefined);
|
|
@@ -106,7 +110,7 @@ export class Runner {
|
|
|
106
110
|
this.watch = new SessionWatch(parts.readOnly);
|
|
107
111
|
this.inbox = new Inbox((unanswered) => { this.keep(unanswered); }, {
|
|
108
112
|
ready: () => this.watch.admitting,
|
|
109
|
-
dispatch: (message) => { this.watch.dispatched(message.uuid); },
|
|
113
|
+
dispatch: (message) => { this.automation?.dispatched(message.uuid); this.watch.dispatched(message.uuid); },
|
|
110
114
|
input: (input) => { this.cancelCompact(); parts.activity?.input(input); },
|
|
111
115
|
queue: (count, oldest) => { parts.activity?.pending(count, oldest); },
|
|
112
116
|
});
|
|
@@ -117,6 +121,15 @@ export class Runner {
|
|
|
117
121
|
this.parts.activity?.fail(INTERRUPTED_NOTICE);
|
|
118
122
|
this.close(false);
|
|
119
123
|
}, Date.now, () => { parts.activity?.recovered(); });
|
|
124
|
+
this.automation = parts.automationStore === undefined ? null : new Automation(parts.automationStore, this.inbox, (uuid, at) => {
|
|
125
|
+
if (this.recovery.ledger.snapshot().some((task) => task.id === `input:${uuid}`)) return;
|
|
126
|
+
this.recovery.ledger.interrupted([{ uuid, at, text: '' }], Date.now());
|
|
127
|
+
this.recovery.start();
|
|
128
|
+
}, (err) => {
|
|
129
|
+
log.error({ err: errMsg(err) }, 'sdk-runner: local automation could not be saved');
|
|
130
|
+
this.parts.activity?.fail('Local scheduled work could not be saved. Check metro task status before resuming.');
|
|
131
|
+
this.close(false);
|
|
132
|
+
});
|
|
120
133
|
this.watch.restoreContext(context ?? 0);
|
|
121
134
|
parts.activity?.recover(tasks);
|
|
122
135
|
this.interrupted = interrupted.length;
|
|
@@ -134,6 +147,7 @@ export class Runner {
|
|
|
134
147
|
this.model = options.model ?? null;
|
|
135
148
|
this.queueModel(this.model);
|
|
136
149
|
this.recovery.start();
|
|
150
|
+
this.automation?.start();
|
|
137
151
|
return this.session;
|
|
138
152
|
}
|
|
139
153
|
|
|
@@ -151,6 +165,7 @@ export class Runner {
|
|
|
151
165
|
if (message.type === 'system') this.tasks.observe(message);
|
|
152
166
|
const m: Record<string, unknown> = { ...message };
|
|
153
167
|
this.recovery.observe(m);
|
|
168
|
+
this.automation?.observe(m);
|
|
154
169
|
this.trackInput(m);
|
|
155
170
|
this.watch.observe(m);
|
|
156
171
|
this.note(m);
|
|
@@ -161,6 +176,7 @@ export class Runner {
|
|
|
161
176
|
}
|
|
162
177
|
} finally {
|
|
163
178
|
this.cancelCompact();
|
|
179
|
+
this.automation?.close(false);
|
|
164
180
|
this.recovery.close(false);
|
|
165
181
|
this.ended = true;
|
|
166
182
|
}
|
|
@@ -187,6 +203,7 @@ export class Runner {
|
|
|
187
203
|
this.calls.close();
|
|
188
204
|
try {
|
|
189
205
|
this.recovery.close(cancelActive);
|
|
206
|
+
this.automation?.close(cancelActive);
|
|
190
207
|
} finally {
|
|
191
208
|
this.ended = true;
|
|
192
209
|
this.inbox.close();
|