pi-better-background-tasks 0.18.0 → 0.20.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/README.md +25 -13
- package/package.json +1 -1
- package/runtime-client/artifacts/darwin-arm64.gz +0 -0
- package/runtime-client/artifacts/darwin-arm64.json +1 -1
- package/runtime-client/artifacts/darwin-x64.gz +0 -0
- package/runtime-client/artifacts/darwin-x64.json +1 -1
- package/runtime-client/artifacts/linux-arm64.gz +0 -0
- package/runtime-client/artifacts/linux-arm64.json +1 -1
- package/runtime-client/artifacts/linux-x64.gz +0 -0
- package/runtime-client/artifacts/linux-x64.json +1 -1
- package/runtime-client/src/runtime/client.mjs +30 -3
- package/runtime-client/src/runtime/root.mjs +5 -2
- package/runtime-client/src/runtime/work-client.mjs +150 -7
- package/src/adapter-contract.ts +1 -1
- package/src/goal-provider.ts +31 -16
- package/src/index.ts +25 -9
- package/src/managed-authority.ts +5 -3
- package/src/managed-client.ts +20 -7
- package/src/managed-frontend.ts +135 -19
- package/src/navigator-provider.ts +19 -5
- package/src/observed-wait-client.ts +10 -0
- package/src/observed-waits.ts +321 -53
- package/src/process-identity.ts +18 -2
- package/src/process.ts +48 -14
- package/src/registry.ts +53 -5
- package/src/review-settings.ts +18 -0
- package/src/runtime.ts +27 -82
- package/src/sandbox.ts +14 -11
- package/src/shared-callback-batcher.ts +11 -2
- package/src/shared-navigator-panels.ts +26 -4
- package/src/shared-navigator.ts +244 -40
- package/src/shared-operation-coordinator/assignment-observation.mjs +43 -35
- package/src/shared-operation-coordinator/src/assignment-changes.ts +73 -0
- package/src/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
- package/src/shared-operation-coordinator/src/background-requests.ts +14 -3
- package/src/shared-operation-coordinator/src/discovery.ts +5 -3
- package/src/shared-operation-coordinator/src/operations.ts +50 -2
- package/src/shared-operation-coordinator/src/outbox.ts +9 -0
- package/src/shared-operation-coordinator/src/result-supervision.ts +12 -0
- package/src/shared-operation-coordinator/src/rows.ts +2 -0
- package/src/shared-operation-coordinator/src/schema.ts +40 -24
- package/src/shared-operation-coordinator/src/store.ts +40 -8
- package/src/shared-operation-coordinator/src/subagent-launch.ts +24 -1
- package/src/shared-operation-coordinator/src/types.ts +5 -1
- package/src/shared-sandbox-core.ts +1 -1
- package/src/shared-work-client.mjs +150 -7
- package/src/stall.ts +7 -4
- package/src/supervised-progress.ts +43 -0
- package/src/supervisor/README.md +1 -4
- package/src/supervisor/emit-runner.mjs +1 -0
- package/src/supervisor/generated/process-identity.mjs +20 -2
- package/src/supervisor/generated/process.mjs +52 -14
- package/src/supervisor/generated/runner.mjs +47 -4
- package/src/supervisor/generated/store.mjs +3 -3
- package/src/supervisor/generated/watch-fingerprint.mjs +69 -0
- package/src/supervisor/runner.ts +38 -3
- package/src/supervisor/store.ts +3 -3
- package/src/supervisor/supervisor.ts +6 -3
- package/src/task-diagnostics.ts +1 -1
- package/src/tools.ts +67 -54
- package/src/types.ts +7 -3
- package/src/watch-fingerprint.ts +70 -0
- package/src/work-observation.ts +46 -19
package/src/tools.ts
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import { Type } from "typebox";
|
|
2
2
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import {
|
|
4
|
+
truncateToWidth as piTruncateToWidth,
|
|
5
|
+
visibleWidth as piVisibleWidth,
|
|
6
|
+
wrapTextWithAnsi as piWrapTextWithAnsi,
|
|
7
|
+
} from "@earendil-works/pi-tui";
|
|
3
8
|
import { advertiseBackgroundAdapter } from "./adapter-contract.js";
|
|
4
|
-
import { formatBatchLaunch, spawnTaskBatch } from "./batch.js";
|
|
5
9
|
import { refreshBackgroundTasksNavigator } from "./navigator-provider.js";
|
|
6
10
|
import {
|
|
7
11
|
classifyOwnership,
|
|
@@ -18,26 +22,19 @@ import {
|
|
|
18
22
|
import { cursorKind, readOutputControls } from "./shared-log-utils.js";
|
|
19
23
|
import { cancelCallbackBatch, getCallbackBatcher, setCallbackBatchContext } from "./shared-callback-batcher.js";
|
|
20
24
|
import { registerDeliveryObserver } from "./delivery-observer.js";
|
|
21
|
-
import {
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
observedWaitServiceUnavailableReason,
|
|
25
|
-
type DurableTaskKind,
|
|
26
|
-
type DurableLaunch,
|
|
27
|
-
type WaitView,
|
|
28
|
-
} from "./observed-waits.js";
|
|
29
|
-
import { backgroundObservation } from "./work-observation.js";
|
|
25
|
+
import { getObservedWaitHost } from "./observed-wait-client.js";
|
|
26
|
+
import type { DurableTaskKind, DurableLaunch, WaitView } from "./observed-waits.js";
|
|
27
|
+
import { backgroundListNeedsHistory, backgroundObservation } from "./work-observation.js";
|
|
30
28
|
import { inspectMeta, listMetasForOrigin, readMeta, writeMeta } from "./registry.js";
|
|
31
|
-
import {
|
|
32
|
-
import { runTaskMaintenance } from "./maintenance.js";
|
|
29
|
+
import type { WatchTaskParams, BackgroundTaskRuntime } from "./runtime.js";
|
|
33
30
|
import { backgroundProcessDiagnosticsAccess, ForegroundSandboxBlockedError } from "./sandbox.js";
|
|
34
31
|
import { inspectTaskProcess } from "./task-diagnostics.js";
|
|
35
32
|
import type { BackgroundTaskCallbackOrigin, BackgroundTaskMeta } from "./types.js";
|
|
36
|
-
import { isTerminalStatus } from "./types.js";
|
|
33
|
+
import { FIRST_WATCH_CHECK_WAIT_MS, isTerminalStatus } from "./types.js";
|
|
37
34
|
|
|
38
35
|
export { formatLaunch } from "./output.js";
|
|
39
36
|
|
|
40
|
-
|
|
37
|
+
type ToolRuntime = Pick<BackgroundTaskRuntime, "awaitFirstWatchCheck" | "resumeRunningTask" | "spawnTask" | "startWatchTask" | "stopTask">;
|
|
41
38
|
|
|
42
39
|
const JsonPathSchema = Type.String({
|
|
43
40
|
pattern: "^\\$",
|
|
@@ -178,7 +175,7 @@ const IdParams = Type.Object({
|
|
|
178
175
|
...CursorFields,
|
|
179
176
|
});
|
|
180
177
|
const HistoryField = {
|
|
181
|
-
diagnostics: Type.Optional(Type.Boolean({ description: "For status: sample registered task process identity, CPU time, state and wait evidence. Requires
|
|
178
|
+
diagnostics: Type.Optional(Type.Boolean({ description: "For status: sample registered task process identity, CPU time, state and wait evidence. Requires Process access Read in each enabled sandbox profile (Main and Background tasks); unavailable under Main confinement. No arguments, environment or remote probes; a snapshot cannot prove useful work or a hang." })),
|
|
182
179
|
history: Type.Optional(Type.Boolean({ description: "If true, return an incident page that also lists failure history: expected failures and recovered or superseded incidents. Default output lists only failures that need action and counts the rest." })),
|
|
183
180
|
};
|
|
184
181
|
const StatusParams = Type.Object({
|
|
@@ -299,8 +296,7 @@ const BACKGROUND_ORCHESTRATION_GUIDELINES = [
|
|
|
299
296
|
"Do not treat launch as completion of the parent milestone; relevant background work must be terminal, inspected, and integrated before verification or completion.",
|
|
300
297
|
];
|
|
301
298
|
|
|
302
|
-
export function registerTools(pi: ExtensionAPI, runtime
|
|
303
|
-
const { resumeRunningTask, spawnTask } = runtime;
|
|
299
|
+
export function registerTools(pi: ExtensionAPI, runtime?: ToolRuntime, refreshNavigator = refreshBackgroundTasksNavigator, options: { resumeLocal?: boolean } = {}): void {
|
|
304
300
|
let activeSession: BackgroundTaskCallbackOrigin | undefined;
|
|
305
301
|
const getActiveSession = () => activeSession;
|
|
306
302
|
const schemas = new Map<string, object>();
|
|
@@ -316,12 +312,14 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
|
|
|
316
312
|
setCallbackBatchContext(pi, ctx);
|
|
317
313
|
activeSession = getCallbackOrigin(ctx);
|
|
318
314
|
if (options.resumeLocal !== false) {
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
315
|
+
const { resumeRunningTask } = runtime ?? await import("./runtime.js");
|
|
316
|
+
const { runTaskMaintenance } = await import("./maintenance.js");
|
|
317
|
+
for (const meta of listMetasForOrigin(activeSession)) {
|
|
318
|
+
if (meta.status === "running" || (meta.callback !== false && !meta.callbackSentAt && !meta.callbackSuppressedAt)) {
|
|
319
|
+
resumeRunningTask(pi, meta, getActiveSession);
|
|
320
|
+
}
|
|
322
321
|
}
|
|
323
|
-
|
|
324
|
-
runTaskMaintenance({ activeOrigin: activeSession });
|
|
322
|
+
runTaskMaintenance({ activeOrigin: activeSession });
|
|
325
323
|
}
|
|
326
324
|
});
|
|
327
325
|
pi.on("agent_start", (_event, ctx) => {
|
|
@@ -360,6 +358,7 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
|
|
|
360
358
|
refreshNavigator(ctx);
|
|
361
359
|
return text(durable, launchReceipt(receipt));
|
|
362
360
|
}
|
|
361
|
+
const { spawnTask } = runtime ?? await import("./runtime.js");
|
|
363
362
|
const launched = reportLaunch(() => spawnTask(pi, params, ctx.cwd, origin, getActiveSession));
|
|
364
363
|
refreshNavigator(ctx);
|
|
365
364
|
return text(launched);
|
|
@@ -374,6 +373,7 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
|
|
|
374
373
|
parameters: BatchParams,
|
|
375
374
|
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
376
375
|
activeSession = getCallbackOrigin(ctx);
|
|
376
|
+
const { formatBatchLaunch, spawnTaskBatch } = await import("./batch.js");
|
|
377
377
|
const launched = spawnTaskBatch(pi, params, ctx.cwd, activeSession, getActiveSession, {}, runtime);
|
|
378
378
|
refreshNavigator(ctx);
|
|
379
379
|
return text(formatBatchLaunch(launched), launched);
|
|
@@ -456,7 +456,7 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
|
|
|
456
456
|
refreshNavigator(ctx);
|
|
457
457
|
return text(durable);
|
|
458
458
|
}
|
|
459
|
-
const result = await formatStop(pi, params.id, ctx, getActiveSession, statusOptions(params, origin), runtime);
|
|
459
|
+
const result = await formatStop(pi, params.id, ctx, getActiveSession, statusOptions(params, origin), runtime ?? await import("./runtime.js"));
|
|
460
460
|
refreshNavigator(ctx);
|
|
461
461
|
return text(result);
|
|
462
462
|
},
|
|
@@ -473,7 +473,7 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
|
|
|
473
473
|
},
|
|
474
474
|
async execute(toolCallId, params, signal, _onUpdate, ctx) {
|
|
475
475
|
activeSession = getCallbackOrigin(ctx);
|
|
476
|
-
return actionText(pi, { ...params, request_id: params.request_id ?? toolCallId }, ctx, activeSession, getActiveSession, signal, runtime, refreshNavigator);
|
|
476
|
+
return actionText(pi, { ...params, request_id: params.request_id ?? toolCallId }, ctx, activeSession, getActiveSession, signal, runtime ?? await import("./runtime.js"), refreshNavigator);
|
|
477
477
|
},
|
|
478
478
|
});
|
|
479
479
|
|
|
@@ -487,7 +487,7 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
|
|
|
487
487
|
},
|
|
488
488
|
async execute(toolCallId, params, _signal, _onUpdate, ctx) {
|
|
489
489
|
activeSession = getCallbackOrigin(ctx);
|
|
490
|
-
return actionText(pi, { ...params, request_id: params.request_id ?? toolCallId }, ctx, activeSession, getActiveSession, undefined, runtime, refreshNavigator);
|
|
490
|
+
return actionText(pi, { ...params, request_id: params.request_id ?? toolCallId }, ctx, activeSession, getActiveSession, undefined, runtime ?? await import("./runtime.js"), refreshNavigator);
|
|
491
491
|
},
|
|
492
492
|
});
|
|
493
493
|
|
|
@@ -503,14 +503,14 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
|
|
|
503
503
|
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
504
504
|
const host = getObservedWaitHost(pi);
|
|
505
505
|
if (!host?.available) {
|
|
506
|
-
return text(observedWaitServiceUnavailableReason(pi)
|
|
506
|
+
return text((await import("./observed-waits.js")).observedWaitServiceUnavailableReason(pi)
|
|
507
507
|
?? "Observed waits are unavailable in this session; inspect tasks directly and continue without a durable wait.");
|
|
508
508
|
}
|
|
509
509
|
try {
|
|
510
510
|
const wait = host.usesServerResults
|
|
511
511
|
? await host.superviseParentWait(ctx, params.task_ids, params.continuation_note)
|
|
512
512
|
: host.waitForParent(ctx, params.task_ids, params.continuation_note);
|
|
513
|
-
return text(formatWaitView(wait), wait);
|
|
513
|
+
return text((await import("./observed-waits.js")).formatWaitView(wait), wait);
|
|
514
514
|
} catch (error) {
|
|
515
515
|
return text(`Wait was not registered: ${readableError(error)}`);
|
|
516
516
|
}
|
|
@@ -525,7 +525,7 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
|
|
|
525
525
|
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
526
526
|
const host = getObservedWaitHost(pi);
|
|
527
527
|
if (!host?.available) {
|
|
528
|
-
return text(observedWaitServiceUnavailableReason(pi)
|
|
528
|
+
return text((await import("./observed-waits.js")).observedWaitServiceUnavailableReason(pi)
|
|
529
529
|
?? "Observed waits are unavailable in this session; no wait was consumed.");
|
|
530
530
|
}
|
|
531
531
|
try {
|
|
@@ -571,6 +571,7 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
|
|
|
571
571
|
try {
|
|
572
572
|
const waits = host.listWaitsForParent(ctx, { pendingOnly: params.pending_only === true });
|
|
573
573
|
if (waits.length === 0) return text("No durable waits for this session.");
|
|
574
|
+
const { formatWaitView } = await import("./observed-waits.js");
|
|
574
575
|
return text(waits.map((wait: WaitView) => formatWaitView(wait)).join("\n\n"), waits);
|
|
575
576
|
} catch (error) {
|
|
576
577
|
return text(`Waits could not be listed: ${readableError(error)}`);
|
|
@@ -671,7 +672,7 @@ async function actionText(
|
|
|
671
672
|
callbackOrigin: BackgroundTaskCallbackOrigin,
|
|
672
673
|
getActiveSession: () => BackgroundTaskCallbackOrigin | undefined,
|
|
673
674
|
signal: AbortSignal | undefined,
|
|
674
|
-
runtime:
|
|
675
|
+
runtime: ToolRuntime,
|
|
675
676
|
refreshNavigator: typeof refreshBackgroundTasksNavigator,
|
|
676
677
|
) {
|
|
677
678
|
if (params.action === "log" && params.id) {
|
|
@@ -691,7 +692,7 @@ async function runAction(
|
|
|
691
692
|
callbackOrigin: BackgroundTaskCallbackOrigin,
|
|
692
693
|
getActiveSession: () => BackgroundTaskCallbackOrigin | undefined,
|
|
693
694
|
signal: AbortSignal | undefined,
|
|
694
|
-
runtime:
|
|
695
|
+
runtime: ToolRuntime,
|
|
695
696
|
refreshNavigator: typeof refreshBackgroundTasksNavigator,
|
|
696
697
|
onLaunch?: (launch: DurableLaunch) => void,
|
|
697
698
|
): Promise<string> {
|
|
@@ -746,7 +747,7 @@ async function runAction(
|
|
|
746
747
|
}
|
|
747
748
|
}
|
|
748
749
|
|
|
749
|
-
/**
|
|
750
|
+
/** Ordinary lists reuse retained activity; explicit filtered/paged lists open history. */
|
|
750
751
|
async function durableAwareList(
|
|
751
752
|
pi: ExtensionAPI,
|
|
752
753
|
params: Record<string, unknown>,
|
|
@@ -754,10 +755,16 @@ async function durableAwareList(
|
|
|
754
755
|
ctx: ExtensionContext,
|
|
755
756
|
): Promise<string> {
|
|
756
757
|
const options = listOptions(params, origin);
|
|
757
|
-
const
|
|
758
|
+
const history = backgroundListNeedsHistory(params);
|
|
759
|
+
const snapshot = origin && !unavailableSessionOrigins.has(origin) ? await backgroundObservation(pi, ctx, history, params.all === true,
|
|
758
760
|
{ limit: options.limit, statuses: options.statuses, cursor: options.cursor }) : undefined;
|
|
759
761
|
if (snapshot && snapshot.status !== "ready") throw new Error(snapshot.reason ?? "Background activity is unverified");
|
|
760
|
-
const
|
|
762
|
+
const index = snapshot?.backgroundIndex ?? (snapshot ? { records: snapshot.rows
|
|
763
|
+
.map((row: any) => ({ found: true, meta: row.meta.durable ? { ...row.meta,
|
|
764
|
+
callbackOrigin: { cwd: row.meta.owner.workspace, sessionId: row.meta.owner.sessionId },
|
|
765
|
+
logPath: row.meta.logPaths?.stdout ?? "" } : row.meta }))
|
|
766
|
+
.sort((a: any, b: any) => b.meta.startedAt - a.meta.startedAt || b.meta.id.localeCompare(a.meta.id)) } : undefined);
|
|
767
|
+
const legacy = formatList(options, index);
|
|
761
768
|
if (snapshot) return legacy;
|
|
762
769
|
const host = getObservedWaitHost(pi);
|
|
763
770
|
if ((!snapshot && !host?.available) || !origin || typeof params.cursor === "string") return legacy;
|
|
@@ -925,9 +932,9 @@ export async function launchWatch(
|
|
|
925
932
|
getActiveSession: () => BackgroundTaskCallbackOrigin | undefined,
|
|
926
933
|
waitMs = FIRST_WATCH_CHECK_WAIT_MS,
|
|
927
934
|
signal?: AbortSignal,
|
|
928
|
-
runtime
|
|
935
|
+
runtime?: ToolRuntime,
|
|
929
936
|
): Promise<string> {
|
|
930
|
-
const { startWatchTask, awaitFirstWatchCheck } = runtime;
|
|
937
|
+
const { startWatchTask, awaitFirstWatchCheck } = runtime ?? await import("./runtime.js");
|
|
931
938
|
let meta: BackgroundTaskMeta;
|
|
932
939
|
try {
|
|
933
940
|
meta = startWatchTask(pi, params, cwd, callbackOrigin, getActiveSession);
|
|
@@ -954,7 +961,8 @@ function getCallbackOrigin(ctx: ExtensionContext | undefined): BackgroundTaskCal
|
|
|
954
961
|
sessionId = undefined;
|
|
955
962
|
unavailable = true;
|
|
956
963
|
}
|
|
957
|
-
const origin = { cwd: ctx?.cwd ?? "", sessionId
|
|
964
|
+
const origin: BackgroundTaskCallbackOrigin = { cwd: ctx?.cwd ?? "", sessionId,
|
|
965
|
+
branchId: ctx?.sessionManager?.getLeafId?.() ?? null };
|
|
958
966
|
if (unavailable) unavailableSessionOrigins.add(origin);
|
|
959
967
|
return origin;
|
|
960
968
|
}
|
|
@@ -1042,29 +1050,34 @@ function renderLines(lines: string[], mode: "truncate" | "wrap" = "truncate") {
|
|
|
1042
1050
|
};
|
|
1043
1051
|
}
|
|
1044
1052
|
|
|
1053
|
+
/**
|
|
1054
|
+
* Split one display line into rows of at most `width` terminal columns.
|
|
1055
|
+
*
|
|
1056
|
+
* Measures columns rather than characters: a CJK grapheme or emoji occupies two,
|
|
1057
|
+
* so counting characters emitted rows wider than the width Pi asked for. Pi
|
|
1058
|
+
* asserts every rendered line fits the terminal and exits the process when one
|
|
1059
|
+
* does not, which turned any log holding double-width text into a crash that
|
|
1060
|
+
* replayed on resume, because the tool result stays in session history.
|
|
1061
|
+
*/
|
|
1045
1062
|
function wrapLineToVisibleWidth(line: string, width: number): string[] {
|
|
1046
1063
|
const str = String(line ?? "");
|
|
1047
1064
|
const max = Math.max(1, Number(width) || 80);
|
|
1048
|
-
if (
|
|
1049
|
-
const
|
|
1050
|
-
|
|
1051
|
-
let visible = 0;
|
|
1052
|
-
for (const char of str) {
|
|
1053
|
-
if (visible >= max) {
|
|
1054
|
-
out.push(current);
|
|
1055
|
-
current = "";
|
|
1056
|
-
visible = 0;
|
|
1057
|
-
}
|
|
1058
|
-
current += char;
|
|
1059
|
-
visible += 1;
|
|
1060
|
-
}
|
|
1061
|
-
out.push(current);
|
|
1062
|
-
return out;
|
|
1065
|
+
if (piVisibleWidth(str) <= max) return [str];
|
|
1066
|
+
const wrapped = piWrapTextWithAnsi(str, max);
|
|
1067
|
+
return (wrapped.length > 0 ? wrapped : [str]).map((row) => fitToVisibleWidth(row, max));
|
|
1063
1068
|
}
|
|
1064
1069
|
|
|
1065
1070
|
function truncateToVisibleWidth(value: string, width: number): string {
|
|
1066
1071
|
const max = Math.max(0, Math.floor(width || 0));
|
|
1067
|
-
return String(value ?? "")
|
|
1072
|
+
return fitToVisibleWidth(String(value ?? ""), max);
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
/** Last resort for anything a wrap missed: never return a line wider than `max`. */
|
|
1076
|
+
function fitToVisibleWidth(value: string, max: number): string {
|
|
1077
|
+
const str = String(value ?? "");
|
|
1078
|
+
const limit = Math.max(0, Math.floor(max || 0));
|
|
1079
|
+
if (piVisibleWidth(str) <= limit) return str;
|
|
1080
|
+
return piTruncateToWidth(str, limit, "");
|
|
1068
1081
|
}
|
|
1069
1082
|
|
|
1070
1083
|
async function formatStop(
|
|
@@ -1073,9 +1086,9 @@ async function formatStop(
|
|
|
1073
1086
|
_ctx: ExtensionContext,
|
|
1074
1087
|
getActiveSession?: () => BackgroundTaskCallbackOrigin | undefined,
|
|
1075
1088
|
options: OutputOptions = {},
|
|
1076
|
-
runtime
|
|
1089
|
+
runtime?: Pick<BackgroundTaskRuntime, "stopTask">,
|
|
1077
1090
|
): Promise<string> {
|
|
1078
|
-
const { stopTask } = runtime;
|
|
1091
|
+
const { stopTask } = runtime ?? await import("./runtime.js");
|
|
1079
1092
|
const existing = inspectMeta(id);
|
|
1080
1093
|
if (!existing.meta && !existing.found) return formatStopResult(existing, options);
|
|
1081
1094
|
if (!existing.meta) return formatMissingTask(existing, options);
|
package/src/types.ts
CHANGED
|
@@ -24,6 +24,8 @@ export interface CommandSpec {
|
|
|
24
24
|
shell?: boolean;
|
|
25
25
|
/** Run the shell as a login shell (`bash -lc`, the default). False runs `bash -c`, skipping profile sourcing. */
|
|
26
26
|
loginShell?: boolean;
|
|
27
|
+
/** Internal executable selected by the host for a Windows shell or log trampoline. */
|
|
28
|
+
resolvedWindowsShell?: string;
|
|
27
29
|
cwd?: string;
|
|
28
30
|
env?: Record<string, string>;
|
|
29
31
|
}
|
|
@@ -93,6 +95,7 @@ export interface ResolvedRemoteTaskMetadata {
|
|
|
93
95
|
export interface BackgroundTaskCallbackOrigin {
|
|
94
96
|
cwd: string;
|
|
95
97
|
sessionId?: string;
|
|
98
|
+
branchId?: string | null;
|
|
96
99
|
}
|
|
97
100
|
|
|
98
101
|
export interface TaskSandboxProvenance {
|
|
@@ -159,8 +162,8 @@ export interface BackgroundTaskMeta {
|
|
|
159
162
|
env?: Record<string, string>;
|
|
160
163
|
/**
|
|
161
164
|
* The executable and argv this task was actually launched with, when that
|
|
162
|
-
* differs from `command`/`argv` above
|
|
163
|
-
*
|
|
165
|
+
* differs from `command`/`argv` above, such as an OS write-sandbox wrapper
|
|
166
|
+
* or a Windows watch shell selected at launch. Re-running a watch poll uses
|
|
164
167
|
* it verbatim, which is how a running task keeps the policy it started under
|
|
165
168
|
* even after the foreground policy changes. `command`/`argv` stay the operator's
|
|
166
169
|
* own request, so status, navigator, and goal surfaces read unchanged.
|
|
@@ -231,4 +234,5 @@ export interface TerminalResult {
|
|
|
231
234
|
|
|
232
235
|
export function isTerminalStatus(status: BackgroundTaskStatus): boolean {
|
|
233
236
|
return status !== "running";
|
|
234
|
-
}
|
|
237
|
+
}
|
|
238
|
+
export const FIRST_WATCH_CHECK_WAIT_MS = 15_000;
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import type { CommandResult } from "./types.js";
|
|
3
|
+
|
|
4
|
+
/** Version tag of the watch outcome fingerprint. A value from another version is adopted, never compared. */
|
|
5
|
+
export const WATCH_FINGERPRINT_VERSION = "v1";
|
|
6
|
+
/** OSC and CSI control sequences are display markup, not content. */
|
|
7
|
+
const TERMINAL_ESCAPE = /\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)|\u001b\[[0-?]*[ -/]*[@-~]/g;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Text as the terminal would settle it. Redraw frames and control sequences are
|
|
11
|
+
* display churn: repainting the same visible line is not a new observation.
|
|
12
|
+
*/
|
|
13
|
+
function settledTerminalText(text: string): string {
|
|
14
|
+
return text
|
|
15
|
+
.replace(TERMINAL_ESCAPE, "")
|
|
16
|
+
.split("\n")
|
|
17
|
+
.map((line) => {
|
|
18
|
+
// A CR immediately before LF ends the line; any other CR overwrites it in place.
|
|
19
|
+
const body = line.endsWith("\r") ? line.slice(0, -1) : line;
|
|
20
|
+
return (body.split("\r").at(-1) ?? "").replace(/[ \t]+$/, "");
|
|
21
|
+
})
|
|
22
|
+
.join("\n")
|
|
23
|
+
.replace(/\n+$/, "");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Objects compare by content regardless of key order, so reordered keys are not progress. */
|
|
27
|
+
function canonicalJsonText(value: unknown): string {
|
|
28
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJsonText).join(",")}]`;
|
|
29
|
+
if (value && typeof value === "object") {
|
|
30
|
+
const record = value as Record<string, unknown>;
|
|
31
|
+
const entries = Object.keys(record).sort()
|
|
32
|
+
.map((key) => `${JSON.stringify(key)}:${canonicalJsonText(record[key])}`);
|
|
33
|
+
return `{${entries.join(",")}}`;
|
|
34
|
+
}
|
|
35
|
+
return JSON.stringify(value) ?? "null";
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** stdout compares as JSON content when it parses, and as settled text otherwise. */
|
|
39
|
+
function canonicalWatchStdout(stdout: string): string {
|
|
40
|
+
const settled = settledTerminalText(stdout);
|
|
41
|
+
try {
|
|
42
|
+
return `json:${canonicalJsonText(JSON.parse(settled))}`;
|
|
43
|
+
} catch {
|
|
44
|
+
return `text:${settled}`;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* What a poll observed, independent of when it ran. Exit status, signal, error,
|
|
50
|
+
* stdout content, and stderr content are included; poll metadata (start time,
|
|
51
|
+
* end time, duration, check count) is deliberately not, so it can never hide a
|
|
52
|
+
* watch that reports the same outcome forever. Watch stdout may carry its own
|
|
53
|
+
* timestamps: projecting meaningful fields is the caller's job, not this
|
|
54
|
+
* fingerprint's guess.
|
|
55
|
+
*/
|
|
56
|
+
export function watchOutcomeFingerprint(result: CommandResult): string {
|
|
57
|
+
// A runner may report why the check itself could not run; that is part of the
|
|
58
|
+
// observed outcome, not poll metadata.
|
|
59
|
+
const reported = (result as CommandResult & { error?: unknown }).error;
|
|
60
|
+
const error = typeof reported === "string" ? settledTerminalText(reported) : null;
|
|
61
|
+
const payload = JSON.stringify([
|
|
62
|
+
result.exitCode,
|
|
63
|
+
result.signal ?? null,
|
|
64
|
+
result.timedOut === true,
|
|
65
|
+
error,
|
|
66
|
+
canonicalWatchStdout(result.stdout),
|
|
67
|
+
settledTerminalText(result.stderr),
|
|
68
|
+
]);
|
|
69
|
+
return `${WATCH_FINGERPRINT_VERSION}:${createHash("sha256").update(payload).digest("hex")}`;
|
|
70
|
+
}
|
package/src/work-observation.ts
CHANGED
|
@@ -4,18 +4,44 @@ import { join } from "node:path";
|
|
|
4
4
|
import { homedir } from "node:os";
|
|
5
5
|
import { setTimeout as delay } from "node:timers/promises";
|
|
6
6
|
|
|
7
|
+
import { cursorKind } from "./shared-log-utils.js";
|
|
8
|
+
|
|
7
9
|
const hostedClients = new WeakSet<object>();
|
|
10
|
+
const connectionAborts = new WeakMap<object, AbortController>();
|
|
8
11
|
const clients = new WeakMap<object, Promise<any>>();
|
|
9
12
|
const generations = new WeakMap<object, number>();
|
|
10
13
|
const listeners = new WeakMap<object, Set<() => void>>();
|
|
14
|
+
const subscribedClients = new WeakMap<object, any>();
|
|
15
|
+
const activityScopes = new WeakMap<object, string>();
|
|
16
|
+
|
|
17
|
+
/** Goal reads the subscribed observation, never a periodic full-state RPC. */
|
|
18
|
+
export async function backgroundGoalObservation(pi: ExtensionAPI, ctx: ExtensionContext, cachedOnly = false): Promise<any> {
|
|
19
|
+
const scope = { background: true, cwd: ctx.cwd, sessionId: ctx.sessionManager?.getSessionId(), processId: process.pid };
|
|
20
|
+
const key = JSON.stringify(scope);
|
|
21
|
+
if (cachedOnly) {
|
|
22
|
+
const client = subscribedClients.get(pi);
|
|
23
|
+
return client && !client.closed && activityScopes.get(client) === key ? client.snapshot : undefined;
|
|
24
|
+
}
|
|
25
|
+
const client = await observationClient(pi, scope);
|
|
26
|
+
if (activityScopes.get(client) !== key) {
|
|
27
|
+
await client.subscribe(scope);
|
|
28
|
+
activityScopes.set(client, key);
|
|
29
|
+
}
|
|
30
|
+
return client.snapshot;
|
|
31
|
+
}
|
|
11
32
|
export function onBackgroundObservation(pi: ExtensionAPI, notify: () => void): () => void {
|
|
12
33
|
let set = listeners.get(pi);
|
|
13
34
|
if (!set) { set = new Set(); listeners.set(pi, set); }
|
|
14
35
|
set.add(notify); return () => { set.delete(notify); };
|
|
15
36
|
}
|
|
16
37
|
|
|
38
|
+
export function backgroundListNeedsHistory(params: Record<string, unknown>): boolean {
|
|
39
|
+
return params.all === true || params.limit !== undefined || params.status !== undefined
|
|
40
|
+
|| typeof params.cursor === "string" && cursorKind(params.cursor) !== "s";
|
|
41
|
+
}
|
|
42
|
+
|
|
17
43
|
/** A query connection grants no supervisor, transcript writer or retention authority. */
|
|
18
|
-
export function backgroundObservation(pi: ExtensionAPI, ctx: ExtensionContext, history = false, all = false, page?: { limit?: number; statuses?: string[]; cursor?: string }): Promise<any> {
|
|
44
|
+
export function backgroundObservation(pi: ExtensionAPI, ctx: ExtensionContext, history = false, all = false, page?: { limit?: number; statuses?: string[]; cursor?: string }, wait?: { timeoutMs: number; signal?: AbortSignal }): Promise<any> {
|
|
19
45
|
const scope = { background: true, cwd: ctx.cwd, sessionId: ctx.sessionManager?.getSessionId(), processId: process.pid };
|
|
20
46
|
const generation = generations.get(pi) ?? 0;
|
|
21
47
|
const read = async (retry: boolean): Promise<any> => {
|
|
@@ -24,12 +50,13 @@ export function backgroundObservation(pi: ExtensionAPI, ctx: ExtensionContext, h
|
|
|
24
50
|
const client = await connection;
|
|
25
51
|
if ((generations.get(pi) ?? 0) !== generation) throw new Error("runtime-unavailable: client closed");
|
|
26
52
|
try {
|
|
27
|
-
const deadline = Date.now() + 20000;
|
|
53
|
+
const deadline = Date.now() + (wait?.timeoutMs ?? 20000);
|
|
28
54
|
for (;;) {
|
|
55
|
+
wait?.signal?.throwIfAborted();
|
|
29
56
|
checkGeneration();
|
|
30
57
|
const snapshot = await client.get({ ...scope, backgroundHistory: history, backgroundAll: all, ...page });
|
|
31
58
|
if (!history || snapshot.status !== "rebuilding" || Date.now() >= deadline) return snapshot;
|
|
32
|
-
await delay(20);
|
|
59
|
+
await delay(wait ? 100 : 20, undefined, { signal: wait?.signal });
|
|
33
60
|
}
|
|
34
61
|
}
|
|
35
62
|
catch (error) {
|
|
@@ -49,6 +76,8 @@ function observationClient(pi: ExtensionAPI, scope: { background: boolean; cwd:
|
|
|
49
76
|
};
|
|
50
77
|
let pending = clients.get(pi);
|
|
51
78
|
if (!pending) {
|
|
79
|
+
const controller = new AbortController();
|
|
80
|
+
connectionAborts.set(pi, controller);
|
|
52
81
|
pending = (async () => {
|
|
53
82
|
let hosted: any;
|
|
54
83
|
let rejected: unknown;
|
|
@@ -59,50 +88,46 @@ function observationClient(pi: ExtensionAPI, scope: { background: boolean; cwd:
|
|
|
59
88
|
if (hosted) {
|
|
60
89
|
hostedClients.add(hosted);
|
|
61
90
|
hosted.onChange(() => { for (const notify of listeners.get(pi) ?? []) notify(); });
|
|
62
|
-
try { await hosted.subscribe(scope); checkOpen(); return hosted; }
|
|
91
|
+
try { await hosted.subscribe(scope); activityScopes.set(hosted, JSON.stringify({ ...scope, processId: process.pid })); checkOpen(); subscribedClients.set(pi, hosted); return hosted; }
|
|
63
92
|
catch (error) { hosted.close(); throw error; }
|
|
64
93
|
}
|
|
65
94
|
const requestedRoot = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
|
|
66
95
|
mkdirSync(requestedRoot, { recursive: true, mode: 0o700 });
|
|
67
96
|
const root = realpathSync(requestedRoot);
|
|
68
|
-
const ensure = async () => {
|
|
69
|
-
checkOpen();
|
|
97
|
+
const ensure = async (timeoutMs?: number, signal?: AbortSignal) => {
|
|
70
98
|
const installer = new URL("../runtime-client/src/runtime/client.mjs", import.meta.url).href;
|
|
71
99
|
const { ensureRuntime } = await import(installer);
|
|
72
|
-
|
|
73
|
-
await ensureRuntime({ agentDir: root, serverDir: process.env.PI_SERVER_DIR });
|
|
100
|
+
await ensureRuntime({ agentDir: root, serverDir: process.env.PI_SERVER_DIR, timeoutMs, signal });
|
|
74
101
|
};
|
|
75
102
|
let registration;
|
|
76
103
|
try { registration = JSON.parse(readFileSync(join(root, "server-registration-v1.json"), "utf8")); }
|
|
77
104
|
catch (error) {
|
|
78
105
|
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
79
|
-
await ensure();
|
|
106
|
+
await ensure(undefined, controller.signal);
|
|
80
107
|
registration = JSON.parse(readFileSync(join(root, "server-registration-v1.json"), "utf8"));
|
|
81
108
|
}
|
|
82
109
|
if (registration.version !== 1 || registration.agentDir !== root) throw new Error("Invalid canonical runtime registration");
|
|
83
110
|
const module = new URL("./shared-work-client.mjs", import.meta.url).href;
|
|
84
|
-
const {
|
|
111
|
+
const { connectWorkClient } = await import(module);
|
|
85
112
|
const connect = async () => {
|
|
86
113
|
checkOpen();
|
|
87
|
-
const client =
|
|
114
|
+
const client = await connectWorkClient(join(registration.serverDir, "pi-server.sock"), root, ["runtime-background-state-v1"], {
|
|
115
|
+
signal: controller.signal, recover: ({ timeoutMs, signal }: { timeoutMs: number; signal: AbortSignal }) => ensure(timeoutMs, signal),
|
|
116
|
+
});
|
|
88
117
|
let subscribed = false;
|
|
89
118
|
client.onChange(() => {
|
|
90
119
|
if (!subscribed || clients.get(pi) !== pending) return;
|
|
91
120
|
if (client.closed) clients.delete(pi);
|
|
92
121
|
for (const notify of listeners.get(pi) ?? []) notify();
|
|
93
122
|
});
|
|
94
|
-
try { await client.subscribe(scope); }
|
|
123
|
+
try { checkOpen(); await client.subscribe(scope); checkOpen(); }
|
|
95
124
|
catch (error) { client.close(); throw error; }
|
|
125
|
+
subscribedClients.set(pi, client);
|
|
96
126
|
subscribed = true;
|
|
127
|
+
activityScopes.set(client, JSON.stringify({ ...scope, processId: process.pid }));
|
|
97
128
|
return client;
|
|
98
129
|
};
|
|
99
|
-
|
|
100
|
-
catch (error) {
|
|
101
|
-
if (!["ENOENT", "ECONNREFUSED"].includes((error as NodeJS.ErrnoException).code ?? "")) throw error;
|
|
102
|
-
// Registration chooses transport; only the owner-safe installer may recover it.
|
|
103
|
-
await ensure();
|
|
104
|
-
return connect();
|
|
105
|
-
}
|
|
130
|
+
return connect();
|
|
106
131
|
})();
|
|
107
132
|
clients.set(pi, pending);
|
|
108
133
|
pending.catch(() => { if (clients.get(pi) === pending) clients.delete(pi); });
|
|
@@ -111,7 +136,9 @@ function observationClient(pi: ExtensionAPI, scope: { background: boolean; cwd:
|
|
|
111
136
|
}
|
|
112
137
|
|
|
113
138
|
export function closeBackgroundObservation(pi: ExtensionAPI): void {
|
|
139
|
+
subscribedClients.delete(pi);
|
|
114
140
|
generations.set(pi, (generations.get(pi) ?? 0) + 1);
|
|
141
|
+
connectionAborts.get(pi)?.abort(); connectionAborts.delete(pi);
|
|
115
142
|
const pending = clients.get(pi); clients.delete(pi);
|
|
116
143
|
void pending?.then(client => client.close(), () => {});
|
|
117
144
|
}
|