{"version":3,"file":"index.cjs","names":[],"sources":["../../../../src/services/piToolBridge/index.ts"],"sourcesContent":["/**\n * Pure bridging logic between MCP tool results and the Pi tool surface.\n *\n * DESIGN PATTERNS:\n * - Adapter pattern: MCP `CallToolResult` is converted to Pi's result shape\n * - Pure module: no service or tool-class imports, so this is unit-testable\n *   without constructing the workflow execution stack\n *\n * CODING STANDARDS:\n * - Named exports only\n * - Explicit return types on exported functions\n *\n * AVOID:\n * - Importing tool classes or services here (that belongs in `piTools.ts`)\n * - Returning an error flag Pi does not read; Pi tools signal failure by throwing\n */\n\nimport type { WorkflowProgressJob, WorkflowRunRecord } from '@agimon-ai/workflow-mcp';\nimport type { AgentToolResult } from '@earendil-works/pi-coding-agent';\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\n\n/**\n * Environment variable stamped onto every run launched from a Pi session.\n *\n * `RunWorkflowService` forwards `env` to the inner CLI invocation across the\n * `launch-command` delegation boundary and persists it on the run record, so\n * this survives backgrounding and identifies the launching session afterwards.\n */\nexport const PI_SESSION_ENV = 'PI_SESSION_ID';\n\n/** Operator override for the per-session launch ceiling. */\nconst MAX_CONCURRENT_ENV = 'WORKFLOW_MCP_MAX_CONCURRENT';\nconst DEFAULT_MAX_CONCURRENT = 5;\n\nexport interface WorkflowToolDetails {\n  tool: string;\n}\n\n/** Resolve the per-session launch ceiling from the environment. */\nexport function resolveMaxConcurrent(env: NodeJS.ProcessEnv = process.env): number {\n  const parsed = Number(env[MAX_CONCURRENT_ENV]);\n  return Number.isInteger(parsed) && parsed > 0 ? parsed : DEFAULT_MAX_CONCURRENT;\n}\n\n/**\n * True when this session launched the run.\n *\n * Fails closed on a missing session id: an unstamped record (a CLI launch) and\n * a call arriving before the session id is known both match nothing, so no run\n * ever leaks across sessions through an undefined-equals-undefined comparison.\n */\nexport function isSessionRun(record: WorkflowRunRecord, sessionId: string | undefined): boolean {\n  return sessionId !== undefined && record.env?.[PI_SESSION_ENV] === sessionId;\n}\n\n/** Runs launched by one Pi session that are still running. */\nexport function runsForSession(records: WorkflowRunRecord[], sessionId: string): WorkflowRunRecord[] {\n  return records.filter((record) => isSessionRun(record, sessionId) && record.stage === 'running');\n}\n\n/**\n * What the caller is told when the registry, not the launcher, acknowledged a\n * launch.\n *\n * Leads with the run key because it is the handle every other workflow action\n * takes, and it is no longer available any other way: the launcher's own output\n * is not waited for, so nothing else in this result carries it.\n */\nexport function launchedRunSummary(record: WorkflowRunRecord): string {\n  return [\n    `Started ${record.displayName} in workspace ${record.workspace}.`,\n    `Run key: ${record.runKey}`,\n    'The run is registered and going. This call returned at that point rather than waiting for the launcher process to exit.',\n  ].join('\\n');\n}\n\n/**\n * What the caller is told when the launch was handed off but no run has\n * registered inside the acknowledgement budget.\n *\n * Deliberately not an error: the launcher is slow rather than broken often\n * enough that failing here would strand runs that go on to start normally.\n * There is no run key to offer yet, so it points at the surfaces that do not\n * need one.\n */\nexport function launchHandoffSummary(workflowPath: string): string {\n  return [\n    `Launch handed off for ${workflowPath}, but no run has registered yet.`,\n    'Nothing was cancelled: the launcher is still starting, and a run that registers later still reports back here when it finishes.',\n    'Do not launch it again. Ask the user to check the active workflow list if they need to see it sooner.',\n  ].join('\\n');\n}\n\n/**\n * Escape sequences a terminal consumes rather than prints.\n *\n * Built from a string with the rule silenced, the way `doom-runner`'s own\n * scrubber does it, because matching the escape byte is the entire job. Not\n * imported from there: that package's published build is a stale artifact\n * missing the export, and a launch notice should not need another package's\n * build to be current.\n */\n// oxlint-disable-next-line no-control-regex -- matching terminal control bytes is the point\nconst ESCAPE_SEQUENCE = new RegExp(\n  ['\\\\u001B\\\\[[0-9;?]*[ -/]*[@-~]', '\\\\u001B\\\\][^\\\\u0007\\\\u001B]*(?:\\\\u0007|\\\\u001B\\\\\\\\)', '\\\\u001B[@-Z\\\\\\\\-_]'].join(\n    '|',\n  ),\n  'g',\n);\n\n/** Rows made only of box-drawing: separators that carry nothing once trimmed. */\nconst RULE_ROW = /^[\\s─-╿]*$/u;\nconst NOTICE_LINE_LIMIT = 3;\n/**\n * Widest a notice row may be before it is clipped.\n *\n * A three-line cap does not bound a toast on its own: the engine announces its\n * delegation by echoing the whole shell command, temp script path included, and\n * one line of that wraps across three rows of a narrow terminal and shoves the\n * transcript around. Clipped at a width every terminal can hold instead.\n */\nconst NOTICE_WIDTH_LIMIT = 100;\n\n/**\n * Cut a tool result down to something a toast can hold.\n *\n * The launch result used to reach `ui.notify` whole, and for a workflow that\n * executes in this process that result is the engine's entire console log:\n * banner, run directory, job tree, rules, colour. Pi rendered every line of it\n * over the transcript, which reads as a broken screen rather than as output.\n * Escape sequences go first: the log carries colour the notification would\n * render as literal text, and a stray clear or cursor-move would do to the\n * screen exactly what this function exists to prevent.\n */\nexport function launchNotice(text: string, limit: number = NOTICE_LINE_LIMIT): string {\n  const lines = text\n    .replace(ESCAPE_SEQUENCE, '')\n    .split('\\n')\n    .map((line) => line.trimEnd())\n    .filter((line) => line.trim().length > 0 && !RULE_ROW.test(line))\n    .map((line) => (line.length > NOTICE_WIDTH_LIMIT ? `${line.slice(0, NOTICE_WIDTH_LIMIT - 1)}…` : line));\n  if (lines.length === 0) return 'Workflow started.';\n  if (lines.length <= limit) return lines.join('\\n');\n  return [...lines.slice(0, limit), `… ${lines.length - limit} more lines, in the run's own output.`].join('\\n');\n}\n\n/** Flatten MCP tool content to text for Pi. */\nexport function toolResultText(result: CallToolResult): string {\n  return result.content\n    .map((part) => (part.type === 'text' ? part.text : ''))\n    .filter(Boolean)\n    .join('\\n')\n    .trim();\n}\n\n/**\n * Convert an MCP tool result into a Pi tool result.\n *\n * Pi signals tool failure by throwing: the agent loop catches it and builds the\n * error result. So an `isError` MCP result becomes a thrown error rather than a\n * successful result carrying a flag Pi would ignore.\n */\nexport function toAgentToolResult(\n  tool: string,\n  result: CallToolResult,\n  errorOptions: string[] = [],\n): AgentToolResult<WorkflowToolDetails> {\n  const text = toolResultText(result) || 'No output.';\n  if (result.isError) throw new Error(withOptions(text, errorOptions));\n  return { content: [{ type: 'text', text }], details: { tool } };\n}\n\n/**\n * Attach a short menu of next steps to a problem.\n *\n * An error with no route forward is where an agent invents one: retrying a\n * capacity limit, relaunching a run that should be recovered, or silently\n * giving up on work the user is waiting for. Naming two or three real options\n * turns an error into a decision, and the decision belongs to the user.\n */\nexport function withOptions(problem: string, options: string[]): string {\n  if (options.length === 0) return problem;\n  return [problem, '', 'Options, put these to the user rather than picking one yourself:', ...options.map(bullet)].join(\n    '\\n',\n  );\n}\n\nfunction bullet(option: string): string {\n  return `- ${option}`;\n}\n\n/** The job and step a run died on, preferring the progress log to the record. */\nfunction failurePosition(\n  record: WorkflowRunRecord,\n  jobs: WorkflowProgressJob[],\n): { job?: string; step?: string; reason?: string } {\n  // The progress log knows which step was in flight; the record only names the\n  // job. Falling back keeps this working for runs that predate the log.\n  const failedJob = jobs.find((job) => job.status === 'failed');\n  const failedStep = failedJob?.steps.find((step) => step.status === 'failed');\n  return {\n    job: failedJob?.name ?? record.failedJob,\n    step: failedStep?.name,\n    reason: failedStep?.reason ?? failedJob?.reason,\n  };\n}\n\n/**\n * Describe a finished run for the agent that launched it.\n *\n * Carries the job identifiers back so a dispatching agent can match the run to\n * the work item it launched it for without another lookup. When the run failed,\n * carries the failing step and a set of options too: the agent is being told\n * about this out of band, with no user question in flight, so without them it\n * has to guess whether to recover, relaunch, or report.\n */\nexport function finishedRunSummary(record: WorkflowRunRecord, jobs: WorkflowProgressJob[] = []): string {\n  const outcome = record.stage === 'completed' ? 'completed' : `ended in ${record.stage}`;\n  const failure = failurePosition(record, jobs);\n  const lines: Array<string | undefined> = [\n    `Workflow run ${record.runKey} in workspace ${record.workspace} ${outcome}.`,\n    record.workflowId ? `Workflow: ${record.workflowId}` : undefined,\n    failure.job ? `Failed job: ${failure.job}${failure.step ? ` (step: ${failure.step})` : ''}` : undefined,\n    record.errorMessage ? `Error: ${record.errorMessage}` : undefined,\n    failure.reason && failure.reason !== record.errorMessage ? `Step reported: ${failure.reason}` : undefined,\n  ];\n  const jobId = record.env?.AGIFLOW_JOB_ID;\n  if (jobId) lines.push(`Agiflow job: ${record.env?.AGIFLOW_JOB_KIND ?? 'unknown'} ${jobId}`);\n\n  const summary = lines.filter((line): line is string => Boolean(line)).join('\\n');\n  if (record.stage === 'completed') return summary;\n\n  // A run the user stopped is not a defect, so it gets no diagnosis step: the\n  // question is only whether to pick it back up.\n  const stopped = record.outcome === 'interrupted';\n  if (stopped) {\n    return withOptions(summary, [\n      `workflow_run {\"action\":\"recover\",\"runKey\":${JSON.stringify(record.runKey)}}: pick it up where it stopped.`,\n      'Leave it stopped and move on.',\n    ]);\n  }\n\n  const diagnosticText = [record.errorMessage, failure.reason].filter(Boolean).join('\\n');\n  if (diagnosticText.includes('JOB_ALREADY_CLAIMED')) {\n    return withOptions(summary, [\n      'Report contention: another worker owns this job. Do not unlock, release, or retry the claim automatically.',\n    ]);\n  }\n  if (diagnosticText.includes('WORKFLOW_NOT_OWNED') || /release failed/i.test(diagnosticText)) {\n    return withOptions(summary, [\n      'Inspect the current workflow ownership and ask the user before any release or unlock. Never force another worker’s lock.',\n    ]);\n  }\n  if (/running workflow not found/i.test(diagnosticText)) {\n    return withOptions(summary, [\n      `workflow_run {\"action\":\"status\",\"runKey\":${JSON.stringify(record.runKey)}}: re-check current state before retrying.`,\n      'Report the recorded terminal state when no running owner remains.',\n    ]);\n  }\n\n  return withOptions(summary, [\n    `workflow_run {\"action\":\"tail\",\"runKey\":${JSON.stringify(record.runKey)}}: read the run's own output first, when the error above does not explain the failure.`,\n    `workflow_run {\"action\":\"recover\",\"runKey\":${JSON.stringify(record.runKey)}}: resume from the failed job, keeping the work already done. Fits a transient or external cause.`,\n    'Report the failure and stop, when it needs a code change or a decision you cannot make.',\n  ]);\n}\n"],"mappings":";;;;;;;;AA4BA,MAAa,iBAAiB;;AAG9B,MAAM,qBAAqB;AAC3B,MAAM,yBAAyB;;AAO/B,SAAgB,qBAAqB,MAAyB,QAAQ,KAAa;CACjF,MAAM,SAAS,OAAO,I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