pi-suite 0.0.0-stage → 0.3.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.
- package/LICENSE +21 -0
- package/README.md +100 -2
- package/README.zh-CN.md +101 -0
- package/package.json +63 -4
- package/skills/pi-suite-jobs/SKILL.md +76 -0
- package/skills/pi-suite-workflow/SKILL.md +114 -0
- package/src/agents/catalog.ts +80 -0
- package/src/agents/child.ts +79 -0
- package/src/agents/commands.ts +17 -0
- package/src/agents/defaults.ts +78 -0
- package/src/agents/history.ts +112 -0
- package/src/agents/index.ts +211 -0
- package/src/agents/manager.ts +438 -0
- package/src/agents/mentions/clone.ts +51 -0
- package/src/agents/mentions/grammar.ts +64 -0
- package/src/agents/mentions/index.ts +76 -0
- package/src/agents/mentions/provider.ts +79 -0
- package/src/agents/model-editor.ts +95 -0
- package/src/agents/models.ts +43 -0
- package/src/agents/output/schema.ts +101 -0
- package/src/agents/output/tool.ts +98 -0
- package/src/agents/parent.ts +13 -0
- package/src/agents/questions.ts +63 -0
- package/src/agents/records.ts +90 -0
- package/src/agents/registry.ts +20 -0
- package/src/agents/render.ts +85 -0
- package/src/agents/resources/context.ts +48 -0
- package/src/agents/resources/loader.ts +86 -0
- package/src/agents/resources/memory.ts +67 -0
- package/src/agents/resources/packages.ts +96 -0
- package/src/agents/resources/paths.ts +8 -0
- package/src/agents/resources/prompts.ts +11 -0
- package/src/agents/resources/scope.ts +147 -0
- package/src/agents/resources/selectors.ts +186 -0
- package/src/agents/retry.ts +20 -0
- package/src/agents/rpc/handlers.ts +62 -0
- package/src/agents/rpc/index.ts +73 -0
- package/src/agents/rpc/options.ts +44 -0
- package/src/agents/run-groups.ts +16 -0
- package/src/agents/runner.ts +131 -0
- package/src/agents/runtime.ts +40 -0
- package/src/agents/schedules/index.ts +136 -0
- package/src/agents/schedules/menu.ts +38 -0
- package/src/agents/schedules/parse.ts +42 -0
- package/src/agents/schedules/store.ts +78 -0
- package/src/agents/schema.ts +5 -0
- package/src/agents/session.ts +29 -0
- package/src/agents/tools.ts +177 -0
- package/src/agents/types.ts +87 -0
- package/src/agents/ui/index.ts +42 -0
- package/src/agents/ui/runs.ts +122 -0
- package/src/agents/ui/types.ts +91 -0
- package/src/agents/viewer-info.ts +36 -0
- package/src/agents/viewer.ts +160 -0
- package/src/agents/workflow/collisions.ts +124 -0
- package/src/agents/workflow/entry.ts +93 -0
- package/src/agents/workflow/host.ts +119 -0
- package/src/agents/workflow/index.ts +100 -0
- package/src/agents/workflow/journal.ts +147 -0
- package/src/agents/workflow/literal.ts +57 -0
- package/src/agents/workflow/manager.ts +169 -0
- package/src/agents/workflow/meta.ts +323 -0
- package/src/agents/workflow/progress/format.ts +184 -0
- package/src/agents/workflow/progress/index.ts +3 -0
- package/src/agents/workflow/progress/model.ts +224 -0
- package/src/agents/workflow/progress/types.ts +144 -0
- package/src/agents/workflow/render.ts +46 -0
- package/src/agents/workflow/runtime/helpers.ts +236 -0
- package/src/agents/workflow/runtime/index.ts +3 -0
- package/src/agents/workflow/runtime/run.ts +646 -0
- package/src/agents/workflow/runtime/types.ts +273 -0
- package/src/agents/workflow/saved.ts +74 -0
- package/src/agents/workflow/store.ts +23 -0
- package/src/agents/workflow/task.ts +277 -0
- package/src/agents/workflow/tool-description.ts +32 -0
- package/src/agents/workflow/tools.ts +66 -0
- package/src/agents/workflow/ui/menu.ts +144 -0
- package/src/agents/workflow/ui/progress.ts +91 -0
- package/src/agents/workflow/worker/bootstrap.ts +316 -0
- package/src/agents/workflow/worker/flow.ts +218 -0
- package/src/agents/workflow/worker/index.ts +7 -0
- package/src/agents/workflow/worker/scope.ts +215 -0
- package/src/ask/.gitkeep +0 -0
- package/src/ask/form.ts +67 -0
- package/src/ask/index.ts +73 -0
- package/src/ask/keys.ts +32 -0
- package/src/ask/layout.ts +78 -0
- package/src/ask/queue.ts +40 -0
- package/src/ask/render.ts +62 -0
- package/src/ask/result.ts +56 -0
- package/src/ask/schema.ts +67 -0
- package/src/ask/tool-render.ts +49 -0
- package/src/ask/view.ts +406 -0
- package/src/goal/.gitkeep +0 -0
- package/src/goal/activity.ts +50 -0
- package/src/goal/commands.ts +75 -0
- package/src/goal/context.ts +36 -0
- package/src/goal/index.ts +38 -0
- package/src/goal/manager.ts +386 -0
- package/src/goal/presentation.ts +15 -0
- package/src/goal/render.ts +36 -0
- package/src/goal/snapshot.ts +78 -0
- package/src/goal/state.ts +39 -0
- package/src/goal/store.ts +59 -0
- package/src/goal/tools.ts +59 -0
- package/src/goal/wait.ts +39 -0
- package/src/index.ts +20 -0
- package/src/jobs/backends/linux-tree.ts +87 -0
- package/src/jobs/backends/pipe.ts +74 -0
- package/src/jobs/backends/process.ts +79 -0
- package/src/jobs/backends/pty-job.ts +45 -0
- package/src/jobs/backends/pty.ts +502 -0
- package/src/jobs/backends/windows-tree.ts +289 -0
- package/src/jobs/commands.ts +7 -0
- package/src/jobs/control.ts +13 -0
- package/src/jobs/index.ts +331 -0
- package/src/jobs/launch/config.ts +26 -0
- package/src/jobs/launch/name.ts +16 -0
- package/src/jobs/launch/presets.ts +61 -0
- package/src/jobs/log-viewer.ts +147 -0
- package/src/jobs/manager.ts +507 -0
- package/src/jobs/monitors/compile.ts +101 -0
- package/src/jobs/monitors/hands-free.ts +108 -0
- package/src/jobs/monitors/runtime.ts +165 -0
- package/src/jobs/output.ts +54 -0
- package/src/jobs/query.ts +62 -0
- package/src/jobs/render.ts +103 -0
- package/src/jobs/runtime.ts +89 -0
- package/src/jobs/state.ts +25 -0
- package/src/jobs/store.ts +168 -0
- package/src/jobs/terminal/keys.ts +292 -0
- package/src/jobs/terminal/protocol.ts +37 -0
- package/src/jobs/terminal/read.ts +131 -0
- package/src/jobs/terminal/render.ts +70 -0
- package/src/jobs/terminal/screen.ts +92 -0
- package/src/jobs/terminal/session.ts +100 -0
- package/src/jobs/terminal/shell.ts +22 -0
- package/src/jobs/terminal/snapshot.ts +8 -0
- package/src/jobs/terminal/visible-text.ts +53 -0
- package/src/jobs/tools.ts +203 -0
- package/src/jobs/types.ts +60 -0
- package/src/jobs/viewer/component.ts +209 -0
- package/src/jobs/viewer/metadata.ts +9 -0
- package/src/jobs/viewer.ts +149 -0
- package/src/jobs/workspace.ts +31 -0
- package/src/runtime/.gitkeep +0 -0
- package/src/runtime/binding.ts +26 -0
- package/src/runtime/cli-prompt.ts +24 -0
- package/src/runtime/clipboard.ts +16 -0
- package/src/runtime/config-edit.ts +31 -0
- package/src/runtime/config-fields.ts +65 -0
- package/src/runtime/config.ts +111 -0
- package/src/runtime/errors.ts +11 -0
- package/src/runtime/json-store.ts +156 -0
- package/src/runtime/notification-render.ts +35 -0
- package/src/runtime/notifications.ts +98 -0
- package/src/runtime/owner.ts +54 -0
- package/src/runtime/read.ts +200 -0
- package/src/runtime/renderers.ts +50 -0
- package/src/runtime/responses/index.ts +108 -0
- package/src/runtime/responses/payload.ts +78 -0
- package/src/runtime/settings/index.ts +24 -0
- package/src/runtime/settings/view.ts +84 -0
- package/src/runtime/suite.ts +192 -0
- package/src/runtime/text.ts +6 -0
- package/src/runtime/tools.ts +131 -0
- package/src/runtime/wait-render.ts +33 -0
- package/src/runtime/wait.ts +134 -0
- package/src/tasks/commands.ts +41 -0
- package/src/tasks/index.ts +305 -0
- package/src/tasks/model.ts +152 -0
- package/src/tasks/presentation.ts +40 -0
- package/src/tasks/query.ts +38 -0
- package/src/tasks/render.ts +54 -0
- package/src/tasks/schema.ts +25 -0
- package/src/tasks/store.ts +164 -0
- package/src/tasks/tools.ts +69 -0
- package/src/tasks/types.ts +61 -0
- package/src/tasks/viewer.ts +68 -0
- package/src/ui/.gitkeep +0 -0
- package/src/ui/actions.ts +50 -0
- package/src/ui/browser-chrome.ts +175 -0
- package/src/ui/browser.ts +292 -0
- package/src/ui/details.ts +111 -0
- package/src/ui/dock/line.ts +14 -0
- package/src/ui/dock/rows.ts +78 -0
- package/src/ui/dock.ts +224 -0
- package/src/ui/format.ts +25 -0
- package/src/ui/frame.ts +8 -0
- package/src/ui/inline-input.ts +98 -0
- package/src/ui/reading.ts +105 -0
- package/src/ui/rendering/builtin-command.ts +34 -0
- package/src/ui/rendering/command.ts +60 -0
- package/src/ui/rendering/read-page.ts +15 -0
- package/src/ui/rendering/shell/bash.ts +281 -0
- package/src/ui/rendering/shell/index.ts +24 -0
- package/src/ui/rendering/shell/powershell.ts +155 -0
- package/src/ui/rendering/shell/spans.ts +28 -0
- package/src/ui/scroll.ts +111 -0
- package/src/ui/select.ts +67 -0
- package/src/ui/status.ts +67 -0
- package/src/ui/structured-details.ts +41 -0
- package/src/ui/terminal.ts +137 -0
- package/src/ui/ticker.ts +18 -0
- package/src/ui/tool-render.ts +152 -0
- package/src/ui/transcript.ts +140 -0
- package/src/ui/viewer/agent-information.ts +34 -0
- package/src/ui/viewer/editor.ts +18 -0
- package/src/ui/viewer/navigation.ts +25 -0
- package/themes/oh-my-pi.json +95 -0
- package/third-party/UPSTREAM.md +88 -0
- package/third-party/licenses/.gitkeep +0 -0
- package/third-party/licenses/oh-my-pi.txt +23 -0
- package/third-party/licenses/pi-ask-user.txt +21 -0
- package/third-party/licenses/pi-background-jobs.txt +21 -0
- package/third-party/licenses/pi-goal.txt +21 -0
- package/third-party/licenses/pi-interactive-shell.txt +25 -0
- package/third-party/licenses/pi-subagents.txt +21 -0
- package/third-party/licenses/pi-tasks.txt +21 -0
- package/third-party/sources.json +111 -0
|
@@ -0,0 +1,507 @@
|
|
|
1
|
+
// Adapted from pi-background-jobs 0.1.3 src/jobs.ts (MIT, third-party/licenses/pi-background-jobs.txt).
|
|
2
|
+
// pi-suite changes: pipe and PTY modes behind one Tracked handle; one job.json record; monotonic
|
|
3
|
+
// elapsed time; input records; creator ownership with cascading stop; no workspace exclusive lock.
|
|
4
|
+
import { performance } from 'node:perf_hooks';
|
|
5
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
6
|
+
import { JobStore } from './store.ts';
|
|
7
|
+
import { jobName } from './launch/name.ts';
|
|
8
|
+
import { resolveWorkspace } from './workspace.ts';
|
|
9
|
+
import { isActive, isTerminal, settleExit } from './state.ts';
|
|
10
|
+
import { stopTracked, stopTrackedSync, type Tracked } from './backends/process.ts';
|
|
11
|
+
import { launchPipe } from './backends/pipe.ts';
|
|
12
|
+
import type { ResolvedShellConfig } from './terminal/shell.ts';
|
|
13
|
+
import type { PtyTerminalSession } from './terminal/session.ts';
|
|
14
|
+
import { requireGeneration } from '../tasks/types.ts';
|
|
15
|
+
import { ToolError } from '../runtime/errors.ts';
|
|
16
|
+
import { compileMonitor, type CompiledMonitor } from './monitors/compile.ts';
|
|
17
|
+
import { JobMonitor, type MonitorEvent } from './monitors/runtime.ts';
|
|
18
|
+
import { compileHandsFree, HandsFreeSupervisor, type HandsFreeUpdate } from './monitors/hands-free.ts';
|
|
19
|
+
import { outputPreview } from './output.ts';
|
|
20
|
+
import { errnoCode, isWorkflowGate, LIMITS, type InputRecord, type JobSummary, type StartRequest, type StopReason, type StopResult, type Stream, type Workspace } from './types.ts';
|
|
21
|
+
|
|
22
|
+
const JOB_ID = /^job_[a-f0-9]{8}$/;
|
|
23
|
+
let ptyBackend: Promise<typeof import('./backends/pty-job.ts')> | undefined;
|
|
24
|
+
type Owned = {
|
|
25
|
+
job: JobSummary; run?: Tracked; launched: boolean; ready: PromiseWithResolvers<void>;
|
|
26
|
+
settlement?: Promise<void>;
|
|
27
|
+
stopPromise?: Promise<StopResult>; stopDone?: boolean; cleanupSettled?: boolean;
|
|
28
|
+
stopDeadline?: number; stopController?: AbortController; stopTimer?: NodeJS.Timeout;
|
|
29
|
+
timeoutTimer?: NodeJS.Timeout;
|
|
30
|
+
saveQueue: Promise<void>; dirty?: boolean; saveAttempts?: number; retryAt?: number; persistenceError?: string;
|
|
31
|
+
deleting?: boolean;
|
|
32
|
+
inputQueue: Promise<void>;
|
|
33
|
+
/** Set while the user types in the terminal view; model input is refused until control returns. */
|
|
34
|
+
userControl?: boolean;
|
|
35
|
+
watcher?: JobMonitor;
|
|
36
|
+
supervisor?: HandsFreeSupervisor;
|
|
37
|
+
pendingUpdate?: HandsFreeUpdate;
|
|
38
|
+
/** Monitor events not yet delivered to the model, newest last, capped for the notice digest. */
|
|
39
|
+
pendingEvents: MonitorEvent[];
|
|
40
|
+
};
|
|
41
|
+
/** Events kept for one notice; the count still covers every undelivered event. */
|
|
42
|
+
const NOTICE_EVENTS = 10;
|
|
43
|
+
const abortError = () => new DOMException('Operation aborted', 'AbortError');
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Process-lifetime owner of every job started in this Pi process. It never holds a Pi context:
|
|
47
|
+
* sessions subscribe through JobsModule bindings, so reload/new/resume/fork only change who
|
|
48
|
+
* listens, never whether a job runs.
|
|
49
|
+
*/
|
|
50
|
+
export class JobManager {
|
|
51
|
+
readonly runtimeId: string;
|
|
52
|
+
private store: JobStore;
|
|
53
|
+
private jobs = new Map<string, Owned>();
|
|
54
|
+
private listeners = new Set<() => void>();
|
|
55
|
+
private stoppingCreators = new Set<string>();
|
|
56
|
+
/** Jobs whose automatic wake was paused by Esc; their results arrive with the next user turn. */
|
|
57
|
+
readonly quietWakes = new Set<string>();
|
|
58
|
+
private closing = false;
|
|
59
|
+
private quitDeadline?: number;
|
|
60
|
+
private shutdownPromise?: Promise<void>;
|
|
61
|
+
private monitor: NodeJS.Timeout;
|
|
62
|
+
private monitoring = false;
|
|
63
|
+
|
|
64
|
+
constructor(options: { agentDir: string; runtimeId: string }) {
|
|
65
|
+
this.runtimeId = options.runtimeId;
|
|
66
|
+
this.store = new JobStore(options.agentDir);
|
|
67
|
+
this.monitor = setInterval(() => { void this.monitorJobs(); }, LIMITS.monitorMs);
|
|
68
|
+
this.monitor.unref();
|
|
69
|
+
}
|
|
70
|
+
get closed(): boolean { return this.closing; }
|
|
71
|
+
subscribe(listener: () => void): () => void { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; }
|
|
72
|
+
private changed(): void { for (const listener of [...this.listeners]) { try { listener(); } catch {} } }
|
|
73
|
+
|
|
74
|
+
private view(item: Owned): JobSummary {
|
|
75
|
+
const job = structuredClone(item.job);
|
|
76
|
+
if (item.run?.terminal?.fullScreen) job.fullScreen = true;
|
|
77
|
+
// Live elapsed is monotonic; endedAt fixes the saved value.
|
|
78
|
+
if (item.run && job.endedAt === undefined) job.elapsedMs = Math.round(performance.now() - item.run.startedMonotonic);
|
|
79
|
+
if (item.persistenceError) job.error = [job.error, `history not saved: ${item.persistenceError}`].filter(Boolean).join('; ');
|
|
80
|
+
return job;
|
|
81
|
+
}
|
|
82
|
+
private setError(item: Owned, error: unknown): void {
|
|
83
|
+
const text = String(error instanceof Error ? error.message : error).slice(0, 1024);
|
|
84
|
+
item.job.error = item.job.error ? `${item.job.error}; ${text}` : text;
|
|
85
|
+
}
|
|
86
|
+
private persist(item: Owned): Promise<void> {
|
|
87
|
+
item.dirty = true;
|
|
88
|
+
// History deletion owns the final disk state; late notice consumption must not recreate it.
|
|
89
|
+
if (item.deleting) return item.saveQueue;
|
|
90
|
+
item.saveQueue = item.saveQueue.then(async () => {
|
|
91
|
+
if (!item.dirty) return;
|
|
92
|
+
item.dirty = false;
|
|
93
|
+
try {
|
|
94
|
+
await this.store.save(item.job);
|
|
95
|
+
item.persistenceError = undefined; item.saveAttempts = 0; item.retryAt = undefined;
|
|
96
|
+
} catch (error) {
|
|
97
|
+
item.dirty = true; item.persistenceError = String(error);
|
|
98
|
+
item.saveAttempts = (item.saveAttempts ?? 0) + 1;
|
|
99
|
+
item.retryAt = Date.now() + Math.min(30000, 1000 * 2 ** Math.min(item.saveAttempts - 1, 5));
|
|
100
|
+
}
|
|
101
|
+
}).finally(() => this.changed());
|
|
102
|
+
return item.saveQueue;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async start(request: StartRequest, shell: ResolvedShellConfig, signal?: AbortSignal): Promise<JobSummary> {
|
|
106
|
+
if (request.taskId) requireGeneration(request.taskGeneration);
|
|
107
|
+
const mode = request.mode ?? 'pipe';
|
|
108
|
+
const handsFree = request.handsFree ? compileHandsFree(request.handsFree, mode) : undefined;
|
|
109
|
+
// A monitor decides the command the job runs: its poll loop, or a generated file watcher.
|
|
110
|
+
const monitor: CompiledMonitor | undefined = request.monitor ? compileMonitor(request.monitor, request.command, shell) : undefined;
|
|
111
|
+
const command = monitor?.command ?? request.command;
|
|
112
|
+
if (!command?.trim() || command.length > 32768 || (request.name?.length ?? 0) > 80 ||
|
|
113
|
+
(request.timeoutMs !== undefined && (!Number.isInteger(request.timeoutMs) || request.timeoutMs < 1 || request.timeoutMs > LIMITS.maxRunMs))) {
|
|
114
|
+
throw new ToolError('INVALID_ARGS', 'command must be 1-32768 characters, name at most 80, timeoutMs 1-86400000');
|
|
115
|
+
}
|
|
116
|
+
this.admit(signal);
|
|
117
|
+
const workspace = await resolveWorkspace(request.cwd);
|
|
118
|
+
if (await this.store.workspaceBytes(workspace) >= LIMITS.workspaceBytes) {
|
|
119
|
+
throw new ToolError('WORKSPACE_CAPACITY', 'Workspace job history reached 1 GiB; ask the user to delete finished jobs in /jobs');
|
|
120
|
+
}
|
|
121
|
+
this.admit(signal);
|
|
122
|
+
const id = this.store.allocate(workspace);
|
|
123
|
+
const job: JobSummary = {
|
|
124
|
+
schemaVersion: 1, id, workspace, ownerRuntimeId: this.runtimeId, ownerSessionId: request.ownerSessionId,
|
|
125
|
+
anchorEntryId: request.anchorEntryId,
|
|
126
|
+
name: jobName(request).slice(0, 80),
|
|
127
|
+
command, cwd: request.cwd, mode, ...(request.taskId ? { taskId: request.taskId, taskGeneration: request.taskGeneration } : {}),
|
|
128
|
+
...(request.creator ? { creator: request.creator } : {}),
|
|
129
|
+
...(request.monitor ? { monitor: { config: request.monitor, events: 0, notifiedEvents: 0 } } : {}),
|
|
130
|
+
...(handsFree ? { handsFree: { config: handsFree, updates: 0, notifiedUpdates: 0, totalCharsSent: 0 } } : {}),
|
|
131
|
+
state: 'starting', createdAt: new Date().toISOString(),
|
|
132
|
+
...(request.timeoutMs ? { timeoutMs: request.timeoutMs } : {}), exitCode: null,
|
|
133
|
+
cleanup: { state: 'not_required', scope: [], rootExited: false },
|
|
134
|
+
};
|
|
135
|
+
const item: Owned = { job, launched: false, ready: Promise.withResolvers(), saveQueue: Promise.resolve(), inputQueue: Promise.resolve(), pendingEvents: [] };
|
|
136
|
+
// Registered before any await so a concurrent creator stop or quit includes this job.
|
|
137
|
+
this.jobs.set(id, item);
|
|
138
|
+
if (this.creatorStopping(request.creator)) job.stopReason = 'agent';
|
|
139
|
+
const onAbort = () => { void this.stop(id, 'start_aborted').catch(() => {}); };
|
|
140
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
141
|
+
try {
|
|
142
|
+
await this.store.create(job);
|
|
143
|
+
if (job.stopReason || this.closing || signal?.aborted) throw new ToolError('START_NOT_COMMITTED', 'Start cancelled before spawn', id);
|
|
144
|
+
const run = mode === 'pty'
|
|
145
|
+
? await (await (ptyBackend ??= import('./backends/pty-job.ts'))).launchPty({ command: job.command, cwd: job.cwd, shell, outputPath: this.store.logPath(job, 'output'), cols: request.cols ?? 120, rows: request.rows ?? 30 })
|
|
146
|
+
: await launchPipe({ command: job.command, cwd: job.cwd, shell, stdoutPath: this.store.logPath(job, 'stdout'), stderrPath: this.store.logPath(job, 'stderr') });
|
|
147
|
+
this.install(item, run, monitor && { monitor, shell });
|
|
148
|
+
if (request.closeInput) run.endInput?.();
|
|
149
|
+
await this.persist(item);
|
|
150
|
+
} catch (error) {
|
|
151
|
+
if (!item.run) {
|
|
152
|
+
// Never spawned: no runtime to report and nothing to clean up.
|
|
153
|
+
job.state = job.stopReason || error instanceof ToolError && error.code === 'START_NOT_COMMITTED' ? 'stopped' : 'failed';
|
|
154
|
+
job.stopReason ??= job.state === 'stopped' ? (this.closing ? 'quit' : 'start_aborted') : undefined;
|
|
155
|
+
job.endedAt = new Date().toISOString();
|
|
156
|
+
job.cleanup = { state: 'not_required', scope: [], rootExited: true };
|
|
157
|
+
if (job.state === 'failed') this.setError(item, error);
|
|
158
|
+
await this.persist(item);
|
|
159
|
+
}
|
|
160
|
+
throw error;
|
|
161
|
+
} finally {
|
|
162
|
+
signal?.removeEventListener('abort', onAbort);
|
|
163
|
+
item.launched = true; item.ready.resolve(); this.changed();
|
|
164
|
+
}
|
|
165
|
+
if (job.stopReason || this.closing || signal?.aborted) {
|
|
166
|
+
await this.stop(id, signal?.aborted ? 'start_aborted' : 'quit');
|
|
167
|
+
throw new ToolError('START_NOT_COMMITTED', `Job was stopped during start; inspect with job_get({"id":"${id}"})`, id);
|
|
168
|
+
}
|
|
169
|
+
return this.view(item);
|
|
170
|
+
}
|
|
171
|
+
private admit(signal?: AbortSignal): void {
|
|
172
|
+
if (this.closing) throw new ToolError('CLOSING', 'Pi is quitting; no new jobs');
|
|
173
|
+
if (signal?.aborted) throw abortError();
|
|
174
|
+
}
|
|
175
|
+
private install(item: Owned, run: Tracked, watch?: { monitor: CompiledMonitor; shell: ResolvedShellConfig }): void {
|
|
176
|
+
const job = item.job;
|
|
177
|
+
item.run = run;
|
|
178
|
+
job.startedAt = new Date(run.spawnedAt).toISOString();
|
|
179
|
+
job.state = 'running';
|
|
180
|
+
if (job.timeoutMs) {
|
|
181
|
+
item.timeoutTimer = setTimeout(() => { void this.stop(job.id, 'timeout').catch(() => {}); }, job.timeoutMs);
|
|
182
|
+
item.timeoutTimer.unref();
|
|
183
|
+
}
|
|
184
|
+
if (watch) {
|
|
185
|
+
const streams: Stream[] = job.mode === 'pty' ? ['output'] : ['stdout', 'stderr'];
|
|
186
|
+
item.watcher = new JobMonitor(watch.monitor, JobMonitor.sources(streams.map(stream => ({ path: this.store.logPath(job, stream), stream: stream as MonitorEvent['stream'] })), job.mode === 'pty'),
|
|
187
|
+
watch.shell, job.cwd, candidate => this.recordEvent(item, candidate));
|
|
188
|
+
}
|
|
189
|
+
if (job.handsFree) item.supervisor = new HandsFreeSupervisor(run.terminal!, job.handsFree,
|
|
190
|
+
update => { item.pendingUpdate = update; void this.persist(item); this.changed(); },
|
|
191
|
+
() => { void this.stop(job.id, 'quiet'); });
|
|
192
|
+
// Exit is the only settlement evidence; a stop request alone never settles the job.
|
|
193
|
+
item.settlement = run.exited.then(async exit => {
|
|
194
|
+
clearTimeout(item.timeoutTimer);
|
|
195
|
+
job.exitCode = exit.code; job.signal = exit.signal;
|
|
196
|
+
job.endedAt = new Date().toISOString();
|
|
197
|
+
job.elapsedMs = Math.round(performance.now() - run.startedMonotonic);
|
|
198
|
+
item.supervisor?.dispose();
|
|
199
|
+
// A result replaces any queued progress snapshot; never wake twice for final output.
|
|
200
|
+
item.pendingUpdate = undefined;
|
|
201
|
+
this.changed();
|
|
202
|
+
// The logs are flushed by now; the monitor matches the last lines before the job settles,
|
|
203
|
+
// so a settled job never reports fewer events than its output holds.
|
|
204
|
+
try { await item.watcher?.stop(); } catch (error) { this.setError(item, `monitor: ${String(error)}`); }
|
|
205
|
+
job.fullScreen = run.terminal?.fullScreen || undefined;
|
|
206
|
+
if (run.terminal) {
|
|
207
|
+
try {
|
|
208
|
+
const snapshot = run.terminal.snapshot();
|
|
209
|
+
await this.store.saveTerminalSnapshot(job, snapshot);
|
|
210
|
+
const {data: _data, ...metadata} = snapshot; job.terminalSnapshot = metadata;
|
|
211
|
+
} catch (error) { this.setError(item, `final terminal snapshot unavailable: ${String(error)}`); }
|
|
212
|
+
}
|
|
213
|
+
// The logs are flushed, but the run remains active until its final preview
|
|
214
|
+
// exists. Publishing terminal state first would split output and result wakes.
|
|
215
|
+
try { job.outputPreview = await outputPreview(this, job); }
|
|
216
|
+
catch (error) { this.setError(item, `output preview unavailable: ${String(error)}`); }
|
|
217
|
+
if (exit.error) this.setError(item, exit.error);
|
|
218
|
+
// Input and monitor events are real streams too; publish settlement only after their
|
|
219
|
+
// serialized append queue drains, so the viewer's final size read cannot miss them.
|
|
220
|
+
await item.inputQueue;
|
|
221
|
+
if (job.stopReason) job.cleanup.rootExited = true;
|
|
222
|
+
else { job.cleanup = { state: run.knownResidual ? 'unconfirmed' : 'not_required', scope: [], rootExited: true }; run.dispose(); }
|
|
223
|
+
job.state = settleExit(exit, job.stopReason);
|
|
224
|
+
if (job.handsFree) job.completionReason = job.stopReason === 'quiet' ? 'quiet' : job.stopReason === 'timeout' ? 'timeout' : job.stopReason ? 'stopped' : 'exited';
|
|
225
|
+
void this.persist(item);
|
|
226
|
+
this.changed();
|
|
227
|
+
});
|
|
228
|
+
this.changed();
|
|
229
|
+
}
|
|
230
|
+
private recordEvent(item: Owned, candidate: Omit<MonitorEvent, 'eventId' | 'at'>): void {
|
|
231
|
+
const monitor = item.job.monitor!;
|
|
232
|
+
const event: MonitorEvent = { eventId: ++monitor.events, at: new Date().toISOString(), ...candidate };
|
|
233
|
+
item.pendingEvents = [...item.pendingEvents, event].slice(-NOTICE_EVENTS);
|
|
234
|
+
item.inputQueue = item.inputQueue.then(() => this.store.appendEvent(item.job, event)).catch(error => { this.setError(item, `monitor event not saved: ${String(error)}`); this.changed(); });
|
|
235
|
+
void this.persist(item);
|
|
236
|
+
this.changed();
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** Repeated calls join the stop in progress; a settled job returns its existing result. */
|
|
240
|
+
stop(id: string, reason: StopReason = 'user', deadline = Date.now() + LIMITS.stopMs): Promise<StopResult> {
|
|
241
|
+
const item = this.owned(id), job = item.job;
|
|
242
|
+
if (item.stopPromise) {
|
|
243
|
+
if (!item.stopDone) this.shortenStop(item, deadline);
|
|
244
|
+
return item.stopPromise.then(() => ({ job: this.view(item), requested: true }));
|
|
245
|
+
}
|
|
246
|
+
if (item.launched && isTerminal(job.state)) return Promise.resolve({ job: this.view(item), requested: false });
|
|
247
|
+
// Exit can precede settlement while logs/monitor detectors drain. The process is already
|
|
248
|
+
// gone: preserve its natural result and wait for that evidence, rather than signal again.
|
|
249
|
+
if (item.run?.exitObserved) return item.settlement!.then(() => ({ job: this.view(item), requested: false }));
|
|
250
|
+
job.stopReason ??= reason;
|
|
251
|
+
item.supervisor?.dispose(); item.pendingUpdate = undefined;
|
|
252
|
+
if (!isTerminal(job.state)) job.state = 'stopping';
|
|
253
|
+
job.cleanup.state = 'pending';
|
|
254
|
+
item.stopController = new AbortController();
|
|
255
|
+
// Installed before observers run, so re-entrant stops join this one.
|
|
256
|
+
item.stopPromise = Promise.resolve().then(() => this.runStop(item));
|
|
257
|
+
this.shortenStop(item, deadline);
|
|
258
|
+
this.changed();
|
|
259
|
+
return item.stopPromise;
|
|
260
|
+
}
|
|
261
|
+
private async runStop(item: Owned): Promise<StopResult> {
|
|
262
|
+
const job = item.job;
|
|
263
|
+
try {
|
|
264
|
+
await this.untilLaunched(item);
|
|
265
|
+
const run = item.run;
|
|
266
|
+
if (run) {
|
|
267
|
+
run.cleanupDeadline = item.stopDeadline; run.cleanupSignal = item.stopController!.signal;
|
|
268
|
+
const cleanup = await stopTracked(run, item.stopDeadline!);
|
|
269
|
+
cleanup.rootExited ||= job.cleanup.rootExited || !!run.exitObserved;
|
|
270
|
+
job.cleanup = cleanup;
|
|
271
|
+
// Process cleanup is finished; join its output settlement before returning
|
|
272
|
+
// a confirmed stop, so the tool and completion notice see the same terminal result.
|
|
273
|
+
item.cleanupSettled = true;
|
|
274
|
+
if (cleanup.rootExited) await item.settlement;
|
|
275
|
+
} else job.cleanup = { state: 'not_required', scope: [], rootExited: true };
|
|
276
|
+
} catch (error) {
|
|
277
|
+
job.cleanup.state = 'unconfirmed'; job.cleanup.error = String(error);
|
|
278
|
+
} finally {
|
|
279
|
+
item.cleanupSettled = true; item.stopDone = true; clearTimeout(item.stopTimer);
|
|
280
|
+
await this.persist(item);
|
|
281
|
+
}
|
|
282
|
+
return { job: this.view(item), requested: true };
|
|
283
|
+
}
|
|
284
|
+
private async untilLaunched(item: Owned): Promise<void> {
|
|
285
|
+
if (item.launched) return;
|
|
286
|
+
const signal = item.stopController!.signal;
|
|
287
|
+
const aborted = Promise.withResolvers<never>();
|
|
288
|
+
const abort = () => aborted.reject(new Error('Cleanup deadline exhausted during launch'));
|
|
289
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
290
|
+
if (signal.aborted) abort();
|
|
291
|
+
try { await Promise.race([item.ready.promise, aborted.promise]); }
|
|
292
|
+
finally { signal.removeEventListener('abort', abort); }
|
|
293
|
+
}
|
|
294
|
+
private shortenStop(item: Owned, deadline: number): void {
|
|
295
|
+
item.stopDeadline = Math.min(item.stopDeadline ?? deadline, deadline, this.quitDeadline ?? deadline);
|
|
296
|
+
if (item.run) item.run.cleanupDeadline = item.stopDeadline;
|
|
297
|
+
clearTimeout(item.stopTimer);
|
|
298
|
+
const expired = () => {
|
|
299
|
+
item.run?.identityController?.abort(); item.stopController?.abort();
|
|
300
|
+
if (!item.cleanupSettled) {
|
|
301
|
+
item.job.cleanup.state = 'unconfirmed'; item.job.cleanup.error = 'Cleanup deadline exhausted';
|
|
302
|
+
void this.persist(item); this.changed();
|
|
303
|
+
}
|
|
304
|
+
};
|
|
305
|
+
const delay = item.stopDeadline - Date.now();
|
|
306
|
+
if (delay <= 0) expired(); else item.stopTimer = setTimeout(expired, delay);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
private createdItems(runIds: string[]): Owned[] {
|
|
310
|
+
const roots = new Set(runIds);
|
|
311
|
+
return [...this.jobs.values()].filter(({job}) => job.creator &&
|
|
312
|
+
[job.creator.runId, ...job.creator.ancestors].some(runId => roots.has(runId)));
|
|
313
|
+
}
|
|
314
|
+
/** Complete creation scope across workspaces and notification owners, without pagination. */
|
|
315
|
+
createdBy(runIds: string[]): JobSummary[] { return this.createdItems(runIds).map(item => this.view(item)); }
|
|
316
|
+
/** Session ownership spans working directories; branch visibility belongs to JobsModule. */
|
|
317
|
+
sessionJobs(sessionId: string): JobSummary[] {
|
|
318
|
+
return [...this.jobs.values()].filter(item => item.job.ownerSessionId === sessionId).map(item => this.view(item));
|
|
319
|
+
}
|
|
320
|
+
/** Stop every job created by these agent runs or their descendants, including detached ones. */
|
|
321
|
+
async stopCreatedBy(runIds: string[]): Promise<StopResult[]> {
|
|
322
|
+
for (const runId of runIds) this.stoppingCreators.add(runId);
|
|
323
|
+
// Closed creators stay closed for future launches; selection matches the public query.
|
|
324
|
+
return Promise.all(this.createdItems(runIds).map(item => this.stop(item.job.id, 'agent')));
|
|
325
|
+
}
|
|
326
|
+
private creatorStopping(creator: StartRequest['creator']): boolean {
|
|
327
|
+
return !!creator && [creator.runId, ...creator.ancestors].some(runId => this.stoppingCreators.has(runId));
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** Input goes to the program first; the record is written after and only proves it was sent. */
|
|
331
|
+
write(id: string, data: string, record: Omit<InputRecord, 'at' | 'bytes'>): JobSummary {
|
|
332
|
+
const item = this.owned(id), job = item.job, run = item.run;
|
|
333
|
+
if (!run || run.exitObserved || job.state !== 'running') throw new ToolError('NOT_RUNNING', `${id} is ${job.state} and does not accept input`, id);
|
|
334
|
+
if (item.userControl && record.source !== 'user') throw new ToolError('USER_CONTROL', `The user controls ${id} in the terminal view; wait until control returns`, id);
|
|
335
|
+
try { run.write(data); } catch (error) { throw new ToolError('NOT_RUNNING', String(error instanceof Error ? error.message : error), id); }
|
|
336
|
+
if (record.source === 'user' && !item.userControl) {
|
|
337
|
+
item.userControl = true; item.supervisor?.pause(); item.pendingUpdate = undefined; this.changed();
|
|
338
|
+
} else if (record.source !== 'user') item.supervisor?.input();
|
|
339
|
+
const entry: InputRecord = { at: new Date().toISOString(), ...record, bytes: Buffer.byteLength(data) };
|
|
340
|
+
if (entry.sensitive) delete entry.text;
|
|
341
|
+
item.inputQueue = item.inputQueue.then(() => this.store.appendInput(job, entry)).catch(error => { this.setError(item, `input record not saved: ${String(error)}`); this.changed(); });
|
|
342
|
+
return this.view(item);
|
|
343
|
+
}
|
|
344
|
+
/** Close pipe stdin so programs that read to end of input can finish. */
|
|
345
|
+
endInput(id: string): JobSummary {
|
|
346
|
+
const item = this.owned(id);
|
|
347
|
+
if (!item.run?.endInput || item.run.exitObserved) throw new ToolError('NOT_RUNNING', `${id} has no open stdin`, id);
|
|
348
|
+
item.run.endInput();
|
|
349
|
+
return this.view(item);
|
|
350
|
+
}
|
|
351
|
+
resize(id: string, cols: number, rows: number): void { this.owned(id).run?.resize?.(cols, rows); }
|
|
352
|
+
terminal(id: string): PtyTerminalSession | undefined { return this.jobs.get(id)?.run?.terminal; }
|
|
353
|
+
/** Claiming input sends no program bytes; merely opening a readonly screen never calls this. */
|
|
354
|
+
takeControl(id: string): void {
|
|
355
|
+
const item = this.owned(id);
|
|
356
|
+
if (!item.run?.terminal || item.run.exitObserved || item.job.state !== 'running') throw new ToolError('NOT_RUNNING', `${id} has no active PTY input`, id);
|
|
357
|
+
if (!item.userControl) { item.userControl = true; item.supervisor?.pause(); item.pendingUpdate = undefined; this.changed(); }
|
|
358
|
+
}
|
|
359
|
+
userControlled(id: string): boolean { return !!this.jobs.get(id)?.userControl; }
|
|
360
|
+
/** Hand input back to the model (Ctrl+G or leaving the terminal view). */
|
|
361
|
+
returnControl(id: string): void {
|
|
362
|
+
const item = this.jobs.get(id);
|
|
363
|
+
if (item?.userControl) { item.userControl = false; item.supervisor?.resume(); this.changed(); }
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
private owned(id: string): Owned {
|
|
367
|
+
if (!JOB_ID.test(id)) throw new ToolError('INVALID_ARGS', 'id must look like job_1a2b3c4d');
|
|
368
|
+
const item = this.jobs.get(id);
|
|
369
|
+
if (!item) throw new ToolError('HISTORY_READ_ONLY', `${id} is not controlled by this Pi process; history can still be read`, id);
|
|
370
|
+
return item;
|
|
371
|
+
}
|
|
372
|
+
isLive(id: string): boolean { return this.jobs.has(id); }
|
|
373
|
+
/** Current view of a job this process controls; throws for unknown or history-only IDs. */
|
|
374
|
+
peek(id: string): JobSummary { return this.view(this.owned(id)); }
|
|
375
|
+
/** Await actual process exit, persistence and any requested cleanup using the owner's lifecycle. */
|
|
376
|
+
async wait(id: string): Promise<JobSummary> {
|
|
377
|
+
const item = this.owned(id);
|
|
378
|
+
await item.ready.promise;
|
|
379
|
+
await item.settlement;
|
|
380
|
+
await item.stopPromise;
|
|
381
|
+
await item.saveQueue;
|
|
382
|
+
return this.view(item);
|
|
383
|
+
}
|
|
384
|
+
async get(id: string, workspace: Workspace): Promise<{ job: JobSummary; live: boolean }> {
|
|
385
|
+
if (!JOB_ID.test(id)) throw new ToolError('INVALID_ARGS', 'id must look like job_1a2b3c4d');
|
|
386
|
+
const item = this.jobs.get(id);
|
|
387
|
+
if (item) return { job: this.view(item), live: true };
|
|
388
|
+
try { return { job: await this.store.load(workspace, id), live: false }; }
|
|
389
|
+
catch (error) {
|
|
390
|
+
if (errnoCode(error) === 'ENOENT') throw new ToolError('NOT_FOUND', `No job ${id} in this workspace; discover with job_list({"scope":"workspace","state":"all"})`, id);
|
|
391
|
+
throw error;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
/** Delete settled history and logs; this operation never controls historical processes. */
|
|
395
|
+
async clear(id: string, workspace: Workspace): Promise<void> {
|
|
396
|
+
const {job} = await this.get(id, workspace), item = this.jobs.get(id);
|
|
397
|
+
if (item && (!item.launched || item.stopPromise && !item.stopDone || item.deleting)
|
|
398
|
+
|| !isTerminal(job.state) || ['pending', 'unconfirmed'].includes(job.cleanup.state)) {
|
|
399
|
+
throw new ToolError('JOB_OCCUPIED', 'Cannot delete an active, pending or unconfirmed job', id);
|
|
400
|
+
}
|
|
401
|
+
if (item) item.deleting = true;
|
|
402
|
+
try {
|
|
403
|
+
await item?.settlement;
|
|
404
|
+
await item?.inputQueue;
|
|
405
|
+
await item?.saveQueue;
|
|
406
|
+
// Retry an unsaved terminal result before removal; failed writes remain explicit.
|
|
407
|
+
if (item?.dirty) await this.store.save(item.job);
|
|
408
|
+
await this.store.remove(job);
|
|
409
|
+
item?.run?.terminal?.releaseScreen();
|
|
410
|
+
this.jobs.delete(id); this.quietWakes.delete(id); this.changed();
|
|
411
|
+
} finally { if (item) item.deleting = false; }
|
|
412
|
+
}
|
|
413
|
+
async list(workspace: Workspace): Promise<{ jobs: { job: JobSummary; live: boolean }[]; errors: string[] }> {
|
|
414
|
+
const stored = await this.store.list(workspace);
|
|
415
|
+
const all = new Map(stored.jobs.map(job => [job.id, { job, live: false }]));
|
|
416
|
+
for (const item of this.jobs.values()) if (item.job.workspace.key === workspace.key) all.set(item.job.id, { job: this.view(item), live: true });
|
|
417
|
+
return { jobs: [...all.values()], errors: stored.errors };
|
|
418
|
+
}
|
|
419
|
+
logPath(job: JobSummary, stream: Stream): string { return this.store.logPath(job, stream); }
|
|
420
|
+
readTerminalSnapshot(job: JobSummary) { return this.store.readTerminalSnapshot(job); }
|
|
421
|
+
markNotified(id: string): void {
|
|
422
|
+
const item = this.jobs.get(id);
|
|
423
|
+
if (!item || item.job.notified) return;
|
|
424
|
+
item.job.notified = true; void this.persist(item);
|
|
425
|
+
}
|
|
426
|
+
activeIds(sessionId: string): string[] {
|
|
427
|
+
return [...this.jobs.values()].filter(item => !isWorkflowGate(item.job) && item.job.ownerSessionId === sessionId && isActive(item.job)).map(item => item.job.id);
|
|
428
|
+
}
|
|
429
|
+
/** Settled, unnotified jobs; JobsModule decides session and branch eligibility. */
|
|
430
|
+
unnotified(): JobSummary[] {
|
|
431
|
+
return [...this.jobs.values()].filter(item => item.launched && isTerminal(item.job.state) && !item.job.notified && (!item.stopPromise || item.stopDone)).map(item => this.view(item));
|
|
432
|
+
}
|
|
433
|
+
/** Jobs with monitor events the model has not seen, with the newest of them for the notice. */
|
|
434
|
+
unseenEvents(): { job: JobSummary; count: number; recent: MonitorEvent[] }[] {
|
|
435
|
+
return [...this.jobs.values()].filter(item => item.job.monitor && item.job.monitor.events > item.job.monitor.notifiedEvents)
|
|
436
|
+
.map(item => ({ job: this.view(item), count: item.job.monitor!.events - item.job.monitor!.notifiedEvents, recent: item.pendingEvents }));
|
|
437
|
+
}
|
|
438
|
+
/** Events up to upTo were delivered (notice or wait); later events stay pending. */
|
|
439
|
+
markEventsNotified(id: string, upTo: number): void {
|
|
440
|
+
const item = this.jobs.get(id), monitor = item?.job.monitor;
|
|
441
|
+
if (!monitor || upTo <= monitor.notifiedEvents) return;
|
|
442
|
+
monitor.notifiedEvents = Math.min(upTo, monitor.events);
|
|
443
|
+
item.pendingEvents = item.pendingEvents.filter(event => event.eventId > monitor.notifiedEvents);
|
|
444
|
+
void this.persist(item);
|
|
445
|
+
}
|
|
446
|
+
/** One latest update per job; bounded output is charged when produced, including replacements. */
|
|
447
|
+
unseenUpdates(): { job: JobSummary; update: HandsFreeUpdate }[] {
|
|
448
|
+
return [...this.jobs.values()].filter(item => item.pendingUpdate && item.pendingUpdate.updateId > item.job.handsFree!.notifiedUpdates)
|
|
449
|
+
.map(item => ({ job: this.view(item), update: item.pendingUpdate! }));
|
|
450
|
+
}
|
|
451
|
+
markUpdateNotified(id: string, upTo: number): void {
|
|
452
|
+
const item = this.owned(id), state = item.job.handsFree!;
|
|
453
|
+
if (upTo <= state.notifiedUpdates) return;
|
|
454
|
+
state.notifiedUpdates = Math.min(upTo, state.updates);
|
|
455
|
+
if (item.pendingUpdate && item.pendingUpdate.updateId <= state.notifiedUpdates) item.pendingUpdate = undefined;
|
|
456
|
+
void this.persist(item);
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
private async monitorJobs(): Promise<void> {
|
|
460
|
+
if (this.monitoring || this.closing) return;
|
|
461
|
+
this.monitoring = true;
|
|
462
|
+
try {
|
|
463
|
+
for (const item of this.jobs.values()) {
|
|
464
|
+
if (item.dirty && item.retryAt !== undefined && Date.now() >= item.retryAt) void this.persist(item);
|
|
465
|
+
if (!item.run || item.job.state !== 'running') continue;
|
|
466
|
+
try { if (await this.store.logBytes(item.job) >= LIMITS.jobLogBytes) void this.stop(item.job.id, 'log_limit').catch(() => {}); }
|
|
467
|
+
catch (error) { this.setError(item, error); this.changed(); }
|
|
468
|
+
}
|
|
469
|
+
} finally { this.monitoring = false; }
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
/** Quit: close admission synchronously, stop every live job under one shared deadline. */
|
|
473
|
+
shutdown(deadline: number): Promise<void> {
|
|
474
|
+
this.closing = true; clearInterval(this.monitor);
|
|
475
|
+
this.quitDeadline = Math.min(this.quitDeadline ?? deadline, deadline);
|
|
476
|
+
for (const item of this.jobs.values()) if (item.stopPromise && !item.stopDone) this.shortenStop(item, this.quitDeadline);
|
|
477
|
+
this.shutdownPromise ??= (async () => {
|
|
478
|
+
const active = [...this.jobs.values()].filter(item => !item.launched || !isTerminal(item.job.state) || item.stopPromise && !item.stopDone);
|
|
479
|
+
const work = Promise.all(active.map(item => this.stop(item.job.id, 'quit', this.quitDeadline).catch(() => {})))
|
|
480
|
+
.then(() => Promise.all([...this.jobs.values()].map(item => item.dirty ? this.persist(item) : item.saveQueue)));
|
|
481
|
+
await Promise.race([work, sleep(Math.max(0, this.quitDeadline! - Date.now()), undefined, { ref: false })]);
|
|
482
|
+
})();
|
|
483
|
+
return this.shutdownPromise;
|
|
484
|
+
}
|
|
485
|
+
/** process 'exit' fallback: synchronous stop and save for anything quit did not settle. */
|
|
486
|
+
exitSync(deadline: number): void {
|
|
487
|
+
this.closing = true; clearInterval(this.monitor);
|
|
488
|
+
deadline = Math.min(deadline, Date.now() + LIMITS.exitFallbackMs, this.quitDeadline ?? deadline);
|
|
489
|
+
for (const item of this.jobs.values()) {
|
|
490
|
+
const job = item.job;
|
|
491
|
+
const unsettled = !isTerminal(job.state) || job.cleanup.state === 'pending' || job.cleanup.state === 'unconfirmed' && !job.cleanup.rootExited;
|
|
492
|
+
if (!unsettled && !item.dirty) continue;
|
|
493
|
+
if (unsettled && item.run && !item.cleanupSettled) {
|
|
494
|
+
job.stopReason ??= 'quit';
|
|
495
|
+
job.cleanup = stopTrackedSync(item.run, deadline);
|
|
496
|
+
if (!isTerminal(job.state)) {
|
|
497
|
+
job.state = job.cleanup.rootExited ? settleExit(item.run.exitObserved ?? { code: null, signal: null }, job.stopReason) : 'stopping';
|
|
498
|
+
job.endedAt ??= new Date().toISOString();
|
|
499
|
+
}
|
|
500
|
+
} else if (unsettled && !item.run) { job.cleanup.state = 'unconfirmed'; job.cleanup.error = 'Pi exited during job startup'; }
|
|
501
|
+
try { this.store.saveSync(job); } catch {}
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
hasOccupancy(): boolean {
|
|
505
|
+
return [...this.jobs.values()].some(item => item.deleting || !item.launched || item.dirty || isActive(item.job));
|
|
506
|
+
}
|
|
507
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// Trigger compilation, poll-diff loop and file-watch command adapted from pi-interactive-shell
|
|
2
|
+
// 0.18.0 index.ts (MIT, third-party/licenses/pi-interactive-shell.txt). pi-suite changes: one
|
|
3
|
+
// pattern syntax shared with job_read search; eq threshold; semantic strategy dropped.
|
|
4
|
+
import { Type, type Static } from 'typebox';
|
|
5
|
+
import { compileSearch } from '../../runtime/read.ts';
|
|
6
|
+
import { ToolError } from '../../runtime/errors.ts';
|
|
7
|
+
import type { ResolvedShellConfig } from '../terminal/shell.ts';
|
|
8
|
+
|
|
9
|
+
// Private OSC survives raw logs but is invisible in terminal/text readers. Only completed
|
|
10
|
+
// iterations are samples; a timer cannot distinguish a slow command from an empty result.
|
|
11
|
+
export const POLL_BOUNDARY = '\x1b]777;pi-suite-poll\x07';
|
|
12
|
+
const ops = ['lt', 'lte', 'gt', 'gte', 'eq'] as const;
|
|
13
|
+
export const monitorSchema = Type.Object({
|
|
14
|
+
strategy: Type.Optional(Type.Union([Type.Literal('stream'), Type.Literal('poll-diff'), Type.Literal('file-watch')], { description: 'stream (default) matches each output line; poll-diff reruns command every poll.intervalMs and matches changed output; file-watch watches fileWatch.path instead of running a command' })),
|
|
15
|
+
triggers: Type.Array(Type.Object({
|
|
16
|
+
id: Type.String({ minLength: 1, maxLength: 64 }),
|
|
17
|
+
literal: Type.Optional(Type.String({ minLength: 1, maxLength: 1000 })),
|
|
18
|
+
regex: Type.Optional(Type.String({ minLength: 1, maxLength: 1000, description: '/re/flags, or a bare pattern matched case-insensitively' })),
|
|
19
|
+
threshold: Type.Optional(Type.Object({
|
|
20
|
+
captureGroup: Type.Integer({ minimum: 1 }), value: Type.Number(),
|
|
21
|
+
op: Type.Union([Type.Literal('lt'), Type.Literal('lte'), Type.Literal('gt'), Type.Literal('gte'), Type.Literal('eq')]),
|
|
22
|
+
}, { additionalProperties: false })),
|
|
23
|
+
cooldownMs: Type.Optional(Type.Integer({ minimum: 0, maximum: 86400000 })),
|
|
24
|
+
}, { additionalProperties: false }), { minItems: 1, maxItems: 20 }),
|
|
25
|
+
poll: Type.Optional(Type.Object({ intervalMs: Type.Integer({ minimum: 250, maximum: 3600000 }) }, { additionalProperties: false })),
|
|
26
|
+
fileWatch: Type.Optional(Type.Object({
|
|
27
|
+
path: Type.String({ minLength: 1 }), recursive: Type.Optional(Type.Boolean()),
|
|
28
|
+
events: Type.Optional(Type.Array(Type.Union([Type.Literal('rename'), Type.Literal('change')]), { minItems: 1 })),
|
|
29
|
+
}, { additionalProperties: false })),
|
|
30
|
+
dedupeExactLine: Type.Optional(Type.Boolean({ description: 'Default true: the same line fires a trigger once' })),
|
|
31
|
+
cooldownMs: Type.Optional(Type.Integer({ minimum: 0, maximum: 86400000, description: 'Per-trigger minimum gap; a trigger cooldownMs overrides it' })),
|
|
32
|
+
detector: Type.Optional(Type.Object({
|
|
33
|
+
command: Type.String({ minLength: 1, maxLength: 4096, description: 'Receives the candidate event JSON on stdin; stdout true/false or {"emit":bool,...} decides' }),
|
|
34
|
+
timeoutMs: Type.Optional(Type.Integer({ minimum: 100, maximum: 60000 })),
|
|
35
|
+
}, { additionalProperties: false })),
|
|
36
|
+
}, { additionalProperties: false });
|
|
37
|
+
export type MonitorInput = Static<typeof monitorSchema>;
|
|
38
|
+
export type Strategy = 'stream' | 'poll-diff' | 'file-watch';
|
|
39
|
+
export type Trigger = { id: string; cooldownMs?: number; match(text: string): string | undefined };
|
|
40
|
+
export type CompiledMonitor = {
|
|
41
|
+
strategy: Strategy; triggers: Trigger[]; pollMs: number; dedupe: boolean; cooldownMs?: number;
|
|
42
|
+
detector?: { command: string; timeoutMs: number };
|
|
43
|
+
/** The command the job actually runs: the caller's, its poll loop, or the generated watcher. */
|
|
44
|
+
command: string;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
function compare(value: number, op: typeof ops[number], expected: number): boolean {
|
|
48
|
+
return op === 'lt' ? value < expected : op === 'lte' ? value <= expected : op === 'gt' ? value > expected : op === 'gte' ? value >= expected : value === expected;
|
|
49
|
+
}
|
|
50
|
+
function compileTrigger(trigger: MonitorInput['triggers'][number]): Trigger {
|
|
51
|
+
if ((trigger.literal === undefined) === (trigger.regex === undefined)) throw new ToolError('INVALID_ARGS', `monitor trigger ${trigger.id} needs exactly one of literal or regex`);
|
|
52
|
+
if (trigger.threshold && trigger.regex === undefined) throw new ToolError('INVALID_ARGS', `monitor trigger ${trigger.id}: threshold needs regex`);
|
|
53
|
+
if (trigger.literal !== undefined) {
|
|
54
|
+
const literal = trigger.literal;
|
|
55
|
+
return { id: trigger.id, cooldownMs: trigger.cooldownMs, match: text => text.includes(literal) ? literal : undefined };
|
|
56
|
+
}
|
|
57
|
+
const regex = compileSearch(trigger.regex!), threshold = trigger.threshold;
|
|
58
|
+
return {
|
|
59
|
+
id: trigger.id, cooldownMs: trigger.cooldownMs,
|
|
60
|
+
match(text) {
|
|
61
|
+
const match = regex.exec(text);
|
|
62
|
+
if (!match) return undefined;
|
|
63
|
+
if (!threshold) return match[0];
|
|
64
|
+
// Threshold compares a captured number, e.g. /coverage (\d+)%/ with lt 80.
|
|
65
|
+
const value = Number(match[threshold.captureGroup]);
|
|
66
|
+
return Number.isFinite(value) && compare(value, threshold.op, threshold.value) ? match[0] : undefined;
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Bash single quoting keeps $, backticks and backslashes literal on every platform Pi's Bash runs. */
|
|
72
|
+
function shellQuote(value: string): string { return `'${value.replace(/'/g, `'\\''`)}'`; }
|
|
73
|
+
function fileWatchCommand(watch: NonNullable<MonitorInput['fileWatch']>): string {
|
|
74
|
+
const script = `const fs=require("node:fs");const allowed=new Set(process.argv[3].split(","));
|
|
75
|
+
let watcher;try{watcher=fs.watch(process.argv[1],{recursive:process.argv[2]==="1"},(type,name)=>{if(allowed.has(type))process.stdout.write(type.toUpperCase()+" "+(name?String(name):".")+"\\n");});}
|
|
76
|
+
catch(error){console.error("file-watch failed: "+(error instanceof Error?error.message:String(error)));process.exit(1);}
|
|
77
|
+
watcher.on("error",error=>{console.error("file-watch error: "+(error instanceof Error?error.message:String(error)));process.exit(1);});
|
|
78
|
+
process.stdin.resume();`;
|
|
79
|
+
const encoded = Buffer.from(script, 'utf8').toString('base64');
|
|
80
|
+
return `${shellQuote(process.execPath)} -e "eval(Buffer.from('${encoded}','base64').toString('utf8'))" ${shellQuote(watch.path)} ${watch.recursive ? '1' : '0'} ${shellQuote([...new Set(watch.events ?? ['rename', 'change'])].join(','))}`;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function compileMonitor(input: MonitorInput, command: string | undefined, shell: ResolvedShellConfig): CompiledMonitor {
|
|
84
|
+
const strategy = input.strategy ?? 'stream';
|
|
85
|
+
if (strategy !== 'file-watch' && input.fileWatch) throw new ToolError('INVALID_ARGS', 'monitor.fileWatch needs strategy file-watch');
|
|
86
|
+
if (strategy !== 'poll-diff' && input.poll) throw new ToolError('INVALID_ARGS', 'monitor.poll needs strategy poll-diff');
|
|
87
|
+
if (strategy === 'file-watch' ? command !== undefined || !input.fileWatch : command === undefined) {
|
|
88
|
+
throw new ToolError('INVALID_ARGS', strategy === 'file-watch' ? 'file-watch needs monitor.fileWatch and no command' : 'command is required');
|
|
89
|
+
}
|
|
90
|
+
// A stdin-transport shell (legacy WSL bash) cannot also pipe the candidate JSON to a detector.
|
|
91
|
+
if (input.detector && shell.commandTransport !== 'argv') throw new ToolError('INVALID_ARGS', 'monitor.detector needs a Bash that takes commands as arguments (Git Bash shellPath on Windows)');
|
|
92
|
+
const ids = input.triggers.map(trigger => trigger.id);
|
|
93
|
+
if (new Set(ids).size !== ids.length) throw new ToolError('INVALID_ARGS', 'monitor trigger ids must be unique');
|
|
94
|
+
const pollMs = input.poll?.intervalMs ?? 5000;
|
|
95
|
+
return {
|
|
96
|
+
strategy, triggers: input.triggers.map(compileTrigger), pollMs, dedupe: input.dedupeExactLine !== false, cooldownMs: input.cooldownMs,
|
|
97
|
+
detector: input.detector ? { command: input.detector.command, timeoutMs: input.detector.timeoutMs ?? 3000 } : undefined,
|
|
98
|
+
command: strategy === 'file-watch' ? fileWatchCommand(input.fileWatch!)
|
|
99
|
+
: strategy === 'poll-diff' ? `while true; do (\n${command}\n) 2>&1; printf '\\033]777;pi-suite-poll\\007'; sleep ${Number((pollMs / 1000).toFixed(3))}; done` : command!,
|
|
100
|
+
};
|
|
101
|
+
}
|