{"version":3,"file":"index.cjs","names":["createEmbeddedWorkflowFeature","createWorkflowLaunchExecutor","LIST_WORKFLOWS_TOOL_NAME","z","toAgentToolResult","LAUNCH_WORKFLOW_TOOL_NAME","launchFailureOptions","appendGuidance","WORKFLOW_RUN_TOOL_NAME","workflowRunInputSchema","resolveRootSessionId","actionGuidance"],"sources":["../../../../src/services/workflowTools/index.ts"],"sourcesContent":["import { resolveRootSessionId } from '@agimon-ai/doompi-core/child-process';\nimport {\n  createEmbeddedWorkflowFeature,\n  type WorkflowRunRecord,\n  type EmbeddedWorkflowFeature,\n} from '@agimon-ai/workflow-mcp';\nimport type { ExtensionAPI, ToolDefinition } from '@earendil-works/pi-coding-agent';\nimport { z } from 'zod';\n\nimport { workflowRunInputSchema } from '../../schemas/workflowPi';\nimport { toAgentToolResult, type WorkflowToolDetails } from '../../services/piToolBridge';\nimport {\n  type WorkflowLaunchInput,\n  type WorkflowRunSelector,\n  launchFailureOptions,\n} from '../../services/workflowExecution';\nimport {\n  createWorkflowLaunchExecutor,\n  reportProgress,\n  appendGuidance,\n  actionGuidance,\n  type WorkflowPiToolDependencies,\n} from '../../services/workflowExecution';\ntype WorkflowToolSchema = Parameters<ExtensionAPI['registerTool']>[0]['parameters'];\nimport {\n  WORKFLOW_PI_TOOL_NAMES,\n  LIST_WORKFLOWS_TOOL_NAME,\n  LAUNCH_WORKFLOW_TOOL_NAME,\n  WORKFLOW_RUN_TOOL_NAME,\n} from '../../constants/workflow';\nconst PI_LAUNCH_FIELDS = {\n  workflowPath: true,\n  workspace: true,\n  runner: true,\n  name: true,\n  env: true,\n  prompt: true,\n  job: true,\n  inputs: true,\n} as const;\nexport type WorkflowNativeTool = ToolDefinition<WorkflowToolSchema, WorkflowToolDetails>;\nexport type WorkflowToolRenderers = Pick<WorkflowNativeTool, 'renderCall' | 'renderResult'>;\nexport function createWorkflowTools(\n  dependencies: WorkflowPiToolDependencies,\n  renderers: (name: (typeof WORKFLOW_PI_TOOL_NAMES)[number]) => WorkflowToolRenderers = () => ({}),\n): WorkflowNativeTool[] {\n  const feature = dependencies.feature ?? createEmbeddedWorkflowFeature();\n  const runTool = dependencies.runTool ?? feature.runTool;\n  const listWorkflowsTool = dependencies.listWorkflowsTool ?? feature.listWorkflowsTool;\n  const recoverTool = dependencies.recoverTool ?? feature.createRecoverTool();\n  const controlTool = dependencies.controlTool ?? feature.createControlTool();\n  const trackPendingRun = dependencies.trackPendingRun ?? (<T>(run: Promise<T>): Promise<T> => run);\n  const launchExecutor =\n    dependencies.launchExecutor ??\n    createWorkflowLaunchExecutor({\n      environment: dependencies.environment,\n      activeRunCount: dependencies.activeRunCount,\n      onLaunch: dependencies.onLaunch,\n      observeSession: dependencies.observeSession,\n      rejectRunner: dependencies.rejectRunner,\n      runTool,\n      trackPendingRun,\n    });\n\n  return [\n    {\n      name: LIST_WORKFLOWS_TOOL_NAME,\n      label: 'List Workflows',\n      description: 'List the workflow definitions available in this repository.',\n      promptSnippet: 'List available workflow definitions',\n      parameters: z.toJSONSchema(listWorkflowsTool.getInputSchema()),\n      renderShell: 'self',\n      ...renderers(LIST_WORKFLOWS_TOOL_NAME),\n      async execute(_toolCallId, params) {\n        return toAgentToolResult(\n          LIST_WORKFLOWS_TOOL_NAME,\n          await listWorkflowsTool.execute(\n            params as Parameters<EmbeddedWorkflowFeature['listWorkflowsTool']['execute']>[0],\n          ),\n        );\n      },\n    },\n\n    {\n      name: LAUNCH_WORKFLOW_TOOL_NAME,\n      label: 'Launch Workflow',\n      description:\n        'Start a workflow run. Returns once the run has started, not once it finishes; use workflow_run with action status or wait for the completion notice.',\n      promptSnippet: 'Start a workflow run and return its identifier',\n      promptGuidelines: [\n        'Before launching, call list_workflows and pick the workflow whose own description matches the work. A workflow description is the source of truth; never infer one from its filename. If nothing matches, say so and stop rather than launching an approximate fit.',\n        'launch_workflow returns when the run has STARTED, not when it has finished. Never report success from its result. Poll workflow_run with action status, or wait for the completion notice the extension delivers on its own.',\n        'When dispatching Agiflow work, pass AGIFLOW_PROJECT_ID, AGIFLOW_JOB_KIND, and AGIFLOW_JOB_ID through env plus a non-empty prompt. Kind must be task or work-unit. The id alone is not a key, and omitting prompt leaves user_prompt workflows waiting for terminal input.',\n        'A workflow claims its own job in its pre step. Never claim a job yourself. JOB_ALREADY_CLAIMED or HTTP 409 means another worker won the race, so report contention and do not unlock, release, or retry automatically.',\n        'If a result says WORKFLOW_NOT_OWNED or a release failed, inspect current ownership and ask the user before any release or unlock. Never force another worker’s lock.',\n        'If a running workflow is not found, call workflow_run with action status to re-check current state before retrying.',\n        'The per-session concurrency ceiling is a real limit. If launch_workflow refuses, wait for a run to finish; do not launch through the shell to get around it.',\n      ],\n      parameters: z.toJSONSchema(runTool.getInputSchema().pick(PI_LAUNCH_FIELDS)),\n      renderShell: 'self',\n      ...renderers(LAUNCH_WORKFLOW_TOOL_NAME),\n      async execute(_toolCallId, params, _signal, onUpdate, ctx) {\n        const input = params as WorkflowLaunchInput;\n        const result = await launchExecutor.execute(input, ctx, onUpdate);\n        const adapted = toAgentToolResult(LAUNCH_WORKFLOW_TOOL_NAME, result, launchFailureOptions);\n        return appendGuidance(\n          adapted,\n          'Next: call workflow_run with action status and verify the recorded stage before reporting the workflow outcome.',\n        );\n      },\n    },\n\n    {\n      name: WORKFLOW_RUN_TOOL_NAME,\n      label: 'Workflow Run',\n      description:\n        'Inspect or control one workflow run. Use action status, tail, recovery-evidence, follow, open, pause, resume, stop, or recover. Every action requires an exact run key.',\n      promptSnippet: 'Inspect or control a workflow run',\n      promptGuidelines: [\n        'Use action status as the authority for stage, outcome, execution state, and pause cursor. A run that started is not a run that succeeded.',\n        'Use action pause or resume for cooperative lifecycle control. Pause is not stop: the run keeps its stage running, capacity, services, and heartbeat while paused.',\n        'Use action stop only when the user requests stopping a run. A user-requested stop is not a failure and needs no failure diagnosis.',\n        'Do not use follow or tail merely to wait for a healthy run; use status or the completion notice. Tail returns chat-safe status without raw PTY frames. Use follow only when the user asks to pin live progress, and open only when a human wants the recorded launcher foregrounded.',\n        'Use action recovery-evidence for terminal-only, durable status and artifacts before recovery. It is the only inspection path that may read a failed run from an earlier session and it never reads a live launcher.',\n        'Use action recover only after loading the `workflow-recovery` skill and gathering its required evidence. Recovery may adopt a terminal failed run from an earlier Pi session; it never grants cross-session control of running work. Never edit issue.md or repair.json, and verify real process and registry progress before recovery.',\n        'Never unlock or force-release an Agiflow claim from this tool.',\n      ],\n      parameters: z.toJSONSchema(workflowRunInputSchema),\n      renderShell: 'self',\n      ...renderers(WORKFLOW_RUN_TOOL_NAME),\n      async execute(_toolCallId, rawParams, _signal, onUpdate, ctx) {\n        const input = workflowRunInputSchema.parse(rawParams);\n        const sessionId = resolveRootSessionId(ctx.sessionManager.getSessionId(), dependencies.environment);\n        dependencies.observeSession?.(sessionId);\n        const selector: WorkflowRunSelector = { runKey: input.runKey, workspace: input.workspace };\n        const requireOwnedRun = async (): Promise<WorkflowRunRecord> => {\n          if (!dependencies.requireSessionRun) {\n            throw new Error('Workflow run ownership is not available in this session.');\n          }\n          return dependencies.requireSessionRun(selector, sessionId);\n        };\n\n        if (input.action === 'status') {\n          const record = await requireOwnedRun();\n          return {\n            content: [{ type: 'text', text: JSON.stringify(record, null, 2) }],\n            details: { tool: WORKFLOW_RUN_TOOL_NAME },\n          };\n        }\n        if (input.action === 'tail') {\n          if (!dependencies.tailRun) throw new Error('Reading workflow output is not available in this session.');\n          const record = await requireOwnedRun();\n          reportProgress(onUpdate, WORKFLOW_RUN_TOOL_NAME, `Reading output for workflow ${input.runKey}...`);\n          await dependencies.tailRun(selector, ctx);\n          return {\n            content: [\n              {\n                type: 'text',\n                text: [\n                  `Workflow: ${record.displayName} (${record.runKey})`,\n                  `Stage: ${record.effectiveStage ?? record.stage}`,\n                  'Raw launcher output is hidden from chat. Use action follow or open to view it.',\n                ].join('\\n'),\n              },\n            ],\n            details: { tool: WORKFLOW_RUN_TOOL_NAME },\n          };\n        }\n        if (input.action === 'recovery-evidence') {\n          if (!dependencies.readRecoveryEvidence) {\n            throw new Error('Reading workflow recovery evidence is not available in this session.');\n          }\n          reportProgress(onUpdate, WORKFLOW_RUN_TOOL_NAME, `Reading recovery evidence for workflow ${input.runKey}...`);\n          return {\n            content: [{ type: 'text', text: await dependencies.readRecoveryEvidence(selector, ctx) }],\n            details: { tool: WORKFLOW_RUN_TOOL_NAME },\n          };\n        }\n        if (input.action === 'follow') {\n          if (!dependencies.followRun) throw new Error('Following workflow output is not available in this session.');\n          await requireOwnedRun();\n          reportProgress(onUpdate, WORKFLOW_RUN_TOOL_NAME, `Following workflow ${input.runKey}...`);\n          return {\n            content: [{ type: 'text', text: await dependencies.followRun(selector, ctx) }],\n            details: { tool: WORKFLOW_RUN_TOOL_NAME },\n          };\n        }\n        if (input.action === 'open') {\n          if (!dependencies.openRun) throw new Error('Opening a workflow launcher is not available in this session.');\n          await requireOwnedRun();\n          reportProgress(onUpdate, WORKFLOW_RUN_TOOL_NAME, `Opening workflow ${input.runKey}...`);\n          return {\n            content: [{ type: 'text', text: await dependencies.openRun(selector, ctx) }],\n            details: { tool: WORKFLOW_RUN_TOOL_NAME },\n          };\n        }\n\n        if (input.action === 'recover') {\n          if (!dependencies.requireRecoverableRun) {\n            throw new Error('Workflow recovery ownership transfer is not available in this session.');\n          }\n          const recoverable = await dependencies.requireRecoverableRun(selector);\n          const recoverySelector = { runKey: recoverable.runKey, workspace: recoverable.workspace };\n          reportProgress(onUpdate, WORKFLOW_RUN_TOOL_NAME, `Recovering workflow ${input.runKey}...`);\n          // A recovery replays the workflow, and the replay skips the launch\n          // step, so every job runs in THIS process. For a workflow whose steps\n          // are interactive that means an agent TUI spawned onto this process's\n          // own terminal. Hand it to a launcher instead, where the workflow says\n          // how. A dry run prints rather than executes, so it stays here.\n          if (!input.dryRun) {\n            const delegated = await dependencies.delegateRecovery?.({ ...recoverySelector, runner: input.runner }, ctx);\n            if (delegated) {\n              const guidance = actionGuidance(input.action, input.runKey);\n              await dependencies.onLaunch?.(ctx);\n              return {\n                content: [{ type: 'text', text: [delegated, guidance[0]].join('\\n\\n') }],\n                details: { tool: WORKFLOW_RUN_TOOL_NAME },\n              };\n            }\n          }\n          const recoverInput = {\n            dryRun: input.dryRun,\n            job: input.job,\n            runKey: recoverySelector.runKey,\n            runner: input.runner,\n            workspace: recoverySelector.workspace,\n          };\n          const result = await trackPendingRun(recoverTool.execute(recoverInput));\n          const guidance = actionGuidance(input.action, input.runKey);\n          const adapted = toAgentToolResult(WORKFLOW_RUN_TOOL_NAME, result, guidance);\n          await dependencies.onLaunch?.(ctx);\n          return appendGuidance(adapted, guidance[0]!);\n        }\n\n        const ownedRun = await requireOwnedRun();\n        if (!ownedRun.runId) throw new Error(`Workflow ${input.runKey} has no controllable run generation.`);\n        reportProgress(onUpdate, WORKFLOW_RUN_TOOL_NAME, `Requesting ${input.action} for workflow ${input.runKey}...`);\n        const result = await controlTool.execute({\n          action: input.action,\n          expectedRunId: ownedRun.runId,\n          reason: input.reason,\n          runKey: input.runKey,\n          workspace: input.workspace,\n        });\n        const guidance = actionGuidance(input.action, input.runKey);\n        const adapted = toAgentToolResult(WORKFLOW_RUN_TOOL_NAME, result, guidance);\n        return appendGuidance(adapted, guidance[0]!);\n      },\n    },\n  ];\n}\n"],"mappings":";;;;;;;;AA8BA,MAAM,mBAAmB;CACvB,cAAc;CACd,WAAW;CACX,QAAQ;CACR,MAAM;CACN,KAAK;CACL,QAAQ;CACR,KAAK;CACL,QAAQ;AACV;AAGA,SAAgB,oBACd,cACA,mBAA6F,CAAC,IACxE;CACtB,MAAM,UAAU,aAAa,YAAA,GAAWA,wBAAAA,8BAAAA,CAA8B;CACtE,MAAM,UAAU,aAAa,WAAW,QAAQ;CAChD,MAAM,oBAAoB,aAAa,qBAAqB,QAAQ;CACpE,MAAM,cAAc,aAAa,eAAe,QAAQ,kBAAkB;CAC1E,MAAM,cAAc,aAAa,eAAe,QAAQ,kBAAkB;CAC1E,MAAM,kBAAkB,aAAa,qBAAwB,QAAgC;CAC7F,MAAM,iBACJ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