pi-better-background-tasks 0.14.1 → 0.14.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-background-tasks",
3
- "version": "0.14.1",
3
+ "version": "0.14.2",
4
4
  "description": "Pi extension for durable background shell tasks, watchers, logs, and status inspection.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/index.ts CHANGED
@@ -8,7 +8,7 @@ import { createObservedWaitHost } from "./observed-waits.js";
8
8
  import { getCallbackBatcher } from "./shared-callback-batcher.js";
9
9
  import { observeForegroundSandboxPolicy } from "./sandbox.js";
10
10
  import { registerTools } from "./tools.js";
11
- import { appendExecutionPolicy } from "./shared-execution-policy.js";
11
+ import { deliverBackgroundTasksPrompt } from "./prompt.js";
12
12
 
13
13
  export default function backgroundTasksExtension(pi: ExtensionAPI): void {
14
14
  // Created before registerTools so the tools can resolve it lazily; the durable
@@ -36,7 +36,10 @@ export default function backgroundTasksExtension(pi: ExtensionAPI): void {
36
36
  },
37
37
  });
38
38
  initializeNavigatorPanels(pi);
39
- pi.on("before_agent_start", (event) => ({ systemPrompt: appendExecutionPolicy(event.systemPrompt) }));
39
+ // Sections on a host that renders them; text only where it renders none.
40
+ // Returning a prompt on modern pi would set forceSystemPrompt, and the request
41
+ // would then carry a snapshot, so sections published after it never arrive.
42
+ pi.on("before_agent_start", (event) => deliverBackgroundTasksPrompt(event));
40
43
  registerBackgroundTasksGoalProvider(pi);
41
44
  ensureBackgroundTasksNavigatorProvider(pi);
42
45
  // Subscribed at load so a sandbox extension that publishes later is heard, and
package/src/prompt.ts ADDED
@@ -0,0 +1,72 @@
1
+ /**
2
+ * The operational prompt this package owns: how to wait, and how to launch.
3
+ *
4
+ * Published as a named section so pi can diff it. It exists because the tool
5
+ * descriptions cannot carry it: a description explains one call, while the
6
+ * failure this prevents is choosing `sleep` over a watcher in the first place.
7
+ *
8
+ * Instructions only. No rationale, no worked examples, and no defaults that the
9
+ * tool schemas already state: the model has every schema in context, and repeated
10
+ * reference just spends prefix tokens on text it can already read.
11
+ */
12
+ export const BACKGROUND_TASKS_SECTION = "background_tasks";
13
+
14
+ import { EXECUTION_POLICY_TEXT, publishExecutionPolicy, supportsPromptSections } from "./shared-execution-policy.js";
15
+
16
+ /** `sections` is optional because the repo typechecks against older pi typings. */
17
+ export interface PromptSectionTarget {
18
+ sections?: Record<string, string>;
19
+ }
20
+
21
+ export const BACKGROUND_TASKS_PROMPT: string = [
22
+ "Background tasks: never wait in the foreground.",
23
+ "",
24
+ "- Never use foreground `sleep` to wait or poll, whether alone, before another command, or inside a loop. The sole permitted foreground sleep is at most 3 s immediately after `pkill`, `kill`, or `systemctl stop`, while the process exits.",
25
+ "- Use `bg_task_spawn` and `bg_task_watch` instead of `nohup`, `&`, or `disown`.",
26
+ "- Treat the wait, not the check, as the long part. Waiting for `gh pr checks` to pass is a `bg_task_watch`, not `sleep 300; gh pr checks`.",
27
+ "- Waiting on an external system (`gh run view`, `gh pr checks`, `mergify queue show`, a redeploy, a dev server, `cloud-init`): `bg_task_watch` with the check command and `success_when`. For a PR you just enqueued, `watch_delivery`.",
28
+ "- Waiting on your own long command (tests, build, migration): `bg_task_spawn`, then `wait_for_operations`. Do not sleep and re-read the log.",
29
+ "- Waiting for a server you just started: `bg_task_spawn` the server, then `bg_task_watch` on a readiness check (`curl -fsS ...`).",
30
+ "- Retry until a condition with one `bg_task_watch`, never `for i in ...; do ...; sleep N; done`.",
31
+ "- If a dependency is pending and no watcher is running, start `bg_task_watch`; do not loop short sleeps.",
32
+ "- Nothing here automatically diverts a foreground command. A sleep or monitor loop submitted through foreground `bash` blocks the turn.",
33
+ "- Omit `timeout_seconds` on `bg_task_spawn` unless you need a bound. Raise it on `bg_task_watch` for a wait longer than 15 minutes, and leave `callback` alone: do not poll.",
34
+ "- Write the check so a broken check is visible; do not end it with `exit 0` or `|| true`.",
35
+ "- Stop tasks you started for a turn-scoped purpose before finishing the turn.",
36
+ ].join("\n");
37
+
38
+ /** Publish the guidance into `options.sections`; assignment keeps it idempotent across turns. */
39
+ export function publishBackgroundTasksGuidance<T extends object>(options: T): T {
40
+ const target = options as PromptSectionTarget;
41
+ const sections = (target.sections ??= {});
42
+ sections[BACKGROUND_TASKS_SECTION] = BACKGROUND_TASKS_PROMPT;
43
+ return options;
44
+ }
45
+
46
+ /** What a handler receives; only these two fields are used. */
47
+ export interface BeforeAgentStartEvent {
48
+ systemPrompt: string;
49
+ systemPromptOptions?: unknown;
50
+ }
51
+
52
+ /**
53
+ * Deliver this package's guidance on both kinds of host.
54
+ *
55
+ * Modern pi renders custom sections, so publishing keeps the prompt structured
56
+ * and lets pi diff it. Older pi (the packages declare support back to 0.84.4)
57
+ * renders no sections at all, so publishing there would silently deliver nothing;
58
+ * returning the text is the behaviour those hosts already had.
59
+ */
60
+ export function deliverBackgroundTasksPrompt(event: BeforeAgentStartEvent): { systemPrompt: string } | undefined {
61
+ if (!supportsPromptSections(event.systemPromptOptions)) {
62
+ // Several packages carry the same policy, so appending blindly would print it
63
+ // once per publisher. The text path stays idempotent exactly as it used to be.
64
+ const policy = event.systemPrompt.includes(EXECUTION_POLICY_TEXT) ? "" : `${EXECUTION_POLICY_TEXT}\n\n`;
65
+ const guidance = event.systemPrompt.includes(BACKGROUND_TASKS_PROMPT) ? "" : BACKGROUND_TASKS_PROMPT;
66
+ return { systemPrompt: `${event.systemPrompt}\n\n${policy}${guidance}` };
67
+ }
68
+ const options = event.systemPromptOptions as { sections?: Record<string, string> };
69
+ publishExecutionPolicy(options);
70
+ publishBackgroundTasksGuidance(options);
71
+ return undefined;
72
+ }
@@ -1,21 +1,61 @@
1
1
  // Generated from packages/pi-better-harness/extensions/execution-policy.ts. Do not edit directly.
2
- /** Harness-wide scheduling guidance, vendored so standalone extensions share it. */
3
- const EXECUTION_POLICY = [
2
+ /**
3
+ * Harness-wide scheduling guidance, vendored so standalone extensions share it.
4
+ *
5
+ * Published as a named system-prompt section, never as appended text. A
6
+ * `before_agent_start` handler that returns `systemPrompt` sets
7
+ * `forceSystemPrompt`, and a forced prompt is opaque to pi: `buildSystemPromptState`
8
+ * returns `{ content }` with no sections while `diffSystemPromptSections` keeps
9
+ * diffing the sections the request therefore never shows. The request carries a
10
+ * rendered snapshot, so any section published after that snapshot never reaches
11
+ * it, so every package that speaks here publishes a section.
12
+ */
13
+ export const EXECUTION_POLICY_SECTION = "harness_execution_policy";
14
+
15
+ /**
16
+ * The minimum shape this module needs. `sections` stays optional because this
17
+ * repo typechecks against older pi typings whose event options predate sections;
18
+ * the shipped runtime always supplies the map.
19
+ */
20
+ export interface PromptSectionTarget {
21
+ sections?: Record<string, string>;
22
+ }
23
+
24
+ export const EXECUTION_POLICY_TEXT: string = [
4
25
  "Harness execution policy: concurrency is separate from subagent delegation.",
5
- "Before multi-unit work, identify ready, authorized, independent units, actual prerequisites, shared mutable resources, and capacity or availability constraints. Represent independently verifiable deliverables (such as each host migration) separately in the plan; do not hide them in one serial rollout step or create dependencies merely from list order.",
26
+ "Before multi-unit work, identify ready, authorized, independent units, actual prerequisites, shared mutable resources, and capacity or availability constraints. Represent each independently verifiable deliverable as its own plan step; do not create dependencies from list order.",
6
27
  "Start all ready, authorized, non-conflicting units concurrently within known resource limits before waiting for any one to finish. Reassess ready work after launches and results; continue unblocked foreground work instead of polling running tasks. Do not equate one background launch with scheduling all ready work.",
7
28
  "Serialize only for a concrete dependency, conflicting writes or ownership, resource or concurrency limit, documented rollout gate, or explicit availability requirement. Record the reason in the plan or explain it to the user. Do not invent a canary or host-by-host availability requirement.",
8
- "If concurrency raises an unresolved material operational trade-off (for example, draining all hosts could leave no available runners), ask the user once before the affected operations. Continue independent preparation meanwhile. Existing authorization, safety checks, workflow prerequisites, and human-approved rollout constraints remain binding; urgency does not waive them.",
9
- "Choose the execution mechanism after deciding what can run together: foreground tools for small, tightly coupled, or interactive work; subagents for bounded independent reasoning or implementation when the active delegation mode permits; background tasks for independent long-running commands or waits. Manual delegation forbids proactive subagents, not concurrent foreground tools or background commands. Use available batch or parallel tool interfaces where appropriate and inspect every launch receipt for failures or skipped work.",
10
- "Established command-only jobs and external waits belong to background operations, including in coordinator mode. Use bg_task_spawn for a long command and bg_task_watch for a repeated check; use watch_delivery for supported merge delivery so a stateful domain watcher observes the queue. A subagent assignment must require reasoning or implementation beyond launching and waiting. Workers retain their assigned validation: use supervised background tools and wait_for_operations to park, then resume the same conversation to interpret and acknowledge the terminal result. A linked external wait must have a registered observer and an execution owner. Continue independent work while it runs; a task launch or a completed parked attempt is not completion of the assignment.",
11
- "If a worker hands back a command, the coordinator launches it through background tools with the supplied cwd and inspects its terminal result before claiming verification. Workers may run focused implementation checks; moving a command to a worker does not make it a background task.",
29
+ "If concurrency raises an unresolved material operational trade-off, ask the user once before the affected operations and continue independent preparation meanwhile. Existing authorization, safety checks, workflow prerequisites, and human-approved rollout constraints remain binding; urgency does not waive them.",
30
+ "Choose the execution mechanism after deciding what can run together: foreground tools for small, tightly coupled, or interactive work; subagents for bounded independent reasoning or implementation when the active delegation mode permits; background tasks for independent long-running commands or waits. Manual delegation forbids proactive subagents, not concurrent foreground tools or background commands. Inspect every launch receipt for failures or skipped work.",
31
+ "Established command-only jobs and external waits belong to background operations, including in coordinator mode. Use bg_task_spawn for a long command, bg_task_watch for a repeated check, and watch_delivery for supported merge delivery. A subagent assignment must require reasoning or implementation beyond launching and waiting. Workers retain their assigned validation: launch or watch, continue independent work, then park with wait_for_operations and inspect the terminal evidence on continuation. Continue independent work while it runs; a task launch is not completion of the assignment.",
32
+ "If a worker hands back a command, launch it through bg_task_spawn or bg_task_watch with the supplied cwd, and inspect its terminal result before claiming verification.",
12
33
  "A unit waiting or failing does not block other ready independent units unless the evidence shows a shared blocker. Preserve each unit's guards and rollback boundary. Before completing verification, the plan, or the goal, inspect and integrate every relevant terminal result or failure; launch is not completion.",
13
34
  ].join("\n");
14
35
 
15
- export function appendExecutionPolicy(systemPrompt: string): string {
16
- // Inspect the prompt, not module-global state: vendored copies have separate
17
- // module identities, and every fresh turn or reload needs the policy again.
18
- return systemPrompt.includes(EXECUTION_POLICY)
19
- ? systemPrompt
20
- : `${systemPrompt}\n\n${EXECUTION_POLICY}`;
21
- }
36
+ /**
37
+ * True when this pi runtime renders custom prompt sections.
38
+ *
39
+ * pi gained `systemPromptOptions.sections` after 0.84.4, and the packages here
40
+ * declare support back to 0.84.4. A section-only publisher is a silent no-op on
41
+ * an older host: the handler runs, the map is populated, and the prompt the model
42
+ * receives is unchanged. Callers must fall back to appending text instead.
43
+ */
44
+ export function supportsPromptSections(options: unknown): boolean {
45
+ const sections = (options as { sections?: unknown } | undefined)?.sections;
46
+ return typeof sections === "object" && sections !== null;
47
+ }
48
+
49
+ /**
50
+ * Publish the policy into `options.sections`.
51
+ *
52
+ * Assignment, not concatenation: two packages publishing the same section write
53
+ * identical text, so load order cannot duplicate or drop it, and a repeated turn
54
+ * rewrites the same value so pi's section diff reports no change.
55
+ */
56
+ export function publishExecutionPolicy<T extends object>(options: T): T {
57
+ const target = options as PromptSectionTarget;
58
+ const sections = (target.sections ??= {});
59
+ sections[EXECUTION_POLICY_SECTION] = EXECUTION_POLICY_TEXT;
60
+ return options;
61
+ }