@agimon-ai/doompi-workflow 0.0.1-alpha.13 → 0.0.1-alpha.14

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.
Files changed (42) hide show
  1. package/README.md +6 -0
  2. package/dist/adapters/pi/workflow/piExtension.cjs +8 -8
  3. package/dist/adapters/pi/workflow/piExtension.cjs.map +1 -1
  4. package/dist/adapters/pi/workflow/piExtension.mjs +8 -8
  5. package/dist/adapters/pi/workflow/piExtension.mjs.map +1 -1
  6. package/dist/adapters/pi/workflow/piToolBridge.cjs +1 -1
  7. package/dist/adapters/pi/workflow/piToolBridge.cjs.map +1 -1
  8. package/dist/adapters/pi/workflow/piToolBridge.mjs +1 -1
  9. package/dist/adapters/pi/workflow/piToolBridge.mjs.map +1 -1
  10. package/dist/adapters/pi/workflow/piTools.cjs +3 -2
  11. package/dist/adapters/pi/workflow/piTools.cjs.map +1 -1
  12. package/dist/adapters/pi/workflow/piTools.mjs +3 -2
  13. package/dist/adapters/pi/workflow/piTools.mjs.map +1 -1
  14. package/dist/services/workflow/workflowNarration.cjs +2 -0
  15. package/dist/services/workflow/workflowNarration.cjs.map +1 -0
  16. package/dist/services/workflow/workflowNarration.mjs +2 -0
  17. package/dist/services/workflow/workflowNarration.mjs.map +1 -0
  18. package/dist/tui/workflow/workflowInspector.cjs +1 -1
  19. package/dist/tui/workflow/workflowInspector.cjs.map +1 -1
  20. package/dist/tui/workflow/workflowInspector.mjs +1 -1
  21. package/dist/tui/workflow/workflowInspector.mjs.map +1 -1
  22. package/dist/tui/workflow/workflowProgressOverlay.cjs +2 -0
  23. package/dist/tui/workflow/workflowProgressOverlay.cjs.map +1 -0
  24. package/dist/tui/workflow/workflowProgressOverlay.mjs +2 -0
  25. package/dist/tui/workflow/workflowProgressOverlay.mjs.map +1 -0
  26. package/dist/tui/workflow/workflowStatusRow.cjs +1 -1
  27. package/dist/tui/workflow/workflowStatusRow.cjs.map +1 -1
  28. package/dist/tui/workflow/workflowStatusRow.mjs +1 -1
  29. package/dist/tui/workflow/workflowStatusRow.mjs.map +1 -1
  30. package/dist/tui/workflow/workflowStepMessage.cjs +1 -1
  31. package/dist/tui/workflow/workflowStepMessage.cjs.map +1 -1
  32. package/dist/tui/workflow/workflowStepMessage.mjs +1 -1
  33. package/dist/tui/workflow/workflowStepMessage.mjs.map +1 -1
  34. package/dist/tui/workflow/workflowToolRender.cjs +7 -0
  35. package/dist/tui/workflow/workflowToolRender.cjs.map +1 -0
  36. package/dist/tui/workflow/workflowToolRender.mjs +7 -0
  37. package/dist/tui/workflow/workflowToolRender.mjs.map +1 -0
  38. package/package.json +6 -6
  39. package/dist/tui/workflow/workflowFooterStatus.cjs +0 -2
  40. package/dist/tui/workflow/workflowFooterStatus.cjs.map +0 -1
  41. package/dist/tui/workflow/workflowFooterStatus.mjs +0 -2
  42. package/dist/tui/workflow/workflowFooterStatus.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"piTools.mjs","names":[],"sources":["../../../../src/adapters/pi/workflow/piTools.ts"],"sourcesContent":["import { resolveRootSessionId } from '@agimon-ai/doompi-extension-contracts/child-process';\nimport {\n createEmbeddedWorkflowFeature,\n type EmbeddedWorkflowFeature,\n type WorkflowRunRecord,\n} from '@agimon-ai/workflow-mcp';\nimport type {\n AgentToolResult,\n AgentToolUpdateCallback,\n ExtensionAPI,\n ExtensionContext,\n} from '@earendil-works/pi-coding-agent';\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport { z } from 'zod';\nimport { type WorkflowRunInput, workflowRunInputSchema } from '../../../schemas/workflowPi.ts';\nimport {\n launchedRunSummary,\n launchHandoffSummary,\n PI_SESSION_ENV,\n resolveMaxConcurrent,\n toAgentToolResult,\n toolResultText,\n withOptions,\n} from './piToolBridge';\n\nconst AGIFLOW_JOB_ID_ENV = 'AGIFLOW_JOB_ID';\nconst AGIFLOW_JOB_KIND_ENV = 'AGIFLOW_JOB_KIND';\n\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;\n\nexport const WORKFLOW_PI_TOOL_NAMES = ['list_workflows', 'launch_workflow', 'workflow_run'] as const;\nconst [LIST_WORKFLOWS_TOOL_NAME, LAUNCH_WORKFLOW_TOOL_NAME, WORKFLOW_RUN_TOOL_NAME] = WORKFLOW_PI_TOOL_NAMES;\n\ntype WorkflowRunSelector = Pick<WorkflowRunInput, 'runKey' | 'workspace'>;\n\nexport type WorkflowLaunchInput = z.infer<ReturnType<EmbeddedWorkflowFeature['runTool']['getInputSchema']>>;\n\n/**\n * Where a launch was answered from, which decides what the caller is told.\n *\n * Tagged rather than inferred from an absent field: the failure carries an\n * `unknown`, and `unknown` includes `undefined`, so only a tag can tell a\n * rejection apart from a result.\n */\ntype LaunchOutcome = { kind: 'value'; result: CallToolResult } | { kind: 'error'; error: unknown };\ntype LaunchAck =\n | { kind: 'settled'; outcome: LaunchOutcome }\n | { kind: 'record'; record: WorkflowRunRecord }\n | { kind: 'handoff' };\n\n/** How often the registry is asked whether the launch has produced a run. */\nconst LAUNCH_ACK_POLL_MS = 500;\n/**\n * How long to wait for that before answering without a run key.\n *\n * Long enough to cover a launcher that is merely slow, short enough that a\n * caller is never left holding a turn open for a launcher that will not answer.\n */\nconst LAUNCH_ACK_TIMEOUT_MS = 15_000;\n\nexport interface LaunchedRunQuery {\n sessionId: string | undefined;\n /** Epoch milliseconds the launch began, so an earlier run cannot match. */\n since: number;\n workflowPath: string;\n}\n\nexport interface WorkflowLaunchExecutorDependencies {\n activeRunCount?: () => Promise<number>;\n onLaunch?: (ctx: ExtensionContext) => Promise<void> | void;\n observeSession?: (sessionId: string | undefined) => void;\n rejectRunner?: (workflowPath: string, runner: string) => string | undefined;\n runTool: EmbeddedWorkflowFeature['runTool'];\n trackPendingRun: <T>(run: Promise<T>) => Promise<T>;\n /**\n * The run this launch registered, or undefined while none has appeared.\n *\n * Its presence is what lets a launch answer on the registry instead of on the\n * launcher process exiting. Left out, the launch waits for the process, which\n * is the behaviour every caller had before.\n */\n findLaunchedRun?: (query: LaunchedRunQuery) => Promise<WorkflowRunRecord | undefined>;\n /** Report a launch that fails after this call already answered \"started\". */\n onLateFailure?: (error: unknown, ctx: ExtensionContext) => void;\n launchAckPollMs?: number;\n launchAckTimeoutMs?: number;\n}\n\nexport interface WorkflowLaunchExecutor {\n execute(\n input: WorkflowLaunchInput,\n ctx: ExtensionContext,\n onUpdate?: AgentToolUpdateCallback<{ tool: string }>,\n ): Promise<CallToolResult>;\n}\n\nexport interface WorkflowPiToolDependencies {\n launchExecutor?: WorkflowLaunchExecutor;\n onLaunch?: (ctx: ExtensionContext) => Promise<void> | void;\n activeRunCount?: () => Promise<number>;\n followRun?: (input: WorkflowRunSelector, ctx: ExtensionContext) => Promise<string>;\n tailRun?: (input: WorkflowRunSelector, ctx: ExtensionContext) => Promise<string>;\n openRun?: (input: WorkflowRunSelector, ctx: ExtensionContext) => Promise<string>;\n rejectRunner?: (workflowPath: string, runner: string) => string | undefined;\n requireSessionRun?: (input: WorkflowRunSelector, sessionId: string | undefined) => Promise<WorkflowRunRecord>;\n /**\n * Resolve a failed recovery target globally.\n *\n * Recovery is the one ownership-transferring action: a replacement Pi\n * session must be able to adopt a terminal run whose launching session is\n * gone. Every non-recovery action remains session-scoped.\n */\n requireRecoverableRun?: (input: WorkflowRunSelector) => Promise<WorkflowRunRecord>;\n readRecoveryEvidence?: (input: WorkflowRunSelector, ctx: ExtensionContext) => Promise<string>;\n /**\n * Hand a recovery to a terminal launcher, returning what to tell the caller.\n *\n * Undefined means this recovery cannot be delegated, and the in-process\n * replay below is used instead.\n */\n delegateRecovery?: (\n input: { runKey: string; workspace?: string; runner?: string },\n ctx: ExtensionContext,\n ) => Promise<string | undefined>;\n observeSession?: (sessionId: string | undefined) => void;\n trackPendingRun?: <T>(run: Promise<T>) => Promise<T>;\n feature?: EmbeddedWorkflowFeature;\n recoverTool?: {\n execute(input: {\n dryRun?: boolean;\n job?: string;\n runKey: string;\n runner?: string;\n workspace?: string;\n }): Promise<CallToolResult>;\n };\n controlTool?: ReturnType<EmbeddedWorkflowFeature['createControlTool']>;\n runTool?: EmbeddedWorkflowFeature['runTool'];\n listWorkflowsTool?: EmbeddedWorkflowFeature['listWorkflowsTool'];\n}\n\nfunction reportProgress(\n onUpdate: AgentToolUpdateCallback<{ tool: string }> | undefined,\n tool: string,\n message: string,\n): void {\n onUpdate?.({ content: [{ type: 'text', text: message }], details: { tool } });\n}\n\nfunction appendGuidance(\n result: AgentToolResult<{ tool: string }>,\n guidance: string,\n): AgentToolResult<{ tool: string }> {\n return { ...result, content: [...result.content, { type: 'text', text: guidance }] };\n}\n\nfunction statusAction(runKey: string): string {\n return `workflow_run {\"action\":\"status\",\"runKey\":${JSON.stringify(runKey)}}`;\n}\n\nfunction actionGuidance(action: WorkflowRunInput['action'], runKey: string): string[] {\n const status = statusAction(runKey);\n if (action === 'stop') return [`Next: call ${status} to confirm the run reached a terminal stage.`];\n if (action === 'recover') {\n return [\n `Report the recovery failure and do not retry it blindly: call ${status} first.`,\n 'Ask the user before launching fresh work when the recorded recovery is no longer valid.',\n ];\n }\n return [`Next: call ${status} to verify the recorded execution state.`];\n}\n\nconst launchFailureOptions = [\n 'Report the failure to the user with the error above. A launch failure is usually a bad workflow path, a missing launcher, or a workflow whose own pre-conditions refused.',\n 'list_workflows: confirm the workflow path exists and its description matches the work, if the path may be wrong.',\n 'workflow_run with action status: check whether an earlier attempt is already running before launching again.',\n];\n\n/**\n * An Error, whatever the launch rejected with.\n *\n * A rejection reaches here as `unknown` because it crossed a promise boundary,\n * and rethrowing that as-is hands Pi's tool layer something it cannot read a\n * message or a stack off. The original is kept as the cause rather than\n * flattened into a string.\n */\nfunction asError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value), { cause: value });\n}\n\n/** Resolves to undefined, so a race against it reads as \"nothing settled yet\". */\nfunction sleep(ms: number): Promise<undefined> {\n return new Promise((settle) => {\n const timer = setTimeout(() => settle(undefined), ms);\n timer.unref?.();\n });\n}\n\n/**\n * Wait for whichever answer arrives first: the launch settling, the run\n * appearing in the registry, or the budget running out.\n *\n * A launch that delegates to a terminal launcher settles when that launcher's\n * whole process chain closes, which on a loaded machine has been measured\n * minutes after the run itself was registered and working. The registry is the\n * earlier and more truthful signal: a run recorded there is a run that started.\n */\nasync function awaitLaunchAck(\n settled: Promise<LaunchOutcome>,\n dependencies: WorkflowLaunchExecutorDependencies,\n query: LaunchedRunQuery,\n): Promise<LaunchAck> {\n const findLaunchedRun = dependencies.findLaunchedRun;\n if (!findLaunchedRun) return { kind: 'settled', outcome: await settled };\n\n const pollMs = dependencies.launchAckPollMs ?? LAUNCH_ACK_POLL_MS;\n const deadline = Date.now() + (dependencies.launchAckTimeoutMs ?? LAUNCH_ACK_TIMEOUT_MS);\n for (;;) {\n const outcome = await Promise.race([settled, sleep(pollMs)]);\n if (outcome) return { kind: 'settled', outcome };\n // A registry read that throws must not fail the launch: the run may be\n // perfectly healthy, and the settled promise is still the fallback.\n const record = await findLaunchedRun(query).catch(() => undefined);\n if (record) return { kind: 'record', record };\n if (Date.now() >= deadline) return { kind: 'handoff' };\n }\n}\n\n/**\n * Carry a failure that lands after the caller was told the run started.\n *\n * Answering early trades the launcher's exit code for timeliness. Dropping that\n * code entirely is not part of the trade: a launch that fails a minute later\n * would otherwise leave a user waiting on a run that never existed.\n */\nfunction reportLateFailure(\n settled: Promise<LaunchOutcome>,\n dependencies: WorkflowLaunchExecutorDependencies,\n ctx: ExtensionContext,\n): void {\n void settled.then((outcome) => {\n if (outcome.kind === 'error') {\n dependencies.onLateFailure?.(asError(outcome.error), ctx);\n return;\n }\n if (outcome.result.isError) {\n dependencies.onLateFailure?.(new Error(toolResultText(outcome.result) || 'Workflow launch failed.'), ctx);\n }\n });\n}\n\nexport function createWorkflowLaunchExecutor(dependencies: WorkflowLaunchExecutorDependencies): WorkflowLaunchExecutor {\n return {\n async execute(input, ctx, onUpdate) {\n const sessionId = resolveRootSessionId(ctx.sessionManager.getSessionId());\n dependencies.observeSession?.(sessionId);\n const agiflowJobKind = input.env?.[AGIFLOW_JOB_KIND_ENV]?.trim();\n const agiflowJobId = input.env?.[AGIFLOW_JOB_ID_ENV]?.trim();\n if (Boolean(agiflowJobKind) !== Boolean(agiflowJobId)) {\n throw new Error('Agiflow workflow launches require AGIFLOW_JOB_KIND and AGIFLOW_JOB_ID together.');\n }\n if (agiflowJobKind && !input.prompt?.trim()) {\n throw new Error(\n 'Agiflow workflow launches require a non-empty prompt so user_prompt runs do not wait for terminal input.',\n );\n }\n reportProgress(onUpdate, LAUNCH_WORKFLOW_TOOL_NAME, 'Checking workflow capacity...');\n const maxConcurrent = resolveMaxConcurrent();\n const active = (await dependencies.activeRunCount?.()) ?? 0;\n if (active >= maxConcurrent) {\n throw new Error(\n withOptions(`This session is at capacity: ${active}/${maxConcurrent} workflows running.`, [\n 'Wait for a running workflow to finish, then launch again. The extension reports each one as it ends.',\n 'workflow_run with action status: show what is running, so the user can judge whether something is stuck.',\n 'workflow_run with action stop: free a slot by stopping a run the user no longer wants.',\n ]),\n );\n }\n\n if (input.runner) {\n const rejection = dependencies.rejectRunner?.(input.workflowPath, input.runner);\n if (rejection) throw new Error(rejection);\n }\n reportProgress(onUpdate, LAUNCH_WORKFLOW_TOOL_NAME, `Launching workflow ${input.workflowPath}...`);\n const workflowEnv = { ...input.env };\n if (process.env.AGIFLOW_DISPATCH_CONTEXT_FILE) {\n for (const key of [\n 'AGIFLOW_ORGANIZATION_ID',\n 'AGIFLOW_PROJECT_ID',\n 'AGIFLOW_DEVICE_ID',\n 'BACKEND_AGIFLOW_API_ENDPOINT',\n 'AGIFLOW_DISPATCH_SECRET_FILE',\n ] as const) {\n const hostValue = process.env[key];\n if (hostValue) workflowEnv[key] = hostValue;\n }\n }\n const since = Date.now();\n const launch = dependencies.trackPendingRun(\n dependencies.runTool.execute({\n ...input,\n env: { ...workflowEnv, [PI_SESSION_ENV]: sessionId },\n }),\n );\n // Folded into a value before anything races it. A promise this function\n // may stop awaiting must never be able to reject unobserved, which in\n // Node ends the whole process, Pi's TUI included.\n const settled: Promise<LaunchOutcome> = launch.then(\n (value): LaunchOutcome => ({ kind: 'value', result: value }),\n (error: unknown): LaunchOutcome => ({ kind: 'error', error }),\n );\n\n const ack = await awaitLaunchAck(settled, dependencies, {\n sessionId,\n since,\n workflowPath: input.workflowPath,\n });\n\n if (ack.kind === 'settled') {\n const outcome = ack.outcome;\n if (outcome.kind === 'error') throw asError(outcome.error);\n const result = outcome.result;\n if (result.isError)\n throw new Error(withOptions(toolResultText(result) || 'Workflow launch failed.', launchFailureOptions));\n await dependencies.onLaunch?.(ctx);\n return result;\n }\n\n reportLateFailure(settled, dependencies, ctx);\n await dependencies.onLaunch?.(ctx);\n return {\n content: [\n {\n type: 'text',\n text: ack.kind === 'record' ? launchedRunSummary(ack.record) : launchHandoffSummary(input.workflowPath),\n },\n ],\n };\n },\n };\n}\n\nexport function registerWorkflowPiTools(pi: ExtensionAPI, dependencies: WorkflowPiToolDependencies = {}): void {\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 activeRunCount: dependencies.activeRunCount,\n onLaunch: dependencies.onLaunch,\n observeSession: dependencies.observeSession,\n rejectRunner: dependencies.rejectRunner,\n runTool,\n trackPendingRun,\n });\n\n pi.registerTool({\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 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 pi.registerTool({\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_JOB_KIND and AGIFLOW_JOB_ID together through env plus a non-empty prompt. 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 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 pi.registerTool({\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 'Use action tail to read session-owned output, action follow to pin live progress, and action 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 async execute(_toolCallId, rawParams, _signal, onUpdate, ctx) {\n const input = workflowRunInputSchema.parse(rawParams);\n const sessionId = resolveRootSessionId(ctx.sessionManager.getSessionId());\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 await requireOwnedRun();\n reportProgress(onUpdate, WORKFLOW_RUN_TOOL_NAME, `Reading output for workflow ${input.runKey}...`);\n return {\n content: [{ type: 'text', text: await dependencies.tailRun(selector, ctx) }],\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"],"mappings":"gcAyBA,MAGM,EAAmB,CACvB,aAAc,GACd,UAAW,GACX,OAAQ,GACR,KAAM,GACN,IAAK,GACL,OAAQ,GACR,IAAK,GACL,OAAQ,EACV,EAEa,EAAyB,CAAC,iBAAkB,kBAAmB,cAAc,EACpF,CAAC,EAA0B,EAA2B,GAA0B,EA8GtF,SAAS,EACP,EACA,EACA,EACM,CACN,IAAW,CAAE,QAAS,CAAC,CAAE,KAAM,OAAQ,KAAM,CAAQ,CAAC,EAAG,QAAS,CAAE,MAAK,CAAE,CAAC,CAC9E,CAEA,SAAS,EACP,EACA,EACmC,CACnC,MAAO,CAAE,GAAG,EAAQ,QAAS,CAAC,GAAG,EAA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AG,CAC7C,CACF,CAAC,CACH"}
1
+ {"version":3,"file":"piTools.mjs","names":[],"sources":["../../../../src/adapters/pi/workflow/piTools.ts"],"sourcesContent":["import { resolveRootSessionId } from '@agimon-ai/doompi-extension-contracts/child-process';\nimport {\n createEmbeddedWorkflowFeature,\n type EmbeddedWorkflowFeature,\n type WorkflowRunRecord,\n} from '@agimon-ai/workflow-mcp';\nimport type {\n AgentToolResult,\n AgentToolUpdateCallback,\n ExtensionAPI,\n ExtensionContext,\n} from '@earendil-works/pi-coding-agent';\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport { z } from 'zod';\nimport { type WorkflowRunInput, workflowRunInputSchema } from '../../../schemas/workflowPi.ts';\nimport { renderWorkflowToolCall, renderWorkflowToolResult } from '../../../tui/workflow/workflowToolRender.ts';\nimport {\n launchedRunSummary,\n launchHandoffSummary,\n PI_SESSION_ENV,\n resolveMaxConcurrent,\n toAgentToolResult,\n toolResultText,\n withOptions,\n} from './piToolBridge';\n\nconst AGIFLOW_JOB_ID_ENV = 'AGIFLOW_JOB_ID';\nconst AGIFLOW_JOB_KIND_ENV = 'AGIFLOW_JOB_KIND';\n\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;\n\nexport const WORKFLOW_PI_TOOL_NAMES = ['list_workflows', 'launch_workflow', 'workflow_run'] as const;\nconst [LIST_WORKFLOWS_TOOL_NAME, LAUNCH_WORKFLOW_TOOL_NAME, WORKFLOW_RUN_TOOL_NAME] = WORKFLOW_PI_TOOL_NAMES;\n\ntype WorkflowRunSelector = Pick<WorkflowRunInput, 'runKey' | 'workspace'>;\n\nexport type WorkflowLaunchInput = z.infer<ReturnType<EmbeddedWorkflowFeature['runTool']['getInputSchema']>>;\n\n/**\n * Where a launch was answered from, which decides what the caller is told.\n *\n * Tagged rather than inferred from an absent field: the failure carries an\n * `unknown`, and `unknown` includes `undefined`, so only a tag can tell a\n * rejection apart from a result.\n */\ntype LaunchOutcome = { kind: 'value'; result: CallToolResult } | { kind: 'error'; error: unknown };\ntype LaunchAck =\n | { kind: 'settled'; outcome: LaunchOutcome }\n | { kind: 'record'; record: WorkflowRunRecord }\n | { kind: 'handoff' };\n\n/** How often the registry is asked whether the launch has produced a run. */\nconst LAUNCH_ACK_POLL_MS = 500;\n/**\n * How long to wait for that before answering without a run key.\n *\n * Long enough to cover a launcher that is merely slow, short enough that a\n * caller is never left holding a turn open for a launcher that will not answer.\n */\nconst LAUNCH_ACK_TIMEOUT_MS = 15_000;\n\nexport interface LaunchedRunQuery {\n sessionId: string | undefined;\n /** Epoch milliseconds the launch began, so an earlier run cannot match. */\n since: number;\n workflowPath: string;\n}\n\nexport interface WorkflowLaunchExecutorDependencies {\n activeRunCount?: () => Promise<number>;\n onLaunch?: (ctx: ExtensionContext) => Promise<void> | void;\n observeSession?: (sessionId: string | undefined) => void;\n rejectRunner?: (workflowPath: string, runner: string) => string | undefined;\n runTool: EmbeddedWorkflowFeature['runTool'];\n trackPendingRun: <T>(run: Promise<T>) => Promise<T>;\n /**\n * The run this launch registered, or undefined while none has appeared.\n *\n * Its presence is what lets a launch answer on the registry instead of on the\n * launcher process exiting. Left out, the launch waits for the process, which\n * is the behaviour every caller had before.\n */\n findLaunchedRun?: (query: LaunchedRunQuery) => Promise<WorkflowRunRecord | undefined>;\n /** Report a launch that fails after this call already answered \"started\". */\n onLateFailure?: (error: unknown, ctx: ExtensionContext) => void;\n launchAckPollMs?: number;\n launchAckTimeoutMs?: number;\n}\n\nexport interface WorkflowLaunchExecutor {\n execute(\n input: WorkflowLaunchInput,\n ctx: ExtensionContext,\n onUpdate?: AgentToolUpdateCallback<{ tool: string }>,\n ): Promise<CallToolResult>;\n}\n\nexport interface WorkflowPiToolDependencies {\n launchExecutor?: WorkflowLaunchExecutor;\n onLaunch?: (ctx: ExtensionContext) => Promise<void> | void;\n activeRunCount?: () => Promise<number>;\n followRun?: (input: WorkflowRunSelector, ctx: ExtensionContext) => Promise<string>;\n tailRun?: (input: WorkflowRunSelector, ctx: ExtensionContext) => Promise<string>;\n openRun?: (input: WorkflowRunSelector, ctx: ExtensionContext) => Promise<string>;\n rejectRunner?: (workflowPath: string, runner: string) => string | undefined;\n requireSessionRun?: (input: WorkflowRunSelector, sessionId: string | undefined) => Promise<WorkflowRunRecord>;\n /**\n * Resolve a failed recovery target globally.\n *\n * Recovery is the one ownership-transferring action: a replacement Pi\n * session must be able to adopt a terminal run whose launching session is\n * gone. Every non-recovery action remains session-scoped.\n */\n requireRecoverableRun?: (input: WorkflowRunSelector) => Promise<WorkflowRunRecord>;\n readRecoveryEvidence?: (input: WorkflowRunSelector, ctx: ExtensionContext) => Promise<string>;\n /**\n * Hand a recovery to a terminal launcher, returning what to tell the caller.\n *\n * Undefined means this recovery cannot be delegated, and the in-process\n * replay below is used instead.\n */\n delegateRecovery?: (\n input: { runKey: string; workspace?: string; runner?: string },\n ctx: ExtensionContext,\n ) => Promise<string | undefined>;\n observeSession?: (sessionId: string | undefined) => void;\n trackPendingRun?: <T>(run: Promise<T>) => Promise<T>;\n feature?: EmbeddedWorkflowFeature;\n recoverTool?: {\n execute(input: {\n dryRun?: boolean;\n job?: string;\n runKey: string;\n runner?: string;\n workspace?: string;\n }): Promise<CallToolResult>;\n };\n controlTool?: ReturnType<EmbeddedWorkflowFeature['createControlTool']>;\n runTool?: EmbeddedWorkflowFeature['runTool'];\n listWorkflowsTool?: EmbeddedWorkflowFeature['listWorkflowsTool'];\n}\n\nfunction reportProgress(\n onUpdate: AgentToolUpdateCallback<{ tool: string }> | undefined,\n tool: string,\n message: string,\n): void {\n onUpdate?.({ content: [{ type: 'text', text: message }], details: { tool } });\n}\n\nfunction appendGuidance(\n result: AgentToolResult<{ tool: string }>,\n guidance: string,\n): AgentToolResult<{ tool: string }> {\n return { ...result, content: [...result.content, { type: 'text', text: guidance }] };\n}\n\nfunction statusAction(runKey: string): string {\n return `workflow_run {\"action\":\"status\",\"runKey\":${JSON.stringify(runKey)}}`;\n}\n\nfunction actionGuidance(action: WorkflowRunInput['action'], runKey: string): string[] {\n const status = statusAction(runKey);\n if (action === 'stop') return [`Next: call ${status} to confirm the run reached a terminal stage.`];\n if (action === 'recover') {\n return [\n `Report the recovery failure and do not retry it blindly: call ${status} first.`,\n 'Ask the user before launching fresh work when the recorded recovery is no longer valid.',\n ];\n }\n return [`Next: call ${status} to verify the recorded execution state.`];\n}\n\nconst launchFailureOptions = [\n 'Report the failure to the user with the error above. A launch failure is usually a bad workflow path, a missing launcher, or a workflow whose own pre-conditions refused.',\n 'list_workflows: confirm the workflow path exists and its description matches the work, if the path may be wrong.',\n 'workflow_run with action status: check whether an earlier attempt is already running before launching again.',\n];\n\n/**\n * An Error, whatever the launch rejected with.\n *\n * A rejection reaches here as `unknown` because it crossed a promise boundary,\n * and rethrowing that as-is hands Pi's tool layer something it cannot read a\n * message or a stack off. The original is kept as the cause rather than\n * flattened into a string.\n */\nfunction asError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value), { cause: value });\n}\n\n/** Resolves to undefined, so a race against it reads as \"nothing settled yet\". */\nfunction sleep(ms: number): Promise<undefined> {\n return new Promise((settle) => {\n const timer = setTimeout(() => settle(undefined), ms);\n timer.unref?.();\n });\n}\n\n/**\n * Wait for whichever answer arrives first: the launch settling, the run\n * appearing in the registry, or the budget running out.\n *\n * A launch that delegates to a terminal launcher settles when that launcher's\n * whole process chain closes, which on a loaded machine has been measured\n * minutes after the run itself was registered and working. The registry is the\n * earlier and more truthful signal: a run recorded there is a run that started.\n */\nasync function awaitLaunchAck(\n settled: Promise<LaunchOutcome>,\n dependencies: WorkflowLaunchExecutorDependencies,\n query: LaunchedRunQuery,\n): Promise<LaunchAck> {\n const findLaunchedRun = dependencies.findLaunchedRun;\n if (!findLaunchedRun) return { kind: 'settled', outcome: await settled };\n\n const pollMs = dependencies.launchAckPollMs ?? LAUNCH_ACK_POLL_MS;\n const deadline = Date.now() + (dependencies.launchAckTimeoutMs ?? LAUNCH_ACK_TIMEOUT_MS);\n for (;;) {\n const outcome = await Promise.race([settled, sleep(pollMs)]);\n if (outcome) return { kind: 'settled', outcome };\n // A registry read that throws must not fail the launch: the run may be\n // perfectly healthy, and the settled promise is still the fallback.\n const record = await findLaunchedRun(query).catch(() => undefined);\n if (record) return { kind: 'record', record };\n if (Date.now() >= deadline) return { kind: 'handoff' };\n }\n}\n\n/**\n * Carry a failure that lands after the caller was told the run started.\n *\n * Answering early trades the launcher's exit code for timeliness. Dropping that\n * code entirely is not part of the trade: a launch that fails a minute later\n * would otherwise leave a user waiting on a run that never existed.\n */\nfunction reportLateFailure(\n settled: Promise<LaunchOutcome>,\n dependencies: WorkflowLaunchExecutorDependencies,\n ctx: ExtensionContext,\n): void {\n void settled.then((outcome) => {\n if (outcome.kind === 'error') {\n dependencies.onLateFailure?.(asError(outcome.error), ctx);\n return;\n }\n if (outcome.result.isError) {\n dependencies.onLateFailure?.(new Error(toolResultText(outcome.result) || 'Workflow launch failed.'), ctx);\n }\n });\n}\n\nexport function createWorkflowLaunchExecutor(dependencies: WorkflowLaunchExecutorDependencies): WorkflowLaunchExecutor {\n return {\n async execute(input, ctx, onUpdate) {\n const sessionId = resolveRootSessionId(ctx.sessionManager.getSessionId());\n dependencies.observeSession?.(sessionId);\n const agiflowJobKind = input.env?.[AGIFLOW_JOB_KIND_ENV]?.trim();\n const agiflowJobId = input.env?.[AGIFLOW_JOB_ID_ENV]?.trim();\n if (Boolean(agiflowJobKind) !== Boolean(agiflowJobId)) {\n throw new Error('Agiflow workflow launches require AGIFLOW_JOB_KIND and AGIFLOW_JOB_ID together.');\n }\n if (agiflowJobKind && !input.prompt?.trim()) {\n throw new Error(\n 'Agiflow workflow launches require a non-empty prompt so user_prompt runs do not wait for terminal input.',\n );\n }\n reportProgress(onUpdate, LAUNCH_WORKFLOW_TOOL_NAME, 'Checking workflow capacity...');\n const maxConcurrent = resolveMaxConcurrent();\n const active = (await dependencies.activeRunCount?.()) ?? 0;\n if (active >= maxConcurrent) {\n throw new Error(\n withOptions(`This session is at capacity: ${active}/${maxConcurrent} workflows running.`, [\n 'Wait for a running workflow to finish, then launch again. The extension reports each one as it ends.',\n 'workflow_run with action status: show what is running, so the user can judge whether something is stuck.',\n 'workflow_run with action stop: free a slot by stopping a run the user no longer wants.',\n ]),\n );\n }\n\n if (input.runner) {\n const rejection = dependencies.rejectRunner?.(input.workflowPath, input.runner);\n if (rejection) throw new Error(rejection);\n }\n reportProgress(onUpdate, LAUNCH_WORKFLOW_TOOL_NAME, `Launching workflow ${input.workflowPath}...`);\n const workflowEnv = { ...input.env };\n if (process.env.AGIFLOW_DISPATCH_CONTEXT_FILE) {\n for (const key of [\n 'AGIFLOW_ORGANIZATION_ID',\n 'AGIFLOW_PROJECT_ID',\n 'AGIFLOW_DEVICE_ID',\n 'BACKEND_AGIFLOW_API_ENDPOINT',\n 'AGIFLOW_DISPATCH_SECRET_FILE',\n ] as const) {\n const hostValue = process.env[key];\n if (hostValue) workflowEnv[key] = hostValue;\n }\n }\n const since = Date.now();\n const launch = dependencies.trackPendingRun(\n dependencies.runTool.execute({\n ...input,\n env: { ...workflowEnv, [PI_SESSION_ENV]: sessionId },\n }),\n );\n // Folded into a value before anything races it. A promise this function\n // may stop awaiting must never be able to reject unobserved, which in\n // Node ends the whole process, Pi's TUI included.\n const settled: Promise<LaunchOutcome> = launch.then(\n (value): LaunchOutcome => ({ kind: 'value', result: value }),\n (error: unknown): LaunchOutcome => ({ kind: 'error', error }),\n );\n\n const ack = await awaitLaunchAck(settled, dependencies, {\n sessionId,\n since,\n workflowPath: input.workflowPath,\n });\n\n if (ack.kind === 'settled') {\n const outcome = ack.outcome;\n if (outcome.kind === 'error') throw asError(outcome.error);\n const result = outcome.result;\n if (result.isError)\n throw new Error(withOptions(toolResultText(result) || 'Workflow launch failed.', launchFailureOptions));\n await dependencies.onLaunch?.(ctx);\n return result;\n }\n\n reportLateFailure(settled, dependencies, ctx);\n await dependencies.onLaunch?.(ctx);\n return {\n content: [\n {\n type: 'text',\n text: ack.kind === 'record' ? launchedRunSummary(ack.record) : launchHandoffSummary(input.workflowPath),\n },\n ],\n };\n },\n };\n}\n\nexport function registerWorkflowPiTools(pi: ExtensionAPI, dependencies: WorkflowPiToolDependencies = {}): void {\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 activeRunCount: dependencies.activeRunCount,\n onLaunch: dependencies.onLaunch,\n observeSession: dependencies.observeSession,\n rejectRunner: dependencies.rejectRunner,\n runTool,\n trackPendingRun,\n });\n\n pi.registerTool({\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 renderCall: (args, theme) =>\n renderWorkflowToolCall(LIST_WORKFLOWS_TOOL_NAME, args as Record<string, unknown>, theme),\n renderResult: (result, options, theme, context) =>\n renderWorkflowToolResult(\n LIST_WORKFLOWS_TOOL_NAME,\n context.args as Record<string, unknown>,\n result,\n { ...options, isError: context.isError },\n theme,\n ),\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 pi.registerTool({\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_JOB_KIND and AGIFLOW_JOB_ID together through env plus a non-empty prompt. 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 renderCall: (args, theme) =>\n renderWorkflowToolCall(LAUNCH_WORKFLOW_TOOL_NAME, args as Record<string, unknown>, theme),\n renderResult: (result, options, theme, context) =>\n renderWorkflowToolResult(\n LAUNCH_WORKFLOW_TOOL_NAME,\n context.args as Record<string, unknown>,\n result,\n { ...options, isError: context.isError },\n theme,\n ),\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 pi.registerTool({\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 renderCall: (args, theme) => renderWorkflowToolCall(WORKFLOW_RUN_TOOL_NAME, args as Record<string, unknown>, theme),\n renderResult: (result, options, theme, context) =>\n renderWorkflowToolResult(\n WORKFLOW_RUN_TOOL_NAME,\n context.args as Record<string, unknown>,\n result,\n { ...options, isError: context.isError },\n theme,\n ),\n async execute(_toolCallId, rawParams, _signal, onUpdate, ctx) {\n const input = workflowRunInputSchema.parse(rawParams);\n const sessionId = resolveRootSessionId(ctx.sessionManager.getSessionId());\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"],"mappings":"ojBA0BA,MAGM,EAAmB,CACvB,aAAc,GACd,UAAW,GACX,OAAQ,GACR,KAAM,GACN,IAAK,GACL,OAAQ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AAM,EAAW,EAAe,EAAM,OAAQ,EAAM,MAAM,EAE1D,OADA,MAAM,EAAa,WAAW,CAAG,EAC1B,CACL,QAAS,CAAC,CAAE,KAAM,OAAQ,KAAM,CAAC,EAAW,EAAS,EAAE,CAAC,CAAC,KAAK;;CAAM,CAAE,CAAC,EACvE,QAAS,CAAE,KAAM,CAAuB,CAC1C,CACF,CACF,CACA,IAAM,EAAe,CACnB,OAAQ,EAAM,OACd,IAAK,EAAM,IACX,OAAQ,EAAiB,OACzB,OAAQ,EAAM,OACd,UAAW,EAAiB,SAC9B,EACM,EAAS,MAAM,EAAgB,EAAY,QAAQ,CAAY,CAAC,EAChE,EAAW,EAAe,EAAM,OAAQ,EAAM,MAAM,EACpD,EAAU,EAAkB,EAAwB,EAAQ,CAAQ,EAE1E,OADA,MAAM,EAAa,WAAW,CAAG,EAC1B,EAAe,EAAS,EAAS,EAAG,CAC7C,CAEA,IAAM,EAAW,MAAM,EAAgB,EACvC,GAAI,CAAC,EAAS,MAAO,MAAU,MAAM,YAAY,EAAM,OAAO,qCAAqC,EACnG,EAAe,EAAU,EAAwB,cAAc,EAAM,OAAO,gBAAgB,EAAM,OAAO,IAAI,EAC7G,IAAM,EAAS,MAAM,EAAY,QAAQ,CACvC,OAAQ,EAAM,OACd,cAAe,EAAS,MACxB,OAAQ,EAAM,OACd,OAAQ,EAAM,OACd,UAAW,EAAM,SACnB,CAAC,EACK,EAAW,EAAe,EAAM,OAAQ,EAAM,MAAM,EAE1D,OAAO,EADS,EAAkB,EAAwB,EAAQ,CACtC,EAAG,EAAS,EAAG,CAC7C,CACF,CAAC,CACH"}
@@ -0,0 +1,2 @@
1
+ function e(e,t,n,r){let i=n===void 0&&r;i&&e.narrate(`Workflow launched: ${t.displayName}.`),!(n!==`running`&&!i)&&(t.stage===`completed`&&e.narrate(`Workflow succeeded: ${t.displayName}.`),t.stage===`error`&&e.narrate(`Workflow failed: ${t.displayName}.`))}exports.narrateWorkflowTransition=e;
2
+ //# sourceMappingURL=workflowNarration.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workflowNarration.cjs","names":[],"sources":["../../../src/services/workflow/workflowNarration.ts"],"sourcesContent":["import type { NarrationRequester } from '@agimon-ai/doompi-extension-contracts/narration';\nimport type { WorkflowRunRecord, WorkflowStage } from '@agimon-ai/workflow-mcp';\n\nconst RUNNING_STAGE: WorkflowStage = 'running';\nconst COMPLETED_STAGE: WorkflowStage = 'completed';\nconst ERROR_STAGE: WorkflowStage = 'error';\n\ntype NarratedWorkflow = Pick<WorkflowRunRecord, 'displayName' | 'stage'>;\n\n/**\n * Translate an observed workflow lifecycle transition into generic speech.\n * Voice owns delivery and ignores requests while its minor mode is inactive.\n */\nexport function narrateWorkflowTransition(\n requester: NarrationRequester,\n record: NarratedWorkflow,\n previousStage: WorkflowStage | undefined,\n startedDuringSession: boolean,\n): void {\n const newlyLaunched = previousStage === undefined && startedDuringSession;\n if (newlyLaunched) requester.narrate(`Workflow launched: ${record.displayName}.`);\n\n if (previousStage !== RUNNING_STAGE && !newlyLaunched) return;\n if (record.stage === COMPLETED_STAGE) requester.narrate(`Workflow succeeded: ${record.displayName}.`);\n if (record.stage === ERROR_STAGE) requester.narrate(`Workflow failed: ${record.displayName}.`);\n}\n"],"mappings":"AAaA,SAAgB,EACd,EACA,EACA,EACA,EACM,CACN,IAAM,EAAgB,IAAkB,IAAA,IAAa,EACjD,GAAe,EAAU,QAAQ,sBAAsB,EAAO,YAAY,EAAE,EAE5E,MAAkB,WAAiB,CAAC,KACpC,EAAO,QAAU,aAAiB,EAAU,QAAQ,uBAAuB,EAAO,YAAY,EAAE,EAChG,EAAO,QAAU,SAAa,EAAU,QAAQ,oBAAoB,EAAO,YAAY,EAAE,EAC/F"}
@@ -0,0 +1,2 @@
1
+ function e(e,t,n,r){let i=n===void 0&&r;i&&e.narrate(`Workflow launched: ${t.displayName}.`),!(n!==`running`&&!i)&&(t.stage===`completed`&&e.narrate(`Workflow succeeded: ${t.displayName}.`),t.stage===`error`&&e.narrate(`Workflow failed: ${t.displayName}.`))}export{e as narrateWorkflowTransition};
2
+ //# sourceMappingURL=workflowNarration.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workflowNarration.mjs","names":[],"sources":["../../../src/services/workflow/workflowNarration.ts"],"sourcesContent":["import type { NarrationRequester } from '@agimon-ai/doompi-extension-contracts/narration';\nimport type { WorkflowRunRecord, WorkflowStage } from '@agimon-ai/workflow-mcp';\n\nconst RUNNING_STAGE: WorkflowStage = 'running';\nconst COMPLETED_STAGE: WorkflowStage = 'completed';\nconst ERROR_STAGE: WorkflowStage = 'error';\n\ntype NarratedWorkflow = Pick<WorkflowRunRecord, 'displayName' | 'stage'>;\n\n/**\n * Translate an observed workflow lifecycle transition into generic speech.\n * Voice owns delivery and ignores requests while its minor mode is inactive.\n */\nexport function narrateWorkflowTransition(\n requester: NarrationRequester,\n record: NarratedWorkflow,\n previousStage: WorkflowStage | undefined,\n startedDuringSession: boolean,\n): void {\n const newlyLaunched = previousStage === undefined && startedDuringSession;\n if (newlyLaunched) requester.narrate(`Workflow launched: ${record.displayName}.`);\n\n if (previousStage !== RUNNING_STAGE && !newlyLaunched) return;\n if (record.stage === COMPLETED_STAGE) requester.narrate(`Workflow succeeded: ${record.displayName}.`);\n if (record.stage === ERROR_STAGE) requester.narrate(`Workflow failed: ${record.displayName}.`);\n}\n"],"mappings":"AAaA,SAAgB,EACd,EACA,EACA,EACA,EACM,CACN,IAAM,EAAgB,IAAkB,IAAA,IAAa,EACjD,GAAe,EAAU,QAAQ,sBAAsB,EAAO,YAAY,EAAE,EAE5E,MAAkB,WAAiB,CAAC,KACpC,EAAO,QAAU,aAAiB,EAAU,QAAQ,uBAAuB,EAAO,YAAY,EAAE,EAChG,EAAO,QAAU,SAAa,EAAU,QAAQ,oBAAoB,EAAO,YAAY,EAAE,EAC/F"}
@@ -1,2 +1,2 @@
1
- const e=require("./doomOverlay.cjs"),t=require("./workflowStatusRow.cjs");let n=require("@agimon-ai/workflow-mcp"),r=require("@earendil-works/pi-tui");e.DOOM_FULLSCREEN_UI_OPTIONS.overlayOptions;const i=`running`,a=`paused`,o=[[`↑↓/jk`,`select`],[`PgUp/PgDn`,`page`],[`enter`,`open`],[`esc`,`close`]];function s(e,t){let n=(0,r.truncateToWidth)(e,Math.max(0,t),`…`).replaceAll(`\x1B[0m`,``);return n+` `.repeat(Math.max(0,t-(0,r.visibleWidth)(n)))}function c(e,t,n){let i=(0,r.visibleWidth)(t),a=Math.max(0,n-i-1);return s(e,a)+` `.repeat(Math.max(1,n-a-i))+s(t,i)}function l(e){return e===`completed`?`✓`:e===`failed`?`✗`:`●`}function u(e){return e===`completed`?`success`:e===`failed`?`error`:`accent`}function d(e,t,n){let a=[];for(let o of e.jobs){let e=o.total?` · ${(o.index??0)+1}/${o.total}`:``;if(a.push((0,r.truncateToWidth)(n.fg(u(o.status),`${l(o.status)} ${o.name}`)+n.fg(`dim`,e),t,`…`)),o.status===i)for(let e of o.steps){let o=e.status===`failed`?`error`:e.status===i?`muted`:`dim`;a.push((0,r.truncateToWidth)(n.fg(o,` ${l(e.status)} ${e.name}`),t,`…`))}}return a}function f(e,o,s,l){if(!e)return[l.fg(`dim`,`Select a workflow to inspect its jobs and output.`)];let u=(0,n.currentWorkflowPosition)(e.jobs),f=t.humanizeDuration(Math.max(0,Date.now()-Date.parse(e.startedAt))),p=e.executionState??i,m=p===a?`warning`:`dim`,h=[c(`${l.fg(`accent`,`●`)} ${l.bold(e.displayName)}`,l.fg(m,p),o),(0,r.truncateToWidth)(l.fg(`dim`,`${e.runKey} · ${e.workspace} · ${f}`),o,`…`),u?(0,r.truncateToWidth)(`${l.fg(`accent`,u.job)}${u.step?l.fg(`muted`,` · ${u.step}`):``}`,o,`…`):l.fg(`dim`,`starting`),``,l.fg(`dim`,`PROGRESS`)],g=e.output.length>0?3:0,_=Math.max(0,s-h.length-g);if(h.push(...d(e,o,l).slice(0,_)),e.output.length>0&&s-h.length>=2){h.push(``,l.fg(`dim`,`OUTPUT · newest last`));let t=Math.max(0,s-h.length);h.push(...e.output.slice(-t).map(e=>(0,r.truncateToWidth)(e,o,`…`)))}return h.slice(0,s)}var p=class extends e.DoomOverlay{source;done;bodyHeight=8;completed=!1;error;items=[];refreshActive=!1;selected=0;selectedKey;timer;constructor(e,t,n,r,i={}){super(e,t),this.source=n,this.done=r,this.selectedKey=i.initialKey,this.refresh(),this.timer=setInterval(()=>void this.refresh(),i.refreshMs??750),this.timer.unref?.()}async refresh(){if(!(this.refreshActive||this.completed)){this.refreshActive=!0;try{let e=this.items[this.selected]?.key??this.selectedKey,t=await this.source.list();if(this.completed)return;let n=e?t.findIndex(t=>t.key===e):-1;this.items=t,this.selected=n>=0?n:Math.min(this.selected,Math.max(0,t.length-1)),this.selectedKey=t[this.selected]?.key;let r=t[this.selected];r&&(r.output=await this.source.output(r)),this.error=void 0,this.completed||this.tui.requestRender()}catch(e){this.error=e instanceof Error?e.message:String(e),this.completed||this.tui.requestRender()}finally{this.refreshActive=!1}}}move(e){this.items.length!==0&&(this.selected=Math.max(0,Math.min(this.items.length-1,this.selected+e)),this.selectedKey=this.items[this.selected]?.key,this.refreshSelectedOutput(),this.tui.requestRender())}async refreshSelectedOutput(){let e=this.items[this.selected];if(!(!e||this.completed)){try{e.output=await this.source.output(e),this.error=void 0}catch(e){this.error=e instanceof Error?e.message:String(e)}!this.completed&&e.key===this.selectedKey&&this.tui.requestRender()}}finish(e){this.completed||(this.completed=!0,clearInterval(this.timer),this.done(e))}close(){this.finish(void 0)}handleInput(e){if((0,r.matchesKey)(e,`escape`)||(0,r.matchesKey)(e,`ctrl+c`)){this.finish(void 0);return}if((0,r.matchesKey)(e,`up`)||e===`k`){this.move(-1);return}if((0,r.matchesKey)(e,`down`)||e===`j`){this.move(1);return}if((0,r.matchesKey)(e,`pageUp`)){this.move(-this.rosterCapacity());return}if((0,r.matchesKey)(e,`pageDown`)){this.move(this.rosterCapacity());return}if((0,r.matchesKey)(e,`enter`)){let e=this.items[this.selected];e&&this.finish({...e.runId?{runId:e.runId}:{},runKey:e.runKey,startedAt:e.startedAt,workspace:e.workspace})}}rosterCapacity(){return Math.max(1,Math.floor((this.bodyHeight-2)/2))}current(){if(this.items.length!==0)return this.items[Math.min(this.selected,this.items.length-1)]}getChrome(){let t=this.current(),n=t?`${t.displayName} · ${t.executionState??i}`:`no active workflows`;return{title:`WORKFLOW SPACE`,accent:e.DOOM_OVERLAY_ACCENT,breadcrumb:`SPC › w / workflows › l / manage`,headerRight:`${this.items.length} running · ${n}`,footer:`↑↓/jk select · PgUp/PgDn page · enter open · esc close`,footerHints:o,footerRight:this.items.length>0?`${Math.min(this.selected,this.items.length-1)+1}/${this.items.length}`:`empty`}}renderBody(e,t){this.bodyHeight=t;let n=e=>this.error?[this.theme.fg(`warning`,`Unable to refresh workflows: ${this.error}`)]:f(this.current(),e,t,this.theme);if(e<48)return n(e).slice(0,t);let i=Math.max(18,Math.floor((e-1)*.3333333333333333)),a=Math.max(1,e-i-1),o=Math.max(1,i-1),c=Math.max(1,a-1),l=this.rosterLines(o),u=n(c),d=this.theme.fg(`borderMuted`,`│`);return Array.from({length:t},(t,n)=>{let i=`${s(l[n]??``,o)} ${d} ${s(u[n]??``,c)}`;return(0,r.truncateToWidth)(i,e,`…`)})}rosterLines(e){let t=[this.theme.bold(`RUNNING · this session`),``];if(this.items.length===0)return t.push(this.theme.fg(`dim`,`No active workflows`)),t;let r=this.rosterCapacity(),i=Math.min(this.selected,this.items.length-1),o=Math.max(0,Math.min(i-r+1,Math.max(0,this.items.length-r)));for(let[c,l]of this.items.slice(o,o+r).entries()){let r=o+c===i,u=l.executionState===a,d=r?this.theme.fg(`accent`,`›`):` `,f=this.theme.fg(u?`warning`:`accent`,`●`),p=r?this.theme.bold(l.displayName):l.displayName,m=u?a:(0,n.currentWorkflowPosition)(l.jobs)?.job??`starting`,h=`${d} ${f} ${p}`,g=`${` `.repeat(4)}${this.theme.fg(u?`warning`:`dim`,m)}`,_=r?`selectedBg`:`userMessageBg`;for(let n of[h,g])t.push(this.theme.bg(_,s(n,e)))}return t}invalidate(){this.refresh()}dispose(){this.completed||(this.completed=!0,clearInterval(this.timer))}};exports.WorkflowInspectorComponent=p;
1
+ const e=require("./doomOverlay.cjs"),t=require("./workflowStatusRow.cjs");let n=require("@agimon-ai/workflow-mcp"),r=require("@earendil-works/pi-tui");e.DOOM_FULLSCREEN_UI_OPTIONS.overlayOptions;const i=`running`,a=`paused`,o=`↑↓`,s=`${o} select · PgUp/PgDn page · enter open · esc close`,c=[[o,`select`],[`PgUp/PgDn`,`page`],[`enter`,`open`],[`esc`,`close`]];function l(e,t){let n=(0,r.truncateToWidth)(e,Math.max(0,t),`…`).replaceAll(`\x1B[0m`,``);return n+` `.repeat(Math.max(0,t-(0,r.visibleWidth)(n)))}function u(e,t,n){let i=(0,r.visibleWidth)(t),a=Math.max(0,n-i-1);return l(e,a)+` `.repeat(Math.max(1,n-a-i))+l(t,i)}function d(e){return e===`completed`?`✓`:e===`failed`?`✗`:`●`}function f(e){return e===`completed`?`success`:e===`failed`?`error`:`accent`}function p(e,t,n){let a=[];for(let o of e.jobs){let e=o.total?` · ${(o.index??0)+1}/${o.total}`:``;if(a.push((0,r.truncateToWidth)(n.fg(f(o.status),`${d(o.status)} ${o.name}`)+n.fg(`dim`,e),t,`…`)),o.status===i)for(let e of o.steps){let o=e.status===`failed`?`error`:e.status===i?`muted`:`dim`;a.push((0,r.truncateToWidth)(n.fg(o,` ${d(e.status)} ${e.name}`),t,`…`))}}return a}function m(e,o,s,c){if(!e)return[c.fg(`dim`,`Select a workflow to inspect its jobs and output.`)];let l=(0,n.currentWorkflowPosition)(e.jobs),d=t.humanizeDuration(Math.max(0,Date.now()-Date.parse(e.startedAt))),f=e.executionState??i,m=f===a?`warning`:`dim`,h=[u(`${c.fg(`accent`,`●`)} ${c.bold(e.displayName)}`,c.fg(m,f),o),(0,r.truncateToWidth)(c.fg(`dim`,`${e.runKey} · ${e.workspace} · ${d}`),o,`…`),l?(0,r.truncateToWidth)(`${c.fg(`accent`,l.job)}${l.step?c.fg(`muted`,` · ${l.step}`):``}`,o,`…`):c.fg(`dim`,`starting`),``,c.fg(`dim`,`PROGRESS`)],g=e.output.length>0?3:0,_=Math.max(0,s-h.length-g);if(h.push(...p(e,o,c).slice(0,_)),e.output.length>0&&s-h.length>=2){h.push(``,c.fg(`dim`,`OUTPUT · newest last`));let t=Math.max(0,s-h.length);h.push(...e.output.slice(-t).map(e=>(0,r.truncateToWidth)(e,o,`…`)))}return h.slice(0,s)}var h=class extends e.DoomOverlay{source;done;bodyHeight=8;completed=!1;error;items=[];refreshActive=!1;selected=0;selectedKey;timer;constructor(e,t,n,r,i={}){super(e,t),this.source=n,this.done=r,this.selectedKey=i.initialKey,this.refresh(),this.timer=setInterval(()=>void this.refresh(),i.refreshMs??750),this.timer.unref?.()}async refresh(){if(!(this.refreshActive||this.completed)){this.refreshActive=!0;try{let e=this.items[this.selected]?.key??this.selectedKey,t=await this.source.list();if(this.completed)return;let n=e?t.findIndex(t=>t.key===e):-1;this.items=t,this.selected=n>=0?n:Math.min(this.selected,Math.max(0,t.length-1)),this.selectedKey=t[this.selected]?.key;let r=t[this.selected];r&&(r.output=await this.source.output(r)),this.error=void 0,this.completed||this.tui.requestRender()}catch(e){this.error=e instanceof Error?e.message:String(e),this.completed||this.tui.requestRender()}finally{this.refreshActive=!1}}}move(e){this.items.length!==0&&(this.selected=Math.max(0,Math.min(this.items.length-1,this.selected+e)),this.selectedKey=this.items[this.selected]?.key,this.refreshSelectedOutput(),this.tui.requestRender())}async refreshSelectedOutput(){let e=this.items[this.selected];if(!(!e||this.completed)){try{e.output=await this.source.output(e),this.error=void 0}catch(e){this.error=e instanceof Error?e.message:String(e)}!this.completed&&e.key===this.selectedKey&&this.tui.requestRender()}}finish(e){this.completed||(this.completed=!0,clearInterval(this.timer),this.done(e))}close(){this.finish(void 0)}handleInput(e){if((0,r.matchesKey)(e,`escape`)||(0,r.matchesKey)(e,`ctrl+c`)){this.finish(void 0);return}if((0,r.matchesKey)(e,`up`)||e===`k`){this.move(-1);return}if((0,r.matchesKey)(e,`down`)||e===`j`){this.move(1);return}if((0,r.matchesKey)(e,`pageUp`)){this.move(-this.rosterCapacity());return}if((0,r.matchesKey)(e,`pageDown`)){this.move(this.rosterCapacity());return}if((0,r.matchesKey)(e,`enter`)){let e=this.items[this.selected];e&&this.finish({...e.runId?{runId:e.runId}:{},runKey:e.runKey,startedAt:e.startedAt,workspace:e.workspace})}}rosterCapacity(){return Math.max(1,Math.floor((this.bodyHeight-2)/2))}current(){if(this.items.length!==0)return this.items[Math.min(this.selected,this.items.length-1)]}getChrome(){let t=this.current(),n=t?`${t.displayName} · ${t.executionState??i}`:`no active workflows`;return{title:`WORKFLOW SPACE`,accent:e.DOOM_OVERLAY_ACCENT,breadcrumb:`SPC › w / workflows › l / manage`,headerRight:`${this.items.length} running · ${n}`,footer:s,footerHints:c,footerRight:this.items.length>0?`${Math.min(this.selected,this.items.length-1)+1}/${this.items.length}`:`empty`}}renderBody(e,t){this.bodyHeight=t;let n=e=>this.error?[this.theme.fg(`warning`,`Unable to refresh workflows: ${this.error}`)]:m(this.current(),e,t,this.theme);if(e<48)return n(e).slice(0,t);let i=Math.max(18,Math.floor((e-1)*.3333333333333333)),a=Math.max(1,e-i-1),o=Math.max(1,i-1),s=Math.max(1,a-1),c=this.rosterLines(o),u=n(s),d=this.theme.fg(`borderMuted`,`│`);return Array.from({length:t},(t,n)=>{let i=`${l(c[n]??``,o)} ${d} ${l(u[n]??``,s)}`;return(0,r.truncateToWidth)(i,e,`…`)})}rosterLines(e){let t=[this.theme.bold(`RUNNING · this session`),``];if(this.items.length===0)return t.push(this.theme.fg(`dim`,`No active workflows`)),t;let r=this.rosterCapacity(),i=Math.min(this.selected,this.items.length-1),o=Math.max(0,Math.min(i-r+1,Math.max(0,this.items.length-r)));for(let[s,c]of this.items.slice(o,o+r).entries()){let r=o+s===i,u=c.executionState===a,d=r?this.theme.fg(`accent`,`›`):` `,f=this.theme.fg(u?`warning`:`accent`,`●`),p=r?this.theme.bold(c.displayName):c.displayName,m=u?a:(0,n.currentWorkflowPosition)(c.jobs)?.job??`starting`,h=`${d} ${f} ${p}`,g=`${` `.repeat(4)}${this.theme.fg(u?`warning`:`dim`,m)}`,_=r?`selectedBg`:`userMessageBg`;for(let n of[h,g])t.push(this.theme.bg(_,l(n,e)))}return t}invalidate(){this.refresh()}dispose(){this.completed||(this.completed=!0,clearInterval(this.timer))}};exports.WorkflowInspectorComponent=h;
2
2
  //# sourceMappingURL=workflowInspector.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"workflowInspector.cjs","names":["DOOM_FULLSCREEN_UI_OPTIONS","truncateToWidth","visibleWidth","currentWorkflowPosition","humanizeDuration","DoomOverlay","matchesKey","DOOM_OVERLAY_ACCENT"],"sources":["../../../src/tui/workflow/workflowInspector.ts"],"sourcesContent":["/**\n * Workflow Space: the `SPC w l` overlay.\n *\n * A doom overlay rather than a hand-rolled frame: the roster owns the left\n * third, the run under the cursor owns the right two thirds, and the chrome is\n * the same frame, breadcrumb and key legend every other doom surface draws.\n *\n * Rendering is pure -- `renderBody(width, height)` reads the last polled\n * snapshot and returns lines with no side effects -- so the surface can be\n * asserted as text without a live terminal.\n */\n\nimport { currentWorkflowPosition, type WorkflowProgressJob } from '@agimon-ai/workflow-mcp';\nimport type { Theme } from '@earendil-works/pi-coding-agent';\nimport { matchesKey, truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';\nimport {\n DOOM_FULLSCREEN_UI_OPTIONS,\n DOOM_OVERLAY_ACCENT,\n DoomOverlay,\n type DoomOverlayChrome,\n type DoomOverlayTui,\n} from './doomOverlay.ts';\nimport { humanizeDuration } from './workflowStatusRow';\n\nexport const WORKFLOW_INSPECTOR_OVERLAY_OPTIONS = DOOM_FULLSCREEN_UI_OPTIONS.overlayOptions;\n\nexport interface WorkflowInspectorSelection {\n runId?: string;\n runKey: string;\n startedAt: string;\n workspace: string;\n}\n\nexport interface WorkflowInspectorItem extends WorkflowInspectorSelection {\n displayName: string;\n executionState?: string;\n jobs: WorkflowProgressJob[];\n key: string;\n output: string[];\n}\n\nexport interface WorkflowInspectorSource {\n list(): Promise<WorkflowInspectorItem[]>;\n output(item: WorkflowInspectorItem): Promise<string[]>;\n}\n\nexport interface WorkflowInspectorOptions {\n initialKey?: string;\n refreshMs?: number;\n}\n\nconst TITLE = 'WORKFLOW SPACE';\nconst BREADCRUMB = 'SPC › w / workflows › l / manage';\nconst ROSTER_HEADING = 'RUNNING · this session';\nconst EMPTY_ROSTER = 'No active workflows';\nconst PROGRESS_HEADING = 'PROGRESS';\nconst OUTPUT_HEADING = 'OUTPUT · newest last';\nconst NO_SELECTION = 'Select a workflow to inspect its jobs and output.';\nconst RUNNING_STATE = 'running';\nconst PAUSED_STATE = 'paused';\nconst FOOTER = '↑↓/jk select · PgUp/PgDn page · enter open · esc close';\nconst FOOTER_HINTS: readonly (readonly [string, string])[] = [\n ['↑↓/jk', 'select'],\n ['PgUp/PgDn', 'page'],\n ['enter', 'open'],\n ['esc', 'close'],\n];\n\nconst DEFAULT_REFRESH_MS = 750;\nconst SELECTION_MARKER = '›';\nconst ELLIPSIS = '…';\n/** pi-tui brackets a truncation ellipsis with this; see `fit`. */\nconst HARD_RESET = '\\x1b[0m';\n/** A third for the roster, two thirds for the run being read. */\nconst LIST_PANE_RATIO = 1 / 3;\n/** One blank column each side of the divider so neither pane touches it. */\nconst PANE_GUTTER = 1;\nconst MIN_PANE_WIDTH = 18;\n/** Below this the roster cannot hold a readable name, so the detail takes the body. */\nconst MIN_TWO_PANE_WIDTH = 48;\n/** Each run occupies a name row and a state row beneath it. */\nconst ROWS_PER_ITEM = 2;\n/** Hanging indent for the state row: clears the marker and the glyph. */\nconst META_INDENT = 4;\n/** Rows the roster heading and its spacer take. */\nconst ROSTER_CHROME_ROWS = 2;\n/** The output tail keeps at least this many rows, or it is not worth a divider. */\nconst MIN_OUTPUT_ROWS = 2;\n\n/** Neither palette name is exported, so take both from the theme's methods. */\ntype ThemeBg = Parameters<Theme['bg']>[0];\ntype ThemeColor = Parameters<Theme['fg']>[0];\n\n/**\n * Truncates and pads to an exact column count.\n *\n * `truncateToWidth` wraps its ellipsis in a hard `\\x1b[0m`, which would strip a\n * row's background for everything after a clipped name. The theme closes its own\n * colours with `\\x1b[39m` and `\\x1b[49m`, so the injected resets are dropped.\n */\nfunction fit(text: string, width: number): string {\n const clipped = truncateToWidth(text, Math.max(0, width), ELLIPSIS).replaceAll(HARD_RESET, '');\n return clipped + ' '.repeat(Math.max(0, width - visibleWidth(clipped)));\n}\n\nfunction rightAligned(left: string, right: string, width: number): string {\n const rightWidth = visibleWidth(right);\n const leftWidth = Math.max(0, width - rightWidth - 1);\n return fit(left, leftWidth) + ' '.repeat(Math.max(1, width - leftWidth - rightWidth)) + fit(right, rightWidth);\n}\n\nfunction jobGlyph(status: string): string {\n return status === 'completed' ? '✓' : status === 'failed' ? '✗' : '●';\n}\n\nfunction jobColour(status: string): ThemeColor {\n return status === 'completed' ? 'success' : status === 'failed' ? 'error' : 'accent';\n}\n\nfunction progressLines(item: WorkflowInspectorItem, width: number, theme: Theme): string[] {\n const lines: string[] = [];\n for (const job of item.jobs) {\n const position = job.total ? ` · ${(job.index ?? 0) + 1}/${job.total}` : '';\n lines.push(\n truncateToWidth(\n theme.fg(jobColour(job.status), `${jobGlyph(job.status)} ${job.name}`) + theme.fg('dim', position),\n width,\n ELLIPSIS,\n ),\n );\n // Only the running job's steps: every finished job's steps would push the\n // live one off the pane, which is the one thing worth watching.\n if (job.status !== RUNNING_STATE) continue;\n for (const step of job.steps) {\n const stepColour: ThemeColor =\n step.status === 'failed' ? 'error' : step.status === RUNNING_STATE ? 'muted' : 'dim';\n lines.push(truncateToWidth(theme.fg(stepColour, ` ${jobGlyph(step.status)} ${step.name}`), width, ELLIPSIS));\n }\n }\n return lines;\n}\n\nfunction detailLines(item: WorkflowInspectorItem | undefined, width: number, height: number, theme: Theme): string[] {\n if (!item) return [theme.fg('dim', NO_SELECTION)];\n\n const position = currentWorkflowPosition(item.jobs);\n const elapsed = humanizeDuration(Math.max(0, Date.now() - Date.parse(item.startedAt)));\n const executionState = item.executionState ?? RUNNING_STATE;\n const stateColour: ThemeColor = executionState === PAUSED_STATE ? 'warning' : 'dim';\n const lines = [\n rightAligned(\n `${theme.fg('accent', '●')} ${theme.bold(item.displayName)}`,\n theme.fg(stateColour, executionState),\n width,\n ),\n truncateToWidth(theme.fg('dim', `${item.runKey} · ${item.workspace} · ${elapsed}`), width, ELLIPSIS),\n position\n ? truncateToWidth(\n `${theme.fg('accent', position.job)}${position.step ? theme.fg('muted', ` · ${position.step}`) : ''}`,\n width,\n ELLIPSIS,\n )\n : theme.fg('dim', 'starting'),\n '',\n theme.fg('dim', PROGRESS_HEADING),\n ];\n\n // The output tail claims its rows first: progress is a list that can be paged\n // to by opening the run, while the tail is the only live signal on screen.\n const reservedOutput = item.output.length > 0 ? MIN_OUTPUT_ROWS + 1 : 0;\n const progressRoom = Math.max(0, height - lines.length - reservedOutput);\n lines.push(...progressLines(item, width, theme).slice(0, progressRoom));\n\n if (item.output.length > 0 && height - lines.length >= MIN_OUTPUT_ROWS) {\n lines.push('', theme.fg('dim', OUTPUT_HEADING));\n const outputRoom = Math.max(0, height - lines.length);\n lines.push(...item.output.slice(-outputRoom).map((line) => truncateToWidth(line, width, ELLIPSIS)));\n }\n\n return lines.slice(0, height);\n}\n\nexport class WorkflowInspectorComponent extends DoomOverlay {\n private bodyHeight = 8;\n private completed = false;\n private error: string | undefined;\n private items: WorkflowInspectorItem[] = [];\n private refreshActive = false;\n private selected = 0;\n private selectedKey: string | undefined;\n private readonly timer: ReturnType<typeof setInterval>;\n\n constructor(\n tui: DoomOverlayTui,\n theme: Theme,\n private readonly source: WorkflowInspectorSource,\n private readonly done: (selection: WorkflowInspectorSelection | undefined) => void,\n options: WorkflowInspectorOptions = {},\n ) {\n super(tui, theme);\n this.selectedKey = options.initialKey;\n void this.refresh();\n this.timer = setInterval(() => void this.refresh(), options.refreshMs ?? DEFAULT_REFRESH_MS);\n this.timer.unref?.();\n }\n\n private async refresh(): Promise<void> {\n if (this.refreshActive || this.completed) return;\n this.refreshActive = true;\n try {\n const previousKey = this.items[this.selected]?.key ?? this.selectedKey;\n const items = await this.source.list();\n if (this.completed) return;\n const preserved = previousKey ? items.findIndex((item) => item.key === previousKey) : -1;\n this.items = items;\n this.selected = preserved >= 0 ? preserved : Math.min(this.selected, Math.max(0, items.length - 1));\n this.selectedKey = items[this.selected]?.key;\n const selected = items[this.selected];\n if (selected) selected.output = await this.source.output(selected);\n this.error = undefined;\n if (!this.completed) this.tui.requestRender();\n } catch (cause) {\n this.error = cause instanceof Error ? cause.message : String(cause);\n if (!this.completed) this.tui.requestRender();\n } finally {\n this.refreshActive = false;\n }\n }\n\n private move(delta: number): void {\n if (this.items.length === 0) return;\n this.selected = Math.max(0, Math.min(this.items.length - 1, this.selected + delta));\n this.selectedKey = this.items[this.selected]?.key;\n void this.refreshSelectedOutput();\n this.tui.requestRender();\n }\n\n private async refreshSelectedOutput(): Promise<void> {\n const selected = this.items[this.selected];\n if (!selected || this.completed) return;\n try {\n selected.output = await this.source.output(selected);\n this.error = undefined;\n } catch (cause) {\n this.error = cause instanceof Error ? cause.message : String(cause);\n }\n if (!this.completed && selected.key === this.selectedKey) this.tui.requestRender();\n }\n\n private finish(selection: WorkflowInspectorSelection | undefined): void {\n if (this.completed) return;\n this.completed = true;\n clearInterval(this.timer);\n this.done(selection);\n }\n\n close(): void {\n this.finish(undefined);\n }\n\n handleInput(data: string): void {\n if (matchesKey(data, 'escape') || matchesKey(data, 'ctrl+c')) {\n this.finish(undefined);\n return;\n }\n if (matchesKey(data, 'up') || data === 'k') {\n this.move(-1);\n return;\n }\n if (matchesKey(data, 'down') || data === 'j') {\n this.move(1);\n return;\n }\n if (matchesKey(data, 'pageUp')) {\n this.move(-this.rosterCapacity());\n return;\n }\n if (matchesKey(data, 'pageDown')) {\n this.move(this.rosterCapacity());\n return;\n }\n if (matchesKey(data, 'enter')) {\n const selected = this.items[this.selected];\n if (selected) {\n this.finish({\n ...(selected.runId ? { runId: selected.runId } : {}),\n runKey: selected.runKey,\n startedAt: selected.startedAt,\n workspace: selected.workspace,\n });\n }\n }\n }\n\n /** Runs the roster can draw, which is also what a page key moves by. */\n private rosterCapacity(): number {\n return Math.max(1, Math.floor((this.bodyHeight - ROSTER_CHROME_ROWS) / ROWS_PER_ITEM));\n }\n\n private current(): WorkflowInspectorItem | undefined {\n if (this.items.length === 0) return undefined;\n return this.items[Math.min(this.selected, this.items.length - 1)];\n }\n\n protected getChrome(): DoomOverlayChrome {\n const selected = this.current();\n const summary = selected\n ? `${selected.displayName} · ${selected.executionState ?? RUNNING_STATE}`\n : 'no active workflows';\n return {\n title: TITLE,\n accent: DOOM_OVERLAY_ACCENT,\n breadcrumb: BREADCRUMB,\n headerRight: `${this.items.length} running · ${summary}`,\n footer: FOOTER,\n footerHints: FOOTER_HINTS,\n footerRight:\n this.items.length > 0 ? `${Math.min(this.selected, this.items.length - 1) + 1}/${this.items.length}` : 'empty',\n };\n }\n\n protected renderBody(width: number, height: number): string[] {\n this.bodyHeight = height;\n const detailFor = (paneWidth: number): string[] =>\n this.error\n ? [this.theme.fg('warning', `Unable to refresh workflows: ${this.error}`)]\n : detailLines(this.current(), paneWidth, height, this.theme);\n\n // Too narrow for two useful columns: the detail takes the whole body rather\n // than shredding both panes into stubs.\n if (width < MIN_TWO_PANE_WIDTH) return detailFor(width).slice(0, height);\n\n const leftWidth = Math.max(MIN_PANE_WIDTH, Math.floor((width - 1) * LIST_PANE_RATIO));\n const rightWidth = Math.max(1, width - leftWidth - 1);\n const leftContent = Math.max(1, leftWidth - PANE_GUTTER);\n const rightContent = Math.max(1, rightWidth - PANE_GUTTER);\n\n const left = this.rosterLines(leftContent);\n const right = detailFor(rightContent);\n const divider = this.theme.fg('borderMuted', '│');\n return Array.from({ length: height }, (_, index) => {\n const row = `${fit(left[index] ?? '', leftContent)} ${divider} ${fit(right[index] ?? '', rightContent)}`;\n return truncateToWidth(row, width, ELLIPSIS);\n });\n }\n\n private rosterLines(width: number): string[] {\n const lines = [this.theme.bold(ROSTER_HEADING), ''];\n if (this.items.length === 0) {\n lines.push(this.theme.fg('dim', EMPTY_ROSTER));\n return lines;\n }\n\n // Two rows per run: at a third of the width a single row left the name with\n // a handful of columns once the stage took its share.\n const budget = this.rosterCapacity();\n const active = Math.min(this.selected, this.items.length - 1);\n const start = Math.max(0, Math.min(active - budget + 1, Math.max(0, this.items.length - budget)));\n for (const [offset, item] of this.items.slice(start, start + budget).entries()) {\n const current = start + offset === active;\n const paused = item.executionState === PAUSED_STATE;\n const marker = current ? this.theme.fg('accent', SELECTION_MARKER) : ' ';\n const glyph = this.theme.fg(paused ? 'warning' : 'accent', '●');\n const name = current ? this.theme.bold(item.displayName) : item.displayName;\n const stage = paused ? PAUSED_STATE : (currentWorkflowPosition(item.jobs)?.job ?? 'starting');\n const heading = `${marker} ${glyph} ${name}`;\n const meta = `${' '.repeat(META_INDENT)}${this.theme.fg(paused ? 'warning' : 'dim', stage)}`;\n const background: ThemeBg = current ? 'selectedBg' : 'userMessageBg';\n for (const row of [heading, meta]) lines.push(this.theme.bg(background, fit(row, width)));\n }\n return lines;\n }\n\n /** Overridden: a repaint request is also the cue to re-read the registry. */\n invalidate(): void {\n void this.refresh();\n }\n\n dispose(): void {\n if (this.completed) return;\n this.completed = true;\n clearInterval(this.timer);\n }\n}\n"],"mappings":"uJAwBkDA,EAAAA,2BAA2B,eA2B7E,MAOM,EAAgB,UAChB,EAAe,SAEf,EAAuD,CAC3D,CAAC,QAAS,QAAQ,EAClB,CAAC,YAAa,MAAM,EACpB,CAAC,QAAS,MAAM,EAChB,CAAC,MAAO,OAAO,CACjB,EAkCA,SAAS,EAAI,EAAc,EAAuB,CAChD,IAAM,GAAA,EAAUC,EAAAA,gBAAAA,CAAgB,EAAM,KAAK,IAAI,EAAG,CAAK,EA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AAK,EAAK,WAAW,EAAI,EAAK,YAC1D,EAAQ,EAAS,GAAA,EAAgBE,EAAAA,wBAAAA,CAAwB,EAAK,IAAI,CAAC,EAAE,KAAO,WAC5E,EAAU,GAAG,EAAO,GAAG,EAAM,GAAG,IAChC,EAAO,GAAG,IAAI,OAAO,CAAW,IAAI,KAAK,MAAM,GAAG,EAAS,UAAY,MAAO,CAAK,IACnF,EAAsB,EAAU,aAAe,gBACrD,IAAK,IAAM,IAAO,CAAC,EAAS,CAAI,EAAG,EAAM,KAAK,KAAK,MAAM,GAAG,EAAY,EAAI,EAAK,CAAK,CAAC,CAAC,CAC1F,CACA,OAAO,CACT,CAGA,YAAmB,CACjB,KAAU,QAAQ,CACpB,CAEA,SAAgB,CACV,KAAK,YACT,KAAK,UAAY,GACjB,cAAc,KAAK,KAAK,EAC1B,CACF"}
1
+ {"version":3,"file":"workflowInspector.cjs","names":["DOOM_FULLSCREEN_UI_OPTIONS","truncateToWidth","visibleWidth","currentWorkflowPosition","humanizeDuration","DoomOverlay","matchesKey","DOOM_OVERLAY_ACCENT"],"sources":["../../../src/tui/workflow/workflowInspector.ts"],"sourcesContent":["/**\n * Workflow Space: the `SPC w l` overlay.\n *\n * A doom overlay rather than a hand-rolled frame: the roster owns the left\n * third, the run under the cursor owns the right two thirds, and the chrome is\n * the same frame, breadcrumb and key legend every other doom surface draws.\n *\n * Rendering is pure -- `renderBody(width, height)` reads the last polled\n * snapshot and returns lines with no side effects -- so the surface can be\n * asserted as text without a live terminal.\n */\n\nimport { currentWorkflowPosition, type WorkflowProgressJob } from '@agimon-ai/workflow-mcp';\nimport type { Theme } from '@earendil-works/pi-coding-agent';\nimport { matchesKey, truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';\nimport {\n DOOM_FULLSCREEN_UI_OPTIONS,\n DOOM_OVERLAY_ACCENT,\n DoomOverlay,\n type DoomOverlayChrome,\n type DoomOverlayTui,\n} from './doomOverlay.ts';\nimport { humanizeDuration } from './workflowStatusRow';\n\nexport const WORKFLOW_INSPECTOR_OVERLAY_OPTIONS = DOOM_FULLSCREEN_UI_OPTIONS.overlayOptions;\n\nexport interface WorkflowInspectorSelection {\n runId?: string;\n runKey: string;\n startedAt: string;\n workspace: string;\n}\n\nexport interface WorkflowInspectorItem extends WorkflowInspectorSelection {\n displayName: string;\n executionState?: string;\n jobs: WorkflowProgressJob[];\n key: string;\n output: string[];\n}\n\nexport interface WorkflowInspectorSource {\n list(): Promise<WorkflowInspectorItem[]>;\n output(item: WorkflowInspectorItem): Promise<string[]>;\n}\n\nexport interface WorkflowInspectorOptions {\n initialKey?: string;\n refreshMs?: number;\n}\n\nconst TITLE = 'WORKFLOW SPACE';\nconst BREADCRUMB = 'SPC › w / workflows › l / manage';\nconst ROSTER_HEADING = 'RUNNING · this session';\nconst EMPTY_ROSTER = 'No active workflows';\nconst PROGRESS_HEADING = 'PROGRESS';\nconst OUTPUT_HEADING = 'OUTPUT · newest last';\nconst NO_SELECTION = 'Select a workflow to inspect its jobs and output.';\nconst RUNNING_STATE = 'running';\nconst PAUSED_STATE = 'paused';\n/** Mirrors DoomPi's list-navigation legend without adding a runtime doompi-ui dependency. */\nconst LIST_NAVIGATION_KEYS = '↑↓';\nconst FOOTER = `${LIST_NAVIGATION_KEYS} select · PgUp/PgDn page · enter open · esc close`;\nconst FOOTER_HINTS: readonly (readonly [string, string])[] = [\n [LIST_NAVIGATION_KEYS, 'select'],\n ['PgUp/PgDn', 'page'],\n ['enter', 'open'],\n ['esc', 'close'],\n];\n\nconst DEFAULT_REFRESH_MS = 750;\nconst SELECTION_MARKER = '›';\nconst ELLIPSIS = '…';\n/** pi-tui brackets a truncation ellipsis with this; see `fit`. */\nconst HARD_RESET = '\\x1b[0m';\n/** A third for the roster, two thirds for the run being read. */\nconst LIST_PANE_RATIO = 1 / 3;\n/** One blank column each side of the divider so neither pane touches it. */\nconst PANE_GUTTER = 1;\nconst MIN_PANE_WIDTH = 18;\n/** Below this the roster cannot hold a readable name, so the detail takes the body. */\nconst MIN_TWO_PANE_WIDTH = 48;\n/** Each run occupies a name row and a state row beneath it. */\nconst ROWS_PER_ITEM = 2;\n/** Hanging indent for the state row: clears the marker and the glyph. */\nconst META_INDENT = 4;\n/** Rows the roster heading and its spacer take. */\nconst ROSTER_CHROME_ROWS = 2;\n/** The output tail keeps at least this many rows, or it is not worth a divider. */\nconst MIN_OUTPUT_ROWS = 2;\n\n/** Neither palette name is exported, so take both from the theme's methods. */\ntype ThemeBg = Parameters<Theme['bg']>[0];\ntype ThemeColor = Parameters<Theme['fg']>[0];\n\n/**\n * Truncates and pads to an exact column count.\n *\n * `truncateToWidth` wraps its ellipsis in a hard `\\x1b[0m`, which would strip a\n * row's background for everything after a clipped name. The theme closes its own\n * colours with `\\x1b[39m` and `\\x1b[49m`, so the injected resets are dropped.\n */\nfunction fit(text: string, width: number): string {\n const clipped = truncateToWidth(text, Math.max(0, width), ELLIPSIS).replaceAll(HARD_RESET, '');\n return clipped + ' '.repeat(Math.max(0, width - visibleWidth(clipped)));\n}\n\nfunction rightAligned(left: string, right: string, width: number): string {\n const rightWidth = visibleWidth(right);\n const leftWidth = Math.max(0, width - rightWidth - 1);\n return fit(left, leftWidth) + ' '.repeat(Math.max(1, width - leftWidth - rightWidth)) + fit(right, rightWidth);\n}\n\nfunction jobGlyph(status: string): string {\n return status === 'completed' ? '✓' : status === 'failed' ? '✗' : '●';\n}\n\nfunction jobColour(status: string): ThemeColor {\n return status === 'completed' ? 'success' : status === 'failed' ? 'error' : 'accent';\n}\n\nfunction progressLines(item: WorkflowInspectorItem, width: number, theme: Theme): string[] {\n const lines: string[] = [];\n for (const job of item.jobs) {\n const position = job.total ? ` · ${(job.index ?? 0) + 1}/${job.total}` : '';\n lines.push(\n truncateToWidth(\n theme.fg(jobColour(job.status), `${jobGlyph(job.status)} ${job.name}`) + theme.fg('dim', position),\n width,\n ELLIPSIS,\n ),\n );\n // Only the running job's steps: every finished job's steps would push the\n // live one off the pane, which is the one thing worth watching.\n if (job.status !== RUNNING_STATE) continue;\n for (const step of job.steps) {\n const stepColour: ThemeColor =\n step.status === 'failed' ? 'error' : step.status === RUNNING_STATE ? 'muted' : 'dim';\n lines.push(truncateToWidth(theme.fg(stepColour, ` ${jobGlyph(step.status)} ${step.name}`), width, ELLIPSIS));\n }\n }\n return lines;\n}\n\nfunction detailLines(item: WorkflowInspectorItem | undefined, width: number, height: number, theme: Theme): string[] {\n if (!item) return [theme.fg('dim', NO_SELECTION)];\n\n const position = currentWorkflowPosition(item.jobs);\n const elapsed = humanizeDuration(Math.max(0, Date.now() - Date.parse(item.startedAt)));\n const executionState = item.executionState ?? RUNNING_STATE;\n const stateColour: ThemeColor = executionState === PAUSED_STATE ? 'warning' : 'dim';\n const lines = [\n rightAligned(\n `${theme.fg('accent', '●')} ${theme.bold(item.displayName)}`,\n theme.fg(stateColour, executionState),\n width,\n ),\n truncateToWidth(theme.fg('dim', `${item.runKey} · ${item.workspace} · ${elapsed}`), width, ELLIPSIS),\n position\n ? truncateToWidth(\n `${theme.fg('accent', position.job)}${position.step ? theme.fg('muted', ` · ${position.step}`) : ''}`,\n width,\n ELLIPSIS,\n )\n : theme.fg('dim', 'starting'),\n '',\n theme.fg('dim', PROGRESS_HEADING),\n ];\n\n // The output tail claims its rows first: progress is a list that can be paged\n // to by opening the run, while the tail is the only live signal on screen.\n const reservedOutput = item.output.length > 0 ? MIN_OUTPUT_ROWS + 1 : 0;\n const progressRoom = Math.max(0, height - lines.length - reservedOutput);\n lines.push(...progressLines(item, width, theme).slice(0, progressRoom));\n\n if (item.output.length > 0 && height - lines.length >= MIN_OUTPUT_ROWS) {\n lines.push('', theme.fg('dim', OUTPUT_HEADING));\n const outputRoom = Math.max(0, height - lines.length);\n lines.push(...item.output.slice(-outputRoom).map((line) => truncateToWidth(line, width, ELLIPSIS)));\n }\n\n return lines.slice(0, height);\n}\n\nexport class WorkflowInspectorComponent extends DoomOverlay {\n private bodyHeight = 8;\n private completed = false;\n private error: string | undefined;\n private items: WorkflowInspectorItem[] = [];\n private refreshActive = false;\n private selected = 0;\n private selectedKey: string | undefined;\n private readonly timer: ReturnType<typeof setInterval>;\n\n constructor(\n tui: DoomOverlayTui,\n theme: Theme,\n private readonly source: WorkflowInspectorSource,\n private readonly done: (selection: WorkflowInspectorSelection | undefined) => void,\n options: WorkflowInspectorOptions = {},\n ) {\n super(tui, theme);\n this.selectedKey = options.initialKey;\n void this.refresh();\n this.timer = setInterval(() => void this.refresh(), options.refreshMs ?? DEFAULT_REFRESH_MS);\n this.timer.unref?.();\n }\n\n private async refresh(): Promise<void> {\n if (this.refreshActive || this.completed) return;\n this.refreshActive = true;\n try {\n const previousKey = this.items[this.selected]?.key ?? this.selectedKey;\n const items = await this.source.list();\n if (this.completed) return;\n const preserved = previousKey ? items.findIndex((item) => item.key === previousKey) : -1;\n this.items = items;\n this.selected = preserved >= 0 ? preserved : Math.min(this.selected, Math.max(0, items.length - 1));\n this.selectedKey = items[this.selected]?.key;\n const selected = items[this.selected];\n if (selected) selected.output = await this.source.output(selected);\n this.error = undefined;\n if (!this.completed) this.tui.requestRender();\n } catch (cause) {\n this.error = cause instanceof Error ? cause.message : String(cause);\n if (!this.completed) this.tui.requestRender();\n } finally {\n this.refreshActive = false;\n }\n }\n\n private move(delta: number): void {\n if (this.items.length === 0) return;\n this.selected = Math.max(0, Math.min(this.items.length - 1, this.selected + delta));\n this.selectedKey = this.items[this.selected]?.key;\n void this.refreshSelectedOutput();\n this.tui.requestRender();\n }\n\n private async refreshSelectedOutput(): Promise<void> {\n const selected = this.items[this.selected];\n if (!selected || this.completed) return;\n try {\n selected.output = await this.source.output(selected);\n this.error = undefined;\n } catch (cause) {\n this.error = cause instanceof Error ? cause.message : String(cause);\n }\n if (!this.completed && selected.key === this.selectedKey) this.tui.requestRender();\n }\n\n private finish(selection: WorkflowInspectorSelection | undefined): void {\n if (this.completed) return;\n this.completed = true;\n clearInterval(this.timer);\n this.done(selection);\n }\n\n close(): void {\n this.finish(undefined);\n }\n\n handleInput(data: string): void {\n if (matchesKey(data, 'escape') || matchesKey(data, 'ctrl+c')) {\n this.finish(undefined);\n return;\n }\n if (matchesKey(data, 'up') || data === 'k') {\n this.move(-1);\n return;\n }\n if (matchesKey(data, 'down') || data === 'j') {\n this.move(1);\n return;\n }\n if (matchesKey(data, 'pageUp')) {\n this.move(-this.rosterCapacity());\n return;\n }\n if (matchesKey(data, 'pageDown')) {\n this.move(this.rosterCapacity());\n return;\n }\n if (matchesKey(data, 'enter')) {\n const selected = this.items[this.selected];\n if (selected) {\n this.finish({\n ...(selected.runId ? { runId: selected.runId } : {}),\n runKey: selected.runKey,\n startedAt: selected.startedAt,\n workspace: selected.workspace,\n });\n }\n }\n }\n\n /** Runs the roster can draw, which is also what a page key moves by. */\n private rosterCapacity(): number {\n return Math.max(1, Math.floor((this.bodyHeight - ROSTER_CHROME_ROWS) / ROWS_PER_ITEM));\n }\n\n private current(): WorkflowInspectorItem | undefined {\n if (this.items.length === 0) return undefined;\n return this.items[Math.min(this.selected, this.items.length - 1)];\n }\n\n protected getChrome(): DoomOverlayChrome {\n const selected = this.current();\n const summary = selected\n ? `${selected.displayName} · ${selected.executionState ?? RUNNING_STATE}`\n : 'no active workflows';\n return {\n title: TITLE,\n accent: DOOM_OVERLAY_ACCENT,\n breadcrumb: BREADCRUMB,\n headerRight: `${this.items.length} running · ${summary}`,\n footer: FOOTER,\n footerHints: FOOTER_HINTS,\n footerRight:\n this.items.length > 0 ? `${Math.min(this.selected, this.items.length - 1) + 1}/${this.items.length}` : 'empty',\n };\n }\n\n protected renderBody(width: number, height: number): string[] {\n this.bodyHeight = height;\n const detailFor = (paneWidth: number): string[] =>\n this.error\n ? [this.theme.fg('warning', `Unable to refresh workflows: ${this.error}`)]\n : detailLines(this.current(), paneWidth, height, this.theme);\n\n // Too narrow for two useful columns: the detail takes the whole body rather\n // than shredding both panes into stubs.\n if (width < MIN_TWO_PANE_WIDTH) return detailFor(width).slice(0, height);\n\n const leftWidth = Math.max(MIN_PANE_WIDTH, Math.floor((width - 1) * LIST_PANE_RATIO));\n const rightWidth = Math.max(1, width - leftWidth - 1);\n const leftContent = Math.max(1, leftWidth - PANE_GUTTER);\n const rightContent = Math.max(1, rightWidth - PANE_GUTTER);\n\n const left = this.rosterLines(leftContent);\n const right = detailFor(rightContent);\n const divider = this.theme.fg('borderMuted', '│');\n return Array.from({ length: height }, (_, index) => {\n const row = `${fit(left[index] ?? '', leftContent)} ${divider} ${fit(right[index] ?? '', rightContent)}`;\n return truncateToWidth(row, width, ELLIPSIS);\n });\n }\n\n private rosterLines(width: number): string[] {\n const lines = [this.theme.bold(ROSTER_HEADING), ''];\n if (this.items.length === 0) {\n lines.push(this.theme.fg('dim', EMPTY_ROSTER));\n return lines;\n }\n\n // Two rows per run: at a third of the width a single row left the name with\n // a handful of columns once the stage took its share.\n const budget = this.rosterCapacity();\n const active = Math.min(this.selected, this.items.length - 1);\n const start = Math.max(0, Math.min(active - budget + 1, Math.max(0, this.items.length - budget)));\n for (const [offset, item] of this.items.slice(start, start + budget).entries()) {\n const current = start + offset === active;\n const paused = item.executionState === PAUSED_STATE;\n const marker = current ? this.theme.fg('accent', SELECTION_MARKER) : ' ';\n const glyph = this.theme.fg(paused ? 'warning' : 'accent', '●');\n const name = current ? this.theme.bold(item.displayName) : item.displayName;\n const stage = paused ? PAUSED_STATE : (currentWorkflowPosition(item.jobs)?.job ?? 'starting');\n const heading = `${marker} ${glyph} ${name}`;\n const meta = `${' '.repeat(META_INDENT)}${this.theme.fg(paused ? 'warning' : 'dim', stage)}`;\n const background: ThemeBg = current ? 'selectedBg' : 'userMessageBg';\n for (const row of [heading, meta]) lines.push(this.theme.bg(background, fit(row, width)));\n }\n return lines;\n }\n\n /** Overridden: a repaint request is also the cue to re-read the registry. */\n invalidate(): void {\n void this.refresh();\n }\n\n dispose(): void {\n if (this.completed) return;\n this.completed = true;\n clearInterval(this.timer);\n }\n}\n"],"mappings":"uJAwBkDA,EAAAA,2BAA2B,eA2B7E,MAOM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,GAAM,CAAC,EAAQ,KAAS,KAAK,MAAM,MAAM,EAAO,EAAQ,CAAM,CAAC,CAAC,QAAQ,EAAG,CAC9E,IAAM,EAAU,EAAQ,IAAW,EAC7B,EAAS,EAAK,iBAAmB,EACjC,EAAS,EAAU,KAAK,MAAM,GAAG,SAAU,GAAgB,EAAI,IAC/D,EAAQ,KAAK,MAAM,GAAG,EAAS,UAAY,SAAU,GAAG,EACxD,EAAO,EAAU,KAAK,MAAM,KAAK,EAAK,WAAW,EAAI,EAAK,YAC1D,EAAQ,EAAS,GAAA,EAAgBE,EAAAA,wBAAAA,CAAwB,EAAK,IAAI,CAAC,EAAE,KAAO,WAC5E,EAAU,GAAG,EAAO,GAAG,EAAM,GAAG,IAChC,EAAO,GAAG,IAAI,OAAO,CAAW,IAAI,KAAK,MAAM,GAAG,EAAS,UAAY,MAAO,CAAK,IACnF,EAAsB,EAAU,aAAe,gBACrD,IAAK,IAAM,IAAO,CAAC,EAAS,CAAI,EAAG,EAAM,KAAK,KAAK,MAAM,GAAG,EAAY,EAAI,EAAK,CAAK,CAAC,CAAC,CAC1F,CACA,OAAO,CACT,CAGA,YAAmB,CACjB,KAAU,QAAQ,CACpB,CAEA,SAAgB,CACV,KAAK,YACT,KAAK,UAAY,GACjB,cAAc,KAAK,KAAK,EAC1B,CACF"}
@@ -1,2 +1,2 @@
1
- import{DOOM_FULLSCREEN_UI_OPTIONS as e,DOOM_OVERLAY_ACCENT as t,DoomOverlay as n}from"./doomOverlay.mjs";import{humanizeDuration as r}from"./workflowStatusRow.mjs";import{currentWorkflowPosition as i}from"@agimon-ai/workflow-mcp";import{matchesKey as a,truncateToWidth as o,visibleWidth as s}from"@earendil-works/pi-tui";e.overlayOptions;const c=`running`,l=`paused`,u=[[`↑↓/jk`,`select`],[`PgUp/PgDn`,`page`],[`enter`,`open`],[`esc`,`close`]];function d(e,t){let n=o(e,Math.max(0,t),`…`).replaceAll(`\x1B[0m`,``);return n+` `.repeat(Math.max(0,t-s(n)))}function f(e,t,n){let r=s(t),i=Math.max(0,n-r-1);return d(e,i)+` `.repeat(Math.max(1,n-i-r))+d(t,r)}function p(e){return e===`completed`?`✓`:e===`failed`?`✗`:`●`}function m(e){return e===`completed`?`success`:e===`failed`?`error`:`accent`}function h(e,t,n){let r=[];for(let i of e.jobs){let e=i.total?` · ${(i.index??0)+1}/${i.total}`:``;if(r.push(o(n.fg(m(i.status),`${p(i.status)} ${i.name}`)+n.fg(`dim`,e),t,`…`)),i.status===c)for(let e of i.steps){let i=e.status===`failed`?`error`:e.status===c?`muted`:`dim`;r.push(o(n.fg(i,` ${p(e.status)} ${e.name}`),t,`…`))}}return r}function g(e,t,n,a){if(!e)return[a.fg(`dim`,`Select a workflow to inspect its jobs and output.`)];let s=i(e.jobs),u=r(Math.max(0,Date.now()-Date.parse(e.startedAt))),d=e.executionState??c,p=d===l?`warning`:`dim`,m=[f(`${a.fg(`accent`,`●`)} ${a.bold(e.displayName)}`,a.fg(p,d),t),o(a.fg(`dim`,`${e.runKey} · ${e.workspace} · ${u}`),t,`…`),s?o(`${a.fg(`accent`,s.job)}${s.step?a.fg(`muted`,` · ${s.step}`):``}`,t,`…`):a.fg(`dim`,`starting`),``,a.fg(`dim`,`PROGRESS`)],g=e.output.length>0?3:0,_=Math.max(0,n-m.length-g);if(m.push(...h(e,t,a).slice(0,_)),e.output.length>0&&n-m.length>=2){m.push(``,a.fg(`dim`,`OUTPUT · newest last`));let r=Math.max(0,n-m.length);m.push(...e.output.slice(-r).map(e=>o(e,t,`…`)))}return m.slice(0,n)}var _=class extends n{source;done;bodyHeight=8;completed=!1;error;items=[];refreshActive=!1;selected=0;selectedKey;timer;constructor(e,t,n,r,i={}){super(e,t),this.source=n,this.done=r,this.selectedKey=i.initialKey,this.refresh(),this.timer=setInterval(()=>void this.refresh(),i.refreshMs??750),this.timer.unref?.()}async refresh(){if(!(this.refreshActive||this.completed)){this.refreshActive=!0;try{let e=this.items[this.selected]?.key??this.selectedKey,t=await this.source.list();if(this.completed)return;let n=e?t.findIndex(t=>t.key===e):-1;this.items=t,this.selected=n>=0?n:Math.min(this.selected,Math.max(0,t.length-1)),this.selectedKey=t[this.selected]?.key;let r=t[this.selected];r&&(r.output=await this.source.output(r)),this.error=void 0,this.completed||this.tui.requestRender()}catch(e){this.error=e instanceof Error?e.message:String(e),this.completed||this.tui.requestRender()}finally{this.refreshActive=!1}}}move(e){this.items.length!==0&&(this.selected=Math.max(0,Math.min(this.items.length-1,this.selected+e)),this.selectedKey=this.items[this.selected]?.key,this.refreshSelectedOutput(),this.tui.requestRender())}async refreshSelectedOutput(){let e=this.items[this.selected];if(!(!e||this.completed)){try{e.output=await this.source.output(e),this.error=void 0}catch(e){this.error=e instanceof Error?e.message:String(e)}!this.completed&&e.key===this.selectedKey&&this.tui.requestRender()}}finish(e){this.completed||(this.completed=!0,clearInterval(this.timer),this.done(e))}close(){this.finish(void 0)}handleInput(e){if(a(e,`escape`)||a(e,`ctrl+c`)){this.finish(void 0);return}if(a(e,`up`)||e===`k`){this.move(-1);return}if(a(e,`down`)||e===`j`){this.move(1);return}if(a(e,`pageUp`)){this.move(-this.rosterCapacity());return}if(a(e,`pageDown`)){this.move(this.rosterCapacity());return}if(a(e,`enter`)){let e=this.items[this.selected];e&&this.finish({...e.runId?{runId:e.runId}:{},runKey:e.runKey,startedAt:e.startedAt,workspace:e.workspace})}}rosterCapacity(){return Math.max(1,Math.floor((this.bodyHeight-2)/2))}current(){if(this.items.length!==0)return this.items[Math.min(this.selected,this.items.length-1)]}getChrome(){let e=this.current(),n=e?`${e.displayName} · ${e.executionState??c}`:`no active workflows`;return{title:`WORKFLOW SPACE`,accent:t,breadcrumb:`SPC › w / workflows › l / manage`,headerRight:`${this.items.length} running · ${n}`,footer:`↑↓/jk select · PgUp/PgDn page · enter open · esc close`,footerHints:u,footerRight:this.items.length>0?`${Math.min(this.selected,this.items.length-1)+1}/${this.items.length}`:`empty`}}renderBody(e,t){this.bodyHeight=t;let n=e=>this.error?[this.theme.fg(`warning`,`Unable to refresh workflows: ${this.error}`)]:g(this.current(),e,t,this.theme);if(e<48)return n(e).slice(0,t);let r=Math.max(18,Math.floor((e-1)*.3333333333333333)),i=Math.max(1,e-r-1),a=Math.max(1,r-1),s=Math.max(1,i-1),c=this.rosterLines(a),l=n(s),u=this.theme.fg(`borderMuted`,`│`);return Array.from({length:t},(t,n)=>{let r=`${d(c[n]??``,a)} ${u} ${d(l[n]??``,s)}`;return o(r,e,`…`)})}rosterLines(e){let t=[this.theme.bold(`RUNNING · this session`),``];if(this.items.length===0)return t.push(this.theme.fg(`dim`,`No active workflows`)),t;let n=this.rosterCapacity(),r=Math.min(this.selected,this.items.length-1),a=Math.max(0,Math.min(r-n+1,Math.max(0,this.items.length-n)));for(let[o,s]of this.items.slice(a,a+n).entries()){let n=a+o===r,c=s.executionState===l,u=n?this.theme.fg(`accent`,`›`):` `,f=this.theme.fg(c?`warning`:`accent`,`●`),p=n?this.theme.bold(s.displayName):s.displayName,m=c?l:i(s.jobs)?.job??`starting`,h=`${u} ${f} ${p}`,g=`${` `.repeat(4)}${this.theme.fg(c?`warning`:`dim`,m)}`,_=n?`selectedBg`:`userMessageBg`;for(let n of[h,g])t.push(this.theme.bg(_,d(n,e)))}return t}invalidate(){this.refresh()}dispose(){this.completed||(this.completed=!0,clearInterval(this.timer))}};export{_ as WorkflowInspectorComponent};
1
+ import{DOOM_FULLSCREEN_UI_OPTIONS as e,DOOM_OVERLAY_ACCENT as t,DoomOverlay as n}from"./doomOverlay.mjs";import{humanizeDuration as r}from"./workflowStatusRow.mjs";import{currentWorkflowPosition as i}from"@agimon-ai/workflow-mcp";import{matchesKey as a,truncateToWidth as o,visibleWidth as s}from"@earendil-works/pi-tui";e.overlayOptions;const c=`running`,l=`paused`,u=`↑↓`,d=`${u} select · PgUp/PgDn page · enter open · esc close`,f=[[u,`select`],[`PgUp/PgDn`,`page`],[`enter`,`open`],[`esc`,`close`]];function p(e,t){let n=o(e,Math.max(0,t),`…`).replaceAll(`\x1B[0m`,``);return n+` `.repeat(Math.max(0,t-s(n)))}function m(e,t,n){let r=s(t),i=Math.max(0,n-r-1);return p(e,i)+` `.repeat(Math.max(1,n-i-r))+p(t,r)}function h(e){return e===`completed`?`✓`:e===`failed`?`✗`:`●`}function g(e){return e===`completed`?`success`:e===`failed`?`error`:`accent`}function _(e,t,n){let r=[];for(let i of e.jobs){let e=i.total?` · ${(i.index??0)+1}/${i.total}`:``;if(r.push(o(n.fg(g(i.status),`${h(i.status)} ${i.name}`)+n.fg(`dim`,e),t,`…`)),i.status===c)for(let e of i.steps){let i=e.status===`failed`?`error`:e.status===c?`muted`:`dim`;r.push(o(n.fg(i,` ${h(e.status)} ${e.name}`),t,`…`))}}return r}function v(e,t,n,a){if(!e)return[a.fg(`dim`,`Select a workflow to inspect its jobs and output.`)];let s=i(e.jobs),u=r(Math.max(0,Date.now()-Date.parse(e.startedAt))),d=e.executionState??c,f=d===l?`warning`:`dim`,p=[m(`${a.fg(`accent`,`●`)} ${a.bold(e.displayName)}`,a.fg(f,d),t),o(a.fg(`dim`,`${e.runKey} · ${e.workspace} · ${u}`),t,`…`),s?o(`${a.fg(`accent`,s.job)}${s.step?a.fg(`muted`,` · ${s.step}`):``}`,t,`…`):a.fg(`dim`,`starting`),``,a.fg(`dim`,`PROGRESS`)],h=e.output.length>0?3:0,g=Math.max(0,n-p.length-h);if(p.push(..._(e,t,a).slice(0,g)),e.output.length>0&&n-p.length>=2){p.push(``,a.fg(`dim`,`OUTPUT · newest last`));let r=Math.max(0,n-p.length);p.push(...e.output.slice(-r).map(e=>o(e,t,`…`)))}return p.slice(0,n)}var y=class extends n{source;done;bodyHeight=8;completed=!1;error;items=[];refreshActive=!1;selected=0;selectedKey;timer;constructor(e,t,n,r,i={}){super(e,t),this.source=n,this.done=r,this.selectedKey=i.initialKey,this.refresh(),this.timer=setInterval(()=>void this.refresh(),i.refreshMs??750),this.timer.unref?.()}async refresh(){if(!(this.refreshActive||this.completed)){this.refreshActive=!0;try{let e=this.items[this.selected]?.key??this.selectedKey,t=await this.source.list();if(this.completed)return;let n=e?t.findIndex(t=>t.key===e):-1;this.items=t,this.selected=n>=0?n:Math.min(this.selected,Math.max(0,t.length-1)),this.selectedKey=t[this.selected]?.key;let r=t[this.selected];r&&(r.output=await this.source.output(r)),this.error=void 0,this.completed||this.tui.requestRender()}catch(e){this.error=e instanceof Error?e.message:String(e),this.completed||this.tui.requestRender()}finally{this.refreshActive=!1}}}move(e){this.items.length!==0&&(this.selected=Math.max(0,Math.min(this.items.length-1,this.selected+e)),this.selectedKey=this.items[this.selected]?.key,this.refreshSelectedOutput(),this.tui.requestRender())}async refreshSelectedOutput(){let e=this.items[this.selected];if(!(!e||this.completed)){try{e.output=await this.source.output(e),this.error=void 0}catch(e){this.error=e instanceof Error?e.message:String(e)}!this.completed&&e.key===this.selectedKey&&this.tui.requestRender()}}finish(e){this.completed||(this.completed=!0,clearInterval(this.timer),this.done(e))}close(){this.finish(void 0)}handleInput(e){if(a(e,`escape`)||a(e,`ctrl+c`)){this.finish(void 0);return}if(a(e,`up`)||e===`k`){this.move(-1);return}if(a(e,`down`)||e===`j`){this.move(1);return}if(a(e,`pageUp`)){this.move(-this.rosterCapacity());return}if(a(e,`pageDown`)){this.move(this.rosterCapacity());return}if(a(e,`enter`)){let e=this.items[this.selected];e&&this.finish({...e.runId?{runId:e.runId}:{},runKey:e.runKey,startedAt:e.startedAt,workspace:e.workspace})}}rosterCapacity(){return Math.max(1,Math.floor((this.bodyHeight-2)/2))}current(){if(this.items.length!==0)return this.items[Math.min(this.selected,this.items.length-1)]}getChrome(){let e=this.current(),n=e?`${e.displayName} · ${e.executionState??c}`:`no active workflows`;return{title:`WORKFLOW SPACE`,accent:t,breadcrumb:`SPC › w / workflows › l / manage`,headerRight:`${this.items.length} running · ${n}`,footer:d,footerHints:f,footerRight:this.items.length>0?`${Math.min(this.selected,this.items.length-1)+1}/${this.items.length}`:`empty`}}renderBody(e,t){this.bodyHeight=t;let n=e=>this.error?[this.theme.fg(`warning`,`Unable to refresh workflows: ${this.error}`)]:v(this.current(),e,t,this.theme);if(e<48)return n(e).slice(0,t);let r=Math.max(18,Math.floor((e-1)*.3333333333333333)),i=Math.max(1,e-r-1),a=Math.max(1,r-1),s=Math.max(1,i-1),c=this.rosterLines(a),l=n(s),u=this.theme.fg(`borderMuted`,`│`);return Array.from({length:t},(t,n)=>{let r=`${p(c[n]??``,a)} ${u} ${p(l[n]??``,s)}`;return o(r,e,`…`)})}rosterLines(e){let t=[this.theme.bold(`RUNNING · this session`),``];if(this.items.length===0)return t.push(this.theme.fg(`dim`,`No active workflows`)),t;let n=this.rosterCapacity(),r=Math.min(this.selected,this.items.length-1),a=Math.max(0,Math.min(r-n+1,Math.max(0,this.items.length-n)));for(let[o,s]of this.items.slice(a,a+n).entries()){let n=a+o===r,c=s.executionState===l,u=n?this.theme.fg(`accent`,`›`):` `,d=this.theme.fg(c?`warning`:`accent`,`●`),f=n?this.theme.bold(s.displayName):s.displayName,m=c?l:i(s.jobs)?.job??`starting`,h=`${u} ${d} ${f}`,g=`${` `.repeat(4)}${this.theme.fg(c?`warning`:`dim`,m)}`,_=n?`selectedBg`:`userMessageBg`;for(let n of[h,g])t.push(this.theme.bg(_,p(n,e)))}return t}invalidate(){this.refresh()}dispose(){this.completed||(this.completed=!0,clearInterval(this.timer))}};export{y as WorkflowInspectorComponent};
2
2
  //# sourceMappingURL=workflowInspector.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"workflowInspector.mjs","names":[],"sources":["../../../src/tui/workflow/workflowInspector.ts"],"sourcesContent":["/**\n * Workflow Space: the `SPC w l` overlay.\n *\n * A doom overlay rather than a hand-rolled frame: the roster owns the left\n * third, the run under the cursor owns the right two thirds, and the chrome is\n * the same frame, breadcrumb and key legend every other doom surface draws.\n *\n * Rendering is pure -- `renderBody(width, height)` reads the last polled\n * snapshot and returns lines with no side effects -- so the surface can be\n * asserted as text without a live terminal.\n */\n\nimport { currentWorkflowPosition, type WorkflowProgressJob } from '@agimon-ai/workflow-mcp';\nimport type { Theme } from '@earendil-works/pi-coding-agent';\nimport { matchesKey, truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';\nimport {\n DOOM_FULLSCREEN_UI_OPTIONS,\n DOOM_OVERLAY_ACCENT,\n DoomOverlay,\n type DoomOverlayChrome,\n type DoomOverlayTui,\n} from './doomOverlay.ts';\nimport { humanizeDuration } from './workflowStatusRow';\n\nexport const WORKFLOW_INSPECTOR_OVERLAY_OPTIONS = DOOM_FULLSCREEN_UI_OPTIONS.overlayOptions;\n\nexport interface WorkflowInspectorSelection {\n runId?: string;\n runKey: string;\n startedAt: string;\n workspace: string;\n}\n\nexport interface WorkflowInspectorItem extends WorkflowInspectorSelection {\n displayName: string;\n executionState?: string;\n jobs: WorkflowProgressJob[];\n key: string;\n output: string[];\n}\n\nexport interface WorkflowInspectorSource {\n list(): Promise<WorkflowInspectorItem[]>;\n output(item: WorkflowInspectorItem): Promise<string[]>;\n}\n\nexport interface WorkflowInspectorOptions {\n initialKey?: string;\n refreshMs?: number;\n}\n\nconst TITLE = 'WORKFLOW SPACE';\nconst BREADCRUMB = 'SPC › w / workflows › l / manage';\nconst ROSTER_HEADING = 'RUNNING · this session';\nconst EMPTY_ROSTER = 'No active workflows';\nconst PROGRESS_HEADING = 'PROGRESS';\nconst OUTPUT_HEADING = 'OUTPUT · newest last';\nconst NO_SELECTION = 'Select a workflow to inspect its jobs and output.';\nconst RUNNING_STATE = 'running';\nconst PAUSED_STATE = 'paused';\nconst FOOTER = '↑↓/jk select · PgUp/PgDn page · enter open · esc close';\nconst FOOTER_HINTS: readonly (readonly [string, string])[] = [\n ['↑↓/jk', 'select'],\n ['PgUp/PgDn', 'page'],\n ['enter', 'open'],\n ['esc', 'close'],\n];\n\nconst DEFAULT_REFRESH_MS = 750;\nconst SELECTION_MARKER = '›';\nconst ELLIPSIS = '…';\n/** pi-tui brackets a truncation ellipsis with this; see `fit`. */\nconst HARD_RESET = '\\x1b[0m';\n/** A third for the roster, two thirds for the run being read. */\nconst LIST_PANE_RATIO = 1 / 3;\n/** One blank column each side of the divider so neither pane touches it. */\nconst PANE_GUTTER = 1;\nconst MIN_PANE_WIDTH = 18;\n/** Below this the roster cannot hold a readable name, so the detail takes the body. */\nconst MIN_TWO_PANE_WIDTH = 48;\n/** Each run occupies a name row and a state row beneath it. */\nconst ROWS_PER_ITEM = 2;\n/** Hanging indent for the state row: clears the marker and the glyph. */\nconst META_INDENT = 4;\n/** Rows the roster heading and its spacer take. */\nconst ROSTER_CHROME_ROWS = 2;\n/** The output tail keeps at least this many rows, or it is not worth a divider. */\nconst MIN_OUTPUT_ROWS = 2;\n\n/** Neither palette name is exported, so take both from the theme's methods. */\ntype ThemeBg = Parameters<Theme['bg']>[0];\ntype ThemeColor = Parameters<Theme['fg']>[0];\n\n/**\n * Truncates and pads to an exact column count.\n *\n * `truncateToWidth` wraps its ellipsis in a hard `\\x1b[0m`, which would strip a\n * row's background for everything after a clipped name. The theme closes its own\n * colours with `\\x1b[39m` and `\\x1b[49m`, so the injected resets are dropped.\n */\nfunction fit(text: string, width: number): string {\n const clipped = truncateToWidth(text, Math.max(0, width), ELLIPSIS).replaceAll(HARD_RESET, '');\n return clipped + ' '.repeat(Math.max(0, width - visibleWidth(clipped)));\n}\n\nfunction rightAligned(left: string, right: string, width: number): string {\n const rightWidth = visibleWidth(right);\n const leftWidth = Math.max(0, width - rightWidth - 1);\n return fit(left, leftWidth) + ' '.repeat(Math.max(1, width - leftWidth - rightWidth)) + fit(right, rightWidth);\n}\n\nfunction jobGlyph(status: string): string {\n return status === 'completed' ? '✓' : status === 'failed' ? '✗' : '●';\n}\n\nfunction jobColour(status: string): ThemeColor {\n return status === 'completed' ? 'success' : status === 'failed' ? 'error' : 'accent';\n}\n\nfunction progressLines(item: WorkflowInspectorItem, width: number, theme: Theme): string[] {\n const lines: string[] = [];\n for (const job of item.jobs) {\n const position = job.total ? ` · ${(job.index ?? 0) + 1}/${job.total}` : '';\n lines.push(\n truncateToWidth(\n theme.fg(jobColour(job.status), `${jobGlyph(job.status)} ${job.name}`) + theme.fg('dim', position),\n width,\n ELLIPSIS,\n ),\n );\n // Only the running job's steps: every finished job's steps would push the\n // live one off the pane, which is the one thing worth watching.\n if (job.status !== RUNNING_STATE) continue;\n for (const step of job.steps) {\n const stepColour: ThemeColor =\n step.status === 'failed' ? 'error' : step.status === RUNNING_STATE ? 'muted' : 'dim';\n lines.push(truncateToWidth(theme.fg(stepColour, ` ${jobGlyph(step.status)} ${step.name}`), width, ELLIPSIS));\n }\n }\n return lines;\n}\n\nfunction detailLines(item: WorkflowInspectorItem | undefined, width: number, height: number, theme: Theme): string[] {\n if (!item) return [theme.fg('dim', NO_SELECTION)];\n\n const position = currentWorkflowPosition(item.jobs);\n const elapsed = humanizeDuration(Math.max(0, Date.now() - Date.parse(item.startedAt)));\n const executionState = item.executionState ?? RUNNING_STATE;\n const stateColour: ThemeColor = executionState === PAUSED_STATE ? 'warning' : 'dim';\n const lines = [\n rightAligned(\n `${theme.fg('accent', '●')} ${theme.bold(item.displayName)}`,\n theme.fg(stateColour, executionState),\n width,\n ),\n truncateToWidth(theme.fg('dim', `${item.runKey} · ${item.workspace} · ${elapsed}`), width, ELLIPSIS),\n position\n ? truncateToWidth(\n `${theme.fg('accent', position.job)}${position.step ? theme.fg('muted', ` · ${position.step}`) : ''}`,\n width,\n ELLIPSIS,\n )\n : theme.fg('dim', 'starting'),\n '',\n theme.fg('dim', PROGRESS_HEADING),\n ];\n\n // The output tail claims its rows first: progress is a list that can be paged\n // to by opening the run, while the tail is the only live signal on screen.\n const reservedOutput = item.output.length > 0 ? MIN_OUTPUT_ROWS + 1 : 0;\n const progressRoom = Math.max(0, height - lines.length - reservedOutput);\n lines.push(...progressLines(item, width, theme).slice(0, progressRoom));\n\n if (item.output.length > 0 && height - lines.length >= MIN_OUTPUT_ROWS) {\n lines.push('', theme.fg('dim', OUTPUT_HEADING));\n const outputRoom = Math.max(0, height - lines.length);\n lines.push(...item.output.slice(-outputRoom).map((line) => truncateToWidth(line, width, ELLIPSIS)));\n }\n\n return lines.slice(0, height);\n}\n\nexport class WorkflowInspectorComponent extends DoomOverlay {\n private bodyHeight = 8;\n private completed = false;\n private error: string | undefined;\n private items: WorkflowInspectorItem[] = [];\n private refreshActive = false;\n private selected = 0;\n private selectedKey: string | undefined;\n private readonly timer: ReturnType<typeof setInterval>;\n\n constructor(\n tui: DoomOverlayTui,\n theme: Theme,\n private readonly source: WorkflowInspectorSource,\n private readonly done: (selection: WorkflowInspectorSelection | undefined) => void,\n options: WorkflowInspectorOptions = {},\n ) {\n super(tui, theme);\n this.selectedKey = options.initialKey;\n void this.refresh();\n this.timer = setInterval(() => void this.refresh(), options.refreshMs ?? DEFAULT_REFRESH_MS);\n this.timer.unref?.();\n }\n\n private async refresh(): Promise<void> {\n if (this.refreshActive || this.completed) return;\n this.refreshActive = true;\n try {\n const previousKey = this.items[this.selected]?.key ?? this.selectedKey;\n const items = await this.source.list();\n if (this.completed) return;\n const preserved = previousKey ? items.findIndex((item) => item.key === previousKey) : -1;\n this.items = items;\n this.selected = preserved >= 0 ? preserved : Math.min(this.selected, Math.max(0, items.length - 1));\n this.selectedKey = items[this.selected]?.key;\n const selected = items[this.selected];\n if (selected) selected.output = await this.source.output(selected);\n this.error = undefined;\n if (!this.completed) this.tui.requestRender();\n } catch (cause) {\n this.error = cause instanceof Error ? cause.message : String(cause);\n if (!this.completed) this.tui.requestRender();\n } finally {\n this.refreshActive = false;\n }\n }\n\n private move(delta: number): void {\n if (this.items.length === 0) return;\n this.selected = Math.max(0, Math.min(this.items.length - 1, this.selected + delta));\n this.selectedKey = this.items[this.selected]?.key;\n void this.refreshSelectedOutput();\n this.tui.requestRender();\n }\n\n private async refreshSelectedOutput(): Promise<void> {\n const selected = this.items[this.selected];\n if (!selected || this.completed) return;\n try {\n selected.output = await this.source.output(selected);\n this.error = undefined;\n } catch (cause) {\n this.error = cause instanceof Error ? cause.message : String(cause);\n }\n if (!this.completed && selected.key === this.selectedKey) this.tui.requestRender();\n }\n\n private finish(selection: WorkflowInspectorSelection | undefined): void {\n if (this.completed) return;\n this.completed = true;\n clearInterval(this.timer);\n this.done(selection);\n }\n\n close(): void {\n this.finish(undefined);\n }\n\n handleInput(data: string): void {\n if (matchesKey(data, 'escape') || matchesKey(data, 'ctrl+c')) {\n this.finish(undefined);\n return;\n }\n if (matchesKey(data, 'up') || data === 'k') {\n this.move(-1);\n return;\n }\n if (matchesKey(data, 'down') || data === 'j') {\n this.move(1);\n return;\n }\n if (matchesKey(data, 'pageUp')) {\n this.move(-this.rosterCapacity());\n return;\n }\n if (matchesKey(data, 'pageDown')) {\n this.move(this.rosterCapacity());\n return;\n }\n if (matchesKey(data, 'enter')) {\n const selected = this.items[this.selected];\n if (selected) {\n this.finish({\n ...(selected.runId ? { runId: selected.runId } : {}),\n runKey: selected.runKey,\n startedAt: selected.startedAt,\n workspace: selected.workspace,\n });\n }\n }\n }\n\n /** Runs the roster can draw, which is also what a page key moves by. */\n private rosterCapacity(): number {\n return Math.max(1, Math.floor((this.bodyHeight - ROSTER_CHROME_ROWS) / ROWS_PER_ITEM));\n }\n\n private current(): WorkflowInspectorItem | undefined {\n if (this.items.length === 0) return undefined;\n return this.items[Math.min(this.selected, this.items.length - 1)];\n }\n\n protected getChrome(): DoomOverlayChrome {\n const selected = this.current();\n const summary = selected\n ? `${selected.displayName} · ${selected.executionState ?? RUNNING_STATE}`\n : 'no active workflows';\n return {\n title: TITLE,\n accent: DOOM_OVERLAY_ACCENT,\n breadcrumb: BREADCRUMB,\n headerRight: `${this.items.length} running · ${summary}`,\n footer: FOOTER,\n footerHints: FOOTER_HINTS,\n footerRight:\n this.items.length > 0 ? `${Math.min(this.selected, this.items.length - 1) + 1}/${this.items.length}` : 'empty',\n };\n }\n\n protected renderBody(width: number, height: number): string[] {\n this.bodyHeight = height;\n const detailFor = (paneWidth: number): string[] =>\n this.error\n ? [this.theme.fg('warning', `Unable to refresh workflows: ${this.error}`)]\n : detailLines(this.current(), paneWidth, height, this.theme);\n\n // Too narrow for two useful columns: the detail takes the whole body rather\n // than shredding both panes into stubs.\n if (width < MIN_TWO_PANE_WIDTH) return detailFor(width).slice(0, height);\n\n const leftWidth = Math.max(MIN_PANE_WIDTH, Math.floor((width - 1) * LIST_PANE_RATIO));\n const rightWidth = Math.max(1, width - leftWidth - 1);\n const leftContent = Math.max(1, leftWidth - PANE_GUTTER);\n const rightContent = Math.max(1, rightWidth - PANE_GUTTER);\n\n const left = this.rosterLines(leftContent);\n const right = detailFor(rightContent);\n const divider = this.theme.fg('borderMuted', '│');\n return Array.from({ length: height }, (_, index) => {\n const row = `${fit(left[index] ?? '', leftContent)} ${divider} ${fit(right[index] ?? '', rightContent)}`;\n return truncateToWidth(row, width, ELLIPSIS);\n });\n }\n\n private rosterLines(width: number): string[] {\n const lines = [this.theme.bold(ROSTER_HEADING), ''];\n if (this.items.length === 0) {\n lines.push(this.theme.fg('dim', EMPTY_ROSTER));\n return lines;\n }\n\n // Two rows per run: at a third of the width a single row left the name with\n // a handful of columns once the stage took its share.\n const budget = this.rosterCapacity();\n const active = Math.min(this.selected, this.items.length - 1);\n const start = Math.max(0, Math.min(active - budget + 1, Math.max(0, this.items.length - budget)));\n for (const [offset, item] of this.items.slice(start, start + budget).entries()) {\n const current = start + offset === active;\n const paused = item.executionState === PAUSED_STATE;\n const marker = current ? this.theme.fg('accent', SELECTION_MARKER) : ' ';\n const glyph = this.theme.fg(paused ? 'warning' : 'accent', '●');\n const name = current ? this.theme.bold(item.displayName) : item.displayName;\n const stage = paused ? PAUSED_STATE : (currentWorkflowPosition(item.jobs)?.job ?? 'starting');\n const heading = `${marker} ${glyph} ${name}`;\n const meta = `${' '.repeat(META_INDENT)}${this.theme.fg(paused ? 'warning' : 'dim', stage)}`;\n const background: ThemeBg = current ? 'selectedBg' : 'userMessageBg';\n for (const row of [heading, meta]) lines.push(this.theme.bg(background, fit(row, width)));\n }\n return lines;\n }\n\n /** Overridden: a repaint request is also the cue to re-read the registry. */\n invalidate(): void {\n void this.refresh();\n }\n\n dispose(): void {\n if (this.completed) return;\n this.completed = true;\n clearInterval(this.timer);\n }\n}\n"],"mappings":"iUAwBkD,EAA2B,eA2B7E,MAOM,EAAgB,UAChB,EAAe,SAEf,EAAuD,CAC3D,CAAC,QAAS,QAAQ,EAClB,CAAC,YAAa,MAAM,EACpB,CAAC,QAAS,MAAM,EAChB,CAAC,MAAO,OAAO,CACjB,EAkCA,SAAS,EAAI,EAAc,EAAuB,CAChD,IAAM,EAAU,EAAgB,EAAM,KAAK,IAAI,EAAG,CAAK,EAAG,GAAQ,CAAC,CAAC,WAAW,UAAY,EAAE,EAC7F,OAAO,EAAU,IAAI,OAAO,KAAK,IAAI,EAAG,EAAQ,EAAa,CAAO,CAAC,CAAC,CACxE,CAEA,SAAS,EAAa,EAAc,EAAe,EAAuB,CACxE,IAAM,EAAa,EAAa,CAAK,EAC/B,EAAY,KAAK,IAAI,EAAG,EAAQ,EAAa,CAAC,EACpD,OAAO,EAAI,EAAM,CAAS,EAAI,IAAI,OAAO,KAAK,IAAI,EAAG,EAAQ,EAAY,CAAU,CAAC,EAAI,EAAI,EAAO,CAAU,CAC/G,CAEA,SAAS,EAAS,EAAwB,CACxC,OAAO,IAAW,YAAc,IAAM,IAAW,SAAW,IAAM,GACpE,CAEA,SAAS,EAAU,EAA4B,CAC7C,OAAO,IAAW,YAAc,UAAY,IAAW,SAAW,QAAU,QAC9E,CAEA,SAAS,EAAc,EAA6B,EAAe,EAAwB,CACzF,IAAM,EAAkB,CAAC,EACzB,IAAK,IAAM,KAAO,EAAK,KAAM,CAC3B,IAAM,EAAW,EAAI,MAAQ,OAAO,EAAI,OAAS,GAAK,EAAE,GAAG,EAAI,QAAU,GACzE,KAAM,KACJ,EACE,EAAM,GAAG,EAAU,EAAI,MAAM,EAAG,GAAG,EAAS,EAAI,MAAM,EAAE,GAAG,EAAI,MAAM,EAAI,EAAM,GAAG,MAAO,CAAQ,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AAM,KAAK,EAAK,WAAW,EAAI,EAAK,YAC1D,EAAQ,EAAS,EAAgB,EAAwB,EAAK,IAAI,CAAC,EAAE,KAAO,WAC5E,EAAU,GAAG,EAAO,GAAG,EAAM,GAAG,IAChC,EAAO,GAAG,IAAI,OAAO,CAAW,IAAI,KAAK,MAAM,GAAG,EAAS,UAAY,MAAO,CAAK,IACnF,EAAsB,EAAU,aAAe,gBACrD,IAAK,IAAM,IAAO,CAAC,EAAS,CAAI,EAAG,EAAM,KAAK,KAAK,MAAM,GAAG,EAAY,EAAI,EAAK,CAAK,CAAC,CAAC,CAC1F,CACA,OAAO,CACT,CAGA,YAAmB,CACjB,KAAU,QAAQ,CACpB,CAEA,SAAgB,CACV,KAAK,YACT,KAAK,UAAY,GACjB,cAAc,KAAK,KAAK,EAC1B,CACF"}
1
+ {"version":3,"file":"workflowInspector.mjs","names":[],"sources":["../../../src/tui/workflow/workflowInspector.ts"],"sourcesContent":["/**\n * Workflow Space: the `SPC w l` overlay.\n *\n * A doom overlay rather than a hand-rolled frame: the roster owns the left\n * third, the run under the cursor owns the right two thirds, and the chrome is\n * the same frame, breadcrumb and key legend every other doom surface draws.\n *\n * Rendering is pure -- `renderBody(width, height)` reads the last polled\n * snapshot and returns lines with no side effects -- so the surface can be\n * asserted as text without a live terminal.\n */\n\nimport { currentWorkflowPosition, type WorkflowProgressJob } from '@agimon-ai/workflow-mcp';\nimport type { Theme } from '@earendil-works/pi-coding-agent';\nimport { matchesKey, truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';\nimport {\n DOOM_FULLSCREEN_UI_OPTIONS,\n DOOM_OVERLAY_ACCENT,\n DoomOverlay,\n type DoomOverlayChrome,\n type DoomOverlayTui,\n} from './doomOverlay.ts';\nimport { humanizeDuration } from './workflowStatusRow';\n\nexport const WORKFLOW_INSPECTOR_OVERLAY_OPTIONS = DOOM_FULLSCREEN_UI_OPTIONS.overlayOptions;\n\nexport interface WorkflowInspectorSelection {\n runId?: string;\n runKey: string;\n startedAt: string;\n workspace: string;\n}\n\nexport interface WorkflowInspectorItem extends WorkflowInspectorSelection {\n displayName: string;\n executionState?: string;\n jobs: WorkflowProgressJob[];\n key: string;\n output: string[];\n}\n\nexport interface WorkflowInspectorSource {\n list(): Promise<WorkflowInspectorItem[]>;\n output(item: WorkflowInspectorItem): Promise<string[]>;\n}\n\nexport interface WorkflowInspectorOptions {\n initialKey?: string;\n refreshMs?: number;\n}\n\nconst TITLE = 'WORKFLOW SPACE';\nconst BREADCRUMB = 'SPC › w / workflows › l / manage';\nconst ROSTER_HEADING = 'RUNNING · this session';\nconst EMPTY_ROSTER = 'No active workflows';\nconst PROGRESS_HEADING = 'PROGRESS';\nconst OUTPUT_HEADING = 'OUTPUT · newest last';\nconst NO_SELECTION = 'Select a workflow to inspect its jobs and output.';\nconst RUNNING_STATE = 'running';\nconst PAUSED_STATE = 'paused';\n/** Mirrors DoomPi's list-navigation legend without adding a runtime doompi-ui dependency. */\nconst LIST_NAVIGATION_KEYS = '↑↓';\nconst FOOTER = `${LIST_NAVIGATION_KEYS} select · PgUp/PgDn page · enter open · esc close`;\nconst FOOTER_HINTS: readonly (readonly [string, string])[] = [\n [LIST_NAVIGATION_KEYS, 'select'],\n ['PgUp/PgDn', 'page'],\n ['enter', 'open'],\n ['esc', 'close'],\n];\n\nconst DEFAULT_REFRESH_MS = 750;\nconst SELECTION_MARKER = '›';\nconst ELLIPSIS = '…';\n/** pi-tui brackets a truncation ellipsis with this; see `fit`. */\nconst HARD_RESET = '\\x1b[0m';\n/** A third for the roster, two thirds for the run being read. */\nconst LIST_PANE_RATIO = 1 / 3;\n/** One blank column each side of the divider so neither pane touches it. */\nconst PANE_GUTTER = 1;\nconst MIN_PANE_WIDTH = 18;\n/** Below this the roster cannot hold a readable name, so the detail takes the body. */\nconst MIN_TWO_PANE_WIDTH = 48;\n/** Each run occupies a name row and a state row beneath it. */\nconst ROWS_PER_ITEM = 2;\n/** Hanging indent for the state row: clears the marker and the glyph. */\nconst META_INDENT = 4;\n/** Rows the roster heading and its spacer take. */\nconst ROSTER_CHROME_ROWS = 2;\n/** The output tail keeps at least this many rows, or it is not worth a divider. */\nconst MIN_OUTPUT_ROWS = 2;\n\n/** Neither palette name is exported, so take both from the theme's methods. */\ntype ThemeBg = Parameters<Theme['bg']>[0];\ntype ThemeColor = Parameters<Theme['fg']>[0];\n\n/**\n * Truncates and pads to an exact column count.\n *\n * `truncateToWidth` wraps its ellipsis in a hard `\\x1b[0m`, which would strip a\n * row's background for everything after a clipped name. The theme closes its own\n * colours with `\\x1b[39m` and `\\x1b[49m`, so the injected resets are dropped.\n */\nfunction fit(text: string, width: number): string {\n const clipped = truncateToWidth(text, Math.max(0, width), ELLIPSIS).replaceAll(HARD_RESET, '');\n return clipped + ' '.repeat(Math.max(0, width - visibleWidth(clipped)));\n}\n\nfunction rightAligned(left: string, right: string, width: number): string {\n const rightWidth = visibleWidth(right);\n const leftWidth = Math.max(0, width - rightWidth - 1);\n return fit(left, leftWidth) + ' '.repeat(Math.max(1, width - leftWidth - rightWidth)) + fit(right, rightWidth);\n}\n\nfunction jobGlyph(status: string): string {\n return status === 'completed' ? '✓' : status === 'failed' ? '✗' : '●';\n}\n\nfunction jobColour(status: string): ThemeColor {\n return status === 'completed' ? 'success' : status === 'failed' ? 'error' : 'accent';\n}\n\nfunction progressLines(item: WorkflowInspectorItem, width: number, theme: Theme): string[] {\n const lines: string[] = [];\n for (const job of item.jobs) {\n const position = job.total ? ` · ${(job.index ?? 0) + 1}/${job.total}` : '';\n lines.push(\n truncateToWidth(\n theme.fg(jobColour(job.status), `${jobGlyph(job.status)} ${job.name}`) + theme.fg('dim', position),\n width,\n ELLIPSIS,\n ),\n );\n // Only the running job's steps: every finished job's steps would push the\n // live one off the pane, which is the one thing worth watching.\n if (job.status !== RUNNING_STATE) continue;\n for (const step of job.steps) {\n const stepColour: ThemeColor =\n step.status === 'failed' ? 'error' : step.status === RUNNING_STATE ? 'muted' : 'dim';\n lines.push(truncateToWidth(theme.fg(stepColour, ` ${jobGlyph(step.status)} ${step.name}`), width, ELLIPSIS));\n }\n }\n return lines;\n}\n\nfunction detailLines(item: WorkflowInspectorItem | undefined, width: number, height: number, theme: Theme): string[] {\n if (!item) return [theme.fg('dim', NO_SELECTION)];\n\n const position = currentWorkflowPosition(item.jobs);\n const elapsed = humanizeDuration(Math.max(0, Date.now() - Date.parse(item.startedAt)));\n const executionState = item.executionState ?? RUNNING_STATE;\n const stateColour: ThemeColor = executionState === PAUSED_STATE ? 'warning' : 'dim';\n const lines = [\n rightAligned(\n `${theme.fg('accent', '●')} ${theme.bold(item.displayName)}`,\n theme.fg(stateColour, executionState),\n width,\n ),\n truncateToWidth(theme.fg('dim', `${item.runKey} · ${item.workspace} · ${elapsed}`), width, ELLIPSIS),\n position\n ? truncateToWidth(\n `${theme.fg('accent', position.job)}${position.step ? theme.fg('muted', ` · ${position.step}`) : ''}`,\n width,\n ELLIPSIS,\n )\n : theme.fg('dim', 'starting'),\n '',\n theme.fg('dim', PROGRESS_HEADING),\n ];\n\n // The output tail claims its rows first: progress is a list that can be paged\n // to by opening the run, while the tail is the only live signal on screen.\n const reservedOutput = item.output.length > 0 ? MIN_OUTPUT_ROWS + 1 : 0;\n const progressRoom = Math.max(0, height - lines.length - reservedOutput);\n lines.push(...progressLines(item, width, theme).slice(0, progressRoom));\n\n if (item.output.length > 0 && height - lines.length >= MIN_OUTPUT_ROWS) {\n lines.push('', theme.fg('dim', OUTPUT_HEADING));\n const outputRoom = Math.max(0, height - lines.length);\n lines.push(...item.output.slice(-outputRoom).map((line) => truncateToWidth(line, width, ELLIPSIS)));\n }\n\n return lines.slice(0, height);\n}\n\nexport class WorkflowInspectorComponent extends DoomOverlay {\n private bodyHeight = 8;\n private completed = false;\n private error: string | undefined;\n private items: WorkflowInspectorItem[] = [];\n private refreshActive = false;\n private selected = 0;\n private selectedKey: string | undefined;\n private readonly timer: ReturnType<typeof setInterval>;\n\n constructor(\n tui: DoomOverlayTui,\n theme: Theme,\n private readonly source: WorkflowInspectorSource,\n private readonly done: (selection: WorkflowInspectorSelection | undefined) => void,\n options: WorkflowInspectorOptions = {},\n ) {\n super(tui, theme);\n this.selectedKey = options.initialKey;\n void this.refresh();\n this.timer = setInterval(() => void this.refresh(), options.refreshMs ?? DEFAULT_REFRESH_MS);\n this.timer.unref?.();\n }\n\n private async refresh(): Promise<void> {\n if (this.refreshActive || this.completed) return;\n this.refreshActive = true;\n try {\n const previousKey = this.items[this.selected]?.key ?? this.selectedKey;\n const items = await this.source.list();\n if (this.completed) return;\n const preserved = previousKey ? items.findIndex((item) => item.key === previousKey) : -1;\n this.items = items;\n this.selected = preserved >= 0 ? preserved : Math.min(this.selected, Math.max(0, items.length - 1));\n this.selectedKey = items[this.selected]?.key;\n const selected = items[this.selected];\n if (selected) selected.output = await this.source.output(selected);\n this.error = undefined;\n if (!this.completed) this.tui.requestRender();\n } catch (cause) {\n this.error = cause instanceof Error ? cause.message : String(cause);\n if (!this.completed) this.tui.requestRender();\n } finally {\n this.refreshActive = false;\n }\n }\n\n private move(delta: number): void {\n if (this.items.length === 0) return;\n this.selected = Math.max(0, Math.min(this.items.length - 1, this.selected + delta));\n this.selectedKey = this.items[this.selected]?.key;\n void this.refreshSelectedOutput();\n this.tui.requestRender();\n }\n\n private async refreshSelectedOutput(): Promise<void> {\n const selected = this.items[this.selected];\n if (!selected || this.completed) return;\n try {\n selected.output = await this.source.output(selected);\n this.error = undefined;\n } catch (cause) {\n this.error = cause instanceof Error ? cause.message : String(cause);\n }\n if (!this.completed && selected.key === this.selectedKey) this.tui.requestRender();\n }\n\n private finish(selection: WorkflowInspectorSelection | undefined): void {\n if (this.completed) return;\n this.completed = true;\n clearInterval(this.timer);\n this.done(selection);\n }\n\n close(): void {\n this.finish(undefined);\n }\n\n handleInput(data: string): void {\n if (matchesKey(data, 'escape') || matchesKey(data, 'ctrl+c')) {\n this.finish(undefined);\n return;\n }\n if (matchesKey(data, 'up') || data === 'k') {\n this.move(-1);\n return;\n }\n if (matchesKey(data, 'down') || data === 'j') {\n this.move(1);\n return;\n }\n if (matchesKey(data, 'pageUp')) {\n this.move(-this.rosterCapacity());\n return;\n }\n if (matchesKey(data, 'pageDown')) {\n this.move(this.rosterCapacity());\n return;\n }\n if (matchesKey(data, 'enter')) {\n const selected = this.items[this.selected];\n if (selected) {\n this.finish({\n ...(selected.runId ? { runId: selected.runId } : {}),\n runKey: selected.runKey,\n startedAt: selected.startedAt,\n workspace: selected.workspace,\n });\n }\n }\n }\n\n /** Runs the roster can draw, which is also what a page key moves by. */\n private rosterCapacity(): number {\n return Math.max(1, Math.floor((this.bodyHeight - ROSTER_CHROME_ROWS) / ROWS_PER_ITEM));\n }\n\n private current(): WorkflowInspectorItem | undefined {\n if (this.items.length === 0) return undefined;\n return this.items[Math.min(this.selected, this.items.length - 1)];\n }\n\n protected getChrome(): DoomOverlayChrome {\n const selected = this.current();\n const summary = selected\n ? `${selected.displayName} · ${selected.executionState ?? RUNNING_STATE}`\n : 'no active workflows';\n return {\n title: TITLE,\n accent: DOOM_OVERLAY_ACCENT,\n breadcrumb: BREADCRUMB,\n headerRight: `${this.items.length} running · ${summary}`,\n footer: FOOTER,\n footerHints: FOOTER_HINTS,\n footerRight:\n this.items.length > 0 ? `${Math.min(this.selected, this.items.length - 1) + 1}/${this.items.length}` : 'empty',\n };\n }\n\n protected renderBody(width: number, height: number): string[] {\n this.bodyHeight = height;\n const detailFor = (paneWidth: number): string[] =>\n this.error\n ? [this.theme.fg('warning', `Unable to refresh workflows: ${this.error}`)]\n : detailLines(this.current(), paneWidth, height, this.theme);\n\n // Too narrow for two useful columns: the detail takes the whole body rather\n // than shredding both panes into stubs.\n if (width < MIN_TWO_PANE_WIDTH) return detailFor(width).slice(0, height);\n\n const leftWidth = Math.max(MIN_PANE_WIDTH, Math.floor((width - 1) * LIST_PANE_RATIO));\n const rightWidth = Math.max(1, width - leftWidth - 1);\n const leftContent = Math.max(1, leftWidth - PANE_GUTTER);\n const rightContent = Math.max(1, rightWidth - PANE_GUTTER);\n\n const left = this.rosterLines(leftContent);\n const right = detailFor(rightContent);\n const divider = this.theme.fg('borderMuted', '│');\n return Array.from({ length: height }, (_, index) => {\n const row = `${fit(left[index] ?? '', leftContent)} ${divider} ${fit(right[index] ?? '', rightContent)}`;\n return truncateToWidth(row, width, ELLIPSIS);\n });\n }\n\n private rosterLines(width: number): string[] {\n const lines = [this.theme.bold(ROSTER_HEADING), ''];\n if (this.items.length === 0) {\n lines.push(this.theme.fg('dim', EMPTY_ROSTER));\n return lines;\n }\n\n // Two rows per run: at a third of the width a single row left the name with\n // a handful of columns once the stage took its share.\n const budget = this.rosterCapacity();\n const active = Math.min(this.selected, this.items.length - 1);\n const start = Math.max(0, Math.min(active - budget + 1, Math.max(0, this.items.length - budget)));\n for (const [offset, item] of this.items.slice(start, start + budget).entries()) {\n const current = start + offset === active;\n const paused = item.executionState === PAUSED_STATE;\n const marker = current ? this.theme.fg('accent', SELECTION_MARKER) : ' ';\n const glyph = this.theme.fg(paused ? 'warning' : 'accent', '●');\n const name = current ? this.theme.bold(item.displayName) : item.displayName;\n const stage = paused ? PAUSED_STATE : (currentWorkflowPosition(item.jobs)?.job ?? 'starting');\n const heading = `${marker} ${glyph} ${name}`;\n const meta = `${' '.repeat(META_INDENT)}${this.theme.fg(paused ? 'warning' : 'dim', stage)}`;\n const background: ThemeBg = current ? 'selectedBg' : 'userMessageBg';\n for (const row of [heading, meta]) lines.push(this.theme.bg(background, fit(row, width)));\n }\n return lines;\n }\n\n /** Overridden: a repaint request is also the cue to re-read the registry. */\n invalidate(): void {\n void this.refresh();\n }\n\n dispose(): void {\n if (this.completed) return;\n this.completed = true;\n clearInterval(this.timer);\n }\n}\n"],"mappings":"iUAwBkD,EAA2B,eA2B7E,MAOM,EAAgB,UAChB,EAAe,SAEf,EAAuB,KACvB,EAAS,GAAG,EAAqB,mDACjC,EAAuD,CAC3D,CAAC,EAAsB,QAAQ,EAC/B,CAAC,YAAa,MAAM,EACpB,CA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Ae,gBACrD,IAAK,IAAM,IAAO,CAAC,EAAS,CAAI,EAAG,EAAM,KAAK,KAAK,MAAM,GAAG,EAAY,EAAI,EAAK,CAAK,CAAC,CAAC,CAC1F,CACA,OAAO,CACT,CAGA,YAAmB,CACjB,KAAU,QAAQ,CACpB,CAEA,SAAgB,CACV,KAAK,YACT,KAAK,UAAY,GACjB,cAAc,KAAK,KAAK,EAC1B,CACF"}
@@ -0,0 +1,2 @@
1
+ let e=require("@earendil-works/pi-tui");const t=`workflow-mcp-progress`,n=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],r={starting:`dim`,running:`accent`,completed:`success`,paused:`warning`,failed:`error`,skipped:`muted`};function i(e){return e.findLast(e=>e.type===`step`&&!!e.step)}function a(e){return e.at(-1)}function o(e,t){if(e.stage===`error`)return`failed`;if(e.stage===`completed`)return`completed`;if(e.executionState===`paused`||e.executionState===`pause_requested`)return`paused`;switch(t?.status){case`failed`:return`failed`;case`paused`:case`pause_requested`:return`paused`;case`completed`:return`completed`;case`skipped`:return`skipped`;case`resumed`:case`running`:return`running`;default:return e.executionCursor?.stepName?`running`:`starting`}}function s(e){switch(e.executionCursor?.phase){case`pre`:return`Preparing workflow`;case`post`:return`Finalizing workflow`;case`job`:case`step`:return`Starting job`;default:return`Starting workflow`}}function c(e,t){let n=i(t),r=a(t),c=e.executionCursor,l=c?.job??n?.job??r?.job??e.job??c?.phase??`workflow`,u=c?.stepName??(n?.job===l?n.step:void 0)??s(e);return{job:l,key:e.runId??`${e.workspace}/${e.runKey}`,name:e.displayName,startedAt:e.startedAt,state:o(e,r),step:u}}function l(e){if(!Number.isFinite(e)||e<0)return`?`;let t=Math.floor(e/1e3),n=t%60,r=Math.floor(t/60);if(r<60)return r===0?`${n}s`:`${r}m${String(n).padStart(2,`0`)}s`;let i=r%60;return`${Math.floor(r/60)}h${String(i).padStart(2,`0`)}m${String(n).padStart(2,`0`)}s`}function u(e,t){if(e!==`running`&&e!==`starting`)return`*`;let r=Number.isFinite(t)?Math.floor(Math.max(0,t)/200):0;return n[r%n.length]??n[0]}function d(e,t,n=Date.now()){let i=Date.parse(e.startedAt),a=l(Number.isFinite(i)?n-i:NaN),o=r[e.state];return[t.fg(o,e.name),t.fg(`muted`,`[${a}][${e.job}]`),t.fg(o,` ${u(e.state,n)} `),t.fg(`text`,e.step)].join(``)}var f=class{rows=[];uiCtx;widgetRegistered=!1;tui;progressTimer;setUICtx(e){e!==this.uiCtx&&(this.uiCtx&&this.widgetRegistered&&this.uiCtx.setWidget(t,void 0),this.stopProgressTimer(),this.uiCtx=e,this.widgetRegistered=!1,this.tui=void 0)}update(e){if(this.rows=e,!this.uiCtx){this.stopProgressTimer();return}if(e.length===0){this.widgetRegistered&&(this.uiCtx.setWidget(t,void 0),this.widgetRegistered=!1,this.tui=void 0),this.stopProgressTimer();return}if(this.widgetRegistered){this.syncProgressTimer(),this.tui?.requestRender();return}this.uiCtx.setWidget(t,(e,t)=>(this.tui=e,{render:e=>this.renderWidget(this.uiCtx?.theme??t,e),invalidate:()=>{}}),{placement:`aboveEditor`}),this.widgetRegistered=!0,this.syncProgressTimer()}syncProgressTimer(){if(!this.widgetRegistered||this.rows.length===0){this.stopProgressTimer();return}this.progressTimer||(this.progressTimer=setInterval(()=>this.tui?.requestRender(),200),this.progressTimer.unref?.())}stopProgressTimer(){this.progressTimer&&clearInterval(this.progressTimer),this.progressTimer=void 0}renderWidget(t,n){if(this.rows.length===0)return[];let r=t=>(0,e.truncateToWidth)(t,n,`…`),i=r(`${t.fg(`accent`,`●`)} ${t.fg(`accent`,`Workflows (${this.rows.length})`)}`),a=Date.now(),o=[i];for(let[e,n]of this.rows.entries()){let i=e===this.rows.length-1?`└─`:`├─`;o.push(r(`${t.fg(`dim`,i)} ${d(n,t,a)}`))}return o.push(``),o}dispose(){this.stopProgressTimer(),this.uiCtx&&this.uiCtx.setWidget(t,void 0),this.rows=[],this.widgetRegistered=!1,this.tui=void 0,this.uiCtx=void 0}};exports.WORKFLOW_PROGRESS_COLORS=r,exports.WORKFLOW_PROGRESS_WIDGET_KEY=t,exports.WorkflowProgressOverlay=f,exports.formatWorkflowDuration=l,exports.formatWorkflowProgressRow=d,exports.workflowProgressRow=c;
2
+ //# sourceMappingURL=workflowProgressOverlay.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workflowProgressOverlay.cjs","names":["truncateToWidth"],"sources":["../../../src/tui/workflow/workflowProgressOverlay.ts"],"sourcesContent":["/**\n * Task-like live workflow list shown above Pi's editor.\n *\n * DESIGN PATTERNS:\n * - The extension owns run/event state; this component only projects and renders it.\n * - Register the widget once, then request redraws as progress, elapsed time, or the spinner changes.\n * - Terminal runs are absent from `rows`, so the widget disappears when the last run ends.\n *\n * CODING STANDARDS:\n * - Every rendered line is ANSI-aware and truncated to the available terminal width.\n * - Theme colors come from Pi's live UI context so theme changes repaint correctly.\n * - Named exports only and explicit return types on exported members.\n *\n * AVOID:\n * - Persisting progress in the chat transcript.\n * - Starting timers while no workflow is visible.\n */\n\nimport type { WorkflowProgressEvent, WorkflowRunRecord } from '@agimon-ai/workflow-mcp';\nimport type { ExtensionUIContext, Theme } from '@earendil-works/pi-coding-agent';\nimport { type TUI, truncateToWidth } from '@earendil-works/pi-tui';\n\nexport const WORKFLOW_PROGRESS_WIDGET_KEY = 'workflow-mcp-progress';\n\nconst OVERLAY_HEADING = 'Workflows';\nconst PROGRESS_TICK_MS = 200;\nconst RUNNING_SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] as const;\nconst STATIC_PROGRESS_MARKER = '*';\nconst MILLISECONDS_PER_SECOND = 1000;\nconst SECONDS_PER_MINUTE = 60;\nconst MINUTES_PER_HOUR = 60;\nconst STARTING_JOB_STEP = 'Starting job';\nconst STARTING_WORKFLOW_STEP = 'Starting workflow';\nconst PREPARING_WORKFLOW_STEP = 'Preparing workflow';\nconst FINALIZING_WORKFLOW_STEP = 'Finalizing workflow';\n\ntype WorkflowProgressColor = Parameters<Theme['fg']>[0];\n\nexport type WorkflowProgressState = 'completed' | 'failed' | 'paused' | 'running' | 'skipped' | 'starting';\n\n/** One explicit palette makes every workflow state visually stable across the list. */\nexport const WORKFLOW_PROGRESS_COLORS: Readonly<Record<WorkflowProgressState, WorkflowProgressColor>> = {\n starting: 'dim',\n running: 'accent',\n completed: 'success',\n paused: 'warning',\n failed: 'error',\n skipped: 'muted',\n};\n\nexport interface WorkflowProgressRow {\n job: string;\n key: string;\n name: string;\n startedAt: string;\n state: WorkflowProgressState;\n step: string;\n}\n\nfunction latestStep(events: readonly WorkflowProgressEvent[]): WorkflowProgressEvent | undefined {\n return events.findLast((event) => event.type === 'step' && !!event.step);\n}\n\nfunction latestEvent(events: readonly WorkflowProgressEvent[]): WorkflowProgressEvent | undefined {\n return events.at(-1);\n}\n\nfunction progressState(record: WorkflowRunRecord, event: WorkflowProgressEvent | undefined): WorkflowProgressState {\n if (record.stage === 'error') return 'failed';\n if (record.stage === 'completed') return 'completed';\n if (record.executionState === 'paused' || record.executionState === 'pause_requested') return 'paused';\n\n switch (event?.status) {\n case 'failed':\n return 'failed';\n case 'paused':\n case 'pause_requested':\n return 'paused';\n case 'completed':\n return 'completed';\n case 'skipped':\n return 'skipped';\n case 'resumed':\n case 'running':\n return 'running';\n default:\n return record.executionCursor?.stepName ? 'running' : 'starting';\n }\n}\n\nfunction fallbackStep(record: WorkflowRunRecord): string {\n switch (record.executionCursor?.phase) {\n case 'pre':\n return PREPARING_WORKFLOW_STEP;\n case 'post':\n return FINALIZING_WORKFLOW_STEP;\n case 'job':\n case 'step':\n return STARTING_JOB_STEP;\n default:\n return STARTING_WORKFLOW_STEP;\n }\n}\n\n/** Derive the single current line for one run from its record and pushed progress events. */\nexport function workflowProgressRow(\n record: WorkflowRunRecord,\n events: readonly WorkflowProgressEvent[],\n): WorkflowProgressRow {\n const stepEvent = latestStep(events);\n const event = latestEvent(events);\n const cursor = record.executionCursor;\n const job = cursor?.job ?? stepEvent?.job ?? event?.job ?? record.job ?? cursor?.phase ?? 'workflow';\n const step = cursor?.stepName ?? (stepEvent?.job === job ? stepEvent.step : undefined) ?? fallbackStep(record);\n\n return {\n job,\n key: record.runId ?? `${record.workspace}/${record.runKey}`,\n name: record.displayName,\n startedAt: record.startedAt,\n state: progressState(record, event),\n step,\n };\n}\n\n/** Task-style elapsed time: whole seconds stay stable and compact between animation ticks. */\nexport function formatWorkflowDuration(durationMs: number): string {\n if (!Number.isFinite(durationMs) || durationMs < 0) return '?';\n const totalSeconds = Math.floor(durationMs / MILLISECONDS_PER_SECOND);\n const seconds = totalSeconds % SECONDS_PER_MINUTE;\n const totalMinutes = Math.floor(totalSeconds / SECONDS_PER_MINUTE);\n if (totalMinutes < MINUTES_PER_HOUR) {\n return totalMinutes === 0 ? `${seconds}s` : `${totalMinutes}m${String(seconds).padStart(2, '0')}s`;\n }\n const minutes = totalMinutes % MINUTES_PER_HOUR;\n const hours = Math.floor(totalMinutes / MINUTES_PER_HOUR);\n return `${hours}h${String(minutes).padStart(2, '0')}m${String(seconds).padStart(2, '0')}s`;\n}\n\nfunction progressMarker(state: WorkflowProgressState, nowMs: number): string {\n if (state !== 'running' && state !== 'starting') return STATIC_PROGRESS_MARKER;\n const tick = Number.isFinite(nowMs) ? Math.floor(Math.max(0, nowMs) / PROGRESS_TICK_MS) : 0;\n return RUNNING_SPINNER_FRAMES[tick % RUNNING_SPINNER_FRAMES.length] ?? RUNNING_SPINNER_FRAMES[0];\n}\n\n/** Render exactly: `<workflow name>[<duration>][<job>] <activity> <step>`. */\nexport function formatWorkflowProgressRow(row: WorkflowProgressRow, theme: Theme, nowMs = Date.now()): string {\n const startedAt = Date.parse(row.startedAt);\n const duration = formatWorkflowDuration(Number.isFinite(startedAt) ? nowMs - startedAt : Number.NaN);\n const color = WORKFLOW_PROGRESS_COLORS[row.state];\n return [\n theme.fg(color, row.name),\n theme.fg('muted', `[${duration}][${row.job}]`),\n theme.fg(color, ` ${progressMarker(row.state, nowMs)} `),\n theme.fg('text', row.step),\n ].join('');\n}\n\n/** Persistent workflow widget with the same heading/tree shape as Doom's task list. */\nexport class WorkflowProgressOverlay {\n private rows: readonly WorkflowProgressRow[] = [];\n private uiCtx: ExtensionUIContext | undefined;\n private widgetRegistered = false;\n private tui: TUI | undefined;\n private progressTimer: NodeJS.Timeout | undefined;\n\n /** Identity-compare so repeated session starts do not register duplicate widgets. */\n setUICtx(ctx: ExtensionUIContext): void {\n if (ctx === this.uiCtx) return;\n if (this.uiCtx && this.widgetRegistered) this.uiCtx.setWidget(WORKFLOW_PROGRESS_WIDGET_KEY, undefined);\n this.stopProgressTimer();\n this.uiCtx = ctx;\n this.widgetRegistered = false;\n this.tui = undefined;\n }\n\n update(rows: readonly WorkflowProgressRow[]): void {\n this.rows = rows;\n if (!this.uiCtx) {\n this.stopProgressTimer();\n return;\n }\n\n if (rows.length === 0) {\n if (this.widgetRegistered) {\n this.uiCtx.setWidget(WORKFLOW_PROGRESS_WIDGET_KEY, undefined);\n this.widgetRegistered = false;\n this.tui = undefined;\n }\n this.stopProgressTimer();\n return;\n }\n\n if (this.widgetRegistered) {\n this.syncProgressTimer();\n this.tui?.requestRender();\n return;\n }\n\n this.uiCtx.setWidget(\n WORKFLOW_PROGRESS_WIDGET_KEY,\n (tui, factoryTheme) => {\n this.tui = tui;\n return {\n render: (width: number) => this.renderWidget(this.uiCtx?.theme ?? factoryTheme, width),\n invalidate: () => {\n // Nothing cached: the next render reads the current rows, clock, and theme.\n },\n };\n },\n { placement: 'aboveEditor' },\n );\n this.widgetRegistered = true;\n this.syncProgressTimer();\n }\n\n private syncProgressTimer(): void {\n if (!this.widgetRegistered || this.rows.length === 0) {\n this.stopProgressTimer();\n return;\n }\n if (this.progressTimer) return;\n this.progressTimer = setInterval(() => this.tui?.requestRender(), PROGRESS_TICK_MS);\n this.progressTimer.unref?.();\n }\n\n private stopProgressTimer(): void {\n if (this.progressTimer) clearInterval(this.progressTimer);\n this.progressTimer = undefined;\n }\n\n private renderWidget(theme: Theme, width: number): string[] {\n if (this.rows.length === 0) return [];\n const truncate = (line: string): string => truncateToWidth(line, width, '…');\n const heading = truncate(\n `${theme.fg('accent', '●')} ${theme.fg('accent', `${OVERLAY_HEADING} (${this.rows.length})`)}`,\n );\n const nowMs = Date.now();\n const lines = [heading];\n\n for (const [index, row] of this.rows.entries()) {\n const branch = index === this.rows.length - 1 ? '└─' : '├─';\n lines.push(truncate(`${theme.fg('dim', branch)} ${formatWorkflowProgressRow(row, theme, nowMs)}`));\n }\n\n // Pi adds space above widgets but not below; keep the list off the editor border.\n lines.push('');\n return lines;\n }\n\n dispose(): void {\n this.stopProgressTimer();\n if (this.uiCtx) this.uiCtx.setWidget(WORKFLOW_PROGRESS_WIDGET_KEY, undefined);\n this.rows = [];\n this.widgetRegistered = false;\n this.tui = undefined;\n this.uiCtx = undefined;\n }\n}\n"],"mappings":"wCAsBA,MAAa,EAA+B,wBAItC,EAAyB,CAAC,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,GAAG,EAenE,EAA2F,CACtG,SAAU,MACV,QAAS,SACT,UAAW,UACX,OAAQ,UACR,OAAQ,QACR,QAAS,OACX,EAWA,SAAS,EAAW,EAA6E,CAC/F,OAAO,EAAO,SAAU,GAAU,EAAM,OAAS,QAAU,CAAC,CAAC,EAAM,IAAI,CACzE,CAEA,SAAS,EAAY,EAA6E,CAChG,OAAO,EAAO,GAAG,EAAE,CACrB,CAEA,SAAS,EAAc,EAA2B,EAAiE,CACjH,GAAI,EAAO,QAAU,QAAS,MAAO,SACrC,GAAI,EAAO,QAAU,YAAa,MAAO,YACzC,GAAI,EAAO,iBAAmB,UAAY,EAAO,iBAAmB,kBAAmB,MAAO,SAE9F,OAAQ,GAAO,OAAf,CACE,IAAK,SACH,MAAO,SACT,IAAK,SACL,IAAK,kBACH,MAAO,SACT,IAAK,YACH,MAAO,YACT,IAAK,UACH,MAA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,GACX,KAAK,MAAQ,IAAA,EACf,CACF"}
@@ -0,0 +1,2 @@
1
+ import{truncateToWidth as e}from"@earendil-works/pi-tui";const t=`workflow-mcp-progress`,n=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],r={starting:`dim`,running:`accent`,completed:`success`,paused:`warning`,failed:`error`,skipped:`muted`};function i(e){return e.findLast(e=>e.type===`step`&&!!e.step)}function a(e){return e.at(-1)}function o(e,t){if(e.stage===`error`)return`failed`;if(e.stage===`completed`)return`completed`;if(e.executionState===`paused`||e.executionState===`pause_requested`)return`paused`;switch(t?.status){case`failed`:return`failed`;case`paused`:case`pause_requested`:return`paused`;case`completed`:return`completed`;case`skipped`:return`skipped`;case`resumed`:case`running`:return`running`;default:return e.executionCursor?.stepName?`running`:`starting`}}function s(e){switch(e.executionCursor?.phase){case`pre`:return`Preparing workflow`;case`post`:return`Finalizing workflow`;case`job`:case`step`:return`Starting job`;default:return`Starting workflow`}}function c(e,t){let n=i(t),r=a(t),c=e.executionCursor,l=c?.job??n?.job??r?.job??e.job??c?.phase??`workflow`,u=c?.stepName??(n?.job===l?n.step:void 0)??s(e);return{job:l,key:e.runId??`${e.workspace}/${e.runKey}`,name:e.displayName,startedAt:e.startedAt,state:o(e,r),step:u}}function l(e){if(!Number.isFinite(e)||e<0)return`?`;let t=Math.floor(e/1e3),n=t%60,r=Math.floor(t/60);if(r<60)return r===0?`${n}s`:`${r}m${String(n).padStart(2,`0`)}s`;let i=r%60;return`${Math.floor(r/60)}h${String(i).padStart(2,`0`)}m${String(n).padStart(2,`0`)}s`}function u(e,t){if(e!==`running`&&e!==`starting`)return`*`;let r=Number.isFinite(t)?Math.floor(Math.max(0,t)/200):0;return n[r%n.length]??n[0]}function d(e,t,n=Date.now()){let i=Date.parse(e.startedAt),a=l(Number.isFinite(i)?n-i:NaN),o=r[e.state];return[t.fg(o,e.name),t.fg(`muted`,`[${a}][${e.job}]`),t.fg(o,` ${u(e.state,n)} `),t.fg(`text`,e.step)].join(``)}var f=class{rows=[];uiCtx;widgetRegistered=!1;tui;progressTimer;setUICtx(e){e!==this.uiCtx&&(this.uiCtx&&this.widgetRegistered&&this.uiCtx.setWidget(t,void 0),this.stopProgressTimer(),this.uiCtx=e,this.widgetRegistered=!1,this.tui=void 0)}update(e){if(this.rows=e,!this.uiCtx){this.stopProgressTimer();return}if(e.length===0){this.widgetRegistered&&(this.uiCtx.setWidget(t,void 0),this.widgetRegistered=!1,this.tui=void 0),this.stopProgressTimer();return}if(this.widgetRegistered){this.syncProgressTimer(),this.tui?.requestRender();return}this.uiCtx.setWidget(t,(e,t)=>(this.tui=e,{render:e=>this.renderWidget(this.uiCtx?.theme??t,e),invalidate:()=>{}}),{placement:`aboveEditor`}),this.widgetRegistered=!0,this.syncProgressTimer()}syncProgressTimer(){if(!this.widgetRegistered||this.rows.length===0){this.stopProgressTimer();return}this.progressTimer||(this.progressTimer=setInterval(()=>this.tui?.requestRender(),200),this.progressTimer.unref?.())}stopProgressTimer(){this.progressTimer&&clearInterval(this.progressTimer),this.progressTimer=void 0}renderWidget(t,n){if(this.rows.length===0)return[];let r=t=>e(t,n,`…`),i=r(`${t.fg(`accent`,`●`)} ${t.fg(`accent`,`Workflows (${this.rows.length})`)}`),a=Date.now(),o=[i];for(let[e,n]of this.rows.entries()){let i=e===this.rows.length-1?`└─`:`├─`;o.push(r(`${t.fg(`dim`,i)} ${d(n,t,a)}`))}return o.push(``),o}dispose(){this.stopProgressTimer(),this.uiCtx&&this.uiCtx.setWidget(t,void 0),this.rows=[],this.widgetRegistered=!1,this.tui=void 0,this.uiCtx=void 0}};export{r as WORKFLOW_PROGRESS_COLORS,t as WORKFLOW_PROGRESS_WIDGET_KEY,f as WorkflowProgressOverlay,l as formatWorkflowDuration,d as formatWorkflowProgressRow,c as workflowProgressRow};
2
+ //# sourceMappingURL=workflowProgressOverlay.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workflowProgressOverlay.mjs","names":[],"sources":["../../../src/tui/workflow/workflowProgressOverlay.ts"],"sourcesContent":["/**\n * Task-like live workflow list shown above Pi's editor.\n *\n * DESIGN PATTERNS:\n * - The extension owns run/event state; this component only projects and renders it.\n * - Register the widget once, then request redraws as progress, elapsed time, or the spinner changes.\n * - Terminal runs are absent from `rows`, so the widget disappears when the last run ends.\n *\n * CODING STANDARDS:\n * - Every rendered line is ANSI-aware and truncated to the available terminal width.\n * - Theme colors come from Pi's live UI context so theme changes repaint correctly.\n * - Named exports only and explicit return types on exported members.\n *\n * AVOID:\n * - Persisting progress in the chat transcript.\n * - Starting timers while no workflow is visible.\n */\n\nimport type { WorkflowProgressEvent, WorkflowRunRecord } from '@agimon-ai/workflow-mcp';\nimport type { ExtensionUIContext, Theme } from '@earendil-works/pi-coding-agent';\nimport { type TUI, truncateToWidth } from '@earendil-works/pi-tui';\n\nexport const WORKFLOW_PROGRESS_WIDGET_KEY = 'workflow-mcp-progress';\n\nconst OVERLAY_HEADING = 'Workflows';\nconst PROGRESS_TICK_MS = 200;\nconst RUNNING_SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] as const;\nconst STATIC_PROGRESS_MARKER = '*';\nconst MILLISECONDS_PER_SECOND = 1000;\nconst SECONDS_PER_MINUTE = 60;\nconst MINUTES_PER_HOUR = 60;\nconst STARTING_JOB_STEP = 'Starting job';\nconst STARTING_WORKFLOW_STEP = 'Starting workflow';\nconst PREPARING_WORKFLOW_STEP = 'Preparing workflow';\nconst FINALIZING_WORKFLOW_STEP = 'Finalizing workflow';\n\ntype WorkflowProgressColor = Parameters<Theme['fg']>[0];\n\nexport type WorkflowProgressState = 'completed' | 'failed' | 'paused' | 'running' | 'skipped' | 'starting';\n\n/** One explicit palette makes every workflow state visually stable across the list. */\nexport const WORKFLOW_PROGRESS_COLORS: Readonly<Record<WorkflowProgressState, WorkflowProgressColor>> = {\n starting: 'dim',\n running: 'accent',\n completed: 'success',\n paused: 'warning',\n failed: 'error',\n skipped: 'muted',\n};\n\nexport interface WorkflowProgressRow {\n job: string;\n key: string;\n name: string;\n startedAt: string;\n state: WorkflowProgressState;\n step: string;\n}\n\nfunction latestStep(events: readonly WorkflowProgressEvent[]): WorkflowProgressEvent | undefined {\n return events.findLast((event) => event.type === 'step' && !!event.step);\n}\n\nfunction latestEvent(events: readonly WorkflowProgressEvent[]): WorkflowProgressEvent | undefined {\n return events.at(-1);\n}\n\nfunction progressState(record: WorkflowRunRecord, event: WorkflowProgressEvent | undefined): WorkflowProgressState {\n if (record.stage === 'error') return 'failed';\n if (record.stage === 'completed') return 'completed';\n if (record.executionState === 'paused' || record.executionState === 'pause_requested') return 'paused';\n\n switch (event?.status) {\n case 'failed':\n return 'failed';\n case 'paused':\n case 'pause_requested':\n return 'paused';\n case 'completed':\n return 'completed';\n case 'skipped':\n return 'skipped';\n case 'resumed':\n case 'running':\n return 'running';\n default:\n return record.executionCursor?.stepName ? 'running' : 'starting';\n }\n}\n\nfunction fallbackStep(record: WorkflowRunRecord): string {\n switch (record.executionCursor?.phase) {\n case 'pre':\n return PREPARING_WORKFLOW_STEP;\n case 'post':\n return FINALIZING_WORKFLOW_STEP;\n case 'job':\n case 'step':\n return STARTING_JOB_STEP;\n default:\n return STARTING_WORKFLOW_STEP;\n }\n}\n\n/** Derive the single current line for one run from its record and pushed progress events. */\nexport function workflowProgressRow(\n record: WorkflowRunRecord,\n events: readonly WorkflowProgressEvent[],\n): WorkflowProgressRow {\n const stepEvent = latestStep(events);\n const event = latestEvent(events);\n const cursor = record.executionCursor;\n const job = cursor?.job ?? stepEvent?.job ?? event?.job ?? record.job ?? cursor?.phase ?? 'workflow';\n const step = cursor?.stepName ?? (stepEvent?.job === job ? stepEvent.step : undefined) ?? fallbackStep(record);\n\n return {\n job,\n key: record.runId ?? `${record.workspace}/${record.runKey}`,\n name: record.displayName,\n startedAt: record.startedAt,\n state: progressState(record, event),\n step,\n };\n}\n\n/** Task-style elapsed time: whole seconds stay stable and compact between animation ticks. */\nexport function formatWorkflowDuration(durationMs: number): string {\n if (!Number.isFinite(durationMs) || durationMs < 0) return '?';\n const totalSeconds = Math.floor(durationMs / MILLISECONDS_PER_SECOND);\n const seconds = totalSeconds % SECONDS_PER_MINUTE;\n const totalMinutes = Math.floor(totalSeconds / SECONDS_PER_MINUTE);\n if (totalMinutes < MINUTES_PER_HOUR) {\n return totalMinutes === 0 ? `${seconds}s` : `${totalMinutes}m${String(seconds).padStart(2, '0')}s`;\n }\n const minutes = totalMinutes % MINUTES_PER_HOUR;\n const hours = Math.floor(totalMinutes / MINUTES_PER_HOUR);\n return `${hours}h${String(minutes).padStart(2, '0')}m${String(seconds).padStart(2, '0')}s`;\n}\n\nfunction progressMarker(state: WorkflowProgressState, nowMs: number): string {\n if (state !== 'running' && state !== 'starting') return STATIC_PROGRESS_MARKER;\n const tick = Number.isFinite(nowMs) ? Math.floor(Math.max(0, nowMs) / PROGRESS_TICK_MS) : 0;\n return RUNNING_SPINNER_FRAMES[tick % RUNNING_SPINNER_FRAMES.length] ?? RUNNING_SPINNER_FRAMES[0];\n}\n\n/** Render exactly: `<workflow name>[<duration>][<job>] <activity> <step>`. */\nexport function formatWorkflowProgressRow(row: WorkflowProgressRow, theme: Theme, nowMs = Date.now()): string {\n const startedAt = Date.parse(row.startedAt);\n const duration = formatWorkflowDuration(Number.isFinite(startedAt) ? nowMs - startedAt : Number.NaN);\n const color = WORKFLOW_PROGRESS_COLORS[row.state];\n return [\n theme.fg(color, row.name),\n theme.fg('muted', `[${duration}][${row.job}]`),\n theme.fg(color, ` ${progressMarker(row.state, nowMs)} `),\n theme.fg('text', row.step),\n ].join('');\n}\n\n/** Persistent workflow widget with the same heading/tree shape as Doom's task list. */\nexport class WorkflowProgressOverlay {\n private rows: readonly WorkflowProgressRow[] = [];\n private uiCtx: ExtensionUIContext | undefined;\n private widgetRegistered = false;\n private tui: TUI | undefined;\n private progressTimer: NodeJS.Timeout | undefined;\n\n /** Identity-compare so repeated session starts do not register duplicate widgets. */\n setUICtx(ctx: ExtensionUIContext): void {\n if (ctx === this.uiCtx) return;\n if (this.uiCtx && this.widgetRegistered) this.uiCtx.setWidget(WORKFLOW_PROGRESS_WIDGET_KEY, undefined);\n this.stopProgressTimer();\n this.uiCtx = ctx;\n this.widgetRegistered = false;\n this.tui = undefined;\n }\n\n update(rows: readonly WorkflowProgressRow[]): void {\n this.rows = rows;\n if (!this.uiCtx) {\n this.stopProgressTimer();\n return;\n }\n\n if (rows.length === 0) {\n if (this.widgetRegistered) {\n this.uiCtx.setWidget(WORKFLOW_PROGRESS_WIDGET_KEY, undefined);\n this.widgetRegistered = false;\n this.tui = undefined;\n }\n this.stopProgressTimer();\n return;\n }\n\n if (this.widgetRegistered) {\n this.syncProgressTimer();\n this.tui?.requestRender();\n return;\n }\n\n this.uiCtx.setWidget(\n WORKFLOW_PROGRESS_WIDGET_KEY,\n (tui, factoryTheme) => {\n this.tui = tui;\n return {\n render: (width: number) => this.renderWidget(this.uiCtx?.theme ?? factoryTheme, width),\n invalidate: () => {\n // Nothing cached: the next render reads the current rows, clock, and theme.\n },\n };\n },\n { placement: 'aboveEditor' },\n );\n this.widgetRegistered = true;\n this.syncProgressTimer();\n }\n\n private syncProgressTimer(): void {\n if (!this.widgetRegistered || this.rows.length === 0) {\n this.stopProgressTimer();\n return;\n }\n if (this.progressTimer) return;\n this.progressTimer = setInterval(() => this.tui?.requestRender(), PROGRESS_TICK_MS);\n this.progressTimer.unref?.();\n }\n\n private stopProgressTimer(): void {\n if (this.progressTimer) clearInterval(this.progressTimer);\n this.progressTimer = undefined;\n }\n\n private renderWidget(theme: Theme, width: number): string[] {\n if (this.rows.length === 0) return [];\n const truncate = (line: string): string => truncateToWidth(line, width, '…');\n const heading = truncate(\n `${theme.fg('accent', '●')} ${theme.fg('accent', `${OVERLAY_HEADING} (${this.rows.length})`)}`,\n );\n const nowMs = Date.now();\n const lines = [heading];\n\n for (const [index, row] of this.rows.entries()) {\n const branch = index === this.rows.length - 1 ? '└─' : '├─';\n lines.push(truncate(`${theme.fg('dim', branch)} ${formatWorkflowProgressRow(row, theme, nowMs)}`));\n }\n\n // Pi adds space above widgets but not below; keep the list off the editor border.\n lines.push('');\n return lines;\n }\n\n dispose(): void {\n this.stopProgressTimer();\n if (this.uiCtx) this.uiCtx.setWidget(WORKFLOW_PROGRESS_WIDGET_KEY, undefined);\n this.rows = [];\n this.widgetRegistered = false;\n this.tui = undefined;\n this.uiCtx = undefined;\n }\n}\n"],"mappings":"yDAsBA,MAAa,EAA+B,wBAItC,EAAyB,CAAC,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,GAAG,EAenE,EAA2F,CACtG,SAAU,MACV,QAAS,SACT,UAAW,UACX,OAAQ,UACR,OAAQ,QACR,QAAS,OACX,EAWA,SAAS,EAAW,EAA6E,CAC/F,OAAO,EAAO,SAAU,GAAU,EAAM,OAAS,QAAU,CAAC,CAAC,EAAM,IAAI,CACzE,CAEA,SAAS,EAAY,EAA6E,CAChG,OAAO,EAAO,GAAG,EAAE,CACrB,CAEA,SAAS,EAAc,EAA2B,EAAiE,CACjH,GAAI,EAAO,QAAU,QAAS,MAAO,SACrC,GAAI,EAAO,QAAU,YAAa,MAAO,YACzC,GAAI,EAAO,iBAAmB,UAAY,EAAO,iBAAmB,kBAAmB,MAAO,SAE9F,OAAQ,GAAO,OAAf,CACE,IAAK,SACH,MAAO,SACT,IAAK,SACL,IAAK,kBACH,MAAO,SACT,IAAK,YACH,MAAO,YACT,IAAK,UACH,MAAO,UACT,IAAK,UACL,IAAK,UACH,MAAO,UACT,QACE,OAAO,EAAO,iBAAiB,SAAW,UAAY,UAC1D,CACF,CAEA,SAAS,EAAa,EAAmC,CACvD,OAAQ,EAAO,iBAAiB,MAAhC,CACE,IAAK,MACH,MAAO,qBACT,IAAK,OACH,MAAO,sBACT,IAAK,MACL,IAAK,OACH,MAAO,eACT,QACE,MAAO,mBACX,CACF,C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KAAK,KAAK,SAAW,EAAG,CACpD,KAAK,kBAAkB,EACvB,MACF,CACI,KAAK,gBACT,KAAK,cAAgB,gBAAkB,KAAK,KAAK,cAAc,EAAG,GAAgB,EAClF,KAAK,cAAc,QAAQ,EAC7B,CAEA,mBAAkC,CAC5B,KAAK,eAAe,cAAc,KAAK,aAAa,EACxD,KAAK,cAAgB,IAAA,EACvB,CAEA,aAAqB,EAAc,EAAyB,CAC1D,GAAI,KAAK,KAAK,SAAW,EAAG,MAAO,CAAC,EACpC,IAAM,EAAY,GAAyB,EAAgB,EAAM,EAAO,GAAG,EACrE,EAAU,EACd,GAAG,EAAM,GAAG,SAAU,GAAG,EAAE,GAAG,EAAM,GAAG,SAAU,cAAuB,KAAK,KAAK,OAAO,EAAE,GAC7F,EACM,EAAQ,KAAK,IAAI,EACjB,EAAQ,CAAC,CAAO,EAEtB,IAAK,GAAM,CAAC,EAAO,KAAQ,KAAK,KAAK,QAAQ,EAAG,CAC9C,IAAM,EAAS,IAAU,KAAK,KAAK,OAAS,EAAI,KAAO,KACvD,EAAM,KAAK,EAAS,GAAG,EAAM,GAAG,MAAO,CAAM,EAAE,GAAG,EAA0B,EAAK,EAAO,CAAK,GAAG,CAAC,CACnG,CAIA,OADA,EAAM,KAAK,EAAE,EACN,CACT,CAEA,SAAgB,CACd,KAAK,kBAAkB,EACnB,KAAK,OAAO,KAAK,MAAM,UAAU,EAA8B,IAAA,EAAS,EAC5E,KAAK,KAAO,CAAC,EACb,KAAK,iBAAmB,GACxB,KAAK,IAAM,IAAA,GACX,KAAK,MAAQ,IAAA,EACf,CACF"}
@@ -1,2 +1,2 @@
1
- function e(e){return e.length<=48?e:`${e.slice(0,47)}…`}function t(e){if(!Number.isFinite(e)||e<0)return`?`;if(e<1e3)return`${e}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60);return n<60?`${n}m${String(t%60).padStart(2,`0`)}s`:`${Math.floor(n/60)}h${String(n%60).padStart(2,`0`)}m`}function n(n,r){let i=new Map,a=[];for(let o of r){if(o.type!==`step`||!o.step)continue;let r=`${`${n}/${o.job}`}/${o.step}`,s=e(o.step);if(o.status===`running`){i.set(r,o.at),a.push({job:o.job,key:`started:${r}:${o.at}`,status:`STARTED`,step:s});continue}let c=i.get(r),l=c?t(Date.parse(o.at)-Date.parse(c)):`?`,u=o.status===`failed`?`FAILED`:`FINISHED`;a.push({duration:l,job:o.job,key:`${u}:${r}:${o.at}`,status:u,step:s})}return a}exports.humanizeDuration=t,exports.stepReportLines=n;
1
+ function e(e){if(!Number.isFinite(e)||e<0)return`?`;if(e<1e3)return`${e}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60);return n<60?`${n}m${String(t%60).padStart(2,`0`)}s`:`${Math.floor(n/60)}h${String(n%60).padStart(2,`0`)}m`}exports.humanizeDuration=e;
2
2
  //# sourceMappingURL=workflowStatusRow.cjs.map