pi-lean-bg 0.0.0-init → 0.1.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 +37 -0
- package/index.ts +1 -0
- package/package.json +60 -1
- package/src/dock.ts +394 -0
- package/src/format.ts +75 -0
- package/src/index.ts +417 -0
- package/src/logs.ts +104 -0
- package/src/registry.ts +512 -0
- package/src/reload-hub.ts +82 -0
- package/src/schemas.ts +54 -0
- package/src/types.ts +54 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,417 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext, ThemeColor } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import { Text, type KeyId } from '@earendil-works/pi-tui';
|
|
3
|
+
import { BgTaskDock } from './dock.ts';
|
|
4
|
+
import {
|
|
5
|
+
formatBytes,
|
|
6
|
+
formatLaunchReceipt,
|
|
7
|
+
formatNotificationXml,
|
|
8
|
+
formatStatusLine,
|
|
9
|
+
formatStatusList,
|
|
10
|
+
} from './format.ts';
|
|
11
|
+
import { TaskRegistry } from './registry.ts';
|
|
12
|
+
import {
|
|
13
|
+
BgKillParams,
|
|
14
|
+
BgLogsParams,
|
|
15
|
+
BgRunParams,
|
|
16
|
+
BgStatusParams,
|
|
17
|
+
type BgKillParamsValue,
|
|
18
|
+
type BgLogsParamsValue,
|
|
19
|
+
type BgRunParamsValue,
|
|
20
|
+
type BgStatusParamsValue,
|
|
21
|
+
} from './schemas.ts';
|
|
22
|
+
import { DEFAULT_LOG_BYTES, type BgTaskSnapshot, type NotifyMode } from './types.ts';
|
|
23
|
+
|
|
24
|
+
const STATUS_KEY = 'bgtask';
|
|
25
|
+
const NOTIFY_CUSTOM_TYPE = 'background-task-notification';
|
|
26
|
+
const STATUS_INTERVAL_MS = 1000;
|
|
27
|
+
const NOTIFY_RETRY_ATTEMPTS = 3;
|
|
28
|
+
const NOTIFY_RETRY_DELAY_MS = 100;
|
|
29
|
+
const LIGHT_BLUE_BG = '\x1b[48;2;183;223;255m';
|
|
30
|
+
const LIGHT_BLUE_FG = '\x1b[38;2;11;70;110m';
|
|
31
|
+
const ANSI_RESET = '\x1b[0m';
|
|
32
|
+
|
|
33
|
+
const ALLOWED_BG_RUN_KEYS = new Set(['name', 'command', 'timeoutSeconds', 'surviveReload', 'notify']);
|
|
34
|
+
|
|
35
|
+
function lightBlue(text: string): string {
|
|
36
|
+
return `${LIGHT_BLUE_BG}${LIGHT_BLUE_FG}${text}${ANSI_RESET}`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function parseBgCommandArgs(raw: string): { command: string; name?: string; surviveReload: boolean } {
|
|
40
|
+
let rest = raw.trim();
|
|
41
|
+
let surviveReload = false;
|
|
42
|
+
let name: string | undefined;
|
|
43
|
+
|
|
44
|
+
while (rest.startsWith('--')) {
|
|
45
|
+
if (rest === '--survive-reload' || rest.startsWith('--survive-reload ')) {
|
|
46
|
+
surviveReload = true;
|
|
47
|
+
rest = rest.slice('--survive-reload'.length).trimStart();
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
if (rest.startsWith('--name ')) {
|
|
51
|
+
rest = rest.slice('--name '.length).trimStart();
|
|
52
|
+
if (rest.startsWith('"') || rest.startsWith("'")) {
|
|
53
|
+
const quote = rest[0]!;
|
|
54
|
+
const end = rest.indexOf(quote, 1);
|
|
55
|
+
if (end === -1) throw new Error('Unterminated quote in --name');
|
|
56
|
+
name = rest.slice(1, end).trim();
|
|
57
|
+
rest = rest.slice(end + 1).trimStart();
|
|
58
|
+
} else {
|
|
59
|
+
const sp = rest.search(/\s/);
|
|
60
|
+
if (sp === -1) throw new Error('Missing command after --name');
|
|
61
|
+
name = rest.slice(0, sp).trim();
|
|
62
|
+
rest = rest.slice(sp + 1).trimStart();
|
|
63
|
+
}
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
break;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if (!rest) throw new Error('Usage: /bg [--survive-reload] [--name "Label"] <command>');
|
|
70
|
+
return { command: rest, name, surviveReload };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function getSessionId(ctx: ExtensionContext): string {
|
|
74
|
+
try {
|
|
75
|
+
return ctx.sessionManager.getSessionId() || 'default';
|
|
76
|
+
} catch {
|
|
77
|
+
return 'default';
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export default function bgTaskExtension(pi: ExtensionAPI): void {
|
|
82
|
+
let currentCtx: ExtensionContext | undefined;
|
|
83
|
+
let statusTimer: NodeJS.Timeout | undefined;
|
|
84
|
+
let dockOpen = false;
|
|
85
|
+
let disposed = false;
|
|
86
|
+
const seenIds = new Set<string>();
|
|
87
|
+
|
|
88
|
+
const deliverNotification = (task: BgTaskSnapshot, attempt = 1): void => {
|
|
89
|
+
if (disposed) return;
|
|
90
|
+
const content = formatNotificationXml(task);
|
|
91
|
+
try {
|
|
92
|
+
pi.sendMessage(
|
|
93
|
+
{
|
|
94
|
+
customType: NOTIFY_CUSTOM_TYPE,
|
|
95
|
+
content,
|
|
96
|
+
display: true,
|
|
97
|
+
details: task,
|
|
98
|
+
},
|
|
99
|
+
{
|
|
100
|
+
deliverAs: 'followUp',
|
|
101
|
+
triggerTurn: task.notify === 'wake',
|
|
102
|
+
},
|
|
103
|
+
);
|
|
104
|
+
} catch {
|
|
105
|
+
if (attempt < NOTIFY_RETRY_ATTEMPTS && !disposed) {
|
|
106
|
+
setTimeout(() => deliverNotification(task, attempt + 1), NOTIFY_RETRY_DELAY_MS).unref();
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
const syncStatusTimer = (): void => {
|
|
112
|
+
const hasRunning = registry.runningCount() > 0;
|
|
113
|
+
if (hasRunning && !statusTimer && !disposed) {
|
|
114
|
+
statusTimer = setInterval(() => updateUi(), STATUS_INTERVAL_MS);
|
|
115
|
+
statusTimer.unref();
|
|
116
|
+
} else if (!hasRunning && statusTimer) {
|
|
117
|
+
clearInterval(statusTimer);
|
|
118
|
+
statusTimer = undefined;
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
const updateUi = (ctx = currentCtx): void => {
|
|
123
|
+
if (disposed || registry.isShuttingDown() || !ctx?.hasUI) return;
|
|
124
|
+
syncStatusTimer();
|
|
125
|
+
|
|
126
|
+
const tasks = registry.allTasks();
|
|
127
|
+
const running = tasks.filter((t) => t.status === 'running').length;
|
|
128
|
+
const unseenFailed = tasks.filter((t) => t.status === 'failed' && !seenIds.has(t.id)).length;
|
|
129
|
+
const unseenStopped = tasks.filter((t) => t.status === 'killed' && !seenIds.has(t.id)).length;
|
|
130
|
+
const unseenDone = tasks.filter((t) => t.status === 'completed' && !seenIds.has(t.id)).length;
|
|
131
|
+
const unseenFinished = unseenFailed + unseenStopped + unseenDone;
|
|
132
|
+
|
|
133
|
+
if (running === 0 && unseenFinished === 0) {
|
|
134
|
+
ctx.ui.setStatus(STATUS_KEY, undefined);
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const parts: string[] = [];
|
|
139
|
+
if (running > 0) parts.push(`${running} running`);
|
|
140
|
+
if (unseenFailed > 0) parts.push(`${unseenFailed} failed`);
|
|
141
|
+
if (unseenStopped > 0) parts.push(`${unseenStopped} stopped`);
|
|
142
|
+
if (unseenDone > 0) parts.push(`${unseenDone} done`);
|
|
143
|
+
parts.push(dockOpen ? 'focused' : 'Shift↓');
|
|
144
|
+
|
|
145
|
+
ctx.ui.setStatus(STATUS_KEY, lightBlue(` bg ${parts.join(' · ')} `));
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
const registry = new TaskRegistry({
|
|
149
|
+
callbacks: {
|
|
150
|
+
onChange: () => updateUi(),
|
|
151
|
+
onNotify: (task) => {
|
|
152
|
+
deliverNotification(task);
|
|
153
|
+
updateUi();
|
|
154
|
+
},
|
|
155
|
+
},
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
const openDock = async (ctx: ExtensionContext): Promise<void> => {
|
|
159
|
+
currentCtx = ctx;
|
|
160
|
+
if (!ctx.hasUI) {
|
|
161
|
+
ctx.ui.notify(formatStatusList(registry.allTasks()), 'info');
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
dockOpen = true;
|
|
165
|
+
updateUi(ctx);
|
|
166
|
+
try {
|
|
167
|
+
await ctx.ui.custom<void>(
|
|
168
|
+
(tui, theme, _kb, done) =>
|
|
169
|
+
new BgTaskDock(tui, theme, () => done(undefined), {
|
|
170
|
+
getTasks: () => registry.allTasks(),
|
|
171
|
+
stopTask: async (id) => {
|
|
172
|
+
await registry.stopTask(id, 'user');
|
|
173
|
+
updateUi(ctx);
|
|
174
|
+
},
|
|
175
|
+
rerunTask: async (task) => {
|
|
176
|
+
const started = await registry.startTask(
|
|
177
|
+
ctx.cwd,
|
|
178
|
+
getSessionId(ctx),
|
|
179
|
+
task.command,
|
|
180
|
+
{
|
|
181
|
+
name: task.name,
|
|
182
|
+
timeoutSeconds: task.timeoutSeconds,
|
|
183
|
+
surviveReload: task.surviveReload,
|
|
184
|
+
notify: 'silent',
|
|
185
|
+
},
|
|
186
|
+
);
|
|
187
|
+
updateUi(ctx);
|
|
188
|
+
return started;
|
|
189
|
+
},
|
|
190
|
+
isSeen: (id) => seenIds.has(id),
|
|
191
|
+
markSeen: (id) => {
|
|
192
|
+
seenIds.add(id);
|
|
193
|
+
updateUi(ctx);
|
|
194
|
+
},
|
|
195
|
+
markAllFinishedSeen: () => {
|
|
196
|
+
for (const t of registry.allTasks()) {
|
|
197
|
+
if (t.status !== 'running') seenIds.add(t.id);
|
|
198
|
+
}
|
|
199
|
+
updateUi(ctx);
|
|
200
|
+
},
|
|
201
|
+
}),
|
|
202
|
+
{
|
|
203
|
+
overlay: true,
|
|
204
|
+
overlayOptions: {
|
|
205
|
+
anchor: 'bottom-center',
|
|
206
|
+
width: '96%',
|
|
207
|
+
minWidth: 64,
|
|
208
|
+
maxHeight: '60%',
|
|
209
|
+
margin: { bottom: 1, left: 1, right: 1 },
|
|
210
|
+
},
|
|
211
|
+
},
|
|
212
|
+
);
|
|
213
|
+
} finally {
|
|
214
|
+
dockOpen = false;
|
|
215
|
+
updateUi(ctx);
|
|
216
|
+
}
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
// --- Message renderer ---
|
|
220
|
+
pi.registerMessageRenderer<BgTaskSnapshot>(NOTIFY_CUSTOM_TYPE, (message, _options, theme) => {
|
|
221
|
+
const task = message.details;
|
|
222
|
+
const status = task?.status ?? 'completed';
|
|
223
|
+
const color: ThemeColor =
|
|
224
|
+
status === 'completed'
|
|
225
|
+
? 'success'
|
|
226
|
+
: status === 'failed'
|
|
227
|
+
? 'error'
|
|
228
|
+
: status === 'killed'
|
|
229
|
+
? 'warning'
|
|
230
|
+
: 'accent';
|
|
231
|
+
const name = task?.name ?? 'Background task';
|
|
232
|
+
const id = task?.id ?? '';
|
|
233
|
+
const output = task?.outputPath ? `\n${theme.fg('dim', `Output: ${task.outputPath}`)}` : '';
|
|
234
|
+
const err = task?.error ? `\n${theme.fg('error', task.error)}` : '';
|
|
235
|
+
return new Text(
|
|
236
|
+
`${theme.fg(color, `[bg ${status}]`)} ${theme.fg('accent', name)} ${theme.fg('dim', `(${id})`)}${output}${err}`,
|
|
237
|
+
0,
|
|
238
|
+
0,
|
|
239
|
+
);
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
// --- Lifecycle hooks ---
|
|
243
|
+
pi.on('session_start', (_event, ctx) => {
|
|
244
|
+
if (disposed) return;
|
|
245
|
+
currentCtx = ctx;
|
|
246
|
+
const { seenIds: restoredSeen } = registry.adoptReloadTasks(getSessionId(ctx), ctx.cwd);
|
|
247
|
+
for (const id of restoredSeen) seenIds.add(id);
|
|
248
|
+
updateUi(ctx);
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
pi.on('session_shutdown', async (event, ctx) => {
|
|
252
|
+
disposed = true;
|
|
253
|
+
if (statusTimer) {
|
|
254
|
+
clearInterval(statusTimer);
|
|
255
|
+
statusTimer = undefined;
|
|
256
|
+
}
|
|
257
|
+
if (ctx.hasUI) ctx.ui.setStatus(STATUS_KEY, undefined);
|
|
258
|
+
await registry.shutdown(event.reason, getSessionId(ctx), ctx.cwd, seenIds);
|
|
259
|
+
});
|
|
260
|
+
|
|
261
|
+
// --- Shortcut & commands ---
|
|
262
|
+
pi.registerShortcut('shift+down' satisfies KeyId, {
|
|
263
|
+
description: 'Open background task dock',
|
|
264
|
+
handler: async (ctx) => openDock(ctx),
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
pi.registerCommand('bg', {
|
|
268
|
+
description: 'Start a background shell command: /bg [--survive-reload] [--name "Label"] <command>',
|
|
269
|
+
handler: async (args, ctx) => {
|
|
270
|
+
try {
|
|
271
|
+
currentCtx = ctx;
|
|
272
|
+
const parsed = parseBgCommandArgs(args);
|
|
273
|
+
const task = await registry.startTask(ctx.cwd, getSessionId(ctx), parsed.command, {
|
|
274
|
+
name: parsed.name ?? parsed.command.slice(0, 40),
|
|
275
|
+
surviveReload: parsed.surviveReload,
|
|
276
|
+
notify: 'silent',
|
|
277
|
+
});
|
|
278
|
+
updateUi(ctx);
|
|
279
|
+
ctx.ui.notify(formatLaunchReceipt(task), 'info');
|
|
280
|
+
} catch (err) {
|
|
281
|
+
ctx.ui.notify(err instanceof Error ? err.message : String(err), 'error');
|
|
282
|
+
}
|
|
283
|
+
},
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
pi.registerCommand('jobs', {
|
|
287
|
+
description: 'Open background task dock (or list tasks)',
|
|
288
|
+
handler: async (_args, ctx) => openDock(ctx),
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
// --- Tools ---
|
|
292
|
+
pi.registerTool<typeof BgRunParams, BgTaskSnapshot>({
|
|
293
|
+
name: 'bg_run',
|
|
294
|
+
label: 'Background Run',
|
|
295
|
+
description:
|
|
296
|
+
'Run a long-running shell command in the background via /bin/bash -c. Returns task ID and log path immediately; terminal <background-task-notification> wakes a follow-up turn by default.',
|
|
297
|
+
promptSnippet: 'Start a background bash command; terminal notification wakes you automatically',
|
|
298
|
+
promptGuidelines: [
|
|
299
|
+
'Use bg_run for long-running shell commands; terminal <background-task-notification> wakes you automatically — do not poll bg_status/bg_logs to wait.',
|
|
300
|
+
'Use bg_logs only when output is needed; use bg_kill to stop unneeded tasks.',
|
|
301
|
+
],
|
|
302
|
+
parameters: BgRunParams,
|
|
303
|
+
prepareArguments(raw): BgRunParamsValue {
|
|
304
|
+
if (!raw || typeof raw !== 'object') throw new Error('bg_run expects an object.');
|
|
305
|
+
const input = raw as Record<string, unknown>;
|
|
306
|
+
for (const key of Object.keys(input)) {
|
|
307
|
+
if (!ALLOWED_BG_RUN_KEYS.has(key)) {
|
|
308
|
+
const hint = key === 'timeout' ? ' (did you mean "timeoutSeconds"?)' : '';
|
|
309
|
+
throw new Error(`Unknown bg_run parameter "${key}"${hint}.`);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
if (typeof input['command'] !== 'string' || !input['command'].trim()) {
|
|
313
|
+
throw new Error('bg_run requires a non-empty "command" string.');
|
|
314
|
+
}
|
|
315
|
+
const name =
|
|
316
|
+
typeof input['name'] === 'string' && input['name'].trim()
|
|
317
|
+
? input['name'].trim()
|
|
318
|
+
: input['command'].trim().slice(0, 40);
|
|
319
|
+
const out: BgRunParamsValue = { name, command: input['command'] };
|
|
320
|
+
if (input['timeoutSeconds'] !== undefined) {
|
|
321
|
+
if (typeof input['timeoutSeconds'] !== 'number' || !Number.isFinite(input['timeoutSeconds']) || input['timeoutSeconds'] < 1) {
|
|
322
|
+
throw new Error('bg_run "timeoutSeconds" must be a number >= 1.');
|
|
323
|
+
}
|
|
324
|
+
out.timeoutSeconds = input['timeoutSeconds'];
|
|
325
|
+
}
|
|
326
|
+
if (input['surviveReload'] !== undefined) {
|
|
327
|
+
if (typeof input['surviveReload'] !== 'boolean') {
|
|
328
|
+
throw new Error('bg_run "surviveReload" must be a boolean.');
|
|
329
|
+
}
|
|
330
|
+
out.surviveReload = input['surviveReload'];
|
|
331
|
+
}
|
|
332
|
+
if (input['notify'] !== undefined) {
|
|
333
|
+
if (input['notify'] !== 'wake' && input['notify'] !== 'silent' && input['notify'] !== 'none') {
|
|
334
|
+
throw new Error('bg_run "notify" must be "wake", "silent", or "none".');
|
|
335
|
+
}
|
|
336
|
+
out.notify = input['notify'] as NotifyMode;
|
|
337
|
+
}
|
|
338
|
+
return out;
|
|
339
|
+
},
|
|
340
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
341
|
+
currentCtx = ctx;
|
|
342
|
+
const task = await registry.startTask(ctx.cwd, getSessionId(ctx), params.command, {
|
|
343
|
+
name: params.name,
|
|
344
|
+
timeoutSeconds: params.timeoutSeconds,
|
|
345
|
+
surviveReload: params.surviveReload,
|
|
346
|
+
notify: params.notify ?? 'wake',
|
|
347
|
+
});
|
|
348
|
+
updateUi(ctx);
|
|
349
|
+
return {
|
|
350
|
+
content: [{ type: 'text', text: formatLaunchReceipt(task) }],
|
|
351
|
+
details: task,
|
|
352
|
+
};
|
|
353
|
+
},
|
|
354
|
+
});
|
|
355
|
+
|
|
356
|
+
pi.registerTool<typeof BgStatusParams, { tasks: BgTaskSnapshot[] }>({
|
|
357
|
+
name: 'bg_status',
|
|
358
|
+
label: 'Background Status',
|
|
359
|
+
description: 'Inspect status of one background task or list all tasks in this session.',
|
|
360
|
+
promptSnippet: 'Inspect background task status (not a polling loop)',
|
|
361
|
+
parameters: BgStatusParams,
|
|
362
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
363
|
+
currentCtx = ctx;
|
|
364
|
+
if (params.taskId) {
|
|
365
|
+
const task = registry.resolveTask(params.taskId);
|
|
366
|
+
const snap = registry.allTasks().find((t) => t.id === task.id)!;
|
|
367
|
+
return {
|
|
368
|
+
content: [{ type: 'text', text: formatStatusLine(snap) }],
|
|
369
|
+
details: { tasks: [snap] },
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
const tasks = registry.allTasks();
|
|
373
|
+
return {
|
|
374
|
+
content: [{ type: 'text', text: formatStatusList(tasks) }],
|
|
375
|
+
details: { tasks },
|
|
376
|
+
};
|
|
377
|
+
},
|
|
378
|
+
});
|
|
379
|
+
|
|
380
|
+
pi.registerTool<typeof BgLogsParams, { task: BgTaskSnapshot; truncated: boolean; totalBytes: number }>({
|
|
381
|
+
name: 'bg_logs',
|
|
382
|
+
label: 'Background Logs',
|
|
383
|
+
description: 'Read bounded tail (default) or head of a background task log file (max 50 KiB).',
|
|
384
|
+
promptSnippet: 'Read bounded output from a background task',
|
|
385
|
+
parameters: BgLogsParams,
|
|
386
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
387
|
+
currentCtx = ctx;
|
|
388
|
+
const { task, logs } = registry.readLogs(params.taskId, {
|
|
389
|
+
maxBytes: params.maxBytes ?? DEFAULT_LOG_BYTES,
|
|
390
|
+
tail: params.tail ?? true,
|
|
391
|
+
});
|
|
392
|
+
const header = `${task.name} (${task.id}) [${task.status}] · showing ${formatBytes(logs.readBytes)} / ${formatBytes(logs.totalBytes)}${logs.truncated ? ` (truncated; full log: ${task.outputPath})` : ''}`;
|
|
393
|
+
const body = logs.text ? `${header}\n---\n${logs.text}` : `${header}\n(no output)`;
|
|
394
|
+
return {
|
|
395
|
+
content: [{ type: 'text', text: body }],
|
|
396
|
+
details: { task, truncated: logs.truncated, totalBytes: logs.totalBytes },
|
|
397
|
+
};
|
|
398
|
+
},
|
|
399
|
+
});
|
|
400
|
+
|
|
401
|
+
pi.registerTool<typeof BgKillParams, BgTaskSnapshot>({
|
|
402
|
+
name: 'bg_kill',
|
|
403
|
+
label: 'Background Kill',
|
|
404
|
+
description: 'Stop a running background task and its process group.',
|
|
405
|
+
promptSnippet: 'Stop a running background task by ID',
|
|
406
|
+
parameters: BgKillParams,
|
|
407
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
408
|
+
currentCtx = ctx;
|
|
409
|
+
const task = await registry.stopTask(params.taskId, 'user');
|
|
410
|
+
updateUi(ctx);
|
|
411
|
+
return {
|
|
412
|
+
content: [{ type: 'text', text: `Stopped "${task.name}" (${task.id}). Output: ${task.outputPath}` }],
|
|
413
|
+
details: task,
|
|
414
|
+
};
|
|
415
|
+
},
|
|
416
|
+
});
|
|
417
|
+
}
|
package/src/logs.ts
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { openSync, closeSync, readSync, statSync, fsyncSync, createWriteStream, type WriteStream } from 'node:fs';
|
|
2
|
+
import { mkdir } from 'node:fs/promises';
|
|
3
|
+
import { join, relative } from 'node:path';
|
|
4
|
+
import { DEFAULT_MAX_OUTPUT_BYTES, MAX_LOG_BYTES } from './types.ts';
|
|
5
|
+
|
|
6
|
+
export interface BoundedReadResult {
|
|
7
|
+
text: string;
|
|
8
|
+
totalBytes: number;
|
|
9
|
+
readBytes: number;
|
|
10
|
+
truncated: boolean;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function resolveMaxOutputBytes(): number {
|
|
14
|
+
const raw = process.env['PI_BG_MAX_OUTPUT_BYTES'];
|
|
15
|
+
if (!raw) return DEFAULT_MAX_OUTPUT_BYTES;
|
|
16
|
+
const parsed = Number(raw);
|
|
17
|
+
if (!Number.isFinite(parsed) || parsed < 1024) return DEFAULT_MAX_OUTPUT_BYTES;
|
|
18
|
+
return Math.floor(parsed);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function sanitizeSessionDirName(sessionId: string): string {
|
|
22
|
+
const cleaned = sessionId.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 32);
|
|
23
|
+
return cleaned || 'session';
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export async function ensureTaskDir(cwd: string, sessionId: string): Promise<string> {
|
|
27
|
+
const dir = join(cwd, '.pi', 'tasks', `${sanitizeSessionDirName(sessionId)}-${process.pid}`);
|
|
28
|
+
await mkdir(dir, { recursive: true });
|
|
29
|
+
return dir;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function taskLogPaths(cwd: string, taskDir: string, taskId: string): { outputAbsPath: string; outputPath: string } {
|
|
33
|
+
const outputAbsPath = join(taskDir, `${taskId}.log`);
|
|
34
|
+
const rel = relative(cwd, outputAbsPath);
|
|
35
|
+
const outputPath = rel && !rel.startsWith('..') ? rel : outputAbsPath;
|
|
36
|
+
return { outputAbsPath, outputPath };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function openLogStream(absPath: string): WriteStream {
|
|
40
|
+
return createWriteStream(absPath, { flags: 'a' });
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export async function closeAndFsyncStream(stream: WriteStream | undefined, absPath: string): Promise<void> {
|
|
44
|
+
if (stream && !stream.closed && !stream.destroyed) {
|
|
45
|
+
await new Promise<void>((resolve) => {
|
|
46
|
+
stream.end(() => resolve());
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
try {
|
|
50
|
+
const fd = openSync(absPath, 'r');
|
|
51
|
+
try {
|
|
52
|
+
fsyncSync(fd);
|
|
53
|
+
} finally {
|
|
54
|
+
closeSync(fd);
|
|
55
|
+
}
|
|
56
|
+
} catch {
|
|
57
|
+
// File may not exist if spawn failed before any write.
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function boundedRead(absPath: string, maxBytes: number, tail = true): BoundedReadResult {
|
|
62
|
+
const cap = Math.max(1, Math.min(Math.floor(maxBytes), 512 * 1024));
|
|
63
|
+
let totalBytes = 0;
|
|
64
|
+
try {
|
|
65
|
+
totalBytes = statSync(absPath).size;
|
|
66
|
+
} catch {
|
|
67
|
+
return { text: '', totalBytes: 0, readBytes: 0, truncated: false };
|
|
68
|
+
}
|
|
69
|
+
if (totalBytes === 0) {
|
|
70
|
+
return { text: '', totalBytes: 0, readBytes: 0, truncated: false };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const toRead = Math.min(totalBytes, cap);
|
|
74
|
+
const start = tail ? totalBytes - toRead : 0;
|
|
75
|
+
const buf = Buffer.allocUnsafe(toRead);
|
|
76
|
+
const fd = openSync(absPath, 'r');
|
|
77
|
+
let bytesRead = 0;
|
|
78
|
+
try {
|
|
79
|
+
bytesRead = readSync(fd, buf, 0, toRead, start);
|
|
80
|
+
} finally {
|
|
81
|
+
closeSync(fd);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
let slice = buf.subarray(0, bytesRead);
|
|
85
|
+
// When tail-reading from the middle of a UTF-8 file, drop any partial leading line/sequence.
|
|
86
|
+
if (tail && start > 0) {
|
|
87
|
+
const nl = slice.indexOf(0x0a);
|
|
88
|
+
if (nl !== -1 && nl + 1 < slice.length) {
|
|
89
|
+
slice = slice.subarray(nl + 1);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return {
|
|
94
|
+
text: slice.toString('utf8'),
|
|
95
|
+
totalBytes,
|
|
96
|
+
readBytes: slice.length,
|
|
97
|
+
truncated: totalBytes > toRead,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function clampModelLogBytes(requested: number | undefined, fallback: number): number {
|
|
102
|
+
if (requested === undefined || !Number.isFinite(requested) || requested < 1) return fallback;
|
|
103
|
+
return Math.min(Math.floor(requested), MAX_LOG_BYTES);
|
|
104
|
+
}
|