pi-better-background-tasks 0.14.2 → 0.14.4

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/src/runtime.ts CHANGED
@@ -10,7 +10,7 @@ import type { RemoteRunner, ResolvedSshRemoteTask } from "./remote-task-preset.j
10
10
  import { ensureTaskDir, logPathFor, nextTaskId, readMeta, sandboxProfilePathFor, writeMeta } from "./registry.js";
11
11
  import { assertBackgroundExecutionAllowed, backgroundExecutionLimits, confineCommandSpec, isCommandTimeoutSeconds, resolveForegroundSandboxPlan, sandboxProvenance } from "./sandbox.js";
12
12
  import { takeRecoverySnapshot } from "./shared-sandbox-core.js";
13
- import { failurePath, readTaskIntent, recordExitFailure, recordFailure, recoverDeclaredOperation, recoverFailure, resumeFailureAttention, scheduleFailureAttention, stopFailureAttention, suspendFailureAttention, terminalFailureAttention } from "./failures.js";
13
+ import { failurePath, readTaskIntent, recordExitFailure, recordFailure, recoverDeclaredOperation, recoverFailure, createFailureAttention, defaultAttention, terminalFailureAttention } from "./failures.js";
14
14
  import { markFailureAttentionDelivered } from "./shared-failure-observations.js";
15
15
  import { getCallbackBatcher } from "./shared-callback-batcher.js";
16
16
  import { formatCallbackFacts } from "./output.js";
@@ -29,6 +29,89 @@ import type {
29
29
  import { observeTaskStallAttention } from "./stall-attention.js";
30
30
  import { isTerminalStatus } from "./types.js";
31
31
 
32
+ export type ActiveSessionProvider = () => BackgroundTaskCallbackOrigin | undefined;
33
+
34
+ /** Structured intent (#325), declared by the launching agent and shared by spawns and watchers. */
35
+ export interface TaskIntentParams {
36
+ /** Stable id shared by modified retries of one operation. */
37
+ operation_id?: string | null;
38
+ /** Non-zero exit codes declared intentional before launch. */
39
+ expected_exit_codes?: number[] | null;
40
+ }
41
+
42
+ export interface SpawnTaskParams extends CommandSpec, TaskIntentParams {
43
+ name?: string;
44
+ /**
45
+ * Batch identity assigned by the batch launcher, never declared by a caller.
46
+ * Absent for a single spawn; carried into the persisted metadata so batch
47
+ * membership survives a reload instead of living only in the launch result.
48
+ */
49
+ batchId?: string;
50
+ /** Batch label from the same launch, when the operator gave one. */
51
+ batchName?: string;
52
+ callback?: boolean;
53
+ timeout_seconds?: number;
54
+ max_log_bytes?: number;
55
+ /**
56
+ * Opt-in step gate (#619): run the command under bash errexit, so the first
57
+ * unhandled failing step ends the task with that step's exit code and a later
58
+ * command cannot mask it.
59
+ */
60
+ require_successful_steps?: boolean;
61
+ ssh?: SshConnectionParams;
62
+ remote?: RemoteTaskParams;
63
+ }
64
+
65
+ export interface WatchTaskParams extends CommandSpec, TaskIntentParams {
66
+ name?: string;
67
+ callback?: boolean;
68
+ interval_seconds?: number;
69
+ timeout_seconds?: number;
70
+ max_log_bytes?: number;
71
+ success_when: Condition;
72
+ failure_when?: Condition;
73
+ /**
74
+ * Rejected (#619): a watch check is one polled command whose own exit code is the
75
+ * outcome, so the step gate cannot apply. Accepted in the shared schema only where
76
+ * the same wrapper also spawns.
77
+ */
78
+ require_successful_steps?: boolean;
79
+ /** Consecutive blind checks before the watch is flagged (#359). Default 3; 0 turns it off. */
80
+ blind_checks?: number;
81
+ ssh?: SshConnectionParams;
82
+ remote?: RemoteTaskParams;
83
+ }
84
+
85
+ type WatchPollRunner = (timeoutMs?: number) => Promise<CommandResult>;
86
+
87
+ export interface TaskRuntimeDependencies {
88
+ remoteRunner?: RemoteRunner;
89
+ /**
90
+ * Embedding/test seam for a local watch's poll command. Production polls run
91
+ * the persisted command through `runCommandOnce`; a remote watch keeps using
92
+ * its SSH runner instead.
93
+ */
94
+ watchPollRunner?: WatchPollRunner;
95
+ }
96
+
97
+ export const DEFAULT_WATCH_TIMEOUT_SECONDS = 15 * 60;
98
+ /** Consecutive blind checks (exit 0, stderr, no condition matched) before a watch is flagged (#359). */
99
+ export const DEFAULT_BLIND_CHECKS = 3;
100
+ /** How long bg_task_watch waits for the first check before returning (#359). */
101
+ export const FIRST_WATCH_CHECK_WAIT_MS = 15_000;
102
+ /** How to fix a false alarm: some tools write progress or warnings to stderr on success. */
103
+ export const BLIND_CHECK_HINT = "If the stderr is expected (progress or warnings), redirect it (2>/dev/null) or set blind_checks:0.";
104
+ /**
105
+ * Why the launch stopped waiting before the first check finished (#359): the bounded wait
106
+ * ran out, the tool call was aborted (Esc), or the session shut down.
107
+ */
108
+ export type FirstCheckWaitEnd = "timeout" | "aborted" | "suspended";
109
+ /** A first check's outcome, or why it is not known yet; undefined when the watch ended without one. */
110
+ export type FirstCheckOutcome = FirstWatchCheck | { pending: FirstCheckWaitEnd; waitedMs: number } | undefined;
111
+
112
+ /** Each cached extension factory owns its scheduling and suspension state. */
113
+ export function createBackgroundTaskRuntime(attention = createFailureAttention()) {
114
+ const { resumeFailureAttention, scheduleFailureAttention, stopFailureAttention, suspendFailureAttention } = attention;
32
115
  const watcherTimers = new Map<string, ReturnType<typeof setTimeout>>();
33
116
  const remoteSessionTimers = new Map<string, ReturnType<typeof setTimeout>>();
34
117
  const processTimeoutTimers = new Map<string, ReturnType<typeof setTimeout>>();
@@ -49,22 +132,7 @@ const HANDOFF_LOST_GRACE_MS = 5_000;
49
132
  let scheduledWorkSuspended = false;
50
133
  const REMOTE_SESSION_POLL_MS = 100;
51
134
 
52
- export const DEFAULT_WATCH_TIMEOUT_SECONDS = 15 * 60;
53
- /** Consecutive blind checks (exit 0, stderr, no condition matched) before a watch is flagged (#359). */
54
- export const DEFAULT_BLIND_CHECKS = 3;
55
- /** How long bg_task_watch waits for the first check before returning (#359). */
56
- export const FIRST_WATCH_CHECK_WAIT_MS = 15_000;
57
135
  const BLIND_OPERATION = "watch-blind";
58
- /** How to fix a false alarm: some tools write progress or warnings to stderr on success. */
59
- export const BLIND_CHECK_HINT = "If the stderr is expected (progress or warnings), redirect it (2>/dev/null) or set blind_checks:0.";
60
-
61
- /**
62
- * Why the launch stopped waiting before the first check finished (#359): the bounded wait
63
- * ran out, the tool call was aborted (Esc), or the session shut down.
64
- */
65
- export type FirstCheckWaitEnd = "timeout" | "aborted" | "suspended";
66
- /** A first check's outcome, or why it is not known yet; undefined when the watch ended without one. */
67
- export type FirstCheckOutcome = FirstWatchCheck | { pending: FirstCheckWaitEnd; waitedMs: number } | undefined;
68
136
 
69
137
  /** In-flight first checks of watches launched by this instance, keyed by task id. */
70
138
  const firstCheckWaiters = new Map<string, { promise: Promise<FirstWatchCheck | "suspended" | undefined>; resolve: (check: FirstWatchCheck | "suspended" | undefined) => void }>();
@@ -74,7 +142,7 @@ const firstCheckWaiters = new Map<string, { promise: Promise<FirstWatchCheck | "
74
142
  * outcome when the wait ends first, and undefined when this instance did not launch the watch
75
143
  * or the watch ended without a check.
76
144
  */
77
- export async function awaitFirstWatchCheck(id: string, timeoutMs = FIRST_WATCH_CHECK_WAIT_MS, signal?: AbortSignal): Promise<FirstCheckOutcome> {
145
+ async function awaitFirstWatchCheck(id: string, timeoutMs = FIRST_WATCH_CHECK_WAIT_MS, signal?: AbortSignal): Promise<FirstCheckOutcome> {
78
146
  const waiter = firstCheckWaiters.get(id);
79
147
  if (!waiter) return undefined;
80
148
  const started = Date.now();
@@ -132,7 +200,7 @@ function settleFirstCheck(id: string, check: FirstWatchCheck | "suspended" | und
132
200
  * is recorded as terminal and its callback is delivered when its session resumes;
133
201
  * after Pi quits, a resumed task whose process is gone is marked lost instead.
134
202
  */
135
- export function suspendScheduledWork(): void {
203
+ function suspendScheduledWork(): void {
136
204
  scheduledWorkSuspended = true;
137
205
  for (const timer of watcherTimers.values()) clearTimeout(timer);
138
206
  for (const timer of remoteSessionTimers.values()) clearTimeout(timer);
@@ -150,76 +218,12 @@ export function suspendScheduledWork(): void {
150
218
  }
151
219
 
152
220
  /** Allow scheduling again; called at session_start before running tasks are resumed. */
153
- export function resumeScheduledWork(): void {
221
+ function resumeScheduledWork(): void {
154
222
  scheduledWorkSuspended = false;
155
223
  resumeFailureAttention();
156
224
  }
157
225
 
158
226
 
159
-
160
- export type ActiveSessionProvider = () => BackgroundTaskCallbackOrigin | undefined;
161
-
162
- /** Structured intent (#325), declared by the launching agent and shared by spawns and watchers. */
163
- export interface TaskIntentParams {
164
- /** Stable id shared by modified retries of one operation. */
165
- operation_id?: string | null;
166
- /** Non-zero exit codes declared intentional before launch. */
167
- expected_exit_codes?: number[] | null;
168
- }
169
-
170
- export interface SpawnTaskParams extends CommandSpec, TaskIntentParams {
171
- name?: string;
172
- /**
173
- * Batch identity assigned by the batch launcher, never declared by a caller.
174
- * Absent for a single spawn; carried into the persisted metadata so batch
175
- * membership survives a reload instead of living only in the launch result.
176
- */
177
- batchId?: string;
178
- /** Batch label from the same launch, when the operator gave one. */
179
- batchName?: string;
180
- callback?: boolean;
181
- timeout_seconds?: number;
182
- max_log_bytes?: number;
183
- /**
184
- * Opt-in step gate (#619): run the command under bash errexit, so the first
185
- * unhandled failing step ends the task with that step's exit code and a later
186
- * command cannot mask it.
187
- */
188
- require_successful_steps?: boolean;
189
- ssh?: SshConnectionParams;
190
- remote?: RemoteTaskParams;
191
- }
192
-
193
- export interface WatchTaskParams extends CommandSpec, TaskIntentParams {
194
- name?: string;
195
- callback?: boolean;
196
- interval_seconds?: number;
197
- timeout_seconds?: number;
198
- max_log_bytes?: number;
199
- success_when: Condition;
200
- failure_when?: Condition;
201
- /**
202
- * Rejected (#619): a watch check is one polled command whose own exit code is the
203
- * outcome, so the step gate cannot apply. Accepted in the shared schema only where
204
- * the same wrapper also spawns.
205
- */
206
- require_successful_steps?: boolean;
207
- /** Consecutive blind checks before the watch is flagged (#359). Default 3; 0 turns it off. */
208
- blind_checks?: number;
209
- ssh?: SshConnectionParams;
210
- remote?: RemoteTaskParams;
211
- }
212
-
213
- export interface TaskRuntimeDependencies {
214
- remoteRunner?: RemoteRunner;
215
- /**
216
- * Embedding/test seam for a local watch's poll command. Production polls run
217
- * the persisted command through `runCommandOnce`; a remote watch keeps using
218
- * its SSH runner instead.
219
- */
220
- watchPollRunner?: WatchPollRunner;
221
- }
222
-
223
227
  /**
224
228
  * Persist the launch-time per-command cap with the task metadata. Reload and
225
229
  * resume go through `readMeta`, so the value travels as ordinary JSON and the
@@ -286,9 +290,7 @@ function invalidPersistedCommandCap(meta: BackgroundTaskMeta): string | undefine
286
290
  return `Persisted command time limit ${JSON.stringify(meta.commandTimeoutSeconds)} is invalid; the task was not resumed with an unlimited command.`;
287
291
  }
288
292
 
289
- type WatchPollRunner = (timeoutMs?: number) => Promise<CommandResult>;
290
-
291
- export function spawnTask(
293
+ function spawnTask(
292
294
  pi: ExtensionAPI,
293
295
  params: SpawnTaskParams,
294
296
  defaultCwd: string,
@@ -601,7 +603,7 @@ function failRemoteTask(
601
603
  finalize(meta, { status: "failed", reason }, pi, getActiveSession);
602
604
  }
603
605
 
604
- export function startWatchTask(
606
+ function startWatchTask(
605
607
  pi: ExtensionAPI,
606
608
  params: WatchTaskParams,
607
609
  defaultCwd: string,
@@ -698,7 +700,7 @@ function resolveWatchTimeoutSeconds(timeoutSeconds: number | undefined): number
698
700
  return timeoutSeconds;
699
701
  }
700
702
 
701
- export function resumeRunningTask(
703
+ function resumeRunningTask(
702
704
  pi: ExtensionAPI,
703
705
  meta: BackgroundTaskMeta,
704
706
  getActiveSession?: ActiveSessionProvider,
@@ -859,7 +861,7 @@ function resolvePersistedRemoteTask(
859
861
  }, remoteRunner);
860
862
  }
861
863
 
862
- export async function stopTask(
864
+ async function stopTask(
863
865
  pi: ExtensionAPI,
864
866
  id: string,
865
867
  getActiveSession?: ActiveSessionProvider,
@@ -1608,3 +1610,11 @@ function observeWatchOutcome(meta: BackgroundTaskMeta, result: CommandResult): v
1608
1610
  }
1609
1611
  if (prior !== fingerprint) meta.lastProgressAt = meta.lastCheckedAt ?? Date.now();
1610
1612
  }
1613
+
1614
+ return { awaitFirstWatchCheck, suspendScheduledWork, resumeScheduledWork, spawnTask, startWatchTask, resumeRunningTask, stopTask };
1615
+ }
1616
+
1617
+ export type BackgroundTaskRuntime = ReturnType<typeof createBackgroundTaskRuntime>;
1618
+ const defaultRuntime = createBackgroundTaskRuntime(defaultAttention);
1619
+ /** Compatibility for callers using the original singleton API. */
1620
+ export const { awaitFirstWatchCheck, suspendScheduledWork, resumeScheduledWork, spawnTask, startWatchTask, resumeRunningTask, stopTask } = defaultRuntime;
@@ -82,8 +82,10 @@ type HostDeps = {
82
82
 
83
83
  type NavigatorState = {
84
84
  providers: Map<string, BackgroundWorkProvider>;
85
+ registrationTokens?: Map<string, symbol>;
85
86
  unsubscribers: Map<string, () => void>;
86
87
  uiCtx?: ExtensionContext;
88
+ uiOwner?: symbol;
87
89
  deps?: HostDeps;
88
90
  lastHint?: string | null;
89
91
  lastMainListLines?: string[];
@@ -137,6 +139,8 @@ function state(): NavigatorState {
137
139
 
138
140
  export function registerBackgroundWorkProvider(provider: BackgroundWorkProvider): () => void {
139
141
  const s = state();
142
+ const token = Symbol(provider.id);
143
+ (s.registrationTokens ??= new Map()).set(provider.id, token);
140
144
  const previousUnsub = s.unsubscribers.get(provider.id);
141
145
  if (previousUnsub) {
142
146
  try { previousUnsub(); } catch { /* ignore */ }
@@ -152,7 +156,10 @@ export function registerBackgroundWorkProvider(provider: BackgroundWorkProvider)
152
156
  s.unsubscribers.delete(provider.id);
153
157
  }
154
158
  refreshBackgroundWorkNavigator();
155
- return () => unregisterBackgroundWorkProvider(provider.id);
159
+ // A stale factory must not unregister its replacement from another cached module.
160
+ return () => {
161
+ if (state().registrationTokens?.get(provider.id) === token) unregisterBackgroundWorkProvider(provider.id);
162
+ };
156
163
  }
157
164
 
158
165
  export function unregisterBackgroundWorkProvider(id: string): void {
@@ -163,6 +170,7 @@ export function unregisterBackgroundWorkProvider(id: string): void {
163
170
  }
164
171
  s.unsubscribers.delete(id);
165
172
  s.providers.delete(id);
173
+ s.registrationTokens?.delete(id);
166
174
  refreshBackgroundWorkNavigator();
167
175
  }
168
176
 
@@ -188,10 +196,11 @@ export function applyCloseConfirmFooter(ui: { setStatus(key: string, value: stri
188
196
  return hint ?? null;
189
197
  }
190
198
 
191
- export function ensureBackgroundWorkNavigator(ctx: ExtensionContext, deps: HostDeps): void {
199
+ export function ensureBackgroundWorkNavigator(ctx: ExtensionContext, deps: HostDeps, owner?: symbol): void {
192
200
  if (!isNavigatorUiAvailable(ctx)) return;
193
201
  const s = state();
194
202
  s.uiCtx = ctx;
203
+ s.uiOwner = owner;
195
204
  s.deps = {
196
205
  ...deps,
197
206
  createTranscriptComponent: deps.createTranscriptComponent ?? s.deps?.createTranscriptComponent,
@@ -207,14 +216,26 @@ export function ensureBackgroundWorkNavigator(ctx: ExtensionContext, deps: HostD
207
216
  refreshMainListWidget();
208
217
  }
209
218
 
210
- export function disposeBackgroundWorkNavigator(ctx?: ExtensionContext): void {
219
+ export function disposeBackgroundWorkNavigator(ctx?: ExtensionContext, owner?: symbol): void {
211
220
  const s = state();
221
+ if (owner !== undefined) {
222
+ // Only the factory that installed the current navigator may dispose it.
223
+ if (s.uiOwner !== owner) return;
224
+ } else if (s.uiOwner !== undefined) {
225
+ // Ownership is never inferred: an omitted owner must not clear a navigator
226
+ // another cached factory (or a headless child) owns.
227
+ return;
228
+ } else if (ctx !== undefined) {
229
+ // Unowned navigators stay releasable by a live, matching UI context.
230
+ if (!isNavigatorUiAvailable(ctx) || (s.uiCtx && ctx.ui !== s.uiCtx.ui)) return;
231
+ }
212
232
  try { s.dispose?.(); } catch { /* ignore */ }
213
233
  s.dispose = undefined;
214
234
  s.overlay = undefined;
215
235
  stopMainListWidget();
216
236
  const activeCtx = ctx ?? s.uiCtx;
217
237
  s.uiCtx = undefined;
238
+ s.uiOwner = undefined;
218
239
  if (activeCtx && isNavigatorUiAvailable(activeCtx)) {
219
240
  try { setNavigatorPanel(activeCtx, MAIN_LIST_WIDGET_KEY, undefined); } catch { /* ignore */ }
220
241
  }
@@ -342,6 +342,11 @@ export function listOperations(
342
342
  ): OperationRecord[] {
343
343
  const clauses: string[] = [];
344
344
  const params: Array<string | number> = [];
345
+ if (filter.ownerScope) {
346
+ const owner = normalizeOwner("ownerScope", filter.ownerScope);
347
+ clauses.push("owner_kind = ? AND owner_session_id = ? AND owner_workspace = ?");
348
+ params.push(owner.kind, owner.sessionId, owner.workspace);
349
+ }
345
350
  if (filter.owner) {
346
351
  const owner = normalizeOwner("owner", filter.owner);
347
352
  clauses.push(
@@ -204,6 +204,8 @@ export interface RecordTerminalOutcomeResult {
204
204
  /** Filter for `listOperations`. */
205
205
  export interface OperationFilter {
206
206
  owner?: OwnerIdentity;
207
+ /** Session/workspace scope spanning all branches and goals. */
208
+ ownerScope?: Pick<OwnerIdentity, "kind" | "sessionId" | "workspace">;
207
209
  phase?: OperationPhase;
208
210
  taskId?: string;
209
211
  }
@@ -11,6 +11,7 @@
11
11
  * reference channels (`continuationNote`, `reason`, `summary`, `authorityRef`)
12
12
  * that a caller could otherwise use to persist a secret.
13
13
  */
14
+ import { isAbsolute } from "node:path";
14
15
  import { StoreError } from "./errors.ts";
15
16
  import type { EvidenceKind, OwnerIdentity, OwnerKind } from "./types.ts";
16
17
 
@@ -143,7 +144,8 @@ export function requirePath(field: string, value: unknown): string {
143
144
  /** Workspace binding: an absolute path that may contain spaces. */
144
145
  export function requireWorkspace(value: unknown): string {
145
146
  const workspace = assertPlainString("owner.workspace", value, TEXT_LIMITS.workspace).trim();
146
- if (!workspace.startsWith("/")) fail("owner.workspace", "must be an absolute path");
147
+ // Platform-aware: a Windows workspace is "C:\...", which never starts with "/".
148
+ if (!isAbsolute(workspace)) fail("owner.workspace", "must be an absolute path");
147
149
  return workspace;
148
150
  }
149
151
 
@@ -90,6 +90,7 @@ export interface SshMuxControllerOptions extends ResolvedSshCommand {
90
90
  runner: RemoteRunner;
91
91
  sessionScope: string;
92
92
  controlPathRoot?: string;
93
+ platform?: NodeJS.Platform;
93
94
  }
94
95
 
95
96
  export interface SshMuxStatus {
@@ -101,7 +102,6 @@ export interface SshMuxStatus {
101
102
  }
102
103
 
103
104
  export interface SshMuxEnsureResult extends SshMuxStatus {
104
- state: "up";
105
105
  reused: boolean;
106
106
  }
107
107
 
@@ -340,6 +340,35 @@ export function defaultSshControlPathRoot(): string {
340
340
  */
341
341
  export function createSshMuxController(options: SshMuxControllerOptions): SshMuxController {
342
342
  const sessionScope = requireValue(options.sessionScope, "ssh mux sessionScope is required").trim();
343
+ // Native Windows OpenSSH cannot provide a working ControlMaster socket.
344
+ if ((options.platform ?? process.platform) === "win32") {
345
+ const commandResult: CommandResult = {
346
+ exitCode: null, signal: null, stdout: "", stderr: "", startedAt: 0, endedAt: 0,
347
+ };
348
+ const disabled: SshMuxStatus = {
349
+ state: "down",
350
+ target: options.identity.target,
351
+ controlPath: "",
352
+ detail: "SSH multiplexing is disabled on Windows; commands use independent connections.",
353
+ commandResult,
354
+ };
355
+ const unsupportedForward = async (): Promise<SshMuxForwardResult> => {
356
+ throw new SshMuxError("SSH Unix socket forwarding is not supported on Windows without ControlMaster.", commandResult);
357
+ };
358
+ return {
359
+ controlPath: "",
360
+ forwardUnixSocket: unsupportedForward,
361
+ cancelUnixSocketForward: unsupportedForward,
362
+ status: async () => disabled,
363
+ ensure: async () => ({ ...disabled, reused: false }),
364
+ cleanup: async () => ({ ...disabled, state: "not_running" }),
365
+ withMux: (commandSpec) => muxCommandSpec(commandSpec, options.identity.target, [
366
+ "-o", "ControlMaster=no",
367
+ "-o", "ControlPersist=no",
368
+ "-o", "ControlPath=none",
369
+ ], true),
370
+ };
371
+ }
343
372
  const controlPathRoot = resolve(options.controlPathRoot ?? defaultSshControlPathRoot());
344
373
  const controlPath = join(controlPathRoot, `cm-${muxIdentityHash(options.identity, sessionScope)}`);
345
374
  if (Buffer.byteLength(controlPath) > MAX_SSH_CONTROL_PATH_BYTES) {
@@ -35,7 +35,7 @@
35
35
  import { createHash, randomBytes } from "node:crypto";
36
36
  import { createRequire } from "node:module";
37
37
  import { appendFileSync, closeSync, fsyncSync, linkSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeSync, } from "node:fs";
38
- import { dirname, isAbsolute, join, resolve } from "node:path";
38
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
39
39
  import { validateCondition } from "./conditions.mjs";
40
40
  import { SUPERVISOR_FENCE_WAIT_MS, SUPERVISOR_RECORD_VERSION, SUPERVISOR_TASK_ID_PATTERN, SUPERVISOR_TASK_ID_PREFIX, } from "./types.mjs";
41
41
  /** The task id is derived from the token, so one token can only ever name one execution. */
@@ -113,7 +113,9 @@ function fsyncDirectoryOf(path) {
113
113
  }
114
114
  }
115
115
  function tempPathFor(path) {
116
- return join(dirname(path), `.${path.split("/").at(-1)}.tmp-${process.pid}-${randomBytes(6).toString("hex")}`);
116
+ // `basename`, not `split("/")`: a Windows path has no `/`, so the whole path
117
+ // would become the temp file name.
118
+ return join(dirname(path), `.${basename(path)}.tmp-${process.pid}-${randomBytes(6).toString("hex")}`);
117
119
  }
118
120
  /** Write a durable temp file; the caller publishes it. */
119
121
  function writeDurableTemp(path, text) {
@@ -45,7 +45,7 @@ import {
45
45
  writeFileSync,
46
46
  writeSync,
47
47
  } from "node:fs";
48
- import { dirname, isAbsolute, join, resolve } from "node:path";
48
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
49
49
  import { validateCondition } from "../conditions.ts";
50
50
  import {
51
51
  SUPERVISOR_FENCE_WAIT_MS,
@@ -171,7 +171,9 @@ function fsyncDirectoryOf(path: string): void {
171
171
  }
172
172
 
173
173
  function tempPathFor(path: string): string {
174
- return join(dirname(path), `.${path.split("/").at(-1)}.tmp-${process.pid}-${randomBytes(6).toString("hex")}`);
174
+ // `basename`, not `split("/")`: a Windows path has no `/`, so the whole path
175
+ // would become the temp file name.
176
+ return join(dirname(path), `.${basename(path)}.tmp-${process.pid}-${randomBytes(6).toString("hex")}`);
175
177
  }
176
178
 
177
179
  /** Write a durable temp file; the caller publishes it. */
package/src/tools.ts CHANGED
@@ -25,7 +25,7 @@ import {
25
25
  type WaitView,
26
26
  } from "./observed-waits.js";
27
27
  import { inspectMeta, listMetasForOrigin, readMeta, writeMeta } from "./registry.js";
28
- import { awaitFirstWatchCheck, FIRST_WATCH_CHECK_WAIT_MS, resumeRunningTask, spawnTask, startWatchTask, stopTask, type WatchTaskParams } from "./runtime.js";
28
+ import { awaitFirstWatchCheck, FIRST_WATCH_CHECK_WAIT_MS, resumeRunningTask, spawnTask, startWatchTask, stopTask, type WatchTaskParams, type BackgroundTaskRuntime } from "./runtime.js";
29
29
  import { runTaskMaintenance } from "./maintenance.js";
30
30
  import { backgroundProcessDiagnosticsAccess, ForegroundSandboxBlockedError } from "./sandbox.js";
31
31
  import { inspectTaskProcess } from "./task-diagnostics.js";
@@ -34,6 +34,8 @@ import { isTerminalStatus } from "./types.js";
34
34
 
35
35
  export { formatLaunch } from "./output.js";
36
36
 
37
+ const defaultRuntime = { awaitFirstWatchCheck, resumeRunningTask, spawnTask, startWatchTask, stopTask };
38
+
37
39
  const JsonPathSchema = Type.String({
38
40
  pattern: "^\\$",
39
41
  description: "Root-prefixed JSON path, e.g. $.status, $.terminalFailure, or $.steps[0].status. Bare keys and wildcards are unsupported.",
@@ -292,7 +294,8 @@ const BACKGROUND_ORCHESTRATION_GUIDELINES = [
292
294
  "Do not treat launch as completion of the parent milestone; relevant background work must be terminal, inspected, and integrated before verification or completion.",
293
295
  ];
294
296
 
295
- export function registerTools(pi: ExtensionAPI): void {
297
+ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRuntime, keyof typeof defaultRuntime> = defaultRuntime, refreshNavigator = refreshBackgroundTasksNavigator): void {
298
+ const { resumeRunningTask, spawnTask } = runtime;
296
299
  let activeSession: BackgroundTaskCallbackOrigin | undefined;
297
300
  const getActiveSession = () => activeSession;
298
301
  const schemas = new Map<string, object>();
@@ -345,11 +348,11 @@ export function registerTools(pi: ExtensionAPI): void {
345
348
  activeSession = getCallbackOrigin(ctx);
346
349
  const durable = await durableLaunchText(pi, "process", params, ctx);
347
350
  if (durable !== undefined) {
348
- refreshBackgroundTasksNavigator(ctx);
351
+ refreshNavigator(ctx);
349
352
  return text(durable);
350
353
  }
351
354
  const launched = reportLaunch(() => spawnTask(pi, params, ctx.cwd, activeSession, getActiveSession));
352
- refreshBackgroundTasksNavigator(ctx);
355
+ refreshNavigator(ctx);
353
356
  return text(launched);
354
357
  },
355
358
  });
@@ -362,8 +365,8 @@ export function registerTools(pi: ExtensionAPI): void {
362
365
  parameters: BatchParams,
363
366
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
364
367
  activeSession = getCallbackOrigin(ctx);
365
- const launched = spawnTaskBatch(pi, params, ctx.cwd, activeSession, getActiveSession);
366
- refreshBackgroundTasksNavigator(ctx);
368
+ const launched = spawnTaskBatch(pi, params, ctx.cwd, activeSession, getActiveSession, {}, runtime);
369
+ refreshNavigator(ctx);
367
370
  return text(formatBatchLaunch(launched), launched);
368
371
  },
369
372
  });
@@ -378,11 +381,11 @@ export function registerTools(pi: ExtensionAPI): void {
378
381
  activeSession = getCallbackOrigin(ctx);
379
382
  const durable = await durableLaunchText(pi, "watch", params, ctx);
380
383
  if (durable !== undefined) {
381
- refreshBackgroundTasksNavigator(ctx);
384
+ refreshNavigator(ctx);
382
385
  return text(durable);
383
386
  }
384
- const launched = await launchWatch(pi, params, ctx.cwd, activeSession, getActiveSession, FIRST_WATCH_CHECK_WAIT_MS, signal);
385
- refreshBackgroundTasksNavigator(ctx);
387
+ const launched = await launchWatch(pi, params, ctx.cwd, activeSession, getActiveSession, FIRST_WATCH_CHECK_WAIT_MS, signal, runtime);
388
+ refreshNavigator(ctx);
386
389
  return text(launched);
387
390
  },
388
391
  });
@@ -436,11 +439,11 @@ export function registerTools(pi: ExtensionAPI): void {
436
439
  activeSession = getCallbackOrigin(ctx);
437
440
  const durable = await durableStopText(pi, params.id, ctx);
438
441
  if (durable !== undefined) {
439
- refreshBackgroundTasksNavigator(ctx);
442
+ refreshNavigator(ctx);
440
443
  return text(durable);
441
444
  }
442
- const result = await formatStop(pi, params.id, ctx, getActiveSession, statusOptions(params, activeSession));
443
- refreshBackgroundTasksNavigator(ctx);
445
+ const result = await formatStop(pi, params.id, ctx, getActiveSession, statusOptions(params, activeSession), runtime);
446
+ refreshNavigator(ctx);
444
447
  return text(result);
445
448
  },
446
449
  });
@@ -456,7 +459,7 @@ export function registerTools(pi: ExtensionAPI): void {
456
459
  },
457
460
  async execute(_toolCallId, params, signal, _onUpdate, ctx) {
458
461
  activeSession = getCallbackOrigin(ctx);
459
- return actionText(pi, params, ctx, activeSession, getActiveSession, signal);
462
+ return actionText(pi, params, ctx, activeSession, getActiveSession, signal, runtime, refreshNavigator);
460
463
  },
461
464
  });
462
465
 
@@ -470,7 +473,7 @@ export function registerTools(pi: ExtensionAPI): void {
470
473
  },
471
474
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
472
475
  activeSession = getCallbackOrigin(ctx);
473
- return actionText(pi, params, ctx, activeSession, getActiveSession);
476
+ return actionText(pi, params, ctx, activeSession, getActiveSession, undefined, runtime, refreshNavigator);
474
477
  },
475
478
  });
476
479
 
@@ -646,14 +649,16 @@ async function actionText(
646
649
  ctx: ExtensionContext,
647
650
  callbackOrigin: BackgroundTaskCallbackOrigin,
648
651
  getActiveSession: () => BackgroundTaskCallbackOrigin | undefined,
649
- signal?: AbortSignal,
652
+ signal: AbortSignal | undefined,
653
+ runtime: Pick<BackgroundTaskRuntime, keyof typeof defaultRuntime>,
654
+ refreshNavigator: typeof refreshBackgroundTasksNavigator,
650
655
  ) {
651
656
  if (params.action === "log" && params.id) {
652
657
  const durable = durableLogText(pi, String(params.id), params, ctx);
653
658
  if (durable !== undefined) return text(durable);
654
659
  return logText(String(params.id), logOptions(params, callbackOrigin));
655
660
  }
656
- return text(await runAction(pi, params, ctx, callbackOrigin, getActiveSession, signal));
661
+ return text(await runAction(pi, params, ctx, callbackOrigin, getActiveSession, signal, runtime, refreshNavigator));
657
662
  }
658
663
 
659
664
  async function runAction(
@@ -662,8 +667,12 @@ async function runAction(
662
667
  ctx: ExtensionContext,
663
668
  callbackOrigin: BackgroundTaskCallbackOrigin,
664
669
  getActiveSession: () => BackgroundTaskCallbackOrigin | undefined,
665
- signal?: AbortSignal,
670
+ signal: AbortSignal | undefined,
671
+ runtime: Pick<BackgroundTaskRuntime, keyof typeof defaultRuntime>,
672
+ refreshNavigator: typeof refreshBackgroundTasksNavigator,
666
673
  ): Promise<string> {
674
+ const { spawnTask } = runtime;
675
+ const withNavigatorRefresh = (ctx: ExtensionContext, result: string) => { refreshNavigator(ctx); return result; };
667
676
  switch (params.action) {
668
677
  case "spawn": {
669
678
  const durable = await durableLaunchText(pi, "process", params, ctx);
@@ -674,7 +683,7 @@ async function runAction(
674
683
  if (!params.success_when) return "Invalid parameters: watch requires success_when.";
675
684
  const durable = await durableLaunchText(pi, "watch", params, ctx);
676
685
  if (durable !== undefined) return withNavigatorRefresh(ctx, durable);
677
- return withNavigatorRefresh(ctx, await launchWatch(pi, params as unknown as WatchTaskParams, ctx.cwd, callbackOrigin, getActiveSession, FIRST_WATCH_CHECK_WAIT_MS, signal));
686
+ return withNavigatorRefresh(ctx, await launchWatch(pi, params as unknown as WatchTaskParams, ctx.cwd, callbackOrigin, getActiveSession, FIRST_WATCH_CHECK_WAIT_MS, signal, runtime));
678
687
  }
679
688
  case "list":
680
689
  return durableAwareList(pi, params, callbackOrigin);
@@ -694,7 +703,7 @@ async function runAction(
694
703
  if (!params.id) return "Invalid parameters: stop requires id.";
695
704
  const durable = await durableStopText(pi, String(params.id), ctx);
696
705
  if (durable !== undefined) return withNavigatorRefresh(ctx, durable);
697
- return withNavigatorRefresh(ctx, await formatStop(pi, String(params.id), ctx, getActiveSession, statusOptions(params, callbackOrigin)));
706
+ return withNavigatorRefresh(ctx, await formatStop(pi, String(params.id), ctx, getActiveSession, statusOptions(params, callbackOrigin), runtime));
698
707
  }
699
708
  case "clear": {
700
709
  const host = getObservedWaitHost(pi);
@@ -872,7 +881,9 @@ export async function launchWatch(
872
881
  getActiveSession: () => BackgroundTaskCallbackOrigin | undefined,
873
882
  waitMs = FIRST_WATCH_CHECK_WAIT_MS,
874
883
  signal?: AbortSignal,
884
+ runtime: Pick<BackgroundTaskRuntime, keyof typeof defaultRuntime> = defaultRuntime,
875
885
  ): Promise<string> {
886
+ const { startWatchTask, awaitFirstWatchCheck } = runtime;
876
887
  let meta: BackgroundTaskMeta;
877
888
  try {
878
889
  meta = startWatchTask(pi, params, cwd, callbackOrigin, getActiveSession);
@@ -887,11 +898,6 @@ export async function launchWatch(
887
898
  return formatLaunch(latest);
888
899
  }
889
900
 
890
- function withNavigatorRefresh(ctx: ExtensionContext, result: string): string {
891
- refreshBackgroundTasksNavigator(ctx);
892
- return result;
893
- }
894
-
895
901
  /** Origins whose session identity could not be read (the host threw). */
896
902
  const unavailableSessionOrigins = new WeakSet<BackgroundTaskCallbackOrigin>();
897
903
 
@@ -1023,7 +1029,9 @@ async function formatStop(
1023
1029
  _ctx: ExtensionContext,
1024
1030
  getActiveSession?: () => BackgroundTaskCallbackOrigin | undefined,
1025
1031
  options: OutputOptions = {},
1032
+ runtime: Pick<BackgroundTaskRuntime, "stopTask"> = defaultRuntime,
1026
1033
  ): Promise<string> {
1034
+ const { stopTask } = runtime;
1027
1035
  const existing = inspectMeta(id);
1028
1036
  if (!existing.meta && !existing.found) return formatStopResult(existing, options);
1029
1037
  if (!existing.meta) return formatMissingTask(existing, options);