{"version":3,"file":"background-work.mjs","names":[],"sources":["../../src/pi-extensions/background-work.ts"],"sourcesContent":["/**\n * OpenTag background work Pi extension (trusted built artifact).\n *\n * Pi deliberately has no background shell, and a process started with `&` in its bash tool escapes to\n * its own process group, where nothing can see or stop it. This extension gives the model a tool whose\n * work OpenTag can follow, with the same experience as native Claude Code: the Run stays open while the\n * work is live, and the model is woken with the result when it ends.\n *\n * - The child stays in Pi's process group, so stopping the Run stops the child.\n * - The list goes to OpenTag over `setStatus`, Pi's fire-and-forget channel, as JSON under\n *   `BACKGROUND_WORK_STATUS_KEY`.\n * - Waking uses `sendMessage` with `triggerTurn`, which Pi turns into a new agent run when idle and a\n *   queued continuation when busy, so `agent_settled` never precedes it.\n *\n * This module is intentionally self-contained (Node builtins only, no package imports): it runs inside\n * the Pi process and must never resolve workspace dependencies.\n */\n\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport { closeSync, existsSync, fstatSync, mkdtempSync, openSync, readSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport const BACKGROUND_WORK_STATUS_KEY = \"opentag-background-work\";\nexport const BACKGROUND_WORK_TOOL = \"background_bash\";\nconst OUTPUT_TAIL_BYTES = 4_000;\n\nexport interface BackgroundWorkStatusItem {\n  readonly id: string;\n  readonly label: string;\n  readonly outputPath: string;\n}\n\nexport interface BackgroundWorkFinish {\n  readonly id: string;\n  readonly status: \"completed\" | \"failed\";\n  readonly detail: string;\n  readonly outputPath: string;\n}\n\nexport interface BackgroundWorkStatus {\n  readonly live: readonly BackgroundWorkStatusItem[];\n  readonly finished?: BackgroundWorkFinish;\n}\n\ninterface ExtensionContext {\n  readonly cwd: string;\n  readonly ui: { setStatus(key: string, text: string | undefined): void };\n}\n\ninterface ExtensionApi {\n  registerTool(tool: {\n    name: string;\n    label: string;\n    description: string;\n    promptSnippet: string;\n    promptGuidelines: string[];\n    parameters: Record<string, unknown>;\n    execute(\n      toolCallId: string,\n      params: { command: string; description?: string },\n      signal: AbortSignal | undefined,\n      onUpdate: unknown,\n      ctx: ExtensionContext,\n    ): Promise<{ content: { type: \"text\"; text: string }[]; details: Record<string, unknown> }>;\n  }): void;\n  on(event: \"session_shutdown\", handler: () => void): void;\n  sendMessage(\n    message: { customType: string; content: string; display: boolean },\n    options: { triggerTurn: boolean; deliverAs: \"followUp\" },\n  ): void;\n}\n\nexport default function backgroundWorkExtension(pi: ExtensionApi): void {\n  const live = new Map<string, { item: BackgroundWorkStatusItem; child: ChildProcess }>();\n  let outputDirectory: string | undefined;\n  // The whole process group gets the signal, so a child can end before Pi reports its shutdown. Work the\n  // Run is stopping must not wake the model; OpenTag reports it as stopped itself.\n  let stopping = false;\n  process.once(\"SIGTERM\", () => {\n    stopping = true;\n  });\n  const publish = (ctx: ExtensionContext, finished?: BackgroundWorkFinish) => {\n    const status: BackgroundWorkStatus = {\n      live: [...live.values()].map(({ item }) => item),\n      ...(finished ? { finished } : {}),\n    };\n    ctx.ui.setStatus(BACKGROUND_WORK_STATUS_KEY, JSON.stringify(status));\n  };\n\n  pi.on(\"session_shutdown\", () => {\n    stopping = true;\n    for (const { child } of live.values()) child.kill(\"SIGTERM\");\n  });\n\n  pi.registerTool({\n    name: BACKGROUND_WORK_TOOL,\n    label: \"Background\",\n    description:\n      \"Start a shell command in the background and return at once. The current Run stays open while it runs, you may end your turn, and you are told its exit code and output when it ends. It stops if the Run reaches its limit.\",\n    promptSnippet: \"Start a shell command in the background; you are told when it ends\",\n    promptGuidelines: [\n      \"Use background_bash for any command you do not want to wait for. Never background with bash using &, nohup or setsid: nothing would tell you when such a process ends, and it may stop without notice.\",\n    ],\n    parameters: {\n      type: \"object\",\n      properties: {\n        command: { type: \"string\", description: \"The shell command to run\" },\n        description: { type: \"string\", description: \"A few words naming the work\" },\n      },\n      required: [\"command\"],\n    },\n    async execute(toolCallId, params, _signal, _onUpdate, ctx) {\n      outputDirectory ??= mkdtempSync(join(tmpdir(), \"opentag-background-\"));\n      const outputPath = join(outputDirectory, `${toolCallId.replace(/[^A-Za-z0-9_-]/g, \"_\")}.log`);\n      const output = openSync(outputPath, \"a\");\n      // Not detached: the child must stay in Pi's process group, so that stopping the Run stops it.\n      const child = spawn(existsSync(\"/bin/bash\") ? \"/bin/bash\" : \"sh\", [\"-c\", params.command], {\n        cwd: ctx.cwd,\n        env: process.env,\n        stdio: [\"ignore\", output, output],\n      });\n      closeSync(output);\n      const item = { id: toolCallId, label: params.description || params.command, outputPath };\n      const finish = (status: BackgroundWorkFinish[\"status\"], detail: string) => {\n        if (stopping || !live.delete(toolCallId)) return;\n        publish(ctx, { id: toolCallId, status, detail, outputPath });\n        pi.sendMessage(\n          { customType: BACKGROUND_WORK_STATUS_KEY, content: finishNotice(item, detail), display: false },\n          { triggerTurn: true, deliverAs: \"followUp\" },\n        );\n      };\n      live.set(toolCallId, { item, child });\n      publish(ctx);\n      child.once(\"error\", (error) => finish(\"failed\", `could not start: ${error.message}`));\n      child.once(\"close\", (code, signal) =>\n        finish(code === 0 ? \"completed\" : \"failed\", signal ? `killed by ${signal}` : `exit code ${code}`),\n      );\n      return {\n        content: [\n          {\n            type: \"text\",\n            text: `Started in the background. Output goes to ${outputPath}. You will be told when it ends; you may end your turn.`,\n          },\n        ],\n        details: {},\n      };\n    },\n  });\n}\n\nfunction finishNotice(item: BackgroundWorkStatusItem, detail: string): string {\n  const tail = readTail(item.outputPath);\n  return [\n    `[openTag notice] A background command you started has finished: ${item.label} (${detail}). Full output: ${item.outputPath}`,\n    tail ? `Output (tail):\\n${tail}` : \"It produced no output.\",\n  ].join(\"\\n\");\n}\n\nfunction readTail(path: string): string {\n  const file = openSync(path, \"r\");\n  try {\n    const { size } = fstatSync(file);\n    const tail = Buffer.alloc(Math.min(size, OUTPUT_TAIL_BYTES));\n    readSync(file, tail, 0, tail.length, size - tail.length);\n    return tail.toString(\"utf8\");\n  } finally {\n    closeSync(file);\n  }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAuBA,MAAa,6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