pi-simple-background-tasks 0.0.0-stage → 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/FORK-CHANGES.md +66 -0
- package/LICENSE +15 -0
- package/README.md +100 -2
- package/package.json +59 -4
- package/src/core/common.ts +914 -0
- package/src/core/config.ts +83 -0
- package/src/core/durable-fs.ts +545 -0
- package/src/core/extension-api.ts +70 -0
- package/src/core/lazy-module.ts +55 -0
- package/src/core/registry.ts +2426 -0
- package/src/core/reload-shell-owner.ts +1512 -0
- package/src/core/shell-policy.ts +180 -0
- package/src/core/task-cleanup.ts +146 -0
- package/src/core/task-durable.ts +65 -0
- package/src/core/windows-taskkill.ts +263 -0
- package/src/extension.ts +928 -0
- package/src/ui/background-tasks-manager.ts +731 -0
package/src/extension.ts
ADDED
|
@@ -0,0 +1,928 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { realpathSync } from 'node:fs';
|
|
3
|
+
import type {
|
|
4
|
+
ExtensionAPI,
|
|
5
|
+
ExtensionCommandContext,
|
|
6
|
+
ExtensionContext,
|
|
7
|
+
Theme,
|
|
8
|
+
ThemeColor,
|
|
9
|
+
ToolRenderResultOptions,
|
|
10
|
+
} from '@earendil-works/pi-coding-agent';
|
|
11
|
+
import { formatSize } from '@earendil-works/pi-coding-agent';
|
|
12
|
+
import { type KeyId, Text } from '@earendil-works/pi-tui';
|
|
13
|
+
import { type Static, Type } from 'typebox';
|
|
14
|
+
import {
|
|
15
|
+
type BgKillDetails,
|
|
16
|
+
type BgLogsDetails,
|
|
17
|
+
type BgRunDetails,
|
|
18
|
+
type BgStatusDetails,
|
|
19
|
+
type BgTask,
|
|
20
|
+
type BgTaskSnapshot,
|
|
21
|
+
DEFAULT_LOG_BYTES,
|
|
22
|
+
deriveCompletionDeliveryGuidance,
|
|
23
|
+
deriveTaskNameFromCommand,
|
|
24
|
+
formatSnapshotList,
|
|
25
|
+
MAX_LOG_BYTES,
|
|
26
|
+
normalizeMaxBytes,
|
|
27
|
+
normalizeTaskName,
|
|
28
|
+
parseBgCommandArgs,
|
|
29
|
+
type ReloadShellActivationClaimV1,
|
|
30
|
+
type ReloadShellActivationLeaseV1,
|
|
31
|
+
type ReloadShellIdentityV1,
|
|
32
|
+
ReloadSurvivalError,
|
|
33
|
+
type StartTaskOptions,
|
|
34
|
+
taskDisplayName,
|
|
35
|
+
truncateChars,
|
|
36
|
+
} from './core/common.js';
|
|
37
|
+
import { resolveBackgroundTasksConfig } from './core/config.js';
|
|
38
|
+
import {
|
|
39
|
+
type BackgroundTaskExtensionService,
|
|
40
|
+
installBackgroundTaskExtensionApi,
|
|
41
|
+
} from './core/extension-api.js';
|
|
42
|
+
import { LazyModule, SynchronousActivationCloseFence } from './core/lazy-module.js';
|
|
43
|
+
import { type BackgroundTaskContext, BackgroundTaskRegistry } from './core/registry.js';
|
|
44
|
+
import {
|
|
45
|
+
getProcessReloadShellOwnerV1,
|
|
46
|
+
makeReloadShellIdentity,
|
|
47
|
+
} from './core/reload-shell-owner.js';
|
|
48
|
+
import { createShellPolicyGuidanceHandler, initializeShellPolicy } from './core/shell-policy.js';
|
|
49
|
+
import type { CleanupScope, CleanupSummary } from './core/task-cleanup.js';
|
|
50
|
+
import type { BackgroundTaskForUi, TaskManagerResult } from './ui/background-tasks-manager.js';
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Project-local Pi background task manager.
|
|
54
|
+
*
|
|
55
|
+
* Scope:
|
|
56
|
+
* - Explicit background shell jobs only: /bg and bg_run spawn commands directly.
|
|
57
|
+
* - No Ctrl+B support for backgrounding an already-running built-in bash tool.
|
|
58
|
+
* - Opted ordinary shell jobs can hand their same live process ownership to a
|
|
59
|
+
* fresh extension activation on real same-process reload only.
|
|
60
|
+
* - No PID/file adoption, process-restart survival, or crash recovery.
|
|
61
|
+
*/
|
|
62
|
+
|
|
63
|
+
const COMMAND_PREVIEW_CHARS = 90;
|
|
64
|
+
|
|
65
|
+
function textContent(text: string) {
|
|
66
|
+
return [{ type: 'text' as const, text }];
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
interface TextToolResult {
|
|
70
|
+
content?: ReadonlyArray<{ type: string; text?: string }>;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
interface BgToolArgumentRecord {
|
|
74
|
+
readonly command?: unknown;
|
|
75
|
+
readonly name?: unknown;
|
|
76
|
+
readonly description?: unknown;
|
|
77
|
+
readonly timeoutSeconds?: unknown;
|
|
78
|
+
readonly notifyOnCompletion?: unknown;
|
|
79
|
+
readonly triggerOnCompletion?: unknown;
|
|
80
|
+
readonly surviveReload?: unknown;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function optionalTrimmed(value: string): string | undefined {
|
|
84
|
+
const trimmed = value.trim();
|
|
85
|
+
return trimmed.length > 0 ? trimmed : undefined;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const BgRunParams = Type.Object({
|
|
89
|
+
name: Type.String({
|
|
90
|
+
description: 'Short human-readable task name. Required; use 2-6 words, not the raw command.',
|
|
91
|
+
}),
|
|
92
|
+
command: Type.String({ description: 'Shell command to start in the background' }),
|
|
93
|
+
description: Type.Optional(
|
|
94
|
+
Type.String({ description: 'Optional longer human-readable context for the task' }),
|
|
95
|
+
),
|
|
96
|
+
timeoutSeconds: Type.Optional(
|
|
97
|
+
Type.Number({ description: 'Optional timeout; task is failed and killed when exceeded' }),
|
|
98
|
+
),
|
|
99
|
+
notifyOnCompletion: Type.Optional(
|
|
100
|
+
Type.Boolean({
|
|
101
|
+
description:
|
|
102
|
+
'Whether to deliver the durable terminal notification. Default: true; disable only when deliberately taking over completion monitoring.',
|
|
103
|
+
}),
|
|
104
|
+
),
|
|
105
|
+
triggerOnCompletion: Type.Optional(
|
|
106
|
+
Type.Boolean({
|
|
107
|
+
description:
|
|
108
|
+
'Whether that notification should automatically trigger a follow-up agent turn. Default: true for bg_run; requires notifyOnCompletion.',
|
|
109
|
+
}),
|
|
110
|
+
),
|
|
111
|
+
surviveReload: Type.Optional(
|
|
112
|
+
Type.Boolean({
|
|
113
|
+
description:
|
|
114
|
+
'Opt in to retaining this exact shell execution across a real same-process Pi reload. Default: false.',
|
|
115
|
+
}),
|
|
116
|
+
),
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
const BgStatusParams = Type.Object({
|
|
120
|
+
taskId: Type.Optional(
|
|
121
|
+
Type.String({
|
|
122
|
+
description:
|
|
123
|
+
'Optional task ID or unambiguous prefix. If omitted, all running/recent tasks are returned.',
|
|
124
|
+
}),
|
|
125
|
+
),
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
const BgLogsParams = Type.Object({
|
|
129
|
+
taskId: Type.String({ description: 'Task ID or unambiguous prefix' }),
|
|
130
|
+
maxBytes: Type.Optional(
|
|
131
|
+
Type.Number({
|
|
132
|
+
description: `Maximum bytes to return, capped at ${formatSize(MAX_LOG_BYTES)}. Default: ${formatSize(DEFAULT_LOG_BYTES)}.`,
|
|
133
|
+
}),
|
|
134
|
+
),
|
|
135
|
+
tail: Type.Optional(
|
|
136
|
+
Type.Boolean({
|
|
137
|
+
description: 'Read the tail of the log when true, head when false. Default: true.',
|
|
138
|
+
}),
|
|
139
|
+
),
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
const BgKillParams = Type.Object({
|
|
143
|
+
taskId: Type.String({ description: 'Task ID or unambiguous prefix to stop' }),
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
const BgCleanParams = Type.Object({
|
|
147
|
+
taskId: Type.Optional(
|
|
148
|
+
Type.String({
|
|
149
|
+
description:
|
|
150
|
+
'Delete this single task (by ID or unambiguous prefix). When set, scope is ignored.',
|
|
151
|
+
}),
|
|
152
|
+
),
|
|
153
|
+
scope: Type.Optional(
|
|
154
|
+
Type.Union([Type.Literal('session'), Type.Literal('all')], {
|
|
155
|
+
description:
|
|
156
|
+
"Which finished tasks to delete when taskId is omitted: 'session' (this session, default) or 'all' (the entire tasks folder).",
|
|
157
|
+
}),
|
|
158
|
+
),
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
type BgRunParamsValue = Static<typeof BgRunParams>;
|
|
162
|
+
|
|
163
|
+
function renderPlainResult(result: TextToolResult, options: ToolRenderResultOptions, theme: Theme) {
|
|
164
|
+
void options;
|
|
165
|
+
void theme;
|
|
166
|
+
const text =
|
|
167
|
+
result.content?.map((part) => (part.type === 'text' ? (part.text ?? '') : '')).join('\n') ?? '';
|
|
168
|
+
return new Text(text, 0, 0);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
interface BgCleanDetails {
|
|
172
|
+
scope: CleanupScope;
|
|
173
|
+
deleted: { id: string; status: string }[];
|
|
174
|
+
skipped: { id: string; status: string }[];
|
|
175
|
+
notFound: string[];
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function formatCleanMessage(summary: CleanupSummary): string {
|
|
179
|
+
const scopeLabel =
|
|
180
|
+
summary.scope === 'one'
|
|
181
|
+
? 'the specified task'
|
|
182
|
+
: summary.scope === 'session'
|
|
183
|
+
? 'this session'
|
|
184
|
+
: 'the entire tasks folder';
|
|
185
|
+
const plural = (n: number): string => (n === 1 ? '' : 's');
|
|
186
|
+
const parts = [
|
|
187
|
+
`Cleaned ${summary.deleted.length} finished task${plural(summary.deleted.length)} in ${scopeLabel}.`,
|
|
188
|
+
];
|
|
189
|
+
if (summary.skipped.length > 0) {
|
|
190
|
+
parts.push(
|
|
191
|
+
`Skipped ${summary.skipped.length} running task${plural(summary.skipped.length)}: ${summary.skipped
|
|
192
|
+
.map((s) => s.id)
|
|
193
|
+
.join(', ')}.`,
|
|
194
|
+
);
|
|
195
|
+
}
|
|
196
|
+
if (summary.notFound.length > 0) {
|
|
197
|
+
parts.push(`Not found: ${summary.notFound.join(', ')}.`);
|
|
198
|
+
}
|
|
199
|
+
return parts.join(' ');
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export default async function backgroundTasksExtension(pi: ExtensionAPI): Promise<void> {
|
|
203
|
+
const config = resolveBackgroundTasksConfig(process.cwd());
|
|
204
|
+
const shellPolicy = initializeShellPolicy();
|
|
205
|
+
const reloadShellOwner = getProcessReloadShellOwnerV1();
|
|
206
|
+
pi.on('before_agent_start', createShellPolicyGuidanceHandler(shellPolicy));
|
|
207
|
+
let currentRegistryCtx: BackgroundTaskContext | undefined;
|
|
208
|
+
let activationLease: ReloadShellActivationLeaseV1 | undefined;
|
|
209
|
+
let activationIdentity: ReloadShellIdentityV1 | undefined;
|
|
210
|
+
let pendingActivationClaim: ReloadShellActivationClaimV1 | undefined;
|
|
211
|
+
let disposed = false;
|
|
212
|
+
let shutdownCleanupStarted = false;
|
|
213
|
+
let reloadHandoffFailed = false;
|
|
214
|
+
let shutdownReason = 'shutdown';
|
|
215
|
+
const activationCloseFence = new SynchronousActivationCloseFence();
|
|
216
|
+
const taskManagerLoader = new LazyModule(() => import('./ui/background-tasks-manager.js'));
|
|
217
|
+
|
|
218
|
+
const registryContext = (ctx: ExtensionContext): BackgroundTaskContext => ({
|
|
219
|
+
cwd: ctx.cwd,
|
|
220
|
+
sessionId: ctx.sessionManager.getSessionId(),
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
const registry = new BackgroundTaskRegistry({
|
|
224
|
+
sendCompletionNotification: (message, options) => {
|
|
225
|
+
pi.sendMessage(message, options);
|
|
226
|
+
},
|
|
227
|
+
publishTerminal: (task) => {
|
|
228
|
+
eventService.publishTerminal(task);
|
|
229
|
+
},
|
|
230
|
+
shellPolicy,
|
|
231
|
+
tasksDir: config.tasksDir,
|
|
232
|
+
reloadShellOwner,
|
|
233
|
+
});
|
|
234
|
+
const eventService: BackgroundTaskExtensionService = installBackgroundTaskExtensionApi({
|
|
235
|
+
events: pi.events,
|
|
236
|
+
registry,
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
const beginSessionShutdown = (reason: string): void => {
|
|
240
|
+
let handoffError: unknown;
|
|
241
|
+
if (!disposed) {
|
|
242
|
+
disposed = true;
|
|
243
|
+
registry.closeTaskAdmissions();
|
|
244
|
+
if (pendingActivationClaim !== undefined) {
|
|
245
|
+
const claim = pendingActivationClaim;
|
|
246
|
+
pendingActivationClaim = undefined;
|
|
247
|
+
registry.abortReloadActivation(claim);
|
|
248
|
+
try {
|
|
249
|
+
reloadShellOwner.abortActivation(
|
|
250
|
+
claim,
|
|
251
|
+
new ReloadSurvivalError(
|
|
252
|
+
'pi_bg_reload_owner_stale_claim',
|
|
253
|
+
'activation shut down while its reload claim was staging',
|
|
254
|
+
),
|
|
255
|
+
);
|
|
256
|
+
} catch (error) {
|
|
257
|
+
handoffError = error;
|
|
258
|
+
}
|
|
259
|
+
} else if (reason === 'reload' && activationLease !== undefined) {
|
|
260
|
+
const lease = activationLease;
|
|
261
|
+
try {
|
|
262
|
+
registry.prepareReloadHandoff(lease);
|
|
263
|
+
activationLease = undefined;
|
|
264
|
+
activationIdentity = undefined;
|
|
265
|
+
} catch (error) {
|
|
266
|
+
reloadHandoffFailed = true;
|
|
267
|
+
handoffError = error;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
registry.setShuttingDown(true);
|
|
271
|
+
eventService.close();
|
|
272
|
+
}
|
|
273
|
+
// Teardown remains active on repeated calls so even a handle assigned by a
|
|
274
|
+
// racing continuation is still disposed rather than hidden by idempotence.
|
|
275
|
+
currentRegistryCtx = undefined;
|
|
276
|
+
if (handoffError !== undefined) throw handoffError;
|
|
277
|
+
};
|
|
278
|
+
|
|
279
|
+
// Join the one synchronous all-lane barrier before any facade can register
|
|
280
|
+
// asynchronous cleanup. The core callback performs an eligible reload
|
|
281
|
+
// handoff first; every lazy lane then closes on the same call stack before
|
|
282
|
+
// Pi can await any later cleanup handler.
|
|
283
|
+
activationCloseFence.add(() => {
|
|
284
|
+
beginSessionShutdown(shutdownReason);
|
|
285
|
+
});
|
|
286
|
+
activationCloseFence.add(() => {
|
|
287
|
+
taskManagerLoader.close();
|
|
288
|
+
});
|
|
289
|
+
pi.on('session_shutdown', (event) => {
|
|
290
|
+
shutdownReason = event.reason;
|
|
291
|
+
activationCloseFence.close();
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
// This is the first session_start callback. Claim synchronously before the
|
|
295
|
+
// first await, stage/import durably, then expose the fresh host adapter.
|
|
296
|
+
pi.on('session_start', async (event, ctx) => {
|
|
297
|
+
if (disposed) return;
|
|
298
|
+
const nextRegistryCtx = registryContext(ctx);
|
|
299
|
+
const identity = makeReloadShellIdentity(
|
|
300
|
+
nextRegistryCtx.sessionId ?? '',
|
|
301
|
+
realpathSync(ctx.cwd),
|
|
302
|
+
);
|
|
303
|
+
if (activationLease !== undefined && registry.hasCurrentReloadLease()) {
|
|
304
|
+
if (
|
|
305
|
+
activationIdentity?.hostPid !== identity.hostPid ||
|
|
306
|
+
activationIdentity.sessionId !== identity.sessionId ||
|
|
307
|
+
activationIdentity.cwdRealpath !== identity.cwdRealpath
|
|
308
|
+
) {
|
|
309
|
+
throw new ReloadSurvivalError(
|
|
310
|
+
'pi_bg_reload_owner_activation_conflict',
|
|
311
|
+
'a repeated session_start changed the bound reload owner identity without shutdown',
|
|
312
|
+
);
|
|
313
|
+
}
|
|
314
|
+
currentRegistryCtx = nextRegistryCtx;
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
const activationNonce = randomBytes(16).toString('hex');
|
|
318
|
+
const claim = reloadShellOwner.beginActivation(identity, event.reason, activationNonce);
|
|
319
|
+
pendingActivationClaim = claim;
|
|
320
|
+
try {
|
|
321
|
+
const adapter = await registry.stageReloadActivation(claim);
|
|
322
|
+
if (pendingActivationClaim !== claim) {
|
|
323
|
+
// The synchronous shutdown barrier already aborted this claim and
|
|
324
|
+
// detached staged records while the durable import awaited.
|
|
325
|
+
registry.abortReloadActivation(claim);
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
if (disposed) {
|
|
329
|
+
registry.abortReloadActivation(claim);
|
|
330
|
+
pendingActivationClaim = undefined;
|
|
331
|
+
reloadShellOwner.abortActivation(
|
|
332
|
+
claim,
|
|
333
|
+
new ReloadSurvivalError(
|
|
334
|
+
'pi_bg_reload_owner_stale_claim',
|
|
335
|
+
'activation was disposed before reload claim commit',
|
|
336
|
+
),
|
|
337
|
+
);
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
const lease = reloadShellOwner.commitActivation(claim, adapter);
|
|
341
|
+
pendingActivationClaim = undefined;
|
|
342
|
+
activationLease = lease;
|
|
343
|
+
activationIdentity = identity;
|
|
344
|
+
currentRegistryCtx = nextRegistryCtx;
|
|
345
|
+
} catch (error) {
|
|
346
|
+
registry.abortReloadActivation(claim);
|
|
347
|
+
if (pendingActivationClaim === claim) pendingActivationClaim = undefined;
|
|
348
|
+
try {
|
|
349
|
+
reloadShellOwner.abortActivation(claim, error);
|
|
350
|
+
} catch (abortError) {
|
|
351
|
+
if (
|
|
352
|
+
typeof abortError !== 'object' ||
|
|
353
|
+
abortError === null ||
|
|
354
|
+
Reflect.get(abortError, 'code') !== 'pi_bg_reload_owner_stale_claim'
|
|
355
|
+
) {
|
|
356
|
+
throw new AggregateError([error, abortError], 'Reload activation claim and abort failed');
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
throw error;
|
|
360
|
+
}
|
|
361
|
+
});
|
|
362
|
+
|
|
363
|
+
async function startTask(
|
|
364
|
+
ctx: ExtensionContext,
|
|
365
|
+
command: string,
|
|
366
|
+
options: StartTaskOptions = {},
|
|
367
|
+
): Promise<BgTask> {
|
|
368
|
+
const nextRegistryCtx = registryContext(ctx);
|
|
369
|
+
currentRegistryCtx = nextRegistryCtx;
|
|
370
|
+
return registry.startTask(nextRegistryCtx, command, options);
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
async function openTaskManager(
|
|
374
|
+
ctx: ExtensionCommandContext | ExtensionContext,
|
|
375
|
+
initialTaskId?: string,
|
|
376
|
+
): Promise<void> {
|
|
377
|
+
if (!ctx.hasUI) {
|
|
378
|
+
ctx.ui.notify(
|
|
379
|
+
'Background task manager requires an interactive Pi UI. Use /jobs, /logs, or the bg_status/bg_logs tools in non-interactive mode.',
|
|
380
|
+
'error',
|
|
381
|
+
);
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
const { BackgroundTasksManager } = await taskManagerLoader.run((runtime) => runtime);
|
|
385
|
+
await ctx.ui.custom<TaskManagerResult>(
|
|
386
|
+
(tui, theme, _keybindings, done) => {
|
|
387
|
+
const managerOptions = {
|
|
388
|
+
getTasks: () => registry.allTasks(),
|
|
389
|
+
stopTask: async (task: BackgroundTaskForUi) => {
|
|
390
|
+
await registry.stopTask(registry.resolveTask(task.id), 'user');
|
|
391
|
+
},
|
|
392
|
+
stopAllRunning: async () => {
|
|
393
|
+
const result = await registry.stopAllRunning('user');
|
|
394
|
+
return result;
|
|
395
|
+
},
|
|
396
|
+
rerunTask: async (task: BackgroundTaskForUi) => {
|
|
397
|
+
const rerunOptions: StartTaskOptions = {
|
|
398
|
+
name: taskDisplayName(task),
|
|
399
|
+
surviveReload: task.surviveReload,
|
|
400
|
+
notifyOnCompletion: true,
|
|
401
|
+
triggerOnCompletion: false,
|
|
402
|
+
};
|
|
403
|
+
if (task.description !== undefined) rerunOptions.description = task.description;
|
|
404
|
+
if (task.timeoutSeconds !== undefined)
|
|
405
|
+
rerunOptions.timeoutSeconds = task.timeoutSeconds;
|
|
406
|
+
const rerun = await startTask(ctx, task.command, rerunOptions);
|
|
407
|
+
return rerun;
|
|
408
|
+
},
|
|
409
|
+
showOutputPath: (task: BackgroundTaskForUi) => {
|
|
410
|
+
ctx.ui.notify(
|
|
411
|
+
`Output path for ${taskDisplayName(task)} (${task.id}):\n${task.outputPath}`,
|
|
412
|
+
'info',
|
|
413
|
+
);
|
|
414
|
+
},
|
|
415
|
+
deleteTask: async (task: BackgroundTaskForUi) => {
|
|
416
|
+
await registry.cleanupFinishedTasks('one', task.id);
|
|
417
|
+
},
|
|
418
|
+
};
|
|
419
|
+
if (initialTaskId)
|
|
420
|
+
return new BackgroundTasksManager(tui, theme, done, {
|
|
421
|
+
...managerOptions,
|
|
422
|
+
initialTaskId,
|
|
423
|
+
});
|
|
424
|
+
return new BackgroundTasksManager(tui, theme, done, managerOptions);
|
|
425
|
+
},
|
|
426
|
+
{
|
|
427
|
+
overlay: true,
|
|
428
|
+
overlayOptions: {
|
|
429
|
+
anchor: 'top-right',
|
|
430
|
+
width: 96,
|
|
431
|
+
minWidth: 64,
|
|
432
|
+
margin: { top: 1, left: 1, right: 1 },
|
|
433
|
+
},
|
|
434
|
+
},
|
|
435
|
+
);
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
pi.registerMessageRenderer<BgTaskSnapshot>(
|
|
439
|
+
'background-task-notification',
|
|
440
|
+
(message, _options, theme) => {
|
|
441
|
+
const task = message.details;
|
|
442
|
+
const status = task?.status ?? 'completed';
|
|
443
|
+
const color: ThemeColor =
|
|
444
|
+
status === 'completed'
|
|
445
|
+
? 'success'
|
|
446
|
+
: status === 'failed'
|
|
447
|
+
? 'error'
|
|
448
|
+
: status === 'killed'
|
|
449
|
+
? 'warning'
|
|
450
|
+
: 'accent';
|
|
451
|
+
const id = task?.id ?? 'background task';
|
|
452
|
+
const name = task ? taskDisplayName(task) : 'Background task';
|
|
453
|
+
const output = task?.outputPath ? `\n${theme.fg('dim', `Output: ${task.outputPath}`)}` : '';
|
|
454
|
+
const error = task?.error ? `\n${theme.fg('error', task.error)}` : '';
|
|
455
|
+
return new Text(
|
|
456
|
+
`${theme.fg(color, `[bg ${status}]`)} ${theme.fg('accent', name)} ${theme.fg('dim', `(${id})`)}${output}${error}`,
|
|
457
|
+
0,
|
|
458
|
+
0,
|
|
459
|
+
);
|
|
460
|
+
},
|
|
461
|
+
);
|
|
462
|
+
|
|
463
|
+
pi.on('session_start', async (_event, ctx) => {
|
|
464
|
+
// Pi replacement binds a fresh extension instance. Never revive this old
|
|
465
|
+
// activation if a late lifecycle dispatch reaches it after shutdown.
|
|
466
|
+
if (disposed) return;
|
|
467
|
+
registry.setShuttingDown(false);
|
|
468
|
+
const nextRegistryCtx = currentRegistryCtx ?? registryContext(ctx);
|
|
469
|
+
currentRegistryCtx = nextRegistryCtx;
|
|
470
|
+
await registry.ensureRuntimeDir(nextRegistryCtx);
|
|
471
|
+
if (disposed) return;
|
|
472
|
+
});
|
|
473
|
+
|
|
474
|
+
pi.on('session_shutdown', async (event, ctx) => {
|
|
475
|
+
beginSessionShutdown(event.reason);
|
|
476
|
+
if (shutdownCleanupStarted) return;
|
|
477
|
+
shutdownCleanupStarted = true;
|
|
478
|
+
try {
|
|
479
|
+
// Admission closure aborts cooperative preflight and the drain retains
|
|
480
|
+
// ownership until subprocess/file/managed cleanup settles. Any admitted
|
|
481
|
+
// child is inserted synchronously before spawn and is visible below.
|
|
482
|
+
await registry.waitForTaskAdmissions();
|
|
483
|
+
const running = registry.allTasks().filter((task) => task.status === 'running');
|
|
484
|
+
if (running.length === 0) return;
|
|
485
|
+
|
|
486
|
+
const failures: string[] = [];
|
|
487
|
+
await Promise.all(
|
|
488
|
+
running.map(async (task) => {
|
|
489
|
+
try {
|
|
490
|
+
await registry.stopTask(
|
|
491
|
+
task,
|
|
492
|
+
'shutdown',
|
|
493
|
+
`Killed during Pi session shutdown (${event.reason})`,
|
|
494
|
+
);
|
|
495
|
+
} catch (error) {
|
|
496
|
+
const message = `${task.id}: ${error instanceof Error ? error.message : String(error)}`;
|
|
497
|
+
failures.push(message);
|
|
498
|
+
console.error(`[background-tasks] shutdown cleanup failed for ${message}`);
|
|
499
|
+
}
|
|
500
|
+
}),
|
|
501
|
+
);
|
|
502
|
+
if (failures.length > 0 && ctx.hasUI) {
|
|
503
|
+
ctx.ui.notify(`Background task cleanup failed:\n${failures.join('\n')}`, 'error');
|
|
504
|
+
}
|
|
505
|
+
} finally {
|
|
506
|
+
eventService.close();
|
|
507
|
+
if ((event.reason !== 'reload' || reloadHandoffFailed) && activationLease !== undefined) {
|
|
508
|
+
try {
|
|
509
|
+
await registry.waitForReloadHostSettlement();
|
|
510
|
+
} catch (error) {
|
|
511
|
+
console.error(
|
|
512
|
+
'[background-tasks] reload owner host settlement failed during shutdown:',
|
|
513
|
+
error,
|
|
514
|
+
);
|
|
515
|
+
}
|
|
516
|
+
registry.releaseReloadActivation(activationLease);
|
|
517
|
+
activationLease = undefined;
|
|
518
|
+
activationIdentity = undefined;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
});
|
|
522
|
+
|
|
523
|
+
pi.registerCommand('bg', {
|
|
524
|
+
description:
|
|
525
|
+
'Start a tracked shell command: /bg [--survive-reload] [--name "Task name"] <command>',
|
|
526
|
+
handler: async (args, ctx) => {
|
|
527
|
+
try {
|
|
528
|
+
const parsed = parseBgCommandArgs(args);
|
|
529
|
+
const taskOptions: StartTaskOptions = {
|
|
530
|
+
surviveReload: parsed.surviveReload,
|
|
531
|
+
notifyOnCompletion: true,
|
|
532
|
+
triggerOnCompletion: false,
|
|
533
|
+
};
|
|
534
|
+
if (parsed.name !== undefined) taskOptions.name = parsed.name;
|
|
535
|
+
const task = await startTask(ctx, parsed.command, taskOptions);
|
|
536
|
+
ctx.ui.notify(
|
|
537
|
+
`Started ${taskDisplayName(task)} (${task.id})\nOutput: ${task.outputPath}\nCommand: ${task.command}`,
|
|
538
|
+
'info',
|
|
539
|
+
);
|
|
540
|
+
} catch (error) {
|
|
541
|
+
ctx.ui.notify(
|
|
542
|
+
`Background task failed to start: ${error instanceof Error ? error.message : String(error)}`,
|
|
543
|
+
'error',
|
|
544
|
+
);
|
|
545
|
+
}
|
|
546
|
+
},
|
|
547
|
+
});
|
|
548
|
+
|
|
549
|
+
pi.registerCommand('tasks', {
|
|
550
|
+
description: 'Open the background task manager UI',
|
|
551
|
+
handler: async (args, ctx) => {
|
|
552
|
+
const taskId = optionalTrimmed(args);
|
|
553
|
+
await openTaskManager(ctx, taskId);
|
|
554
|
+
},
|
|
555
|
+
});
|
|
556
|
+
|
|
557
|
+
pi.registerShortcut('shift+down' satisfies KeyId, {
|
|
558
|
+
description: 'Open the background task manager',
|
|
559
|
+
handler: async (ctx) => {
|
|
560
|
+
await openTaskManager(ctx);
|
|
561
|
+
},
|
|
562
|
+
});
|
|
563
|
+
pi.registerShortcut('ctrl+alt+b' satisfies KeyId, {
|
|
564
|
+
description: 'Open the background task manager',
|
|
565
|
+
handler: async (ctx) => {
|
|
566
|
+
await openTaskManager(ctx);
|
|
567
|
+
},
|
|
568
|
+
});
|
|
569
|
+
|
|
570
|
+
pi.registerCommand('jobs', {
|
|
571
|
+
description: 'List running and recent background tasks',
|
|
572
|
+
handler: (_args, ctx) => {
|
|
573
|
+
ctx.ui.notify(
|
|
574
|
+
formatSnapshotList(registry.allTasks().map((task) => registry.snapshot(task))),
|
|
575
|
+
'info',
|
|
576
|
+
);
|
|
577
|
+
return Promise.resolve();
|
|
578
|
+
},
|
|
579
|
+
});
|
|
580
|
+
|
|
581
|
+
pi.registerCommand('logs', {
|
|
582
|
+
description: 'Show bounded output from a background task: /logs <id> [maxBytes]',
|
|
583
|
+
getArgumentCompletions: (prefix) => {
|
|
584
|
+
const matches = registry
|
|
585
|
+
.allTasks()
|
|
586
|
+
.filter((task) => task.id.startsWith(prefix.trim()))
|
|
587
|
+
.slice(0, 20)
|
|
588
|
+
.map((task) => ({
|
|
589
|
+
value: task.id,
|
|
590
|
+
label: `${task.id} ${taskDisplayName(task)}`,
|
|
591
|
+
description: `${task.status} — ${truncateChars(task.command, 60)}`,
|
|
592
|
+
}));
|
|
593
|
+
return matches.length > 0 ? matches : null;
|
|
594
|
+
},
|
|
595
|
+
handler: async (args, ctx) => {
|
|
596
|
+
try {
|
|
597
|
+
const [id, bytes] = args.trim().split(/\s+/, 2);
|
|
598
|
+
const task = registry.resolveTask(id ?? '');
|
|
599
|
+
const maxBytes = normalizeMaxBytes(Number(bytes), DEFAULT_LOG_BYTES);
|
|
600
|
+
const logs = await registry.getTaskLogs(task, maxBytes, true);
|
|
601
|
+
ctx.ui.notify(logs.text, 'info');
|
|
602
|
+
} catch (error) {
|
|
603
|
+
ctx.ui.notify(
|
|
604
|
+
`Background logs error: ${error instanceof Error ? error.message : String(error)}`,
|
|
605
|
+
'error',
|
|
606
|
+
);
|
|
607
|
+
}
|
|
608
|
+
},
|
|
609
|
+
});
|
|
610
|
+
|
|
611
|
+
pi.registerCommand('kill', {
|
|
612
|
+
description: 'Stop a running background task: /kill <id>',
|
|
613
|
+
getArgumentCompletions: (prefix) => {
|
|
614
|
+
const matches = registry
|
|
615
|
+
.allTasks()
|
|
616
|
+
.filter((task) => task.status === 'running' && task.id.startsWith(prefix.trim()))
|
|
617
|
+
.slice(0, 20)
|
|
618
|
+
.map((task) => ({
|
|
619
|
+
value: task.id,
|
|
620
|
+
label: `${task.id} ${taskDisplayName(task)}`,
|
|
621
|
+
description: truncateChars(task.command, 70),
|
|
622
|
+
}));
|
|
623
|
+
return matches.length > 0 ? matches : null;
|
|
624
|
+
},
|
|
625
|
+
handler: async (args, ctx) => {
|
|
626
|
+
try {
|
|
627
|
+
const task = registry.resolveTask(args.trim());
|
|
628
|
+
await registry.stopTask(task, 'user');
|
|
629
|
+
ctx.ui.notify(
|
|
630
|
+
`Killed ${taskDisplayName(task)} (${task.id}). Output: ${task.outputPath}`,
|
|
631
|
+
'info',
|
|
632
|
+
);
|
|
633
|
+
} catch (error) {
|
|
634
|
+
ctx.ui.notify(
|
|
635
|
+
`Background kill error: ${error instanceof Error ? error.message : String(error)}`,
|
|
636
|
+
'error',
|
|
637
|
+
);
|
|
638
|
+
}
|
|
639
|
+
},
|
|
640
|
+
});
|
|
641
|
+
|
|
642
|
+
pi.registerCommand('clean', {
|
|
643
|
+
description: 'Delete finished background tasks: /clean [session|all|<id>]',
|
|
644
|
+
getArgumentCompletions: (prefix) => {
|
|
645
|
+
const p = prefix.trim();
|
|
646
|
+
const scopes = ['session', 'all'].filter((s) => s.startsWith(p));
|
|
647
|
+
const ids = registry
|
|
648
|
+
.allTasks()
|
|
649
|
+
.filter((task) => task.status !== 'running' && task.id.startsWith(p))
|
|
650
|
+
.slice(0, 20)
|
|
651
|
+
.map((task) => ({
|
|
652
|
+
value: task.id,
|
|
653
|
+
label: `${task.id} ${taskDisplayName(task)}`,
|
|
654
|
+
description: `${task.status} — ${truncateChars(task.command, 60)}`,
|
|
655
|
+
}));
|
|
656
|
+
const matches = [
|
|
657
|
+
...scopes.map((s) => ({ value: s, label: s, description: 'scope' })),
|
|
658
|
+
...ids,
|
|
659
|
+
];
|
|
660
|
+
return matches.length > 0 ? matches : null;
|
|
661
|
+
},
|
|
662
|
+
handler: async (args, ctx) => {
|
|
663
|
+
const arg = (args ?? '').trim();
|
|
664
|
+
let scope: CleanupScope;
|
|
665
|
+
let taskId: string | undefined;
|
|
666
|
+
if (arg === 'all') {
|
|
667
|
+
scope = 'all';
|
|
668
|
+
} else if (arg === 'session' || arg === '') {
|
|
669
|
+
scope = 'session';
|
|
670
|
+
} else {
|
|
671
|
+
scope = 'one';
|
|
672
|
+
taskId = arg;
|
|
673
|
+
}
|
|
674
|
+
try {
|
|
675
|
+
const summary = await registry.cleanupFinishedTasks(scope, taskId);
|
|
676
|
+
ctx.ui.notify(formatCleanMessage(summary), 'info');
|
|
677
|
+
} catch (error) {
|
|
678
|
+
ctx.ui.notify(
|
|
679
|
+
`Background clean error: ${error instanceof Error ? error.message : String(error)}`,
|
|
680
|
+
'error',
|
|
681
|
+
);
|
|
682
|
+
}
|
|
683
|
+
},
|
|
684
|
+
});
|
|
685
|
+
|
|
686
|
+
pi.registerTool<typeof BgRunParams, BgRunDetails>({
|
|
687
|
+
name: 'bg_run',
|
|
688
|
+
label: 'Background Run',
|
|
689
|
+
description: `Start a named long-running shell command in the background and return immediately with a task ID and output path. By default, completed, failed, or killed terminal state is delivered automatically as <background-task-notification> and starts a follow-up agent turn; do not sleep or poll merely to wait. Output is written to ${config.tasksDir} and model-visible logs are bounded to ${formatSize(MAX_LOG_BYTES)}.`,
|
|
690
|
+
promptSnippet:
|
|
691
|
+
'Start a named long-running shell command; default terminal notification wakes a follow-up turn, so yield instead of polling',
|
|
692
|
+
promptGuidelines: [
|
|
693
|
+
'Use bg_run instead of bash for commands expected to run for a long time, such as test suites, dev servers, watchers, or builds.',
|
|
694
|
+
'When using bg_run, always set name to a concise 2-6 word human-readable label; do not use the raw command as the name unless it is already short and meaningful.',
|
|
695
|
+
'bg_run returns immediately. With notifyOnCompletion:true and triggerOnCompletion:true (both defaults), completed, failed, or killed terminal state is delivered as <background-task-notification> and automatically starts a follow-up agent turn.',
|
|
696
|
+
'After a default bg_run launch, continue only independent useful work that does not merely wait for the task; otherwise briefly acknowledge it if useful, then end the current turn. Do not call sleep, bg_status, or bg_logs merely to wait; the terminal notification will wake you.',
|
|
697
|
+
'Treat <background-task-notification> as durable terminal truth. Do not call bg_status to reconfirm it; call bg_logs only when the task output is needed.',
|
|
698
|
+
'Use bg_status/bg_logs only when the user explicitly requests an update, automatic notification or wake-up was deliberately disabled, there is concrete evidence the task is hung, or a terminal notification arrived and output details are needed.',
|
|
699
|
+
'Do not set notifyOnCompletion:false or triggerOnCompletion:false unless intentionally opting out of automatic completion handling.',
|
|
700
|
+
],
|
|
701
|
+
parameters: BgRunParams,
|
|
702
|
+
prepareArguments(args): BgRunParamsValue {
|
|
703
|
+
if (!args || typeof args !== 'object') throw new Error('bg_run arguments must be an object');
|
|
704
|
+
const input = args as BgToolArgumentRecord;
|
|
705
|
+
if (typeof input.command !== 'string') throw new Error('bg_run requires command string');
|
|
706
|
+
if (Object.hasOwn(input, 'surviveReload') && typeof input.surviveReload !== 'boolean') {
|
|
707
|
+
throw new ReloadSurvivalError(
|
|
708
|
+
'pi_bg_survive_reload_invalid',
|
|
709
|
+
'bg_run surviveReload must be boolean when present',
|
|
710
|
+
);
|
|
711
|
+
}
|
|
712
|
+
const prepared: BgRunParamsValue = {
|
|
713
|
+
command: input.command,
|
|
714
|
+
name:
|
|
715
|
+
normalizeTaskName(input.name) ??
|
|
716
|
+
normalizeTaskName(input.description) ??
|
|
717
|
+
deriveTaskNameFromCommand(input.command),
|
|
718
|
+
};
|
|
719
|
+
if (typeof input.description === 'string') prepared.description = input.description;
|
|
720
|
+
if (typeof input.timeoutSeconds === 'number') prepared.timeoutSeconds = input.timeoutSeconds;
|
|
721
|
+
if (typeof input.notifyOnCompletion === 'boolean')
|
|
722
|
+
prepared.notifyOnCompletion = input.notifyOnCompletion;
|
|
723
|
+
if (typeof input.triggerOnCompletion === 'boolean')
|
|
724
|
+
prepared.triggerOnCompletion = input.triggerOnCompletion;
|
|
725
|
+
if (typeof input.surviveReload === 'boolean') prepared.surviveReload = input.surviveReload;
|
|
726
|
+
return prepared;
|
|
727
|
+
},
|
|
728
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
729
|
+
const taskOptions: StartTaskOptions = {
|
|
730
|
+
name: params.name,
|
|
731
|
+
surviveReload: params.surviveReload ?? false,
|
|
732
|
+
notifyOnCompletion: params.notifyOnCompletion ?? true,
|
|
733
|
+
triggerOnCompletion: params.triggerOnCompletion ?? true,
|
|
734
|
+
};
|
|
735
|
+
if (params.description !== undefined) taskOptions.description = params.description;
|
|
736
|
+
if (params.timeoutSeconds !== undefined) taskOptions.timeoutSeconds = params.timeoutSeconds;
|
|
737
|
+
const task = await startTask(ctx, params.command, taskOptions);
|
|
738
|
+
const completionDelivery = deriveCompletionDeliveryGuidance(
|
|
739
|
+
task.notifyOnCompletion,
|
|
740
|
+
task.triggerOnCompletion,
|
|
741
|
+
);
|
|
742
|
+
return {
|
|
743
|
+
content: textContent(
|
|
744
|
+
`Started background task ${taskDisplayName(task)} (${task.id})\nStatus: ${task.status}\nPID: ${String(task.pid ?? 'unknown')}\nOutput: ${task.outputPath}\n${completionDelivery.text}`,
|
|
745
|
+
),
|
|
746
|
+
details: { task: registry.snapshot(task) },
|
|
747
|
+
};
|
|
748
|
+
},
|
|
749
|
+
renderCall(args, theme) {
|
|
750
|
+
return new Text(
|
|
751
|
+
`${theme.fg('toolTitle', theme.bold('bg_run '))}${theme.fg('muted', truncateChars(taskDisplayName(args), COMMAND_PREVIEW_CHARS))}`,
|
|
752
|
+
0,
|
|
753
|
+
0,
|
|
754
|
+
);
|
|
755
|
+
},
|
|
756
|
+
renderResult(result, _options, theme) {
|
|
757
|
+
const { task } = result.details;
|
|
758
|
+
return new Text(
|
|
759
|
+
`${theme.fg('success', '✓ started')} ${theme.fg('accent', taskDisplayName(task))} ${theme.fg('dim', `(${task.id})`)}\n${theme.fg('dim', `Output: ${task.outputPath}`)}`,
|
|
760
|
+
0,
|
|
761
|
+
0,
|
|
762
|
+
);
|
|
763
|
+
},
|
|
764
|
+
});
|
|
765
|
+
|
|
766
|
+
pi.registerTool<typeof BgStatusParams, BgStatusDetails>({
|
|
767
|
+
name: 'bg_status',
|
|
768
|
+
label: 'Background Status',
|
|
769
|
+
description:
|
|
770
|
+
'Inspect one background task or list all running/recent background tasks. This is a point-in-time inspection tool, not a waiting primitive.',
|
|
771
|
+
promptSnippet:
|
|
772
|
+
'Inspect point-in-time status for one or all background tasks; never poll it as a wait loop',
|
|
773
|
+
promptGuidelines: [
|
|
774
|
+
'Use bg_status for deliberate point-in-time inspection, not as a waiting primitive.',
|
|
775
|
+
'A running result is not an instruction to poll again. Do not repeatedly call bg_status while an automatic terminal notification is pending.',
|
|
776
|
+
'Use bg_status when the user explicitly requests an update, automatic completion handling was disabled, or concrete evidence suggests a task is hung; terminal notifications do not need reconfirmation.',
|
|
777
|
+
],
|
|
778
|
+
parameters: BgStatusParams,
|
|
779
|
+
execute(_toolCallId, params) {
|
|
780
|
+
const selected = params.taskId ? [registry.resolveTask(params.taskId)] : registry.allTasks();
|
|
781
|
+
const snapshots = selected.map((task) => registry.snapshot(task));
|
|
782
|
+
return Promise.resolve({
|
|
783
|
+
content: textContent(formatSnapshotList(snapshots)),
|
|
784
|
+
details: { tasks: snapshots },
|
|
785
|
+
});
|
|
786
|
+
},
|
|
787
|
+
renderCall(args, theme) {
|
|
788
|
+
return new Text(
|
|
789
|
+
`${theme.fg('toolTitle', theme.bold('bg_status'))}${args.taskId ? ` ${theme.fg('accent', args.taskId)}` : ''}`,
|
|
790
|
+
0,
|
|
791
|
+
0,
|
|
792
|
+
);
|
|
793
|
+
},
|
|
794
|
+
renderResult: renderPlainResult,
|
|
795
|
+
});
|
|
796
|
+
|
|
797
|
+
pi.registerTool<typeof BgLogsParams, BgLogsDetails>({
|
|
798
|
+
name: 'bg_logs',
|
|
799
|
+
label: 'Background Logs',
|
|
800
|
+
description: `Read bounded output from a background task for deliberate inspection; this is not a waiting primitive. Output is capped at ${formatSize(MAX_LOG_BYTES)} for model safety and points to the full output file when truncated.`,
|
|
801
|
+
promptSnippet: 'Read bounded task output when needed; never tail it repeatedly as a wait loop',
|
|
802
|
+
promptGuidelines: [
|
|
803
|
+
'Use bg_logs with a modest maxBytes value only when task output is needed, without flooding context.',
|
|
804
|
+
'Do not repeatedly call bg_logs to wait for completion while an automatic terminal notification is pending.',
|
|
805
|
+
'Use bg_status first only when a deliberate inspection requires the current task state; do not reconfirm a terminal notification.',
|
|
806
|
+
],
|
|
807
|
+
parameters: BgLogsParams,
|
|
808
|
+
async execute(_toolCallId, params) {
|
|
809
|
+
const task = registry.resolveTask(params.taskId);
|
|
810
|
+
const logs = await registry.getTaskLogs(
|
|
811
|
+
task,
|
|
812
|
+
normalizeMaxBytes(params.maxBytes),
|
|
813
|
+
params.tail ?? true,
|
|
814
|
+
);
|
|
815
|
+
return {
|
|
816
|
+
content: textContent(logs.text),
|
|
817
|
+
details: logs.details,
|
|
818
|
+
};
|
|
819
|
+
},
|
|
820
|
+
renderCall(args, theme) {
|
|
821
|
+
return new Text(
|
|
822
|
+
`${theme.fg('toolTitle', theme.bold('bg_logs '))}${theme.fg('accent', args.taskId)}`,
|
|
823
|
+
0,
|
|
824
|
+
0,
|
|
825
|
+
);
|
|
826
|
+
},
|
|
827
|
+
renderResult(result, { expanded }, theme) {
|
|
828
|
+
const details = result.details;
|
|
829
|
+
let text = `${theme.fg('accent', taskDisplayName(details.task))} ${theme.fg('dim', `(${details.task.id})`)} ${theme.fg('muted', details.tail ? 'tail' : 'head')} ${formatSize(details.bytesRead)}`;
|
|
830
|
+
if (details.truncated) text += theme.fg('warning', ' (truncated)');
|
|
831
|
+
text += `\n${theme.fg('dim', `Full output: ${details.path}`)}`;
|
|
832
|
+
if (expanded) {
|
|
833
|
+
const output = result.content
|
|
834
|
+
.map((content) => (content.type === 'text' ? content.text : '[image content]'))
|
|
835
|
+
.join('\n');
|
|
836
|
+
text += `\n${theme.fg('toolOutput', output.split('\n').slice(0, 30).join('\n'))}`;
|
|
837
|
+
}
|
|
838
|
+
return new Text(text, 0, 0);
|
|
839
|
+
},
|
|
840
|
+
});
|
|
841
|
+
|
|
842
|
+
pi.registerTool<typeof BgKillParams, BgKillDetails>({
|
|
843
|
+
name: 'bg_kill',
|
|
844
|
+
label: 'Background Kill',
|
|
845
|
+
description:
|
|
846
|
+
'Stop a running background task by ID. Fails loudly if the task is unknown or already finished.',
|
|
847
|
+
promptSnippet: 'Stop a running background task by ID',
|
|
848
|
+
promptGuidelines: [
|
|
849
|
+
'Use bg_kill when the user asks to stop a background task or when a bg_run command is no longer needed.',
|
|
850
|
+
],
|
|
851
|
+
parameters: BgKillParams,
|
|
852
|
+
async execute(_toolCallId, params) {
|
|
853
|
+
const task = registry.resolveTask(params.taskId);
|
|
854
|
+
await registry.stopTask(task, 'user');
|
|
855
|
+
const message = `Killed background task ${taskDisplayName(task)} (${task.id}). Output: ${task.outputPath}`;
|
|
856
|
+
return {
|
|
857
|
+
content: textContent(message),
|
|
858
|
+
details: { task: registry.snapshot(task), message },
|
|
859
|
+
};
|
|
860
|
+
},
|
|
861
|
+
renderCall(args, theme) {
|
|
862
|
+
return new Text(
|
|
863
|
+
`${theme.fg('toolTitle', theme.bold('bg_kill '))}${theme.fg('accent', args.taskId)}`,
|
|
864
|
+
0,
|
|
865
|
+
0,
|
|
866
|
+
);
|
|
867
|
+
},
|
|
868
|
+
renderResult(result, _options, theme) {
|
|
869
|
+
const { task } = result.details;
|
|
870
|
+
return new Text(
|
|
871
|
+
`${theme.fg('warning', '■ killed')} ${theme.fg('accent', taskDisplayName(task))} ${theme.fg('dim', `(${task.id})`)}\n${theme.fg('dim', `Output: ${task.outputPath}`)}`,
|
|
872
|
+
0,
|
|
873
|
+
0,
|
|
874
|
+
);
|
|
875
|
+
},
|
|
876
|
+
});
|
|
877
|
+
|
|
878
|
+
pi.registerTool<typeof BgCleanParams, BgCleanDetails>({
|
|
879
|
+
name: 'bg_clean',
|
|
880
|
+
label: 'Background Clean',
|
|
881
|
+
description:
|
|
882
|
+
'Delete finished background tasks to free their disk space. Only terminal tasks (completed/failed/killed) are removed; running tasks are left alone and reported. Scope: a single task by ID, all of this session (default), or the entire tasks folder.',
|
|
883
|
+
promptSnippet: 'Delete finished background tasks',
|
|
884
|
+
promptGuidelines: [
|
|
885
|
+
'Use bg_clean when the user asks to clean up, remove, or free space from finished background tasks.',
|
|
886
|
+
'bg_clean never deletes a running task; it reports any running tasks it skipped.',
|
|
887
|
+
'By default it cleans this session; pass scope:"all" to clean the entire tasks folder.',
|
|
888
|
+
],
|
|
889
|
+
parameters: BgCleanParams,
|
|
890
|
+
async execute(_toolCallId, params) {
|
|
891
|
+
const scope: CleanupScope = params.taskId ? 'one' : (params.scope ?? 'session');
|
|
892
|
+
const summary = await registry.cleanupFinishedTasks(scope, params.taskId);
|
|
893
|
+
return {
|
|
894
|
+
content: textContent(formatCleanMessage(summary)),
|
|
895
|
+
details: {
|
|
896
|
+
scope,
|
|
897
|
+
deleted: summary.deleted,
|
|
898
|
+
skipped: summary.skipped,
|
|
899
|
+
notFound: summary.notFound,
|
|
900
|
+
},
|
|
901
|
+
};
|
|
902
|
+
},
|
|
903
|
+
renderCall(args, theme) {
|
|
904
|
+
const target = args.taskId ?? args.scope ?? 'session';
|
|
905
|
+
return new Text(
|
|
906
|
+
`${theme.fg('toolTitle', theme.bold('bg_clean'))} ${theme.fg('accent', target)}`,
|
|
907
|
+
0,
|
|
908
|
+
0,
|
|
909
|
+
);
|
|
910
|
+
},
|
|
911
|
+
renderResult(result, { expanded }, theme) {
|
|
912
|
+
const d = result.details;
|
|
913
|
+
let text = `${theme.fg('muted', `scope=${d.scope}`)} ${theme.fg('accent', `${d.deleted.length} deleted`)}`;
|
|
914
|
+
if (d.skipped.length > 0)
|
|
915
|
+
text += ` ${theme.fg('warning', `${d.skipped.length} skipped (running)`)}`;
|
|
916
|
+
if (d.notFound.length > 0)
|
|
917
|
+
text += ` ${theme.fg('warning', `${d.notFound.length} not found`)}`;
|
|
918
|
+
if (expanded) {
|
|
919
|
+
for (const item of d.deleted)
|
|
920
|
+
text += `\n ✓ ${theme.fg('accent', item.id)} ${theme.fg('dim', item.status)}`;
|
|
921
|
+
for (const item of d.skipped)
|
|
922
|
+
text += `\n ▶ ${theme.fg('accent', item.id)} ${theme.fg('dim', 'running, kept')}`;
|
|
923
|
+
for (const n of d.notFound) text += `\n ${theme.fg('warning', n)}`;
|
|
924
|
+
}
|
|
925
|
+
return new Text(text, 0, 0);
|
|
926
|
+
},
|
|
927
|
+
});
|
|
928
|
+
}
|