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,108 @@
|
|
|
1
|
+
// Quiet/grace lifecycle and incremental update budgets adapted from pi-interactive-shell
|
|
2
|
+
// 0.18.0 headless-monitor.ts and overlay-component.ts (MIT, third-party/licenses/pi-interactive-shell.txt).
|
|
3
|
+
// pi-suite keeps supervision in the process-lifetime manager; only a real exit settles a job.
|
|
4
|
+
import { performance } from 'node:perf_hooks';
|
|
5
|
+
import { Type, type Static } from 'typebox';
|
|
6
|
+
import { Value } from 'typebox/value';
|
|
7
|
+
import { ToolError } from '../../runtime/errors.ts';
|
|
8
|
+
import type { PtyTerminalSession } from '../terminal/session.ts';
|
|
9
|
+
import { normalizeVisibleText } from '../terminal/visible-text.ts';
|
|
10
|
+
|
|
11
|
+
const milliseconds = (description: string, minimum = 1) => Type.Optional(Type.Integer({ minimum, maximum: 86400000, description }));
|
|
12
|
+
export const handsFreeSchema = Type.Object({
|
|
13
|
+
mode: Type.Optional(Type.Union([Type.Literal('hands-free'), Type.Literal('dispatch')], { description: 'hands-free (default): progress updates; dispatch: one result after exit or quiet termination' })),
|
|
14
|
+
updateMode: Type.Optional(Type.Union([Type.Literal('onQuiet'), Type.Literal('interval')])),
|
|
15
|
+
quietMs: milliseconds('Output silence threshold, default 8000'),
|
|
16
|
+
updateIntervalMs: milliseconds('Update interval, or maximum wait for continuously arriving output, default 60000'),
|
|
17
|
+
autoExitOnQuiet: Type.Optional(Type.Boolean({ description: 'Request termination on silence after graceMs; defaults true in dispatch, false in hands-free. Silence does not prove success' })),
|
|
18
|
+
graceMs: milliseconds('Startup grace before quiet termination, default 15000', 0),
|
|
19
|
+
updateMaxChars: Type.Optional(Type.Integer({ minimum: 1, maximum: 65536, description: 'Output characters per update, default 1500' })),
|
|
20
|
+
maxTotalChars: Type.Optional(Type.Integer({ minimum: 0, maximum: 1000000, description: 'Total update output budget, default 100000; after exhaustion updates carry only status' })),
|
|
21
|
+
}, { additionalProperties: false });
|
|
22
|
+
export type HandsFreeInput = Static<typeof handsFreeSchema>;
|
|
23
|
+
export type HandsFreeConfig = Required<HandsFreeInput>;
|
|
24
|
+
export type HandsFreeUpdate = { updateId: number; at: string; text: string; truncated: boolean; totalCharsSent: number; budgetExhausted: boolean };
|
|
25
|
+
export type HandsFreeState = { config: HandsFreeConfig; updates: number; notifiedUpdates: number; totalCharsSent: number };
|
|
26
|
+
|
|
27
|
+
/** Validate at the manager's start boundary, also used by non-tool callers. */
|
|
28
|
+
export function compileHandsFree(input: HandsFreeInput, mode: string): HandsFreeConfig {
|
|
29
|
+
if (mode !== 'pty' || !Value.Check(handsFreeSchema, input)) throw new ToolError('INVALID_ARGS', 'handsFree needs mode pty and valid supervision options');
|
|
30
|
+
return { mode: 'hands-free', updateMode: 'onQuiet', quietMs: 8000, updateIntervalMs: 60000,
|
|
31
|
+
autoExitOnQuiet: input.mode === 'dispatch', graceMs: 15000, updateMaxChars: 1500, maxTotalChars: 100000, ...input };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export class HandsFreeSupervisor {
|
|
35
|
+
private started = performance.now();
|
|
36
|
+
private quietTimer?: NodeJS.Timeout;
|
|
37
|
+
private intervalTimer?: NodeJS.Timeout;
|
|
38
|
+
private unsubscribe: () => void;
|
|
39
|
+
private paused = false;
|
|
40
|
+
private disposed = false;
|
|
41
|
+
private tail = '';
|
|
42
|
+
private outputChars = 0;
|
|
43
|
+
|
|
44
|
+
constructor(terminal: Pick<PtyTerminalSession, 'onData'>, private state: HandsFreeState,
|
|
45
|
+
private update: (value: HandsFreeUpdate) => void, private quiet: () => void) {
|
|
46
|
+
this.unsubscribe = terminal.onData(data => {
|
|
47
|
+
if (this.paused || this.disposed) return;
|
|
48
|
+
const visible = normalizeVisibleText(data);
|
|
49
|
+
if (!visible) return;
|
|
50
|
+
this.outputChars += visible.length;
|
|
51
|
+
// Keep only one update's tail in memory; full output remains in the job log.
|
|
52
|
+
this.tail = (this.tail + visible).slice(-this.state.config.updateMaxChars);
|
|
53
|
+
if (visible.trim()) this.armQuiet();
|
|
54
|
+
});
|
|
55
|
+
this.resumeTimers();
|
|
56
|
+
}
|
|
57
|
+
private armQuiet(): void {
|
|
58
|
+
clearTimeout(this.quietTimer);
|
|
59
|
+
const config = this.state.config;
|
|
60
|
+
if (config.mode === 'dispatch' && !config.autoExitOnQuiet) return;
|
|
61
|
+
const onQuiet = () => {
|
|
62
|
+
if (this.paused || this.disposed) return;
|
|
63
|
+
const remainingGrace = config.graceMs - (performance.now() - this.started);
|
|
64
|
+
if (config.autoExitOnQuiet && remainingGrace <= 0) {
|
|
65
|
+
this.dispose(); this.quiet(); return;
|
|
66
|
+
}
|
|
67
|
+
if (config.mode === 'hands-free' && config.updateMode === 'onQuiet' && this.outputChars) this.emit();
|
|
68
|
+
if (config.autoExitOnQuiet) {
|
|
69
|
+
// Grace is measured from launch, not from the most recent output or a view reattach.
|
|
70
|
+
this.quietTimer = setTimeout(onQuiet, Math.max(1, Math.ceil(remainingGrace)));
|
|
71
|
+
this.quietTimer.unref();
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
this.quietTimer = setTimeout(onQuiet, config.quietMs);
|
|
75
|
+
this.quietTimer.unref();
|
|
76
|
+
}
|
|
77
|
+
private resumeTimers(): void {
|
|
78
|
+
this.armQuiet();
|
|
79
|
+
if (this.state.config.mode === 'dispatch') return;
|
|
80
|
+
this.intervalTimer = setInterval(() => {
|
|
81
|
+
if (this.state.config.updateMode === 'interval' || this.outputChars) this.emit();
|
|
82
|
+
}, this.state.config.updateIntervalMs);
|
|
83
|
+
this.intervalTimer.unref();
|
|
84
|
+
}
|
|
85
|
+
private emit(): void {
|
|
86
|
+
const state = this.state, remaining = Math.max(0, state.config.maxTotalChars - state.totalCharsSent);
|
|
87
|
+
let text = remaining ? this.tail.slice(-remaining) : '';
|
|
88
|
+
// A tail boundary must not expose half of a UTF-16 surrogate pair.
|
|
89
|
+
if (/^[\uDC00-\uDFFF]/.test(text)) text = text.slice(1);
|
|
90
|
+
state.totalCharsSent += text.length;
|
|
91
|
+
const value: HandsFreeUpdate = { updateId: ++state.updates, at: new Date().toISOString(), text,
|
|
92
|
+
truncated: this.outputChars > text.length, totalCharsSent: state.totalCharsSent,
|
|
93
|
+
budgetExhausted: state.totalCharsSent >= state.config.maxTotalChars };
|
|
94
|
+
this.tail = ''; this.outputChars = 0;
|
|
95
|
+
this.update(value);
|
|
96
|
+
}
|
|
97
|
+
/** Model input starts a new quiet window even if the program hasn't echoed it yet. */
|
|
98
|
+
input(): void { if (!this.paused && !this.disposed) this.armQuiet(); }
|
|
99
|
+
/** User control suspends updates and quiet termination; the explicit run timeout still applies. */
|
|
100
|
+
pause(): void {
|
|
101
|
+
this.paused = true; clearTimeout(this.quietTimer); clearInterval(this.intervalTimer);
|
|
102
|
+
this.tail = ''; this.outputChars = 0;
|
|
103
|
+
}
|
|
104
|
+
resume(): void { if (this.disposed || !this.paused) return; this.paused = false; this.resumeTimers(); }
|
|
105
|
+
dispose(): void {
|
|
106
|
+
this.disposed = true; clearTimeout(this.quietTimer); clearInterval(this.intervalTimer); this.unsubscribe();
|
|
107
|
+
}
|
|
108
|
+
}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
// Matching, cooldown, dedupe, poll-diff summary and detector protocol adapted from
|
|
2
|
+
// pi-interactive-shell 0.18.0 headless-monitor.ts and index.ts (MIT,
|
|
3
|
+
// third-party/licenses/pi-interactive-shell.txt). pi-suite changes: the monitor tails the job's
|
|
4
|
+
// own log files, so pipe and PTY jobs share it and the logs stay the single source of output.
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
import { open } from 'node:fs/promises';
|
|
7
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
8
|
+
import { normalizeVisibleText } from '../terminal/visible-text.ts';
|
|
9
|
+
import { sanitizeText } from '../../runtime/text.ts';
|
|
10
|
+
import type { ResolvedShellConfig } from '../terminal/shell.ts';
|
|
11
|
+
import { POLL_BOUNDARY, type CompiledMonitor, type Strategy } from './compile.ts';
|
|
12
|
+
|
|
13
|
+
export type MonitorEvent = {
|
|
14
|
+
eventId: number; at: string; strategy: Strategy; triggerId: string; matchedText: string; lineOrDiff: string;
|
|
15
|
+
stream: 'stdout' | 'stderr' | 'output';
|
|
16
|
+
/** The detector failed; the candidate is delivered with the error instead of being dropped. */
|
|
17
|
+
detectorError?: string;
|
|
18
|
+
};
|
|
19
|
+
type Candidate = Omit<MonitorEvent, 'eventId' | 'at'>;
|
|
20
|
+
type Source = { path: string; stream: MonitorEvent['stream']; pty: boolean; offset: number; decoder: StringDecoder; partial: string };
|
|
21
|
+
const TAIL_MS = 250;
|
|
22
|
+
|
|
23
|
+
function summarizeDiff(previous: string, current: string): string {
|
|
24
|
+
if (!previous) return `Output changed: now has content (${current.length} chars)`;
|
|
25
|
+
if (!current) return 'Output changed: now empty';
|
|
26
|
+
const before = previous.split('\n'), after = current.split('\n');
|
|
27
|
+
for (let index = 0; index < Math.max(before.length, after.length); index++) {
|
|
28
|
+
if (before[index] === after[index]) continue;
|
|
29
|
+
const clip = (line = '') => line.length > 120 ? `${line.slice(0, 117)}...` : line;
|
|
30
|
+
return `Output changed at line ${index + 1}: "${clip(before[index])}" -> "${clip(after[index])}"`;
|
|
31
|
+
}
|
|
32
|
+
return 'Output changed';
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function runDetector(detector: NonNullable<CompiledMonitor['detector']>, candidate: Candidate, shell: ResolvedShellConfig, cwd: string): Promise<Partial<Candidate> & { emit: boolean }> {
|
|
36
|
+
const exited = Promise.withResolvers<number | null>();
|
|
37
|
+
const child = spawn(shell.shell, [...shell.args, detector.command], { cwd, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
|
|
38
|
+
let stdout = '', stderr = '';
|
|
39
|
+
const timer = setTimeout(() => { child.kill(); exited.reject(new Error(`detector timed out after ${detector.timeoutMs}ms`)); }, detector.timeoutMs);
|
|
40
|
+
child.stdout.setEncoding('utf8').on('data', chunk => { stdout += chunk; });
|
|
41
|
+
child.stderr.setEncoding('utf8').on('data', chunk => { stderr += chunk; });
|
|
42
|
+
child.once('error', exited.reject);
|
|
43
|
+
child.once('exit', exited.resolve);
|
|
44
|
+
child.stdin.end(`${JSON.stringify(candidate)}\n`);
|
|
45
|
+
let code: number | null;
|
|
46
|
+
try { code = await exited.promise; } finally { clearTimeout(timer); }
|
|
47
|
+
if (code !== 0) throw new Error(`detector exited with code ${code}${stderr ? `: ${stderr.trim()}` : ''}`);
|
|
48
|
+
if (!stdout.trim()) return { emit: true };
|
|
49
|
+
let parsed: unknown;
|
|
50
|
+
try { parsed = JSON.parse(stdout); } catch (error) { throw new Error(`detector returned invalid JSON: ${error instanceof Error ? error.message : String(error)}`); }
|
|
51
|
+
if (typeof parsed === 'boolean') return { emit: parsed };
|
|
52
|
+
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) throw new Error('detector decision must be true, false or an object');
|
|
53
|
+
const decision = parsed as Record<string, unknown>;
|
|
54
|
+
const fields: Partial<Candidate> = {};
|
|
55
|
+
for (const key of ['triggerId', 'matchedText', 'lineOrDiff'] as const) {
|
|
56
|
+
if (decision[key] === undefined) continue;
|
|
57
|
+
if (typeof decision[key] !== 'string') throw new Error(`detector decision ${key} must be a string`);
|
|
58
|
+
fields[key] = decision[key];
|
|
59
|
+
}
|
|
60
|
+
return { ...fields, emit: decision.emit !== false };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Watches one job's output for trigger matches. stream and file-watch match each complete line;
|
|
65
|
+
* poll-diff compares complete OSC-delimited iterations (including stderr), not wall-clock windows.
|
|
66
|
+
* Candidates pass cooldown and dedupe, then the optional detector, in order; record() persists and notifies.
|
|
67
|
+
*/
|
|
68
|
+
export class JobMonitor {
|
|
69
|
+
private timer: NodeJS.Timeout;
|
|
70
|
+
private queue = Promise.resolve();
|
|
71
|
+
private lastFired = new Map<string, number>();
|
|
72
|
+
private seen = new Set<string>();
|
|
73
|
+
private previous?: string;
|
|
74
|
+
private reading?: Promise<void>;
|
|
75
|
+
|
|
76
|
+
constructor(private config: CompiledMonitor, private sources: Source[], private shell: ResolvedShellConfig, private cwd: string,
|
|
77
|
+
private record: (candidate: Candidate) => void) {
|
|
78
|
+
this.timer = setInterval(() => { void this.tick(); }, TAIL_MS);
|
|
79
|
+
this.timer.unref();
|
|
80
|
+
}
|
|
81
|
+
static sources(entries: { path: string; stream: MonitorEvent['stream'] }[], pty: boolean): Source[] {
|
|
82
|
+
return entries.map(entry => ({ ...entry, pty, offset: 0, decoder: new StringDecoder('utf8'), partial: '' }));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
private tick(final = false): Promise<void> {
|
|
86
|
+
// One read at a time: a slow disk must not interleave two reads of the same offset.
|
|
87
|
+
return this.reading ??= this.readNew(final).finally(() => { this.reading = undefined; });
|
|
88
|
+
}
|
|
89
|
+
private async readNew(final: boolean): Promise<void> {
|
|
90
|
+
for (const source of this.sources) {
|
|
91
|
+
const file = await open(source.path, 'r');
|
|
92
|
+
let text = '';
|
|
93
|
+
try {
|
|
94
|
+
const { size } = await file.stat();
|
|
95
|
+
if (size > source.offset) {
|
|
96
|
+
const buffer = Buffer.alloc(size - source.offset);
|
|
97
|
+
const { bytesRead } = await file.read(buffer, 0, buffer.length, source.offset);
|
|
98
|
+
source.offset += bytesRead;
|
|
99
|
+
text = source.decoder.write(buffer.subarray(0, bytesRead));
|
|
100
|
+
}
|
|
101
|
+
} finally { await file.close(); }
|
|
102
|
+
if (final) text += source.decoder.end();
|
|
103
|
+
this.accept(source, text, final);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
private accept(source: Source, text: string, final: boolean): void {
|
|
107
|
+
if (this.config.strategy === 'poll-diff') {
|
|
108
|
+
// Keep incomplete markers/output across disk reads. A stop in the middle of an iteration
|
|
109
|
+
// must not turn its partial output into a spurious final change.
|
|
110
|
+
const samples = (source.partial + text).split(POLL_BOUNDARY);
|
|
111
|
+
source.partial = final ? '' : samples.pop()!;
|
|
112
|
+
if (final) samples.pop();
|
|
113
|
+
for (const raw of samples) {
|
|
114
|
+
const sample = raw.split(/\r?\n/).map(line =>
|
|
115
|
+
(source.pty ? normalizeVisibleText(line) : sanitizeText(line)).trimEnd()).filter(Boolean).join('\n');
|
|
116
|
+
this.pollSample(sample, source.stream);
|
|
117
|
+
}
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
const lines = (source.partial + text).split(/\r?\n/);
|
|
121
|
+
source.partial = final ? '' : lines.pop()!;
|
|
122
|
+
for (const raw of lines) {
|
|
123
|
+
// PTY lines replay CR overwrites to the final visible text; pipe lines drop control bytes.
|
|
124
|
+
const line = (source.pty ? normalizeVisibleText(raw) : sanitizeText(raw)).trimEnd();
|
|
125
|
+
if (!line) continue;
|
|
126
|
+
this.match(line, line, source.stream);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
private pollSample(sample: string, stream: MonitorEvent['stream']): void {
|
|
130
|
+
// The first sample is the baseline; afterwards only a changed sample can fire.
|
|
131
|
+
if (this.previous === undefined || sample === this.previous) { this.previous ??= sample; return; }
|
|
132
|
+
const diff = summarizeDiff(this.previous, sample);
|
|
133
|
+
this.previous = sample;
|
|
134
|
+
this.match(sample, diff, stream);
|
|
135
|
+
}
|
|
136
|
+
private match(text: string, lineOrDiff: string, stream: MonitorEvent['stream']): void {
|
|
137
|
+
for (const trigger of this.config.triggers) {
|
|
138
|
+
const matchedText = trigger.match(text);
|
|
139
|
+
if (matchedText === undefined) continue;
|
|
140
|
+
const cooldown = trigger.cooldownMs ?? this.config.cooldownMs ?? 0, now = Date.now();
|
|
141
|
+
if (cooldown > 0 && now - (this.lastFired.get(trigger.id) ?? -Infinity) < cooldown) continue;
|
|
142
|
+
const key = `${trigger.id}\u0000${lineOrDiff}`;
|
|
143
|
+
if (this.config.dedupe && this.seen.has(key)) continue;
|
|
144
|
+
this.lastFired.set(trigger.id, now); this.seen.add(key);
|
|
145
|
+
this.decide({ strategy: this.config.strategy, triggerId: trigger.id, matchedText, lineOrDiff, stream });
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
private decide(candidate: Candidate): void {
|
|
149
|
+
const detector = this.config.detector;
|
|
150
|
+
if (!detector) { this.record(candidate); return; }
|
|
151
|
+
this.queue = this.queue.then(async () => {
|
|
152
|
+
try {
|
|
153
|
+
const decision = await runDetector(detector, candidate, this.shell, this.cwd);
|
|
154
|
+
if (decision.emit) this.record({ ...candidate, ...decision, strategy: candidate.strategy, stream: candidate.stream });
|
|
155
|
+
} catch (error) { this.record({ ...candidate, detectorError: error instanceof Error ? error.message : String(error) }); }
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
/** After the job's logs are flushed: read the rest, match the last partial lines, drain detectors. */
|
|
159
|
+
async stop(): Promise<void> {
|
|
160
|
+
clearInterval(this.timer);
|
|
161
|
+
await this.reading;
|
|
162
|
+
await this.tick(true);
|
|
163
|
+
await this.queue;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { fileSource, readBounded, boundedText, READ_LIMITS, type ReadPage, type ReadRequest } from '../runtime/read.ts';
|
|
2
|
+
import { ToolError } from '../runtime/errors.ts';
|
|
3
|
+
import { sanitizeText } from '../runtime/text.ts';
|
|
4
|
+
import type { JobReader } from './control.ts';
|
|
5
|
+
import type { InputRecord, JobSummary, Stream } from './types.ts';
|
|
6
|
+
import type { MonitorEvent } from './monitors/runtime.ts';
|
|
7
|
+
import { normalizeVisibleText } from './terminal/visible-text.ts';
|
|
8
|
+
import { passwordSafeSource } from './terminal/read.ts';
|
|
9
|
+
|
|
10
|
+
export function streamsOf(job: JobSummary): Stream[] {
|
|
11
|
+
return [...job.mode === 'pty' ? ['output'] as const : ['stdout', 'stderr'] as const, 'input', ...job.monitor ? ['events'] as const : []];
|
|
12
|
+
}
|
|
13
|
+
function renderEvents(raw: string): string {
|
|
14
|
+
return raw.split('\n').map(line => {
|
|
15
|
+
if (!line.trim()) return line;
|
|
16
|
+
let event: MonitorEvent;
|
|
17
|
+
try { event = JSON.parse(line); } catch { return line; }
|
|
18
|
+
return `#${event.eventId} ${event.at} ${event.triggerId} ${event.stream}: ${sanitizeText(event.lineOrDiff)}${event.detectorError ? ` · detector failed: ${event.detectorError}` : ''}`;
|
|
19
|
+
}).join('\n');
|
|
20
|
+
}
|
|
21
|
+
export function renderInput(raw: string): string {
|
|
22
|
+
return raw.split('\n').map(line => {
|
|
23
|
+
if (!line.trim()) return line;
|
|
24
|
+
let record: InputRecord;
|
|
25
|
+
try { record = JSON.parse(line); } catch { return line; }
|
|
26
|
+
return `${record.at} ${record.source} ${record.kind} ${record.sensitive ? '[sensitive input sent]' : JSON.stringify(record.text ?? '')}`;
|
|
27
|
+
}).join('\n');
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** One log reader for tools, viewers and settlement previews; all offsets remain raw bytes. */
|
|
31
|
+
export async function readJobLog(manager: Pick<JobReader, 'logPath'>, job: JobSummary, requested: Stream | undefined, request: ReadRequest): Promise<ReadPage & {stream: Stream}> {
|
|
32
|
+
const stream = requested ?? (job.mode === 'pty' ? 'output' : 'stdout'), streams = streamsOf(job);
|
|
33
|
+
if (!streams.includes(stream)) throw new ToolError('UNSUPPORTED_STREAM', `${job.id} has streams ${streams.join(', ')}`, job.id);
|
|
34
|
+
const pty = job.mode === 'pty' && stream === 'output';
|
|
35
|
+
const render = stream === 'input' ? renderInput : stream === 'events' ? renderEvents : pty ? normalizeVisibleText : sanitizeText;
|
|
36
|
+
const raw = await fileSource(manager.logPath(job, stream)), source = pty ? passwordSafeSource(raw) : raw;
|
|
37
|
+
try {
|
|
38
|
+
const page = await readBounded(source, request, render);
|
|
39
|
+
const note = pty && job.fullScreen ? '[Full-screen terminal output; this text log may not match the screen. The user can view the screen in /jobs.]\n' : '';
|
|
40
|
+
const budget = request.limitBytes ?? READ_LIMITS.defaultBytes;
|
|
41
|
+
return {...page, text: note + (pty ? boundedText(page.text, budget) : page.text), stream};
|
|
42
|
+
} finally { await source.close(); }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Collected before publishing the terminal state, so one boundary gets the complete notice. */
|
|
46
|
+
export async function outputPreview(manager: Pick<JobReader, 'logPath'>, job: JobSummary): Promise<string> {
|
|
47
|
+
const streams: Stream[] = job.mode === 'pty' ? ['output'] : ['stdout', 'stderr'];
|
|
48
|
+
const parts: string[] = [];
|
|
49
|
+
for (const stream of streams) {
|
|
50
|
+
const page = await readJobLog(manager, job, stream, {limitBytes: Math.floor(2048 / streams.length)});
|
|
51
|
+
if (page.text.trim()) parts.push(`${stream}:\n${page.text}`);
|
|
52
|
+
}
|
|
53
|
+
return boundedText(parts.join('\n'), 2048);
|
|
54
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { paginate } from '../runtime/tools.ts';
|
|
2
|
+
import { boundedText } from '../runtime/read.ts';
|
|
3
|
+
import { bucket } from './state.ts';
|
|
4
|
+
import type { JobReader } from './control.ts';
|
|
5
|
+
import { isWorkflowGate, type JobSummary, type Workspace } from './types.ts';
|
|
6
|
+
import { displayName, summaryLine } from './index.ts';
|
|
7
|
+
import { field, part, plainDetailLines, statePart, type StructuredDetails } from '../ui/structured-details.ts';
|
|
8
|
+
export { readJobLog, renderInput, streamsOf } from './output.ts';
|
|
9
|
+
|
|
10
|
+
/** Filters shared by job_list and /jobs: same buckets and session scope as the status count. */
|
|
11
|
+
export type ListState = 'active' | 'finished' | 'all';
|
|
12
|
+
export type ListScope = 'session' | 'workspace';
|
|
13
|
+
export interface ListQuery { state: ListState; scope: ListScope; sessionId: string; cursor?: string; limit: number; budgetBytes?: number }
|
|
14
|
+
export interface ListRow { job: JobSummary; live: boolean; unsettled: boolean }
|
|
15
|
+
export interface ListResult { rows: ListRow[]; nextCursor?: string; errors: string[] }
|
|
16
|
+
export interface SessionScope { jobs(): JobSummary[]; visible(job: JobSummary): boolean }
|
|
17
|
+
|
|
18
|
+
export function selectJobRows(jobs: { job: JobSummary; live: boolean }[], query: Pick<ListQuery, 'scope' | 'state' | 'sessionId'>, session?: SessionScope): ListRow[] {
|
|
19
|
+
const merged = new Map(jobs.map(row => [row.job.id, row]));
|
|
20
|
+
// Storage yields to lifecycle changes; use current owned views when merging live jobs.
|
|
21
|
+
if (query.scope === 'session') for (const job of session?.jobs() ?? []) merged.set(job.id, {job, live: true});
|
|
22
|
+
return [...merged.values()].map(({ job, live }) => ({ job, live, unsettled: bucket(job, live) === 'unsettled' }))
|
|
23
|
+
.filter(row => !isWorkflowGate(row.job) && (query.scope === 'workspace' || (session ? session.visible(row.job) : row.job.ownerSessionId === query.sessionId)) &&
|
|
24
|
+
(query.state === 'all' || bucket(row.job, row.live) === query.state));
|
|
25
|
+
}
|
|
26
|
+
export async function listJobs(manager: JobReader, workspace: Workspace, query: ListQuery, session?: SessionScope): Promise<ListResult> {
|
|
27
|
+
const { jobs, errors } = await manager.list(workspace);
|
|
28
|
+
const { page, nextCursor } = paginate(selectJobRows(jobs, query, session), row => row.job, query.cursor, query.limit,
|
|
29
|
+
{ budgetBytes: query.budgetBytes, size: row => Buffer.byteLength(summaryLine(row.job) + boundedText(displayName(row.job), 200) + (row.job.error ?? '')) + 80 });
|
|
30
|
+
return { rows: page, nextCursor, errors };
|
|
31
|
+
}
|
|
32
|
+
/** One field list feeds both the model-visible receipt and the colored Details pane. */
|
|
33
|
+
export function jobDetailView(job: JobSummary, fullCommand = false): StructuredDetails {
|
|
34
|
+
const command = !fullCommand && job.command.length > 2000 ? `${job.command.slice(0, 2000)}… [${job.command.length} chars]` : job.command;
|
|
35
|
+
const {cleanup} = job;
|
|
36
|
+
const exit = job.exitCode ?? job.signal;
|
|
37
|
+
const details: StructuredDetails = {rows: [
|
|
38
|
+
field('name:', part(displayName(job), 'heading')), field('cwd:', part(job.cwd, 'meta')),
|
|
39
|
+
field('mode:', job.mode), field('state:', statePart(job.state)),
|
|
40
|
+
field('runtime:', job.elapsedMs === undefined ? 'not started' : part(`${(job.elapsedMs / 1000).toFixed(1)}s`, 'number')), null,
|
|
41
|
+
field('command:', command), null,
|
|
42
|
+
field('created', part(job.createdAt, 'meta'),
|
|
43
|
+
...(job.startedAt ? [part(' · started ', 'label'), part(job.startedAt, 'meta')] : []),
|
|
44
|
+
...(job.endedAt ? [part(' · ended ', 'label'), part(job.endedAt, 'meta')] : [])),
|
|
45
|
+
job.exitCode !== null || job.signal ? field('exit:', part(`${exit}`, typeof exit === 'number' ? 'number' : undefined)) : undefined,
|
|
46
|
+
job.timeoutMs ? field('timeoutMs:', part(job.timeoutMs, 'number')) : undefined,
|
|
47
|
+
job.handsFree ? field('supervision:', job.handsFree.config.mode, part(' · updates ', 'label'), part(job.handsFree.updates, 'number'),
|
|
48
|
+
part(' · output budget ', 'label'), part(`${job.handsFree.totalCharsSent}/${job.handsFree.config.maxTotalChars} chars`, 'number')) : undefined,
|
|
49
|
+
field('cleanup:', statePart(cleanup.state, cleanup.state === 'pending' ? 'cleanup pending' : cleanup.state === 'unconfirmed' ? 'cleanup unconfirmed' : 'completed'),
|
|
50
|
+
...(cleanup.error ? [part(` (${cleanup.error})`, 'error')] : [])),
|
|
51
|
+
...(job.error ? [null, field('error:', part(job.error, 'error'))] : []), null,
|
|
52
|
+
job.taskId ? field('task:', part(job.taskId, 'id'), part(' · source generation: ', 'label'), part(job.taskGeneration ?? 'unavailable (legacy link expired)', 'id')) : undefined,
|
|
53
|
+
job.creator ? field('created by', part(`${job.creator.agentId ?? job.creator.workflowId}`, 'id'), part(' '), part(job.creator.runId, 'id')) : undefined,
|
|
54
|
+
]};
|
|
55
|
+
return details;
|
|
56
|
+
}
|
|
57
|
+
export const jobDetail = (job: JobSummary, fullCommand = false): string[] => plainDetailLines(jobDetailView(job, fullCommand));
|
|
58
|
+
|
|
59
|
+
export function jobViewerDetails(job: JobSummary, live = true): StructuredDetails {
|
|
60
|
+
return {rows: [field('ID:', part(job.id, 'id')), ...jobDetailView(job, true).rows,
|
|
61
|
+
live ? undefined : [part('history only: not controlled by this Pi process', 'meta')]]};
|
|
62
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import type { MessageRenderer } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import { Box, truncateToWidth } from '@earendil-works/pi-tui';
|
|
3
|
+
import { sanitizeText } from '../runtime/text.ts';
|
|
4
|
+
import { readingText } from '../ui/reading.ts';
|
|
5
|
+
import { readPageFields } from '../ui/rendering/read-page.ts';
|
|
6
|
+
import { toolRenderers, toolLine, stateLine, type ToolExpandedRow, type ToolLine } from '../ui/tool-render.ts';
|
|
7
|
+
import type { ReadPage } from '../runtime/read.ts';
|
|
8
|
+
import type { StopOutcome } from '../runtime/tools.ts';
|
|
9
|
+
import type { JobSummary } from './types.ts';
|
|
10
|
+
|
|
11
|
+
export const JOB_SCREEN = 'pi-suite:job-screen';
|
|
12
|
+
export type JobScreenDetails = Pick<JobSummary, 'id' | 'state'> & { screenLines: string[] };
|
|
13
|
+
type JobDetails = { job: JobSummary; attach?: string; screenLines?: string[] };
|
|
14
|
+
|
|
15
|
+
const screenCaption = ({ id, state }: Pick<JobScreenDetails, 'id' | 'state'>): ToolLine => ({
|
|
16
|
+
icon: '', title: 'Job screen', summary: id, meta: [{ text: state, tone: stateLine(state).tone! }],
|
|
17
|
+
});
|
|
18
|
+
// Keep a terminal row a row, including indentation and blank rows. Never reflow it as Markdown.
|
|
19
|
+
const screenBody = (screenLines: string[]) => {
|
|
20
|
+
const lines = screenLines.map(sanitizeText);
|
|
21
|
+
return readingText(() => lines);
|
|
22
|
+
};
|
|
23
|
+
export const jobScreenRenderer: MessageRenderer<JobScreenDetails> = ({ details }, { expanded, outputPad }, theme) => {
|
|
24
|
+
// A persisted transfer can predate structured details; let Pi show its original content.
|
|
25
|
+
if (!details?.screenLines) return;
|
|
26
|
+
const box = new Box(outputPad, 0, text => theme.bg('customMessageBg', text));
|
|
27
|
+
box.addChild(readingText(width => [toolLine(theme, screenCaption(details), width)]));
|
|
28
|
+
if (expanded) box.addChild(screenBody(details.screenLines));
|
|
29
|
+
return box;
|
|
30
|
+
};
|
|
31
|
+
type JobArgs = { id: string };
|
|
32
|
+
type StartArgs = { name?: string; command?: string; mode?: string };
|
|
33
|
+
type ReadArgs = JobArgs & { stream?: string };
|
|
34
|
+
type ReadDetails = ReadPage & { id: string; stream: string; stderrBytes?: number };
|
|
35
|
+
type WriteArgs = JobArgs & { input?: string; keys?: string[]; paste?: string; sensitive?: boolean };
|
|
36
|
+
// Saved receipts from before these fields were recorded still have a job ID.
|
|
37
|
+
type WriteDetails = JobDetails & { bytesSent?: number; stdinClosed?: boolean };
|
|
38
|
+
const name = (job: JobSummary) => job.name || job.command.split('\n')[0];
|
|
39
|
+
const cleanupTone = (cleanup: string) => cleanup === 'pending' || cleanup === 'unconfirmed' ? 'warning' as const : 'dim' as const;
|
|
40
|
+
function jobFields(job: JobSummary): ToolExpandedRow[] {
|
|
41
|
+
return [
|
|
42
|
+
// Jobs execute through Pi's Bash selection (including Git Bash/WSL on Windows).
|
|
43
|
+
{ command: job.command, shell: 'bash', label: 'command' }, { label: 'cwd', value: job.cwd },
|
|
44
|
+
...job.timeoutMs ? [{ label: 'timeout', value: `${job.timeoutMs}ms` }] : [],
|
|
45
|
+
...job.taskId ? [{ label: 'task', value: `${job.taskId} · source generation: ${job.taskGeneration ?? 'unavailable (legacy link expired)'}` }] : [],
|
|
46
|
+
{ label: 'state', value: job.state, tone: stateLine(job.state).tone },
|
|
47
|
+
{ label: 'cleanup', value: job.cleanup.state, tone: cleanupTone(job.cleanup.state) },
|
|
48
|
+
...job.cleanup.error ? [{ label: 'cleanup error', value: job.cleanup.error, tone: 'warning' as const }] : [],
|
|
49
|
+
...job.error ? [{ label: 'error', value: job.error, tone: 'error' as const }] : [],
|
|
50
|
+
];
|
|
51
|
+
}
|
|
52
|
+
export const startRenderers = toolRenderers<StartArgs, JobDetails>({
|
|
53
|
+
call: args => ({ icon: '⟳', tone: 'accent', title: 'Job', summary: truncateToWidth(args.name ?? args.command?.split('\n')[0] ?? 'agent', 60), meta: [args.mode ?? 'pipe'] }),
|
|
54
|
+
collapsed: ({ job, attach, screenLines }) => screenLines ? screenCaption(job) : ({ ...stateLine(job.state), title: job.id, summary: name(job),
|
|
55
|
+
meta: [{ text: job.state, tone: stateLine(job.state).tone! }, job.mode, ...job.timeoutMs ? [`timeout ${job.timeoutMs / 1000}s`] : [],
|
|
56
|
+
...attach ? [attach === 'transfer' ? 'screen returned' : 'left terminal'] : []] }),
|
|
57
|
+
expanded: ({ job, screenLines }, _args, text) => screenLines ? screenBody(screenLines) : [...jobFields(job), text],
|
|
58
|
+
});
|
|
59
|
+
export const listRenderers = toolRenderers<{ state?: string; scope?: string }, { jobs: JobSummary[]; nextCursor?: string; errors: string[] }>({
|
|
60
|
+
call: () => ({ icon: '⟳', tone: 'accent', title: 'Jobs' }),
|
|
61
|
+
collapsed: (data, args) => ({ icon: '', title: 'Jobs', summary: `${data.jobs.length} ${args.state ?? 'active'} (${args.scope ?? 'session'})`, meta: data.nextCursor ? ['more'] : [] }),
|
|
62
|
+
expanded: data => [...data.jobs.flatMap(job => [
|
|
63
|
+
{ ...stateLine(job.state), title: job.id, summary: name(job), meta: [{ text: job.state, tone: stateLine(job.state).tone! },
|
|
64
|
+
`${((job.elapsedMs ?? Date.now() - Date.parse(job.startedAt ?? job.createdAt)) / 1000).toFixed(1)}s`,
|
|
65
|
+
{ text: `cleanup ${job.cleanup.state}`, tone: cleanupTone(job.cleanup.state) }] },
|
|
66
|
+
...job.error ? [{ label: 'error', value: job.error, tone: 'error' as const }] : [],
|
|
67
|
+
]), ...data.errors.map(error => ({ label: 'history error', value: error, tone: 'error' as const })),
|
|
68
|
+
...data.nextCursor ? [{ label: 'more', value: 'next page available', tone: 'warning' as const }] : []],
|
|
69
|
+
});
|
|
70
|
+
export const getRenderers = toolRenderers<JobArgs, JobDetails & { live: boolean }>({
|
|
71
|
+
call: args => ({ icon: '⟳', tone: 'accent', title: 'Job', summary: args.id }),
|
|
72
|
+
collapsed: ({ job }) => ({ ...stateLine(job.state), title: job.id, summary: name(job),
|
|
73
|
+
meta: [{ text: job.state, tone: stateLine(job.state).tone! }, ...job.error ? [{ text: 'error', tone: 'error' as const }] : []] }),
|
|
74
|
+
expanded: ({ job, live }) => [...jobFields(job), { label: 'live', value: String(live) },
|
|
75
|
+
{ code: JSON.stringify(job, null, 2), language: 'json', label: 'details' }],
|
|
76
|
+
});
|
|
77
|
+
export const readRenderers = toolRenderers<ReadArgs, ReadDetails>({
|
|
78
|
+
call: args => ({ icon: '⟳', tone: 'accent', title: 'Job read', summary: args.id, meta: args.stream ? [args.stream] : [] }),
|
|
79
|
+
collapsed: data => ({ icon: '', title: 'Job read', summary: `${data.id} · ${data.stream} ${data.offset}–${data.nextOffset} / ${data.totalBytes} B`, meta: data.matches !== undefined ? [`${data.matches} matches`] : [] }),
|
|
80
|
+
expanded: data => [...readPageFields(data),
|
|
81
|
+
...data.stderrBytes !== undefined ? [{ label: 'stderrBytes', value: String(data.stderrBytes) }] : [], data.text],
|
|
82
|
+
});
|
|
83
|
+
export const writeRenderers = toolRenderers<WriteArgs, WriteDetails>({
|
|
84
|
+
// Never put input into a call line, including the host's expanded call slot.
|
|
85
|
+
call: args => ({ icon: '⟳', tone: 'accent', title: 'Job input', summary: args.id }),
|
|
86
|
+
// Successful receipts contain only counts. Redact diagnostics, not coincidental receipt words.
|
|
87
|
+
redact: (args, text, isError) => args.sensitive && isError ? [args.input, args.paste, ...(args.keys ?? [])].reduce<string>((shown, value) =>
|
|
88
|
+
value && sanitizeText(value) ? shown.replaceAll(sanitizeText(value), '[sensitive]') : shown, text) : text,
|
|
89
|
+
collapsed: ({ job, bytesSent, stdinClosed }) => ({ icon: '', title: 'Job input',
|
|
90
|
+
summary: bytesSent === undefined ? job.id : `${job.id} · sent ${bytesSent} B`, meta: stdinClosed ? ['stdin closed'] : [] }),
|
|
91
|
+
expanded: ({ bytesSent, stdinClosed }, args) => [{ label: args.keys ? 'keys' : args.paste !== undefined ? 'paste' : 'input',
|
|
92
|
+
value: args.sensitive ? '[sensitive]' : args.keys ? args.keys.join(' ') : args.paste ?? args.input ?? '' },
|
|
93
|
+
...bytesSent !== undefined ? [{ label: 'bytesSent', value: String(bytesSent) }] : [],
|
|
94
|
+
...stdinClosed !== undefined ? [{ label: 'stdinClosed', value: String(stdinClosed) }] : []],
|
|
95
|
+
});
|
|
96
|
+
export const stopRenderers = toolRenderers<JobArgs, StopOutcome & JobDetails>({
|
|
97
|
+
call: args => ({ icon: '⟳', tone: 'accent', title: 'Job stop', summary: args.id }),
|
|
98
|
+
collapsed: data => ({ ...data.requested ? stateLine(data.state) : { icon: '', tone: undefined }, title: data.job.id,
|
|
99
|
+
summary: data.requested ? data.state : 'already settled',
|
|
100
|
+
meta: [{ text: `cleanup ${data.cleanup === 'managed_scope_confirmed' ? 'confirmed' : data.cleanup}`, tone: cleanupTone(data.cleanup) }] }),
|
|
101
|
+
expanded: data => [...jobFields(data.job), { label: 'requested', value: String(data.requested) },
|
|
102
|
+
{ code: JSON.stringify(data.affected, null, 2), language: 'json', label: 'affected' }],
|
|
103
|
+
});
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// Adapted from pi-background-jobs 0.1.3 src/runtime.ts (MIT, third-party/licenses/pi-background-jobs.txt).
|
|
2
|
+
// pi-suite changes: own registration/execution protocol; an independent read/stop bridge
|
|
3
|
+
// retains the owner's public control operations across execution protocol upgrades.
|
|
4
|
+
import { randomBytes } from 'node:crypto';
|
|
5
|
+
import { mkdirSync, realpathSync } from 'node:fs';
|
|
6
|
+
import { JobManager } from './manager.ts';
|
|
7
|
+
import { LIMITS } from './types.ts';
|
|
8
|
+
import type { ControlBridge } from './control.ts';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The manager lives in a process-global slot so reload re-imports this module without losing
|
|
12
|
+
* running jobs. New code cannot drive the internals of a manager built for another protocol, so
|
|
13
|
+
* an occupied incompatible manager keeps running and is reached only through its control bridge.
|
|
14
|
+
*/
|
|
15
|
+
export const PROTOCOL_VERSION = 11;
|
|
16
|
+
export type RuntimeHandle =
|
|
17
|
+
| { mode: 'active'; manager: JobManager }
|
|
18
|
+
| { mode: 'restricted'; reason: string; control: ControlBridge }
|
|
19
|
+
| { mode: 'unavailable'; reason: string };
|
|
20
|
+
type Registration = {
|
|
21
|
+
protocolVersion: number; agentDir: string; manager: JobManager; control: ControlBridge; exitListener: () => void;
|
|
22
|
+
};
|
|
23
|
+
const key = Symbol.for('pi-suite.jobs.runtime');
|
|
24
|
+
const globals = globalThis as typeof globalThis & { [key]?: Registration };
|
|
25
|
+
|
|
26
|
+
function compatible(value: unknown, agentDir: string): value is Registration {
|
|
27
|
+
if (!value || typeof value !== 'object' || !('protocolVersion' in value) || !('agentDir' in value) || !('manager' in value)) return false;
|
|
28
|
+
const manager: unknown = value.manager;
|
|
29
|
+
return value.protocolVersion === PROTOCOL_VERSION && value.agentDir === agentDir &&
|
|
30
|
+
!!manager && typeof manager === 'object' && 'subscribe' in manager && typeof manager.subscribe === 'function';
|
|
31
|
+
}
|
|
32
|
+
/** An old registration of unknown shape counts as occupied unless it proves otherwise. */
|
|
33
|
+
function occupied(value: unknown): boolean {
|
|
34
|
+
if (!value || typeof value !== 'object' || !('manager' in value)) return true;
|
|
35
|
+
const manager: unknown = value.manager;
|
|
36
|
+
if (!manager || typeof manager !== 'object' || !('hasOccupancy' in manager) || typeof manager.hasOccupancy !== 'function') return true;
|
|
37
|
+
return manager.hasOccupancy() !== false;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function acquireRuntime(agentDir: string): RuntimeHandle {
|
|
41
|
+
mkdirSync(agentDir, { recursive: true, mode: 0o700 });
|
|
42
|
+
const root = realpathSync(agentDir);
|
|
43
|
+
const existing = globals[key];
|
|
44
|
+
if (existing !== undefined) {
|
|
45
|
+
if (compatible(existing, root) && !existing.manager.closed) return { mode: 'active', manager: existing.manager };
|
|
46
|
+
if (occupied(existing)) {
|
|
47
|
+
const reason = 'An older pi-suite jobs runtime still has running or unsaved jobs; starting jobs, input and attach are disabled. Stop or wait for those jobs, then /reload';
|
|
48
|
+
if (existing.agentDir === root && (existing.control?.version === 1 || existing.control?.version === 2 || existing.control?.version === 3 || existing.control?.version === 4)) return { mode: 'restricted', reason, control: existing.control };
|
|
49
|
+
return { mode: 'unavailable', reason: existing.agentDir !== root
|
|
50
|
+
? 'The running pi-suite jobs runtime uses a different agent directory; restart Pi to use jobs here'
|
|
51
|
+
: 'An incompatible pi-suite jobs runtime still has running or unsaved jobs; restart Pi to use jobs' };
|
|
52
|
+
}
|
|
53
|
+
// Idle or closed: retire the old registration before publishing a replacement.
|
|
54
|
+
void existing.manager.shutdown(Date.now() + LIMITS.quitMs).catch(error => process.emitWarning(`pi-suite jobs retirement failed: ${String(error)}`));
|
|
55
|
+
if (typeof existing.exitListener === 'function') process.removeListener('exit', existing.exitListener);
|
|
56
|
+
}
|
|
57
|
+
const manager = new JobManager({ agentDir: root, runtimeId: `rt_${randomBytes(4).toString('hex')}` });
|
|
58
|
+
// These closures keep calling this implementation after reload. The bridge has no start or
|
|
59
|
+
// write operation, so newer code cannot launch jobs or send input through this manager.
|
|
60
|
+
const control: ControlBridge = { version: 4, jobs: {
|
|
61
|
+
peek: id => manager.peek(id), get: (id, workspace) => manager.get(id, workspace),
|
|
62
|
+
list: workspace => manager.list(workspace), logPath: (job, stream) => manager.logPath(job, stream),
|
|
63
|
+
subscribe: listener => manager.subscribe(listener), activeIds: sessionId => manager.activeIds(sessionId),
|
|
64
|
+
markNotified: id => manager.markNotified(id),
|
|
65
|
+
stop: (id, reason, deadline) => manager.stop(id, reason, deadline),
|
|
66
|
+
createdBy: runIds => manager.createdBy(runIds),
|
|
67
|
+
sessionJobs: sessionId => manager.sessionJobs(sessionId),
|
|
68
|
+
readTerminalSnapshot: job => manager.readTerminalSnapshot(job),
|
|
69
|
+
clear: (id, workspace) => manager.clear(id, workspace),
|
|
70
|
+
}, quit: () => quitRuntime(manager) };
|
|
71
|
+
const registration: Registration = { protocolVersion: PROTOCOL_VERSION, agentDir: root, manager, control, exitListener: () => manager.exitSync(Date.now() + LIMITS.exitFallbackMs) };
|
|
72
|
+
process.on('exit', registration.exitListener);
|
|
73
|
+
globals[key] = registration;
|
|
74
|
+
return { mode: 'active', manager };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Quit policy: stop every live job under one shared deadline; repeated calls share it. */
|
|
78
|
+
export function quitRuntime(manager: JobManager): Promise<void> {
|
|
79
|
+
return manager.shutdown(Date.now() + LIMITS.quitMs);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Disabling modules removes bindings, but quit must still join the existing owner. */
|
|
83
|
+
export function quitExistingRuntime(agentDir: string): Promise<void> | undefined {
|
|
84
|
+
const existing = globals[key];
|
|
85
|
+
if (!existing || existing.agentDir !== realpathSync(agentDir)) return;
|
|
86
|
+
// An occupied implementation without a supported bridge keeps its original exit
|
|
87
|
+
// listener; invoking unknown manager internals would break that owner's cleanup.
|
|
88
|
+
if (existing.control?.version === 1 || existing.control?.version === 2 || existing.control?.version === 3 || existing.control?.version === 4) return existing.control.quit();
|
|
89
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Adapted from pi-background-jobs 0.1.3 src/state.ts (MIT). The exclusive-lock predicate is
|
|
2
|
+
// dropped with the workspace lock; "cancelled" is reported as "stopped".
|
|
3
|
+
import type { JobState, ExitObservation, StopReason, JobSummary } from './types.ts';
|
|
4
|
+
export function isTerminal(state: JobState): boolean {
|
|
5
|
+
return !['starting', 'running', 'stopping'].includes(state);
|
|
6
|
+
}
|
|
7
|
+
/** A real exit observation settles the job; a stop reason only explains why it ended. */
|
|
8
|
+
export function settleExit(exit: ExitObservation, reason?: StopReason): JobState {
|
|
9
|
+
if (reason === 'timeout') return 'timed_out';
|
|
10
|
+
if (reason === 'log_limit') return 'failed';
|
|
11
|
+
if (reason) return 'stopped';
|
|
12
|
+
return exit.code === 0 && !exit.signal && !exit.error ? 'completed' : 'failed';
|
|
13
|
+
}
|
|
14
|
+
/** Active for status counts: unsettled, or settled while cleanup is still unproven. */
|
|
15
|
+
export function isActive(job: JobSummary): boolean {
|
|
16
|
+
return !isTerminal(job.state) || job.cleanup.state === 'pending' || job.cleanup.state === 'unconfirmed' && !job.cleanup.rootExited;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* List bucket. Only jobs this Pi process controls can be active; a stored record without a
|
|
20
|
+
* proven settlement (another process, or a crash) is "unsettled" and never counted as success.
|
|
21
|
+
*/
|
|
22
|
+
export function bucket(job: JobSummary, live: boolean): 'active' | 'finished' | 'unsettled' {
|
|
23
|
+
if (live) return isActive(job) ? 'active' : 'finished';
|
|
24
|
+
return isTerminal(job.state) && job.cleanup.state !== 'pending' && job.cleanup.state !== 'unconfirmed' ? 'finished' : 'unsettled';
|
|
25
|
+
}
|