@agimon-ai/doompi-workflow 0.0.1-alpha.4 → 0.0.1-alpha.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +6 -0
- package/README.md +108 -26
- package/dist/_virtual/_rolldown/runtime.cjs +1 -0
- package/dist/adapters/pi/extension.cjs +2 -0
- package/dist/adapters/pi/extension.cjs.map +1 -0
- package/dist/adapters/pi/extension.d.cts +8 -0
- package/dist/adapters/pi/extension.d.cts.map +1 -0
- package/dist/adapters/pi/extension.d.mts +8 -0
- package/dist/adapters/pi/extension.d.mts.map +1 -0
- package/dist/adapters/pi/extension.mjs +2 -0
- package/dist/adapters/pi/extension.mjs.map +1 -0
- package/dist/adapters/pi/leader.cjs +2 -0
- package/dist/adapters/pi/leader.cjs.map +1 -0
- package/dist/adapters/pi/leader.mjs +2 -0
- package/dist/adapters/pi/leader.mjs.map +1 -0
- package/dist/adapters/pi/workflow/piExtension.cjs +9 -0
- package/dist/adapters/pi/workflow/piExtension.cjs.map +1 -0
- package/dist/adapters/pi/workflow/piExtension.mjs +9 -0
- package/dist/adapters/pi/workflow/piExtension.mjs.map +1 -0
- package/dist/{workflow → adapters/pi/workflow}/piToolBridge.cjs +1 -1
- package/dist/adapters/pi/workflow/piToolBridge.cjs.map +1 -0
- package/dist/{workflow → adapters/pi/workflow}/piToolBridge.mjs +1 -1
- package/dist/adapters/pi/workflow/piToolBridge.mjs.map +1 -0
- package/dist/adapters/pi/workflow/piTools.cjs +5 -0
- package/dist/adapters/pi/workflow/piTools.cjs.map +1 -0
- package/dist/adapters/pi/workflow/piTools.mjs +5 -0
- package/dist/adapters/pi/workflow/piTools.mjs.map +1 -0
- package/dist/adapters/pi/workflow/workflowLauncher.cjs +2 -0
- package/dist/adapters/pi/workflow/workflowLauncher.cjs.map +1 -0
- package/dist/adapters/pi/workflow/workflowLauncher.mjs +2 -0
- package/dist/adapters/pi/workflow/workflowLauncher.mjs.map +1 -0
- package/dist/adapters/workflowCatalogChannel.cjs +2 -0
- package/dist/adapters/workflowCatalogChannel.cjs.map +1 -0
- package/dist/adapters/workflowCatalogChannel.d.cts +23 -0
- package/dist/adapters/workflowCatalogChannel.d.cts.map +1 -0
- package/dist/adapters/workflowCatalogChannel.d.mts +23 -0
- package/dist/adapters/workflowCatalogChannel.d.mts.map +1 -0
- package/dist/adapters/workflowCatalogChannel.mjs +2 -0
- package/dist/adapters/workflowCatalogChannel.mjs.map +1 -0
- package/dist/adapters/workflowHubApi.cjs +2 -0
- package/dist/adapters/workflowHubApi.cjs.map +1 -0
- package/dist/adapters/workflowHubApi.d.cts +24 -0
- package/dist/adapters/workflowHubApi.d.cts.map +1 -0
- package/dist/adapters/workflowHubApi.d.mts +24 -0
- package/dist/adapters/workflowHubApi.d.mts.map +1 -0
- package/dist/adapters/workflowHubApi.mjs +2 -0
- package/dist/adapters/workflowHubApi.mjs.map +1 -0
- package/dist/adapters/workflowWatcher.cjs +2 -0
- package/dist/adapters/workflowWatcher.cjs.map +1 -0
- package/dist/adapters/workflowWatcher.d.cts +24 -0
- package/dist/adapters/workflowWatcher.d.cts.map +1 -0
- package/dist/adapters/workflowWatcher.d.mts +24 -0
- package/dist/adapters/workflowWatcher.d.mts.map +1 -0
- package/dist/adapters/workflowWatcher.mjs +2 -0
- package/dist/adapters/workflowWatcher.mjs.map +1 -0
- package/dist/adapters/workflowsHubChannel.cjs +2 -0
- package/dist/adapters/workflowsHubChannel.cjs.map +1 -0
- package/dist/adapters/workflowsHubChannel.d.cts +20 -0
- package/dist/adapters/workflowsHubChannel.d.cts.map +1 -0
- package/dist/adapters/workflowsHubChannel.d.mts +20 -0
- package/dist/adapters/workflowsHubChannel.d.mts.map +1 -0
- package/dist/adapters/workflowsHubChannel.mjs +2 -0
- package/dist/adapters/workflowsHubChannel.mjs.map +1 -0
- package/dist/extensions/pi.cjs +1 -2
- package/dist/extensions/pi.d.cts +2 -2
- package/dist/extensions/pi.d.mts +2 -2
- package/dist/extensions/pi.mjs +1 -2
- package/dist/hubApi.cjs +1 -0
- package/dist/hubApi.d.cts +2 -0
- package/dist/hubApi.d.mts +2 -0
- package/dist/hubApi.mjs +1 -0
- package/dist/index.cjs +0 -1
- package/dist/index.d.cts +1 -3
- package/dist/index.d.mts +1 -3
- package/dist/index.mjs +1 -1
- package/dist/schemas/workflowPi.cjs +2 -0
- package/dist/schemas/workflowPi.cjs.map +1 -0
- package/dist/schemas/workflowPi.mjs +2 -0
- package/dist/schemas/workflowPi.mjs.map +1 -0
- package/dist/services/backgroundWork.cjs +2 -0
- package/dist/services/backgroundWork.cjs.map +1 -0
- package/dist/services/backgroundWork.mjs +2 -0
- package/dist/services/backgroundWork.mjs.map +1 -0
- package/dist/services/webWorkflowCatalog.cjs +2 -0
- package/dist/services/webWorkflowCatalog.cjs.map +1 -0
- package/dist/services/webWorkflowCatalog.d.cts +49 -0
- package/dist/services/webWorkflowCatalog.d.cts.map +1 -0
- package/dist/services/webWorkflowCatalog.d.mts +49 -0
- package/dist/services/webWorkflowCatalog.d.mts.map +1 -0
- package/dist/services/webWorkflowCatalog.mjs +2 -0
- package/dist/services/webWorkflowCatalog.mjs.map +1 -0
- package/dist/services/workflowLaunchCommand.cjs +2 -0
- package/dist/services/workflowLaunchCommand.cjs.map +1 -0
- package/dist/services/workflowLaunchCommand.mjs +2 -0
- package/dist/services/workflowLaunchCommand.mjs.map +1 -0
- package/dist/services/workflowNarration.cjs +2 -0
- package/dist/services/workflowNarration.cjs.map +1 -0
- package/dist/services/workflowNarration.mjs +2 -0
- package/dist/services/workflowNarration.mjs.map +1 -0
- package/dist/services/workflowRuns.cjs +3 -0
- package/dist/services/workflowRuns.cjs.map +1 -0
- package/dist/services/workflowRuns.d.cts +15 -0
- package/dist/services/workflowRuns.d.cts.map +1 -0
- package/dist/services/workflowRuns.d.mts +15 -0
- package/dist/services/workflowRuns.d.mts.map +1 -0
- package/dist/services/workflowRuns.mjs +3 -0
- package/dist/services/workflowRuns.mjs.map +1 -0
- package/dist/services/workflowTerminal.cjs +2 -0
- package/dist/services/workflowTerminal.cjs.map +1 -0
- package/dist/services/workflowTerminal.mjs +2 -0
- package/dist/services/workflowTerminal.mjs.map +1 -0
- package/dist/tui/workflow/doomOverlay.cjs.map +1 -0
- package/dist/tui/workflow/doomOverlay.mjs.map +1 -0
- package/dist/tui/workflow/overlayText.cjs +2 -0
- package/dist/tui/workflow/overlayText.cjs.map +1 -0
- package/dist/tui/workflow/overlayText.mjs +2 -0
- package/dist/tui/workflow/overlayText.mjs.map +1 -0
- package/dist/tui/workflow/rendering.cjs.map +1 -0
- package/dist/tui/workflow/rendering.mjs.map +1 -0
- package/dist/tui/workflow/workflowCatalog.cjs +2 -0
- package/dist/tui/workflow/workflowCatalog.cjs.map +1 -0
- package/dist/tui/workflow/workflowCatalog.mjs +2 -0
- package/dist/tui/workflow/workflowCatalog.mjs.map +1 -0
- package/dist/tui/workflow/workflowFinishedMessage.cjs +3 -0
- package/dist/tui/workflow/workflowFinishedMessage.cjs.map +1 -0
- package/dist/tui/workflow/workflowFinishedMessage.mjs +3 -0
- package/dist/tui/workflow/workflowFinishedMessage.mjs.map +1 -0
- package/dist/tui/workflow/workflowInspector.cjs +2 -0
- package/dist/tui/workflow/workflowInspector.cjs.map +1 -0
- package/dist/tui/workflow/workflowInspector.mjs +2 -0
- package/dist/tui/workflow/workflowInspector.mjs.map +1 -0
- package/dist/tui/workflow/workflowOverlay.cjs.map +1 -0
- package/dist/tui/workflow/workflowOverlay.mjs.map +1 -0
- package/dist/tui/workflow/workflowPicker.cjs.map +1 -0
- package/dist/tui/workflow/workflowPicker.mjs.map +1 -0
- package/dist/tui/workflow/workflowProgressOverlay.cjs +2 -0
- package/dist/tui/workflow/workflowProgressOverlay.cjs.map +1 -0
- package/dist/tui/workflow/workflowProgressOverlay.mjs +2 -0
- package/dist/tui/workflow/workflowProgressOverlay.mjs.map +1 -0
- package/dist/tui/workflow/workflowPrompt.cjs.map +1 -0
- package/dist/tui/workflow/workflowPrompt.mjs.map +1 -0
- package/dist/tui/workflow/workflowRunPanel.cjs +2 -0
- package/dist/tui/workflow/workflowRunPanel.cjs.map +1 -0
- package/dist/tui/workflow/workflowRunPanel.mjs +2 -0
- package/dist/tui/workflow/workflowRunPanel.mjs.map +1 -0
- package/dist/tui/workflow/workflowStatusRow.cjs +2 -0
- package/dist/tui/workflow/workflowStatusRow.cjs.map +1 -0
- package/dist/tui/workflow/workflowStatusRow.mjs +2 -0
- package/dist/tui/workflow/workflowStatusRow.mjs.map +1 -0
- package/dist/tui/workflow/workflowStepMessage.cjs +2 -0
- package/dist/tui/workflow/workflowStepMessage.cjs.map +1 -0
- package/dist/tui/workflow/workflowStepMessage.mjs +2 -0
- package/dist/tui/workflow/workflowStepMessage.mjs.map +1 -0
- package/dist/tui/workflow/workflowToolRender.cjs +7 -0
- package/dist/tui/workflow/workflowToolRender.cjs.map +1 -0
- package/dist/tui/workflow/workflowToolRender.mjs +7 -0
- package/dist/tui/workflow/workflowToolRender.mjs.map +1 -0
- package/dist/types/index.cjs +2 -0
- package/dist/types/index.cjs.map +1 -0
- package/dist/types/index.mjs +2 -0
- package/dist/types/index.mjs.map +1 -0
- package/dist/types/webWorkflowTerminal.cjs +2 -0
- package/dist/types/webWorkflowTerminal.cjs.map +1 -0
- package/dist/types/webWorkflowTerminal.mjs +2 -0
- package/dist/types/webWorkflowTerminal.mjs.map +1 -0
- package/dist/types/webWorkflows.cjs +2 -0
- package/dist/types/webWorkflows.cjs.map +1 -0
- package/dist/types/webWorkflows.d.cts +95 -0
- package/dist/types/webWorkflows.d.cts.map +1 -0
- package/dist/types/webWorkflows.d.mts +95 -0
- package/dist/types/webWorkflows.d.mts.map +1 -0
- package/dist/types/webWorkflows.mjs +2 -0
- package/dist/types/webWorkflows.mjs.map +1 -0
- package/dist/webHub.cjs +1 -0
- package/dist/webHub.d.cts +3 -0
- package/dist/webHub.d.mts +3 -0
- package/dist/webHub.mjs +1 -0
- package/llms.txt +16 -0
- package/package.json +78 -22
- package/src/prompts/doompi-author-workflow/SKILL.md +30 -0
- package/src/prompts/doompi-use-workflow/SKILL.md +21 -0
- package/src/types/webWorkflowTerminal.ts +92 -0
- package/src/types/webWorkflows.ts +145 -0
- package/web/ArtifactsPane.tsx +433 -0
- package/web/LICENSE +29 -0
- package/web/LaunchWorkflowDialog.tsx +261 -0
- package/web/StepTerminalPanel.tsx +251 -0
- package/web/WorkflowCatalogDrawer.tsx +228 -0
- package/web/WorkflowToolMessage.tsx +54 -0
- package/web/WorkflowsActivitySection.tsx +152 -0
- package/web/WorkflowsPanel.tsx +739 -0
- package/web/ansiSpans.ts +230 -0
- package/web/catalogStore.ts +112 -0
- package/web/index.ts +61 -0
- package/web/launchLine.ts +66 -0
- package/web/runDuration.ts +15 -0
- package/web/terminalApi.ts +156 -0
- package/web/tsconfig.json +22 -0
- package/web/workflowActivity.ts +102 -0
- package/web/workflowToolRender.ts +585 -0
- package/web/workflowsStore.ts +90 -0
- package/dist/dispatcher.cjs +0 -2
- package/dist/dispatcher.cjs.map +0 -1
- package/dist/dispatcher.d.cts +0 -6
- package/dist/dispatcher.d.cts.map +0 -1
- package/dist/dispatcher.d.mts +0 -6
- package/dist/dispatcher.d.mts.map +0 -1
- package/dist/dispatcher.mjs +0 -2
- package/dist/dispatcher.mjs.map +0 -1
- package/dist/extension.cjs +0 -2
- package/dist/extension.cjs.map +0 -1
- package/dist/extension.d.cts +0 -6
- package/dist/extension.d.cts.map +0 -1
- package/dist/extension.d.mts +0 -6
- package/dist/extension.d.mts.map +0 -1
- package/dist/extension.mjs +0 -2
- package/dist/extension.mjs.map +0 -1
- package/dist/extensions/dispatcher.cjs +0 -2
- package/dist/extensions/dispatcher.cjs.map +0 -1
- package/dist/extensions/dispatcher.d.cts +0 -2
- package/dist/extensions/dispatcher.d.mts +0 -2
- package/dist/extensions/dispatcher.mjs +0 -2
- package/dist/extensions/dispatcher.mjs.map +0 -1
- package/dist/extensions/pi.cjs.map +0 -1
- package/dist/extensions/pi.mjs.map +0 -1
- package/dist/leader.cjs +0 -2
- package/dist/leader.cjs.map +0 -1
- package/dist/leader.mjs +0 -2
- package/dist/leader.mjs.map +0 -1
- package/dist/types.cjs +0 -2
- package/dist/types.cjs.map +0 -1
- package/dist/types.mjs +0 -2
- package/dist/types.mjs.map +0 -1
- package/dist/workflow/backgroundWork.cjs +0 -2
- package/dist/workflow/backgroundWork.cjs.map +0 -1
- package/dist/workflow/backgroundWork.mjs +0 -2
- package/dist/workflow/backgroundWork.mjs.map +0 -1
- package/dist/workflow/doomOverlay.cjs.map +0 -1
- package/dist/workflow/doomOverlay.mjs.map +0 -1
- package/dist/workflow/overlayText.cjs +0 -2
- package/dist/workflow/overlayText.cjs.map +0 -1
- package/dist/workflow/overlayText.mjs +0 -2
- package/dist/workflow/overlayText.mjs.map +0 -1
- package/dist/workflow/piExtension.cjs +0 -11
- package/dist/workflow/piExtension.cjs.map +0 -1
- package/dist/workflow/piExtension.mjs +0 -11
- package/dist/workflow/piExtension.mjs.map +0 -1
- package/dist/workflow/piToolBridge.cjs.map +0 -1
- package/dist/workflow/piToolBridge.mjs.map +0 -1
- package/dist/workflow/piTools.cjs +0 -4
- package/dist/workflow/piTools.cjs.map +0 -1
- package/dist/workflow/piTools.mjs +0 -4
- package/dist/workflow/piTools.mjs.map +0 -1
- package/dist/workflow/rendering.cjs.map +0 -1
- package/dist/workflow/rendering.mjs.map +0 -1
- package/dist/workflow/workflowFooterStatus.cjs +0 -2
- package/dist/workflow/workflowFooterStatus.cjs.map +0 -1
- package/dist/workflow/workflowFooterStatus.mjs +0 -2
- package/dist/workflow/workflowFooterStatus.mjs.map +0 -1
- package/dist/workflow/workflowInspector.cjs +0 -2
- package/dist/workflow/workflowInspector.cjs.map +0 -1
- package/dist/workflow/workflowInspector.mjs +0 -2
- package/dist/workflow/workflowInspector.mjs.map +0 -1
- package/dist/workflow/workflowLauncher.cjs +0 -2
- package/dist/workflow/workflowLauncher.cjs.map +0 -1
- package/dist/workflow/workflowLauncher.mjs +0 -2
- package/dist/workflow/workflowLauncher.mjs.map +0 -1
- package/dist/workflow/workflowOverlay.cjs.map +0 -1
- package/dist/workflow/workflowOverlay.mjs.map +0 -1
- package/dist/workflow/workflowPicker.cjs.map +0 -1
- package/dist/workflow/workflowPicker.mjs.map +0 -1
- package/dist/workflow/workflowPrompt.cjs.map +0 -1
- package/dist/workflow/workflowPrompt.mjs.map +0 -1
- package/dist/workflow/workflowRunPanel.cjs +0 -2
- package/dist/workflow/workflowRunPanel.cjs.map +0 -1
- package/dist/workflow/workflowRunPanel.mjs +0 -2
- package/dist/workflow/workflowRunPanel.mjs.map +0 -1
- package/dist/workflow/workflowStatusRow.cjs +0 -2
- package/dist/workflow/workflowStatusRow.cjs.map +0 -1
- package/dist/workflow/workflowStatusRow.mjs +0 -2
- package/dist/workflow/workflowStatusRow.mjs.map +0 -1
- package/dist/workflow/workflowStepMessage.cjs +0 -2
- package/dist/workflow/workflowStepMessage.cjs.map +0 -1
- package/dist/workflow/workflowStepMessage.mjs +0 -2
- package/dist/workflow/workflowStepMessage.mjs.map +0 -1
- /package/dist/{workflow → tui/workflow}/doomOverlay.cjs +0 -0
- /package/dist/{workflow → tui/workflow}/doomOverlay.mjs +0 -0
- /package/dist/{workflow → tui/workflow}/rendering.cjs +0 -0
- /package/dist/{workflow → tui/workflow}/rendering.mjs +0 -0
- /package/dist/{workflow → tui/workflow}/workflowOverlay.cjs +0 -0
- /package/dist/{workflow → tui/workflow}/workflowOverlay.mjs +0 -0
- /package/dist/{workflow → tui/workflow}/workflowPicker.cjs +0 -0
- /package/dist/{workflow → tui/workflow}/workflowPicker.mjs +0 -0
- /package/dist/{workflow → tui/workflow}/workflowPrompt.cjs +0 -0
- /package/dist/{workflow → tui/workflow}/workflowPrompt.mjs +0 -0
package/LICENSE
CHANGED
|
@@ -1,3 +1,9 @@
|
|
|
1
|
+
Portions of this software are licensed as follows:
|
|
2
|
+
|
|
3
|
+
* All content under the "web/" directory is licensed under the DoomPi Web
|
|
4
|
+
License defined in "web/LICENSE": free to use, not to redistribute.
|
|
5
|
+
* All other content is licensed under the MIT license below.
|
|
6
|
+
|
|
1
7
|
MIT License
|
|
2
8
|
|
|
3
9
|
Copyright (c) 2026 Vuong Ngo
|
package/README.md
CHANGED
|
@@ -1,47 +1,129 @@
|
|
|
1
1
|
# @agimon-ai/doompi-workflow
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Discover, launch, monitor, control, and recover asynchronous DoomPi workflows.
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
`needs:`, `steps:`, timeouts, and declared artifacts. Every step names the session it wants,
|
|
7
|
-
so one run can hand each job exactly the context that job needs.
|
|
5
|
+
Part of the [DoomPi distribution](https://www.npmjs.com/package/@agimon-ai/doompi).
|
|
8
6
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
7
|
+
The integration embeds `@agimon-ai/workflow-mcp`. Workflow files describe job dependencies and
|
|
8
|
+
host-executed steps, while DoomPi provides session-scoped tools and TUI surfaces.
|
|
9
|
+
|
|
10
|
+
> **Alpha:** workflow and recovery contracts may change between releases.
|
|
11
|
+
|
|
12
|
+
## Requirements
|
|
13
|
+
|
|
14
|
+
- Node.js 22.19.0 or newer
|
|
15
|
+
- Pi 0.84.3 and Pi TUI 0.84.3
|
|
12
16
|
|
|
13
17
|
## Install
|
|
14
18
|
|
|
19
|
+
DoomPi includes Workflow in every composition; its tools remain inactive until Workflow mode is
|
|
20
|
+
enabled. For standalone Pi:
|
|
21
|
+
|
|
15
22
|
```bash
|
|
16
|
-
|
|
23
|
+
pi install npm:@agimon-ai/doompi-workflow
|
|
17
24
|
```
|
|
18
25
|
|
|
19
|
-
|
|
26
|
+
Enable tools with `SPC w e`, or set `WORKFLOW_MCP_MODE=on` for a non-interactive harness that cannot
|
|
27
|
+
toggle the minor mode.
|
|
28
|
+
|
|
29
|
+
## Define a workflow
|
|
30
|
+
|
|
31
|
+
Create a `*.workflow.yml` file:
|
|
32
|
+
|
|
33
|
+
```yaml
|
|
34
|
+
name: verify
|
|
35
|
+
|
|
36
|
+
jobs:
|
|
37
|
+
test:
|
|
38
|
+
steps:
|
|
39
|
+
- name: Run tests
|
|
40
|
+
run: pnpm test
|
|
41
|
+
|
|
42
|
+
summarize:
|
|
43
|
+
needs: test
|
|
44
|
+
steps:
|
|
45
|
+
- name: Record result
|
|
46
|
+
run: node scripts/write-verification-summary.mjs
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
`run` commands execute on the host with the workflow process's environment and privileges. There is
|
|
50
|
+
no VM, container, or sandbox. Review workflow files as executable code. Runner-specific
|
|
51
|
+
`interactiveRun` mappings are available for commands that require a TTY.
|
|
52
|
+
|
|
53
|
+
## Launch and monitor
|
|
54
|
+
|
|
55
|
+
Core tools are:
|
|
20
56
|
|
|
21
|
-
|
|
22
|
-
|
|
57
|
+
- `list_workflows`: discover workflows.
|
|
58
|
+
- `launch_workflow`: register and start an asynchronous run.
|
|
59
|
+
- `workflow_run`: inspect or control a run through supported actions.
|
|
23
60
|
|
|
24
|
-
|
|
61
|
+
Launch returns after the run is registered, not after all jobs complete. Use status and follow
|
|
62
|
+
controls for progress, and wait for a terminal notification.
|
|
25
63
|
|
|
26
|
-
|
|
64
|
+
In the TUI, `SPC w l` lists the repository's workflows and launches the one under the cursor with
|
|
65
|
+
`r`, `SPC w r` inspects this session's runs, `SPC w c` opens recovery, and `SPC w e`
|
|
66
|
+
toggles model-visible tools. The root session can launch; child sessions can inspect the catalog but
|
|
67
|
+
do not receive an unrestricted workflow factory.
|
|
27
68
|
|
|
28
|
-
|
|
29
|
-
The recovery picker includes terminal failed runs from earlier Pi sessions. `workflow_run` action `recovery-evidence` reads only terminal registry evidence; generic status/tail and all live controls remain session-scoped. Replay claims the failed record atomically, transfers only `PI_SESSION_ID`, and binds controls to the exact run generation the session authorized.
|
|
69
|
+
## Storage, concurrency, and lifecycle
|
|
30
70
|
|
|
31
|
-
|
|
71
|
+
Registry data defaults to `$HOME/.workflow-mcp`; set `WORKFLOW_MCP_HOME` to relocate it. Persisted
|
|
72
|
+
records contain workflow and run identity, job and step state, ownership, output locations, and
|
|
73
|
+
recovery evidence. The default concurrency ceiling is five runs.
|
|
74
|
+
|
|
75
|
+
Runs embedded directly in the Pi process end with that process. Runs launched through a terminal
|
|
76
|
+
host such as tmux or cmux can have a different lifetime and remain manageable from the CLI. When
|
|
77
|
+
Team is loaded, Workflow contributes active session runs through Team's `doom/background-work`
|
|
78
|
+
service. That contribution reconnects after Team is replaced and is removed when Workflow unloads.
|
|
79
|
+
Reconciliation distinguishes stale registry records from live processes; do not assume every run
|
|
80
|
+
outlives its parent session.
|
|
81
|
+
|
|
82
|
+
Each workflow or repair step can launch commands and model-backed agents, consuming provider quota
|
|
83
|
+
and repeating external side effects.
|
|
84
|
+
|
|
85
|
+
## Recovery
|
|
86
|
+
|
|
87
|
+
Recovery is available only for records in a terminal failure state. A recovery claim atomically
|
|
88
|
+
adopts the eligible failure, validates the evidence, and transfers ownership to the replay session.
|
|
89
|
+
Live controls remain scoped to the owning session. Recovery does not launch a second copy beside a
|
|
90
|
+
still-running job and does not guarantee that parent-session work survives shutdown.
|
|
91
|
+
|
|
92
|
+
The package publishes `workflow-recovery` for active Workflow mode. While parent Help mode is
|
|
93
|
+
active, it also contributes `doompi-author-workflow` for writing workflow definitions and
|
|
94
|
+
`doompi-use-workflow` for launching, monitoring, and recovering runs. Deactivating Help hides both
|
|
95
|
+
descriptors; cached files may remain.
|
|
96
|
+
|
|
97
|
+
Each Pi extension instance uses the runner's shared Doom lifecycle. Reload or shutdown stops retained
|
|
98
|
+
callbacks, interrupts bounded inline work, removes UI and service registrations, and releases
|
|
99
|
+
package resources. Detached children load the same extension entry in their own process.
|
|
100
|
+
|
|
101
|
+
## Pi extension
|
|
102
|
+
|
|
103
|
+
The Pi extension is published at `@agimon-ai/doompi-workflow/extensions/pi` and declared in
|
|
104
|
+
`package.json.pi.extensions`. Installing the package loads it automatically; there is no secondary
|
|
105
|
+
registration or dispatcher export.
|
|
106
|
+
|
|
107
|
+
## Development
|
|
108
|
+
|
|
109
|
+
```bash
|
|
110
|
+
pnpm build
|
|
111
|
+
pnpm typecheck
|
|
112
|
+
pnpm test
|
|
113
|
+
pnpm lint
|
|
114
|
+
```
|
|
32
115
|
|
|
33
|
-
|
|
34
|
-
root session, so a subagent can look but not spawn.
|
|
116
|
+
Maintained by [Agimon](https://agimon.ai/about).
|
|
35
117
|
|
|
36
|
-
##
|
|
118
|
+
## Web cockpit plugin
|
|
37
119
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
| `@agimon-ai/doompi-workflow/skills/workflow-recovery/SKILL.md` |
|
|
120
|
+
The `web/` directory is this package's DoomPi web cockpit plugin: the workflows tab, its store,
|
|
121
|
+
and its `workflow_runs` session channel, compiled into the cockpit bundle by `doompi-web`'s build.
|
|
122
|
+
The hub-side data source ships behind the `./web-hub` subpath and reads the workflow registry
|
|
123
|
+
(run.json plus progress.ndjson) exactly as the engine writes it. Both halves are declared by the
|
|
124
|
+
`doompiWeb` block in package.json.
|
|
44
125
|
|
|
45
126
|
## License
|
|
46
127
|
|
|
47
|
-
MIT
|
|
128
|
+
MIT, except the `web/` directory, which is source available under the DoomPi Web License (see
|
|
129
|
+
`web/LICENSE`): free to use, including commercially, but not to redistribute.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));exports.__toESM=s;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./leader.cjs"),t=require("./workflow/piExtension.cjs");let n=require("node:fs"),r=require("node:path"),i=require("node:async_hooks"),a=require("node:url"),o=require("@agimon-ai/doompi-extension-contracts/child-process"),s=require("@agimon-ai/doompi-extension-contracts/cordis-host"),c=require("@agimon-ai/doompi-extension-contracts/help"),l=require("@agimon-ai/doompi-extension-contracts/skills"),u=require("@agimon-ai/doompi-extension-contracts/ui-hub");const d=`@agimon-ai/doompi-workflow`,f=`agiflow-dispatcher`,p=`The workflow runtime is no longer active.`,m=Symbol(`doom-workflow-cleanup`),h=new Set([`list_workflows`,`launch_workflow`]),g=new Set([`launch_workflow`]);function _(e,t){let n=Reflect.get(e,t,e);return typeof n==`function`?n.bind(e):n}function v(e,t){let n=new Proxy(e.sessionManager,{get(e,n){return n===`getSessionId`?()=>t:_(e,n)}});return new Proxy(e,{get(e,t){return t===`sessionManager`?n:_(e,t)}})}function y(e,t,n=process.env){let r=t?(0,o.resolveRootSessionId)(t,n):void 0;return new Proxy(e,{get(e,t){return t===`setActiveTools`?t=>e.setActiveTools(t.filter(e=>e!==`workflow_run`)):t===`registerTool`?t=>{if(h.has(t.name)){if(!r||!g.has(t.name)){e.registerTool(t);return}e.registerTool({...t,execute:(e,n,i,a,o)=>t.execute(e,n,i,a,v(o,r))})}}:_(e,t)}})}function b(e){return(0,o.readChildProcessContext)(e)?.parentSessionId??(e[o.SUBAGENT_PARENT_SESSION_ENV]?.trim()||void 0)}function x(e){return(0,o.readChildProcessContext)(e)?.mode===f||e.PI_SUBAGENT_CHILD_AGENT===f&&!!e[o.SUBAGENT_PARENT_SESSION_ENV]?.trim()}function S(){return{content:[{type:`text`,text:p}],details:void 0}}function C(e){let t=new i.AsyncLocalStorage,n=!0,r=!1,a=0,o,s,c=()=>{if(!n)return!1;let e=t.getStore();return e===void 0||e===m||e===a},l=e=>{if(!n)return!1;let r=t.getStore();return r===m||e===a&&(r===void 0||r===e)},u=(e,t)=>{let n=new Proxy(e.ui,{get(e,n){let r=Reflect.get(e,n,e);return typeof r==`function`?(...i)=>{if(l(t))return Reflect.apply(r,e,i);if(n===`confirm`)return Promise.resolve(!1);if(n===`custom`||n===`editor`||n===`input`||n===`select`)return Promise.resolve(void 0)}:r}});return new Proxy(e,{get(e,t){return t===`ui`?n:_(e,t)}})},d=i=>{c()&&e.registerTool({...i,execute:async(e,o,s,c,l)=>{let d=a;if(!n||r||s?.aborted)return S();let f=u(l,d),p=c?e=>{n&&d===a&&!s?.aborted&&c(e)}:void 0,m=await t.run(d,()=>i.execute(e,o,s,p,f));return n&&!r&&d===a?m:S()}})},f=(i,o)=>{c()&&e.registerCommand(i,{...o,handler:async(e,i)=>{let s=a;!n||r||await t.run(s,()=>o.handler(e,u(i,s)))}})},h=(i,o)=>{c()&&e.registerShortcut(i,{...o,handler:e=>{let i=a;if(!(!n||r))return t.run(i,()=>o.handler(u(e,i)))}})};return{pi:new Proxy(e,{get(e,i){return i===`on`?(i,c)=>{_(e,`on`)(i,(e,l)=>{if(!n||r)return;i===`session_start`&&(e!==o||l!==s)&&(a+=1,o=e,s=l);let d=a;return t.run(d,()=>c(e,u(l,d)))})}:i===`registerTool`?d:i===`registerCommand`?f:i===`registerShortcut`?h:i===`getActiveTools`?()=>c()?e.getActiveTools():[]:i===`setActiveTools`?t=>{c()&&e.setActiveTools(t)}:i===`sendMessage`?(...t)=>{c()&&e.sendMessage(...t)}:i===`sendUserMessage`?(...t)=>{c()&&e.sendUserMessage(...t)}:i===`exec`?(...t)=>c()?e.exec(...t):Promise.resolve({code:1,killed:!1,stderr:p,stdout:``}):_(e,i)}}),beginDisposal(){r||!n||(r=!0,a+=1)},finishDisposal(){n=!1,r=!1,a+=1},isCurrentInvocation:c,runCleanup:e=>t.run(m,e)}}function w(i,o,s,f=process.env){let p=x(f),m=p?b(f):void 0,h=p?y(o,m,f):o,g;if(i.effect(()=>()=>g?g.dispose():Promise.resolve(),`${d}/runtime`),i.inject([l.DOOM_SKILL_SOURCES_SERVICE],e=>{let t=(0,r.resolve)((0,r.dirname)((0,a.fileURLToPath)(require("url").pathToFileURL(__filename).href)),`../../../skills`);if(!(0,n.existsSync)(t))return;let i=(0,l.requireDoomSkillSourcesService)(e).register({source:d,directories:[t]});return()=>i.dispose()}),p){g=t.installWorkflowPiRuntime({cordis:i,initialMode:!0,isActive:s})(h);return}let _=!1,v;i.inject([u.DOOM_UI_HUB_SERVICE],t=>{let n=e.registerLeaderContribution((0,u.requireDoomUiHub)(t),_);return v=n,()=>{n.dispose(),v===n&&(v=void 0)}}),i.inject([c.DOOM_HELP_SERVICE],e=>{let t=(0,c.requireDoomHelpService)(e).register({source:d,moduleUrl:require("url").pathToFileURL(__filename).href,skills:[{name:`doompi-author-workflow`,description:`Author DoomPi workflow definitions. Use when creating or changing a *.workflow.yml graph, arranging job dependencies and host-executed steps, or deciding how a command requiring a TTY should run.`},{name:`doompi-use-workflow`,description:`Use DoomPi workflows. Use when discovering or launching workflows, monitoring or controlling asynchronous runs, interpreting terminal notifications, or recovering a failed run safely.`}]});return()=>t.dispose()}),g=t.installWorkflowPiRuntime({cordis:i,isActive:s,onModeChange:e=>{_=e,v?.setMode(e)}})(h)}function T(e,{fence:t,environment:n}){w(e,t.pi,t.isCurrentInvocation,n)}async function E(e){let t=await(0,s.connectDoomCordisHost)(e,d),n=C(e),r=t.root.plugin(T,{fence:n,environment:process.env}),i,a=()=>i||(n.beginDisposal(),i=n.runCleanup(async()=>{try{await r.dispose()}finally{try{n.finishDisposal()}finally{await t.dispose()}}}),i);try{await r}catch(e){throw await a(),e}e.on(`session_shutdown`,a)}exports.createDispatcherBridge=y,exports.default=E,exports.workflowExtension=E,exports.installWorkflowRuntime=w,exports.isWorkflowDispatcherProcess=x,exports.resolveDispatcherParentSession=b;
|
|
2
|
+
//# sourceMappingURL=extension.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"extension.cjs","names":["resolveRootSessionId","readChildProcessContext","SUBAGENT_PARENT_SESSION_ENV","AsyncLocalStorage","DOOM_SKILL_SOURCES_SERVICE","resolve","dirname","fileURLToPath","existsSync","requireDoomSkillSourcesService","installWorkflowPiRuntime","DOOM_UI_HUB_SERVICE","registerLeaderContribution","requireDoomUiHub","DOOM_HELP_SERVICE","requireDoomHelpService","connectDoomCordisHost"],"sources":["../../../src/adapters/pi/extension.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport { existsSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport {\n readChildProcessContext,\n resolveRootSessionId,\n SUBAGENT_PARENT_SESSION_ENV,\n} from '@agimon-ai/doompi-extension-contracts/child-process';\nimport { connectDoomCordisHost } from '@agimon-ai/doompi-extension-contracts/cordis-host';\nimport { DOOM_HELP_SERVICE, requireDoomHelpService } from '@agimon-ai/doompi-extension-contracts/help';\nimport {\n DOOM_SKILL_SOURCES_SERVICE,\n requireDoomSkillSourcesService,\n} from '@agimon-ai/doompi-extension-contracts/skills';\nimport { DOOM_UI_HUB_SERVICE, requireDoomUiHub } from '@agimon-ai/doompi-extension-contracts/ui-hub';\nimport type { Context } from '@deepseek-ai/cordis';\nimport type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';\nimport { registerLeaderContribution } from './leader.ts';\nimport { installWorkflowPiRuntime, type WorkflowPiRuntime } from './workflow/piExtension.ts';\n\nconst PACKAGE_SOURCE = '@agimon-ai/doompi-workflow';\nconst SKILL_RELATIVE_PATH = '../../../skills';\nconst DISPATCHER_AGENT_NAME = 'agiflow-dispatcher';\nconst SESSION_START_EVENT = 'session_start';\nconst SESSION_SHUTDOWN_EVENT = 'session_shutdown';\nconst INACTIVE_RUNTIME_MESSAGE = 'The workflow runtime is no longer active.';\nconst CLEANUP_SCOPE = Symbol('doom-workflow-cleanup');\n\nconst DISPATCHER_TOOL_NAMES = new Set(['list_workflows', 'launch_workflow']);\nconst ROOT_SCOPED_TOOL_NAMES = new Set(['launch_workflow']);\n\ntype RegisteredTool = Parameters<ExtensionAPI['registerTool']>[0];\ntype CommandOptions = Parameters<ExtensionAPI['registerCommand']>[1];\ntype ShortcutOptions = Parameters<ExtensionAPI['registerShortcut']>[1];\ntype RuntimeScope = number | typeof CLEANUP_SCOPE;\ntype LifecycleHandler = (event: unknown, context: ExtensionContext) => unknown;\n\ninterface WorkflowFence {\n readonly pi: ExtensionAPI;\n readonly beginDisposal: () => void;\n readonly finishDisposal: () => void;\n readonly isCurrentInvocation: () => boolean;\n readonly runCleanup: <T>(operation: () => T) => T;\n}\n\nfunction boundValue(target: object, property: PropertyKey): unknown {\n const value = Reflect.get(target, property, target);\n return typeof value === 'function' ? value.bind(target) : value;\n}\n\nfunction withParentSession(ctx: ExtensionContext, parentSessionId: string): ExtensionContext {\n const sessionManager = new Proxy(ctx.sessionManager, {\n get(target, property) {\n if (property === 'getSessionId') return () => parentSessionId;\n return boundValue(target, property);\n },\n });\n return new Proxy(ctx, {\n get(target, property) {\n if (property === 'sessionManager') return sessionManager;\n return boundValue(target, property);\n },\n });\n}\n\n/** Restrict a dispatcher child to discovery and root-owned launch. */\nexport function createDispatcherBridge(\n pi: ExtensionAPI,\n parentSessionId: string | undefined,\n environment: Readonly<Record<string, string | undefined>> = process.env,\n): ExtensionAPI {\n const rootSessionId = parentSessionId ? resolveRootSessionId(parentSessionId, environment) : undefined;\n return new Proxy(pi, {\n get(target, property) {\n if (property === 'setActiveTools') {\n return (names: string[]): void => target.setActiveTools(names.filter((name) => name !== 'workflow_run'));\n }\n if (property !== 'registerTool') return boundValue(target, property);\n return (tool: RegisteredTool): void => {\n if (!DISPATCHER_TOOL_NAMES.has(tool.name)) return;\n if (!rootSessionId || !ROOT_SCOPED_TOOL_NAMES.has(tool.name)) {\n target.registerTool(tool);\n return;\n }\n target.registerTool({\n ...tool,\n execute: (toolCallId, params, signal, onUpdate, ctx) =>\n tool.execute(toolCallId, params, signal, onUpdate, withParentSession(ctx, rootSessionId)),\n });\n };\n },\n });\n}\n\nexport function resolveDispatcherParentSession(\n environment: Readonly<Record<string, string | undefined>>,\n): string | undefined {\n const childContext = readChildProcessContext(environment);\n return childContext?.parentSessionId ?? (environment[SUBAGENT_PARENT_SESSION_ENV]?.trim() || undefined);\n}\n\nexport function isWorkflowDispatcherProcess(environment: Readonly<Record<string, string | undefined>>): boolean {\n const childContext = readChildProcessContext(environment);\n if (childContext?.mode === DISPATCHER_AGENT_NAME) return true;\n return (\n environment.PI_SUBAGENT_CHILD_AGENT === DISPATCHER_AGENT_NAME &&\n Boolean(environment[SUBAGENT_PARENT_SESSION_ENV]?.trim())\n );\n}\n\nfunction inactiveToolResult(): Awaited<ReturnType<RegisteredTool['execute']>> {\n return {\n content: [{ type: 'text', text: INACTIVE_RUNTIME_MESSAGE }],\n details: undefined,\n };\n}\n\n/** Fence every callback retained by Pi after this package root is replaced. */\nfunction createWorkflowFence(host: ExtensionAPI): WorkflowFence {\n const scope = new AsyncLocalStorage<RuntimeScope>();\n let active = true;\n let disposing = false;\n let generation = 0;\n let lastSessionStartEvent: unknown;\n let lastSessionStartContext: ExtensionContext | undefined;\n\n const isCurrentInvocation = (): boolean => {\n if (!active) return false;\n const currentScope = scope.getStore();\n return currentScope === undefined || currentScope === CLEANUP_SCOPE || currentScope === generation;\n };\n const ownsContext = (contextGeneration: number): boolean => {\n if (!active) return false;\n const currentScope = scope.getStore();\n return (\n currentScope === CLEANUP_SCOPE ||\n (contextGeneration === generation && (currentScope === undefined || currentScope === contextGeneration))\n );\n };\n\n const guardContext = <TContext extends ExtensionContext>(context: TContext, contextGeneration: number): TContext => {\n const guardedUi = new Proxy(context.ui, {\n get(target, property) {\n const value = Reflect.get(target, property, target);\n if (typeof value !== 'function') return value;\n return (...args: unknown[]): unknown => {\n if (ownsContext(contextGeneration)) return Reflect.apply(value, target, args);\n if (property === 'confirm') return Promise.resolve(false);\n if (property === 'custom' || property === 'editor' || property === 'input' || property === 'select') {\n return Promise.resolve(undefined);\n }\n return undefined;\n };\n },\n });\n return new Proxy(context, {\n get(target, property) {\n if (property === 'ui') return guardedUi;\n return boundValue(target, property);\n },\n }) as TContext;\n };\n\n const registerTool = (tool: RegisteredTool): void => {\n if (!isCurrentInvocation()) return;\n host.registerTool({\n ...tool,\n execute: async (toolCallId, params, signal, onUpdate, context) => {\n const executionGeneration = generation;\n if (!active || disposing || signal?.aborted) return inactiveToolResult();\n const guardedContext = guardContext(context, executionGeneration);\n const guardedUpdate = onUpdate\n ? (update: Parameters<NonNullable<typeof onUpdate>>[0]): void => {\n if (active && executionGeneration === generation && !signal?.aborted) onUpdate(update);\n }\n : undefined;\n const result = await scope.run(executionGeneration, () =>\n tool.execute(toolCallId, params, signal, guardedUpdate, guardedContext),\n );\n return active && !disposing && executionGeneration === generation ? result : inactiveToolResult();\n },\n });\n };\n\n const registerCommand = (name: string, options: CommandOptions): void => {\n if (!isCurrentInvocation()) return;\n host.registerCommand(name, {\n ...options,\n handler: async (args, context) => {\n const executionGeneration = generation;\n if (!active || disposing) return;\n await scope.run(executionGeneration, () => options.handler(args, guardContext(context, executionGeneration)));\n },\n });\n };\n\n const registerShortcut = (\n shortcut: Parameters<ExtensionAPI['registerShortcut']>[0],\n options: ShortcutOptions,\n ): void => {\n if (!isCurrentInvocation()) return;\n host.registerShortcut(shortcut, {\n ...options,\n handler: (context) => {\n const executionGeneration = generation;\n if (!active || disposing) return;\n return scope.run(executionGeneration, () => options.handler(guardContext(context, executionGeneration)));\n },\n });\n };\n\n const guardedPi = new Proxy(host, {\n get(target, property) {\n if (property === 'on') {\n return (eventName: string, handler: LifecycleHandler): void => {\n const registerLifecycleHandler = boundValue(target, 'on') as (\n name: string,\n callback: LifecycleHandler,\n ) => void;\n registerLifecycleHandler(eventName, (event: unknown, context: ExtensionContext) => {\n if (!active || disposing) return undefined;\n if (\n eventName === SESSION_START_EVENT &&\n (event !== lastSessionStartEvent || context !== lastSessionStartContext)\n ) {\n generation += 1;\n lastSessionStartEvent = event;\n lastSessionStartContext = context;\n }\n const eventGeneration = generation;\n return scope.run(eventGeneration, () => handler(event, guardContext(context, eventGeneration)));\n });\n };\n }\n if (property === 'registerTool') return registerTool;\n if (property === 'registerCommand') return registerCommand;\n if (property === 'registerShortcut') return registerShortcut;\n if (property === 'getActiveTools') {\n return (): string[] => (isCurrentInvocation() ? target.getActiveTools() : []);\n }\n if (property === 'setActiveTools') {\n return (names: string[]): void => {\n if (isCurrentInvocation()) target.setActiveTools(names);\n };\n }\n if (property === 'sendMessage') {\n return (...args: Parameters<ExtensionAPI['sendMessage']>): void => {\n if (isCurrentInvocation()) target.sendMessage(...args);\n };\n }\n if (property === 'sendUserMessage') {\n return (...args: Parameters<ExtensionAPI['sendUserMessage']>): void => {\n if (isCurrentInvocation()) target.sendUserMessage(...args);\n };\n }\n if (property === 'exec') {\n return (...args: Parameters<ExtensionAPI['exec']>): ReturnType<ExtensionAPI['exec']> =>\n isCurrentInvocation()\n ? target.exec(...args)\n : Promise.resolve({ code: 1, killed: false, stderr: INACTIVE_RUNTIME_MESSAGE, stdout: '' });\n }\n return boundValue(target, property);\n },\n });\n\n return {\n pi: guardedPi,\n beginDisposal() {\n if (disposing || !active) return;\n disposing = true;\n generation += 1;\n },\n finishDisposal() {\n active = false;\n disposing = false;\n generation += 1;\n },\n isCurrentInvocation,\n runCleanup: (operation) => scope.run(CLEANUP_SCOPE, operation),\n };\n}\n\n/** Install one normal or dispatcher runtime into its host-owned Cordis plugin fiber. */\nexport function installWorkflowRuntime(\n cordis: Context,\n pi: ExtensionAPI,\n isCurrentInvocation: () => boolean,\n environment: Readonly<Record<string, string | undefined>> = process.env,\n): void {\n const dispatcher = isWorkflowDispatcherProcess(environment);\n const parentSessionId = dispatcher ? resolveDispatcherParentSession(environment) : undefined;\n const runtimePi = dispatcher ? createDispatcherBridge(pi, parentSessionId, environment) : pi;\n\n let runtime: WorkflowPiRuntime | undefined;\n cordis.effect(() => () => (runtime ? runtime.dispose() : Promise.resolve()), `${PACKAGE_SOURCE}/runtime`);\n\n cordis.inject([DOOM_SKILL_SOURCES_SERVICE], (skillContext) => {\n const directory = resolve(dirname(fileURLToPath(import.meta.url)), SKILL_RELATIVE_PATH);\n if (!existsSync(directory)) return undefined;\n const contribution = requireDoomSkillSourcesService(skillContext).register({\n source: PACKAGE_SOURCE,\n directories: [directory],\n });\n return () => contribution.dispose();\n });\n\n if (dispatcher) {\n runtime = installWorkflowPiRuntime({ cordis, initialMode: true, isActive: isCurrentInvocation })(runtimePi);\n return;\n }\n\n let workflowMode = false;\n let leader: ReturnType<typeof registerLeaderContribution> | undefined;\n cordis.inject([DOOM_UI_HUB_SERVICE], (uiContext) => {\n const contribution = registerLeaderContribution(requireDoomUiHub(uiContext), workflowMode);\n leader = contribution;\n return () => {\n contribution.dispose();\n if (leader === contribution) leader = undefined;\n };\n });\n cordis.inject([DOOM_HELP_SERVICE], (helpContext) => {\n const help = requireDoomHelpService(helpContext).register({\n source: PACKAGE_SOURCE,\n moduleUrl: import.meta.url,\n skills: [\n {\n name: 'doompi-author-workflow',\n description:\n 'Author DoomPi workflow definitions. Use when creating or changing a *.workflow.yml graph, arranging job dependencies and host-executed steps, or deciding how a command requiring a TTY should run.',\n },\n {\n name: 'doompi-use-workflow',\n description:\n 'Use DoomPi workflows. Use when discovering or launching workflows, monitoring or controlling asynchronous runs, interpreting terminal notifications, or recovering a failed run safely.',\n },\n ],\n });\n return () => help.dispose();\n });\n runtime = installWorkflowPiRuntime({\n cordis,\n isActive: isCurrentInvocation,\n onModeChange: (enabled) => {\n workflowMode = enabled;\n leader?.setMode(enabled);\n },\n })(runtimePi);\n}\n\ninterface WorkflowPluginConfig {\n readonly fence: WorkflowFence;\n readonly environment: Readonly<Record<string, string | undefined>>;\n}\n\nfunction workflowPlugin(cordis: Context, { fence, environment }: WorkflowPluginConfig): void {\n installWorkflowRuntime(cordis, fence.pi, fence.isCurrentInvocation, environment);\n}\n\n/** The package's sole Pi factory; Pi reloads it and Cordis owns all package resources. */\nexport async function workflowExtension(pi: ExtensionAPI): Promise<void> {\n const connection = await connectDoomCordisHost(pi, PACKAGE_SOURCE);\n const fence = createWorkflowFence(pi);\n const fiber = connection.root.plugin(workflowPlugin, { fence, environment: process.env });\n let disposal: Promise<void> | undefined;\n const dispose = (): Promise<void> => {\n if (disposal) return disposal;\n fence.beginDisposal();\n disposal = fence.runCleanup(async () => {\n try {\n await fiber.dispose();\n } finally {\n try {\n fence.finishDisposal();\n } finally {\n await connection.dispose();\n }\n }\n });\n return disposal;\n };\n\n try {\n await fiber;\n } catch (error) {\n await dispose();\n throw error;\n }\n pi.on(SESSION_SHUTDOWN_EVENT, dispose);\n}\n\nexport default workflowExtension;\n"],"mappings":"wdAqBA,MAAM,EAAiB,6BAEjB,EAAwB,qBAGxB,EAA2B,4CAC3B,EAAgB,OAAO,uBAAuB,EAE9C,EAAwB,IAAI,IAAI,CAAC,iBAAkB,iBAAiB,CAAC,EACrE,EAAyB,IAAI,IAAI,CAAC,iBAAiB,CAAC,EAgB1D,SAAS,EAAW,EAAgB,EAAgC,CAClE,IAAM,EAAQ,QAAQ,IAAI,EAAQ,EAAU,CAAM,EAClD,OAAO,OAAO,GAAU,WAAa,EAAM,KAAK,CAAM,EAAI,CAC5D,CAEA,SAAS,EAAkB,EAAuB,EAA2C,CAC3F,IAAM,EAAiB,IAAI,MAAM,EAAI,eAAgB,CACnD,IAAI,EAAQ,EAAU,CAEpB,OADI,IAAa,mBAA6B,EACvC,EAAW,EAAQ,CAAQ,CACpC,CACF,CAAC,EACD,OAAO,IAAI,MAAM,EAAK,CACpB,IAAI,EAAQ,EAAU,CAEpB,OADI,IAAa,iBAAyB,EACnC,EAAW,EAAQ,CAAQ,CACpC,CACF,CAAC,CACH,CAGA,SAAgB,EACd,EACA,EACA,EAA4D,QAAQ,IACtD,CACd,IAAM,EAAgB,GAAA,EAAkBA,EAAAA,qBAAAA,CAAqB,EAAiB,CAAW,EAAI,IAAA,GAC7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@@ -0,0 +1,8 @@
|
|
|
1
|
+
import "@deepseek-ai/cordis";
|
|
2
|
+
import { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
//#region src/adapters/pi/extension.d.ts
|
|
4
|
+
/** The package's sole Pi factory; Pi reloads it and Cordis owns all package resources. */
|
|
5
|
+
declare function workflowExtension(pi: ExtensionAPI): Promise<void>;
|
|
6
|
+
//#endregion
|
|
7
|
+
export { workflowExtension as default, workflowExtension };
|
|
8
|
+
//# sourceMappingURL=extension.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"extension.d.cts","names":[],"sources":["../../../src/adapters/pi/extension.ts"],"mappings":";;;;iBAyWsB,kBAAkB,IAAI,eAAe"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import "@deepseek-ai/cordis";
|
|
2
|
+
import { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
//#region src/adapters/pi/extension.d.ts
|
|
4
|
+
/** The package's sole Pi factory; Pi reloads it and Cordis owns all package resources. */
|
|
5
|
+
declare function workflowExtension(pi: ExtensionAPI): Promise<void>;
|
|
6
|
+
//#endregion
|
|
7
|
+
export { workflowExtension as default, workflowExtension };
|
|
8
|
+
//# sourceMappingURL=extension.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"extension.d.mts","names":[],"sources":["../../../src/adapters/pi/extension.ts"],"mappings":";;;;iBAyWsB,kBAAkB,IAAI,eAAe"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{registerLeaderContribution as e}from"./leader.mjs";import{installWorkflowPiRuntime as t}from"./workflow/piExtension.mjs";import{existsSync as n}from"node:fs";import{dirname as r,resolve as i}from"node:path";import{AsyncLocalStorage as a}from"node:async_hooks";import{fileURLToPath as o}from"node:url";import{SUBAGENT_PARENT_SESSION_ENV as s,readChildProcessContext as c,resolveRootSessionId as l}from"@agimon-ai/doompi-extension-contracts/child-process";import{connectDoomCordisHost as u}from"@agimon-ai/doompi-extension-contracts/cordis-host";import{DOOM_HELP_SERVICE as d,requireDoomHelpService as f}from"@agimon-ai/doompi-extension-contracts/help";import{DOOM_SKILL_SOURCES_SERVICE as p,requireDoomSkillSourcesService as m}from"@agimon-ai/doompi-extension-contracts/skills";import{DOOM_UI_HUB_SERVICE as h,requireDoomUiHub as g}from"@agimon-ai/doompi-extension-contracts/ui-hub";const _=`@agimon-ai/doompi-workflow`,v=`agiflow-dispatcher`,y=`The workflow runtime is no longer active.`,b=Symbol(`doom-workflow-cleanup`),x=new Set([`list_workflows`,`launch_workflow`]),S=new Set([`launch_workflow`]);function C(e,t){let n=Reflect.get(e,t,e);return typeof n==`function`?n.bind(e):n}function w(e,t){let n=new Proxy(e.sessionManager,{get(e,n){return n===`getSessionId`?()=>t:C(e,n)}});return new Proxy(e,{get(e,t){return t===`sessionManager`?n:C(e,t)}})}function T(e,t,n=process.env){let r=t?l(t,n):void 0;return new Proxy(e,{get(e,t){return t===`setActiveTools`?t=>e.setActiveTools(t.filter(e=>e!==`workflow_run`)):t===`registerTool`?t=>{if(x.has(t.name)){if(!r||!S.has(t.name)){e.registerTool(t);return}e.registerTool({...t,execute:(e,n,i,a,o)=>t.execute(e,n,i,a,w(o,r))})}}:C(e,t)}})}function E(e){return c(e)?.parentSessionId??(e[s]?.trim()||void 0)}function D(e){return c(e)?.mode===v||e.PI_SUBAGENT_CHILD_AGENT===v&&!!e[s]?.trim()}function O(){return{content:[{type:`text`,text:y}],details:void 0}}function k(e){let t=new a,n=!0,r=!1,i=0,o,s,c=()=>{if(!n)return!1;let e=t.getStore();return e===void 0||e===b||e===i},l=e=>{if(!n)return!1;let r=t.getStore();return r===b||e===i&&(r===void 0||r===e)},u=(e,t)=>{let n=new Proxy(e.ui,{get(e,n){let r=Reflect.get(e,n,e);return typeof r==`function`?(...i)=>{if(l(t))return Reflect.apply(r,e,i);if(n===`confirm`)return Promise.resolve(!1);if(n===`custom`||n===`editor`||n===`input`||n===`select`)return Promise.resolve(void 0)}:r}});return new Proxy(e,{get(e,t){return t===`ui`?n:C(e,t)}})},d=a=>{c()&&e.registerTool({...a,execute:async(e,o,s,c,l)=>{let d=i;if(!n||r||s?.aborted)return O();let f=u(l,d),p=c?e=>{n&&d===i&&!s?.aborted&&c(e)}:void 0,m=await t.run(d,()=>a.execute(e,o,s,p,f));return n&&!r&&d===i?m:O()}})},f=(a,o)=>{c()&&e.registerCommand(a,{...o,handler:async(e,a)=>{let s=i;!n||r||await t.run(s,()=>o.handler(e,u(a,s)))}})},p=(a,o)=>{c()&&e.registerShortcut(a,{...o,handler:e=>{let a=i;if(!(!n||r))return t.run(a,()=>o.handler(u(e,a)))}})};return{pi:new Proxy(e,{get(e,a){return a===`on`?(a,c)=>{C(e,`on`)(a,(e,l)=>{if(!n||r)return;a===`session_start`&&(e!==o||l!==s)&&(i+=1,o=e,s=l);let d=i;return t.run(d,()=>c(e,u(l,d)))})}:a===`registerTool`?d:a===`registerCommand`?f:a===`registerShortcut`?p:a===`getActiveTools`?()=>c()?e.getActiveTools():[]:a===`setActiveTools`?t=>{c()&&e.setActiveTools(t)}:a===`sendMessage`?(...t)=>{c()&&e.sendMessage(...t)}:a===`sendUserMessage`?(...t)=>{c()&&e.sendUserMessage(...t)}:a===`exec`?(...t)=>c()?e.exec(...t):Promise.resolve({code:1,killed:!1,stderr:y,stdout:``}):C(e,a)}}),beginDisposal(){r||!n||(r=!0,i+=1)},finishDisposal(){n=!1,r=!1,i+=1},isCurrentInvocation:c,runCleanup:e=>t.run(b,e)}}function A(a,s,c,l=process.env){let u=D(l),v=u?E(l):void 0,y=u?T(s,v,l):s,b;if(a.effect(()=>()=>b?b.dispose():Promise.resolve(),`${_}/runtime`),a.inject([p],e=>{let t=i(r(o(import.meta.url)),`../../../skills`);if(!n(t))return;let a=m(e).register({source:_,directories:[t]});return()=>a.dispose()}),u){b=t({cordis:a,initialMode:!0,isActive:c})(y);return}let x=!1,S;a.inject([h],t=>{let n=e(g(t),x);return S=n,()=>{n.dispose(),S===n&&(S=void 0)}}),a.inject([d],e=>{let t=f(e).register({source:_,moduleUrl:import.meta.url,skills:[{name:`doompi-author-workflow`,description:`Author DoomPi workflow definitions. Use when creating or changing a *.workflow.yml graph, arranging job dependencies and host-executed steps, or deciding how a command requiring a TTY should run.`},{name:`doompi-use-workflow`,description:`Use DoomPi workflows. Use when discovering or launching workflows, monitoring or controlling asynchronous runs, interpreting terminal notifications, or recovering a failed run safely.`}]});return()=>t.dispose()}),b=t({cordis:a,isActive:c,onModeChange:e=>{x=e,S?.setMode(e)}})(y)}function j(e,{fence:t,environment:n}){A(e,t.pi,t.isCurrentInvocation,n)}async function M(e){let t=await u(e,_),n=k(e),r=t.root.plugin(j,{fence:n,environment:process.env}),i,a=()=>i||(n.beginDisposal(),i=n.runCleanup(async()=>{try{await r.dispose()}finally{try{n.finishDisposal()}finally{await t.dispose()}}}),i);try{await r}catch(e){throw await a(),e}e.on(`session_shutdown`,a)}export{T as createDispatcherBridge,M as default,M as workflowExtension,A as installWorkflowRuntime,D as isWorkflowDispatcherProcess,E as resolveDispatcherParentSession};
|
|
2
|
+
//# sourceMappingURL=extension.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"extension.mjs","names":[],"sources":["../../../src/adapters/pi/extension.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport { existsSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport {\n readChildProcessContext,\n resolveRootSessionId,\n SUBAGENT_PARENT_SESSION_ENV,\n} from '@agimon-ai/doompi-extension-contracts/child-process';\nimport { connectDoomCordisHost } from '@agimon-ai/doompi-extension-contracts/cordis-host';\nimport { DOOM_HELP_SERVICE, requireDoomHelpService } from '@agimon-ai/doompi-extension-contracts/help';\nimport {\n DOOM_SKILL_SOURCES_SERVICE,\n requireDoomSkillSourcesService,\n} from '@agimon-ai/doompi-extension-contracts/skills';\nimport { DOOM_UI_HUB_SERVICE, requireDoomUiHub } from '@agimon-ai/doompi-extension-contracts/ui-hub';\nimport type { Context } from '@deepseek-ai/cordis';\nimport type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';\nimport { registerLeaderContribution } from './leader.ts';\nimport { installWorkflowPiRuntime, type WorkflowPiRuntime } from './workflow/piExtension.ts';\n\nconst PACKAGE_SOURCE = '@agimon-ai/doompi-workflow';\nconst SKILL_RELATIVE_PATH = '../../../skills';\nconst DISPATCHER_AGENT_NAME = 'agiflow-dispatcher';\nconst SESSION_START_EVENT = 'session_start';\nconst SESSION_SHUTDOWN_EVENT = 'session_shutdown';\nconst INACTIVE_RUNTIME_MESSAGE = 'The workflow runtime is no longer active.';\nconst CLEANUP_SCOPE = Symbol('doom-workflow-cleanup');\n\nconst DISPATCHER_TOOL_NAMES = new Set(['list_workflows', 'launch_workflow']);\nconst ROOT_SCOPED_TOOL_NAMES = new Set(['launch_workflow']);\n\ntype RegisteredTool = Parameters<ExtensionAPI['registerTool']>[0];\ntype CommandOptions = Parameters<ExtensionAPI['registerCommand']>[1];\ntype ShortcutOptions = Parameters<ExtensionAPI['registerShortcut']>[1];\ntype RuntimeScope = number | typeof CLEANUP_SCOPE;\ntype LifecycleHandler = (event: unknown, context: ExtensionContext) => unknown;\n\ninterface WorkflowFence {\n readonly pi: ExtensionAPI;\n readonly beginDisposal: () => void;\n readonly finishDisposal: () => void;\n readonly isCurrentInvocation: () => boolean;\n readonly runCleanup: <T>(operation: () => T) => T;\n}\n\nfunction boundValue(target: object, property: PropertyKey): unknown {\n const value = Reflect.get(target, property, target);\n return typeof value === 'function' ? value.bind(target) : value;\n}\n\nfunction withParentSession(ctx: ExtensionContext, parentSessionId: string): ExtensionContext {\n const sessionManager = new Proxy(ctx.sessionManager, {\n get(target, property) {\n if (property === 'getSessionId') return () => parentSessionId;\n return boundValue(target, property);\n },\n });\n return new Proxy(ctx, {\n get(target, property) {\n if (property === 'sessionManager') return sessionManager;\n return boundValue(target, property);\n },\n });\n}\n\n/** Restrict a dispatcher child to discovery and root-owned launch. */\nexport function createDispatcherBridge(\n pi: ExtensionAPI,\n parentSessionId: string | undefined,\n environment: Readonly<Record<string, string | undefined>> = process.env,\n): ExtensionAPI {\n const rootSessionId = parentSessionId ? resolveRootSessionId(parentSessionId, environment) : undefined;\n return new Proxy(pi, {\n get(target, property) {\n if (property === 'setActiveTools') {\n return (names: string[]): void => target.setActiveTools(names.filter((name) => name !== 'workflow_run'));\n }\n if (property !== 'registerTool') return boundValue(target, property);\n return (tool: RegisteredTool): void => {\n if (!DISPATCHER_TOOL_NAMES.has(tool.name)) return;\n if (!rootSessionId || !ROOT_SCOPED_TOOL_NAMES.has(tool.name)) {\n target.registerTool(tool);\n return;\n }\n target.registerTool({\n ...tool,\n execute: (toolCallId, params, signal, onUpdate, ctx) =>\n tool.execute(toolCallId, params, signal, onUpdate, withParentSession(ctx, rootSessionId)),\n });\n };\n },\n });\n}\n\nexport function resolveDispatcherParentSession(\n environment: Readonly<Record<string, string | undefined>>,\n): string | undefined {\n const childContext = readChildProcessContext(environment);\n return childContext?.parentSessionId ?? (environment[SUBAGENT_PARENT_SESSION_ENV]?.trim() || undefined);\n}\n\nexport function isWorkflowDispatcherProcess(environment: Readonly<Record<string, string | undefined>>): boolean {\n const childContext = readChildProcessContext(environment);\n if (childContext?.mode === DISPATCHER_AGENT_NAME) return true;\n return (\n environment.PI_SUBAGENT_CHILD_AGENT === DISPATCHER_AGENT_NAME &&\n Boolean(environment[SUBAGENT_PARENT_SESSION_ENV]?.trim())\n );\n}\n\nfunction inactiveToolResult(): Awaited<ReturnType<RegisteredTool['execute']>> {\n return {\n content: [{ type: 'text', text: INACTIVE_RUNTIME_MESSAGE }],\n details: undefined,\n };\n}\n\n/** Fence every callback retained by Pi after this package root is replaced. */\nfunction createWorkflowFence(host: ExtensionAPI): WorkflowFence {\n const scope = new AsyncLocalStorage<RuntimeScope>();\n let active = true;\n let disposing = false;\n let generation = 0;\n let lastSessionStartEvent: unknown;\n let lastSessionStartContext: ExtensionContext | undefined;\n\n const isCurrentInvocation = (): boolean => {\n if (!active) return false;\n const currentScope = scope.getStore();\n return currentScope === undefined || currentScope === CLEANUP_SCOPE || currentScope === generation;\n };\n const ownsContext = (contextGeneration: number): boolean => {\n if (!active) return false;\n const currentScope = scope.getStore();\n return (\n currentScope === CLEANUP_SCOPE ||\n (contextGeneration === generation && (currentScope === undefined || currentScope === contextGeneration))\n );\n };\n\n const guardContext = <TContext extends ExtensionContext>(context: TContext, contextGeneration: number): TContext => {\n const guardedUi = new Proxy(context.ui, {\n get(target, property) {\n const value = Reflect.get(target, property, target);\n if (typeof value !== 'function') return value;\n return (...args: unknown[]): unknown => {\n if (ownsContext(contextGeneration)) return Reflect.apply(value, target, args);\n if (property === 'confirm') return Promise.resolve(false);\n if (property === 'custom' || property === 'editor' || property === 'input' || property === 'select') {\n return Promise.resolve(undefined);\n }\n return undefined;\n };\n },\n });\n return new Proxy(context, {\n get(target, property) {\n if (property === 'ui') return guardedUi;\n return boundValue(target, property);\n },\n }) as TContext;\n };\n\n const registerTool = (tool: RegisteredTool): void => {\n if (!isCurrentInvocation()) return;\n host.registerTool({\n ...tool,\n execute: async (toolCallId, params, signal, onUpdate, context) => {\n const executionGeneration = generation;\n if (!active || disposing || signal?.aborted) return inactiveToolResult();\n const guardedContext = guardContext(context, executionGeneration);\n const guardedUpdate = onUpdate\n ? (update: Parameters<NonNullable<typeof onUpdate>>[0]): void => {\n if (active && executionGeneration === generation && !signal?.aborted) onUpdate(update);\n }\n : undefined;\n const result = await scope.run(executionGeneration, () =>\n tool.execute(toolCallId, params, signal, guardedUpdate, guardedContext),\n );\n return active && !disposing && executionGeneration === generation ? result : inactiveToolResult();\n },\n });\n };\n\n const registerCommand = (name: string, options: CommandOptions): void => {\n if (!isCurrentInvocation()) return;\n host.registerCommand(name, {\n ...options,\n handler: async (args, context) => {\n const executionGeneration = generation;\n if (!active || disposing) return;\n await scope.run(executionGeneration, () => options.handler(args, guardContext(context, executionGeneration)));\n },\n });\n };\n\n const registerShortcut = (\n shortcut: Parameters<ExtensionAPI['registerShortcut']>[0],\n options: ShortcutOptions,\n ): void => {\n if (!isCurrentInvocation()) return;\n host.registerShortcut(shortcut, {\n ...options,\n handler: (context) => {\n const executionGeneration = generation;\n if (!active || disposing) return;\n return scope.run(executionGeneration, () => options.handler(guardContext(context, executionGeneration)));\n },\n });\n };\n\n const guardedPi = new Proxy(host, {\n get(target, property) {\n if (property === 'on') {\n return (eventName: string, handler: LifecycleHandler): void => {\n const registerLifecycleHandler = boundValue(target, 'on') as (\n name: string,\n callback: LifecycleHandler,\n ) => void;\n registerLifecycleHandler(eventName, (event: unknown, context: ExtensionContext) => {\n if (!active || disposing) return undefined;\n if (\n eventName === SESSION_START_EVENT &&\n (event !== lastSessionStartEvent || context !== lastSessionStartContext)\n ) {\n generation += 1;\n lastSessionStartEvent = event;\n lastSessionStartContext = context;\n }\n const eventGeneration = generation;\n return scope.run(eventGeneration, () => handler(event, guardContext(context, eventGeneration)));\n });\n };\n }\n if (property === 'registerTool') return registerTool;\n if (property === 'registerCommand') return registerCommand;\n if (property === 'registerShortcut') return registerShortcut;\n if (property === 'getActiveTools') {\n return (): string[] => (isCurrentInvocation() ? target.getActiveTools() : []);\n }\n if (property === 'setActiveTools') {\n return (names: string[]): void => {\n if (isCurrentInvocation()) target.setActiveTools(names);\n };\n }\n if (property === 'sendMessage') {\n return (...args: Parameters<ExtensionAPI['sendMessage']>): void => {\n if (isCurrentInvocation()) target.sendMessage(...args);\n };\n }\n if (property === 'sendUserMessage') {\n return (...args: Parameters<ExtensionAPI['sendUserMessage']>): void => {\n if (isCurrentInvocation()) target.sendUserMessage(...args);\n };\n }\n if (property === 'exec') {\n return (...args: Parameters<ExtensionAPI['exec']>): ReturnType<ExtensionAPI['exec']> =>\n isCurrentInvocation()\n ? target.exec(...args)\n : Promise.resolve({ code: 1, killed: false, stderr: INACTIVE_RUNTIME_MESSAGE, stdout: '' });\n }\n return boundValue(target, property);\n },\n });\n\n return {\n pi: guardedPi,\n beginDisposal() {\n if (disposing || !active) return;\n disposing = true;\n generation += 1;\n },\n finishDisposal() {\n active = false;\n disposing = false;\n generation += 1;\n },\n isCurrentInvocation,\n runCleanup: (operation) => scope.run(CLEANUP_SCOPE, operation),\n };\n}\n\n/** Install one normal or dispatcher runtime into its host-owned Cordis plugin fiber. */\nexport function installWorkflowRuntime(\n cordis: Context,\n pi: ExtensionAPI,\n isCurrentInvocation: () => boolean,\n environment: Readonly<Record<string, string | undefined>> = process.env,\n): void {\n const dispatcher = isWorkflowDispatcherProcess(environment);\n const parentSessionId = dispatcher ? resolveDispatcherParentSession(environment) : undefined;\n const runtimePi = dispatcher ? createDispatcherBridge(pi, parentSessionId, environment) : pi;\n\n let runtime: WorkflowPiRuntime | undefined;\n cordis.effect(() => () => (runtime ? runtime.dispose() : Promise.resolve()), `${PACKAGE_SOURCE}/runtime`);\n\n cordis.inject([DOOM_SKILL_SOURCES_SERVICE], (skillContext) => {\n const directory = resolve(dirname(fileURLToPath(import.meta.url)), SKILL_RELATIVE_PATH);\n if (!existsSync(directory)) return undefined;\n const contribution = requireDoomSkillSourcesService(skillContext).register({\n source: PACKAGE_SOURCE,\n directories: [directory],\n });\n return () => contribution.dispose();\n });\n\n if (dispatcher) {\n runtime = installWorkflowPiRuntime({ cordis, initialMode: true, isActive: isCurrentInvocation })(runtimePi);\n return;\n }\n\n let workflowMode = false;\n let leader: ReturnType<typeof registerLeaderContribution> | undefined;\n cordis.inject([DOOM_UI_HUB_SERVICE], (uiContext) => {\n const contribution = registerLeaderContribution(requireDoomUiHub(uiContext), workflowMode);\n leader = contribution;\n return () => {\n contribution.dispose();\n if (leader === contribution) leader = undefined;\n };\n });\n cordis.inject([DOOM_HELP_SERVICE], (helpContext) => {\n const help = requireDoomHelpService(helpContext).register({\n source: PACKAGE_SOURCE,\n moduleUrl: import.meta.url,\n skills: [\n {\n name: 'doompi-author-workflow',\n description:\n 'Author DoomPi workflow definitions. Use when creating or changing a *.workflow.yml graph, arranging job dependencies and host-executed steps, or deciding how a command requiring a TTY should run.',\n },\n {\n name: 'doompi-use-workflow',\n description:\n 'Use DoomPi workflows. Use when discovering or launching workflows, monitoring or controlling asynchronous runs, interpreting terminal notifications, or recovering a failed run safely.',\n },\n ],\n });\n return () => help.dispose();\n });\n runtime = installWorkflowPiRuntime({\n cordis,\n isActive: isCurrentInvocation,\n onModeChange: (enabled) => {\n workflowMode = enabled;\n leader?.setMode(enabled);\n },\n })(runtimePi);\n}\n\ninterface WorkflowPluginConfig {\n readonly fence: WorkflowFence;\n readonly environment: Readonly<Record<string, string | undefined>>;\n}\n\nfunction workflowPlugin(cordis: Context, { fence, environment }: WorkflowPluginConfig): void {\n installWorkflowRuntime(cordis, fence.pi, fence.isCurrentInvocation, environment);\n}\n\n/** The package's sole Pi factory; Pi reloads it and Cordis owns all package resources. */\nexport async function workflowExtension(pi: ExtensionAPI): Promise<void> {\n const connection = await connectDoomCordisHost(pi, PACKAGE_SOURCE);\n const fence = createWorkflowFence(pi);\n const fiber = connection.root.plugin(workflowPlugin, { fence, environment: process.env });\n let disposal: Promise<void> | undefined;\n const dispose = (): Promise<void> => {\n if (disposal) return disposal;\n fence.beginDisposal();\n disposal = fence.runCleanup(async () => {\n try {\n await fiber.dispose();\n } finally {\n try {\n fence.finishDisposal();\n } finally {\n await connection.dispose();\n }\n }\n });\n return disposal;\n };\n\n try {\n await fiber;\n } catch (error) {\n await dispose();\n throw error;\n }\n pi.on(SESSION_SHUTDOWN_EVENT, dispose);\n}\n\nexport default workflowExtension;\n"],"mappings":"y3BAqBA,MAAM,EAAiB,6BAEjB,EAAwB,qBAGxB,EAA2B,4CAC3B,EAAgB,OAAO,uBAAuB,EAE9C,EAAwB,IAAI,IAAI,CAAC,iBAAkB,iBAAiB,CAAC,EACrE,EAAyB,IAAI,IAAI,CAAC,iBAAiB,CAAC,EAgB1D,SAAS,EAAW,EAAgB,EAAgC,C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AC,EACM,GAGT,GAAI,CACF,MAAM,CACR,OAAS,EAAO,CAEd,MADA,MAAM,EAAQ,EACR,CACR,CACA,EAAG,GAAG,mBAAwB,CAAO,CACvC"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("../../types/index.cjs"),t=`doom-workflow`,n={key:`w`,label:e.LEADER_LABEL,detail:e.LEADER_DETAIL,order:50};function r(r){return[{id:`${t}.catalog`,path:[n,{key:`l`,label:`list`,detail:`browse and launch workflows`}],action:{name:e.LEADER_CATALOG_ACTION}},{id:`${t}.manage`,path:[n,{key:`r`,label:`runs`,detail:`runs in this session`}],action:{name:e.LEADER_MANAGE_ACTION}},r?{id:`${t}.disable`,path:[n,{key:`e`,label:`exit`,detail:`take back workflow tools`,tone:`exit`}],action:{name:e.LEADER_DISABLE_ACTION}}:{id:`${t}.enable`,path:[n,{key:`e`,label:`enter`,detail:`give the agent workflow tools`}],action:{name:e.LEADER_ENABLE_ACTION}},{id:`${t}.recover`,path:[n,{key:`c`,label:`recover`,detail:`adopt a failed run`}],action:{name:e.LEADER_RECOVER_ACTION}}]}function i(t,n=!1){let i=t.registerLeader({source:e.PACKAGE_SOURCE,bindings:r(n)});return{setMode(e){i.update(r(e))},dispose(){i.dispose()}}}exports.registerLeaderContribution=i,exports.workflowLeaderBindings=r;
|
|
2
|
+
//# sourceMappingURL=leader.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"leader.cjs","names":["LEADER_LABEL","LEADER_DETAIL","LEADER_CATALOG_ACTION","LEADER_MANAGE_ACTION","LEADER_DISABLE_ACTION","LEADER_ENABLE_ACTION","LEADER_RECOVER_ACTION","PACKAGE_SOURCE"],"sources":["../../../src/adapters/pi/leader.ts"],"sourcesContent":["import type { LeaderBinding } from '@agimon-ai/doompi-extension-contracts/leader';\nimport type { DoomUiHubService } from '@agimon-ai/doompi-extension-contracts/ui-hub';\nimport {\n LEADER_CATALOG_ACTION,\n LEADER_DETAIL,\n LEADER_DISABLE_ACTION,\n LEADER_ENABLE_ACTION,\n LEADER_KEY,\n LEADER_LABEL,\n LEADER_MANAGE_ACTION,\n LEADER_ORDER,\n LEADER_RECOVER_ACTION,\n PACKAGE_SOURCE,\n} from '../../types/index.ts';\n\nconst LEADER_BINDING_PREFIX = 'doom-workflow';\nconst GROUP_SEGMENT = {\n key: LEADER_KEY,\n label: LEADER_LABEL,\n detail: LEADER_DETAIL,\n order: LEADER_ORDER,\n} as const;\n\nexport interface WorkflowLeaderHandle {\n /** Republish the menu for the mode's current state. */\n setMode(enabled: boolean): void;\n dispose(): void;\n}\n\n/**\n * The menu as it stands with the mode on or off.\n *\n * One entry on `e` rather than an enable row beside a disable row: only one of\n * the two ever does anything, and a menu that prints both makes the reader\n * check the mode line to find out which. The label says which way it flips.\n */\nexport function workflowLeaderBindings(mode: boolean): LeaderBinding[] {\n return [\n {\n id: `${LEADER_BINDING_PREFIX}.catalog`,\n // Launching lives on this board's own `r` key rather than a second menu\n // entry: picking which workflow to run is the same act as reading what\n // one does.\n path: [GROUP_SEGMENT, { key: 'l', label: 'list', detail: 'browse and launch workflows' }],\n action: { name: LEADER_CATALOG_ACTION },\n },\n {\n id: `${LEADER_BINDING_PREFIX}.manage`,\n path: [GROUP_SEGMENT, { key: 'r', label: 'runs', detail: 'runs in this session' }],\n action: { name: LEADER_MANAGE_ACTION },\n },\n mode\n ? {\n id: `${LEADER_BINDING_PREFIX}.disable`,\n path: [GROUP_SEGMENT, { key: 'e', label: 'exit', detail: 'take back workflow tools', tone: 'exit' }],\n action: { name: LEADER_DISABLE_ACTION },\n }\n : {\n id: `${LEADER_BINDING_PREFIX}.enable`,\n path: [GROUP_SEGMENT, { key: 'e', label: 'enter', detail: 'give the agent workflow tools' }],\n action: { name: LEADER_ENABLE_ACTION },\n },\n // `r` is runs everywhere, so recovery moves off it rather than reading as a\n // third flavour of list in the one space that has both.\n {\n id: `${LEADER_BINDING_PREFIX}.recover`,\n path: [GROUP_SEGMENT, { key: 'c', label: 'recover', detail: 'adopt a failed run' }],\n action: { name: LEADER_RECOVER_ACTION },\n },\n ];\n}\n\nexport function registerLeaderContribution(hub: DoomUiHubService, enabled = false): WorkflowLeaderHandle {\n const contribution = hub.registerLeader({\n source: PACKAGE_SOURCE,\n bindings: workflowLeaderBindings(enabled),\n });\n return {\n setMode(enabled) {\n contribution.update(workflowLeaderBindings(enabled));\n },\n dispose() {\n contribution.dispose();\n },\n };\n}\n"],"mappings":"yCAeM,EAAwB,gBACxB,EAAgB,CACpB,IAAA,IACA,MAAOA,EAAAA,aACP,OAAQC,EAAAA,cACR,MAAA,EACF,EAeA,SAAgB,EAAuB,EAAgC,CACrE,MAAO,CACL,CACE,GAAI,GAAG,EAAsB,UAI7B,KAAM,CAAC,EAAe,CAAE,IAAK,IAAK,MAAO,OAAQ,OAAQ,6BAA8B,CAAC,EACxF,OAAQ,CAAE,KAAMC,EAAAA,qBAAsB,CACxC,EACA,CACE,GAAI,GAAG,EAAsB,SAC7B,KAAM,CAAC,EAAe,CAAE,IAAK,IAAK,MAAO,OAAQ,OAAQ,sBAAuB,CAAC,EACjF,OAAQ,CAAE,KAAMC,EAAAA,oBAAqB,CACvC,EACA,EACI,CACE,GAAI,GAAG,EAAsB,UAC7B,KAAM,CAAC,EAAe,CAAE,IAAK,IAAK,MAAO,OAAQ,OAAQ,2BAA4B,KAAM,MAAO,CAAC,EACnG,OAAQ,CAAE,KAAMC,EAAAA,qBAAsB,CACxC,EACA,CACE,GAAI,GAAG,EAAsB,SAC7B,KAAM,CAAC,EAAe,CAAE,IAAK,IAAK,MAAO,QAAS,OAAQ,+BAAgC,CAAC,EAC3F,OAAQ,CAAE,KAAMC,EAAAA,oBAAqB,CACvC,EAGJ,CACE,GAAI,GAAG,EAAsB,UAC7B,KAAM,CAAC,EAAe,CAAE,IAAK,IAAK,MAAO,UAAW,OAAQ,oBAAqB,CAAC,EAClF,OAAQ,CAAE,KAAMC,EAAAA,qBAAsB,CACxC,CACF,CACF,CAEA,SAAgB,EAA2B,EAAuB,EAAU,GAA6B,CACvG,IAAM,EAAe,EAAI,eAAe,CACtC,OAAQC,EAAAA,eACR,SAAU,EAAuB,CAAO,CAC1C,CAAC,EACD,MAAO,CACL,QAAQ,EAAS,CACf,EAAa,OAAO,EAAuB,CAAO,CAAC,CACrD,EACA,SAAU,CACR,EAAa,QAAQ,CACvB,CACF,CACF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{LEADER_CATALOG_ACTION as e,LEADER_DETAIL as t,LEADER_DISABLE_ACTION as n,LEADER_ENABLE_ACTION as r,LEADER_LABEL as i,LEADER_MANAGE_ACTION as a,LEADER_RECOVER_ACTION as o,PACKAGE_SOURCE as s}from"../../types/index.mjs";const c=`doom-workflow`,l={key:`w`,label:i,detail:t,order:50};function u(t){return[{id:`${c}.catalog`,path:[l,{key:`l`,label:`list`,detail:`browse and launch workflows`}],action:{name:e}},{id:`${c}.manage`,path:[l,{key:`r`,label:`runs`,detail:`runs in this session`}],action:{name:a}},t?{id:`${c}.disable`,path:[l,{key:`e`,label:`exit`,detail:`take back workflow tools`,tone:`exit`}],action:{name:n}}:{id:`${c}.enable`,path:[l,{key:`e`,label:`enter`,detail:`give the agent workflow tools`}],action:{name:r}},{id:`${c}.recover`,path:[l,{key:`c`,label:`recover`,detail:`adopt a failed run`}],action:{name:o}}]}function d(e,t=!1){let n=e.registerLeader({source:s,bindings:u(t)});return{setMode(e){n.update(u(e))},dispose(){n.dispose()}}}export{d as registerLeaderContribution,u as workflowLeaderBindings};
|
|
2
|
+
//# sourceMappingURL=leader.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"leader.mjs","names":[],"sources":["../../../src/adapters/pi/leader.ts"],"sourcesContent":["import type { LeaderBinding } from '@agimon-ai/doompi-extension-contracts/leader';\nimport type { DoomUiHubService } from '@agimon-ai/doompi-extension-contracts/ui-hub';\nimport {\n LEADER_CATALOG_ACTION,\n LEADER_DETAIL,\n LEADER_DISABLE_ACTION,\n LEADER_ENABLE_ACTION,\n LEADER_KEY,\n LEADER_LABEL,\n LEADER_MANAGE_ACTION,\n LEADER_ORDER,\n LEADER_RECOVER_ACTION,\n PACKAGE_SOURCE,\n} from '../../types/index.ts';\n\nconst LEADER_BINDING_PREFIX = 'doom-workflow';\nconst GROUP_SEGMENT = {\n key: LEADER_KEY,\n label: LEADER_LABEL,\n detail: LEADER_DETAIL,\n order: LEADER_ORDER,\n} as const;\n\nexport interface WorkflowLeaderHandle {\n /** Republish the menu for the mode's current state. */\n setMode(enabled: boolean): void;\n dispose(): void;\n}\n\n/**\n * The menu as it stands with the mode on or off.\n *\n * One entry on `e` rather than an enable row beside a disable row: only one of\n * the two ever does anything, and a menu that prints both makes the reader\n * check the mode line to find out which. The label says which way it flips.\n */\nexport function workflowLeaderBindings(mode: boolean): LeaderBinding[] {\n return [\n {\n id: `${LEADER_BINDING_PREFIX}.catalog`,\n // Launching lives on this board's own `r` key rather than a second menu\n // entry: picking which workflow to run is the same act as reading what\n // one does.\n path: [GROUP_SEGMENT, { key: 'l', label: 'list', detail: 'browse and launch workflows' }],\n action: { name: LEADER_CATALOG_ACTION },\n },\n {\n id: `${LEADER_BINDING_PREFIX}.manage`,\n path: [GROUP_SEGMENT, { key: 'r', label: 'runs', detail: 'runs in this session' }],\n action: { name: LEADER_MANAGE_ACTION },\n },\n mode\n ? {\n id: `${LEADER_BINDING_PREFIX}.disable`,\n path: [GROUP_SEGMENT, { key: 'e', label: 'exit', detail: 'take back workflow tools', tone: 'exit' }],\n action: { name: LEADER_DISABLE_ACTION },\n }\n : {\n id: `${LEADER_BINDING_PREFIX}.enable`,\n path: [GROUP_SEGMENT, { key: 'e', label: 'enter', detail: 'give the agent workflow tools' }],\n action: { name: LEADER_ENABLE_ACTION },\n },\n // `r` is runs everywhere, so recovery moves off it rather than reading as a\n // third flavour of list in the one space that has both.\n {\n id: `${LEADER_BINDING_PREFIX}.recover`,\n path: [GROUP_SEGMENT, { key: 'c', label: 'recover', detail: 'adopt a failed run' }],\n action: { name: LEADER_RECOVER_ACTION },\n },\n ];\n}\n\nexport function registerLeaderContribution(hub: DoomUiHubService, enabled = false): WorkflowLeaderHandle {\n const contribution = hub.registerLeader({\n source: PACKAGE_SOURCE,\n bindings: workflowLeaderBindings(enabled),\n });\n return {\n setMode(enabled) {\n contribution.update(workflowLeaderBindings(enabled));\n },\n dispose() {\n contribution.dispose();\n },\n };\n}\n"],"mappings":"iOAeA,MAAM,EAAwB,gBACxB,EAAgB,CACpB,IAAA,IACA,MAAO,EACP,OAAQ,EACR,MAAA,EACF,EAeA,SAAgB,EAAuB,EAAgC,CACrE,MAAO,CACL,CACE,GAAI,GAAG,EAAsB,UAI7B,KAAM,CAAC,EAAe,CAAE,IAAK,IAAK,MAAO,OAAQ,OAAQ,6BAA8B,CAAC,EACxF,OAAQ,CAAE,KAAM,CAAsB,CACxC,EACA,CACE,GAAI,GAAG,EAAsB,SAC7B,KAAM,CAAC,EAAe,CAAE,IAAK,IAAK,MAAO,OAAQ,OAAQ,sBAAuB,CAAC,EACjF,OAAQ,CAAE,KAAM,CAAqB,CACvC,EACA,EACI,CACE,GAAI,GAAG,EAAsB,UAC7B,KAAM,CAAC,EAAe,CAAE,IAAK,IAAK,MAAO,OAAQ,OAAQ,2BAA4B,KAAM,MAAO,CAAC,EACnG,OAAQ,CAAE,KAAM,CAAsB,CACxC,EACA,CACE,GAAI,GAAG,EAAsB,SAC7B,KAAM,CAAC,EAAe,CAAE,IAAK,IAAK,MAAO,QAAS,OAAQ,+BAAgC,CAAC,EAC3F,OAAQ,CAAE,KAAM,CAAqB,CACvC,EAGJ,CACE,GAAI,GAAG,EAAsB,UAC7B,KAAM,CAAC,EAAe,CAAE,IAAK,IAAK,MAAO,UAAW,OAAQ,oBAAqB,CAAC,EAClF,OAAQ,CAAE,KAAM,CAAsB,CACxC,CACF,CACF,CAEA,SAAgB,EAA2B,EAAuB,EAAU,GAA6B,CACvG,IAAM,EAAe,EAAI,eAAe,CACtC,OAAQ,EACR,SAAU,EAAuB,CAAO,CAC1C,CAAC,EACD,MAAO,CACL,QAAQ,EAAS,CACf,EAAa,OAAO,EAAuB,CAAO,CAAC,CACrD,EACA,SAAU,CACR,EAAa,QAAQ,CACvB,CACF,CACF"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
const e=require("../../../services/workflowTerminal.cjs"),t=require("../../../types/index.cjs"),n=require("../../../services/backgroundWork.cjs"),r=require("../../../services/workflowNarration.cjs"),i=require("../../../tui/workflow/workflowInspector.cjs"),a=require("../../../tui/workflow/workflowOverlay.cjs"),o=require("../../../tui/workflow/workflowFinishedMessage.cjs"),s=require("../../../tui/workflow/workflowCatalog.cjs"),c=require("../../../tui/workflow/workflowPicker.cjs"),l=require("../../../tui/workflow/workflowProgressOverlay.cjs"),u=require("../../../tui/workflow/workflowPrompt.cjs"),ee=require("../../../tui/workflow/workflowRunPanel.cjs"),d=require("../../../tui/workflow/workflowStepMessage.cjs"),f=require("./piToolBridge.cjs"),p=require("./piTools.cjs"),m=require("./workflowLauncher.cjs"),te=require("../../../services/workflowLaunchCommand.cjs");let ne=require("node:crypto"),re=require("node:fs"),h=require("node:path"),g=require("@agimon-ai/workflow-mcp"),ie=require("node:url"),_=require("@agimon-ai/doompi-extension-contracts/child-process"),ae=require("@agimon-ai/doompi-extension-contracts/ui-hub"),v=require("node:child_process"),oe=require("node:fs/promises"),y=require("node:module"),se=require("@agimon-ai/doompi-extension-contracts/mode"),ce=require("@agimon-ai/doompi-extension-contracts/narration"),le=require("@agimon-ai/doompi-extension-contracts/readiness"),ue=require("@agimon-ai/doompi-telemetry"),b=require("@earendil-works/pi-tui");const de={overlay:!0,overlayOptions:{anchor:`top-left`,width:`100%`,maxHeight:`100%`,margin:0}},fe=`workflow-mcp-follow`,pe=`activate`,me=`deactivate`;function he(e,t){return{activation:e?`active`:`inactive`,condition:`ready`,...e?{detail:t>0?`${t} active runs`:`tools enabled`,color:`accent`}:{},actions:[...e?[{id:pe,enabled:!1,disabledReason:`Workflow mode is active.`}]:[{id:pe,enabled:!0}],...e?[{id:me,enabled:!0}]:[{id:me,enabled:!1,disabledReason:`Workflow mode is inactive.`}]]}}const x=`ctrl+alt+w`,S=`ctrl+alt+q`,ge={alt:`⌥`,cmd:`⌘`,ctrl:`⌃`,meta:`⌘`,shift:`⇧`};function C(e,t=process.platform){let n=e.split(`+`);return t===`darwin`?n.map(e=>ge[e]??e.toUpperCase()).join(``):n.map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(`+`)}const _e=1e4,w=`running`,T=`completed`,E=`failed`,ve=`error`,ye=`error`,be=`doom_workflow.launch_requested`,xe=`../../../../skills`,D={running:`▸`,repair:`⚠`,completed:`✔`,failed:`✖`,separator:`·`};function Se(e,t=process.platform){let n=C(S,t);return e?[`Esc Esc closes this view`,`${C(x,t)} switches typing`,`${n} closes`].join(` ${D.separator} `):`view only ${D.separator} ${n} closes this view`}function Ce(e,t=process.platform){let n=[C(S,t),`close`];return e?[[`Esc Esc`,`close`],[C(x,t),`switch typing`],n]:[n]}function we(e,t,n,r){let i=`${D.running} ${e.runKey}`,a=[e.workspace,De(e),e.runner].filter(Boolean).join(` ${D.separator} `),o=`${C(x)} to background`,s=n.fg(`accent`,(0,b.truncateToWidth)(i,r));return(0,b.visibleWidth)(i)+3+(0,b.visibleWidth)(a)<=r&&(s+=` `+n.fg(`muted`,a),(0,b.visibleWidth)(i)+3+(0,b.visibleWidth)(a)+3+(0,b.visibleWidth)(o)<=r&&(s+=` `+n.fg(`dim`,o))),[s,...t.map(e=>(0,b.truncateToWidth)(e,r))]}function Te(e,t,n){let r=[];for(let i of e){let e=i.status===T?D.completed:i.status===E?D.failed:D.running,a=i.status===T?`success`:i.status===E?ye:`accent`,o=i.total?` ${D.separator} ${(i.index??0)+1}/${i.total}`:``;if(r.push((0,b.truncateToWidth)(t.fg(a,`${e} ${i.name}`)+t.fg(`dim`,o),n)),i.status===w)for(let e of i.steps){let i=e.status===T?D.completed:e.status===E?D.failed:D.running,a=e.status===w?`muted`:e.status===E?ye:`dim`;r.push((0,b.truncateToWidth)(t.fg(a,` ${i} ${e.name}`),n))}}return r}function Ee(e,t){let n=Date.parse(e.startedAt);return Number.isFinite(n)?t.filter(e=>{let t=Date.parse(e.at);return!Number.isFinite(t)||t>=n}):t}function De(e){return e.stale?`stale`:e.stage===ve?E:e.stage}const Oe=[`CMUX_SURFACE_ID`,_.SUBAGENT_ROOT_SESSION_ENV,`CMUX_WORKSPACE_ID`,`TMUX_PANE`,`WORKFLOW_LAUNCHER_TYPE`,`WORKFLOW_TMUX_SESSION_NAME`,`WORKFLOW_STATUS_FILE`],ke=`tmux`,Ae=`cmux`,je=`This run points at Pi's own terminal, so its launcher screen is hidden. Use workflow status instead.`;function Me(e){return(0,h.basename)(e,(0,h.extname)(e))}function Ne(){let e={...process.env};for(let t of Oe)delete e[t];return e}function Pe(){let e=process.env.WORKFLOW_LAUNCHER;return e===ke||e===Ae?e:void 0}function Fe(e){return e.map(e=>`'${e.replaceAll(`'`,`'\\''`)}'`).join(` `)}function Ie(){try{return(0,y.createRequire)(require("url").pathToFileURL(__filename).href).resolve(`@agimon-ai/workflow-mcp/cli`)}catch{return}}const Le=async(e,t,n)=>{await new Promise((r,i)=>{let a=(0,v.spawn)(e,[...t],{...n,detached:!0,stdio:`ignore`});a.once(`error`,i),a.once(`spawn`,()=>{a.off(`error`,i),a.unref(),r()})})};function O(e,t){if(Array.isArray(e)){for(let n of e)O(n,t);return}if(!(!e||typeof e!=`object`))for(let[n,r]of Object.entries(e))(n===`interactiveRun`||n===`run`)&&r&&typeof r==`object`&&!Array.isArray(r)?t.push(Object.keys(r)):O(r,t)}function Re(e){let t=[];if(O(e,t),t.length!==0)return t[0].filter(e=>t.every(t=>t.includes(e))).sort()}async function k(e,t){let n=[],r=1,i=!0;for(;i;){let a=await e.listRunsPage({page:r,pageSize:100,workspace:t});n.push(...a.items),i=a.hasNextPage,r+=1}return n}function ze(e){return[e.runKey,e.workspace,De(e),e.runner].filter(Boolean).join(` ${D.separator} `)}function Be(v={}){return y=>{let b=v.featureFactory?.()??(0,g.createEmbeddedWorkflowFeature)(),ge=(0,ne.randomUUID)(),E=!0,ye=0,Oe,O,Be,Ve=v.isActive??(()=>!0),A=()=>E&&Ve(),He=e=>{let t=e.diagnostics.join(`; `),n=(e.error?.message??t)||`Initialization did not complete.`,r=`${e.packageId} initialization ${e.state}: ${n}`;B?.hasUI?B.ui.notify(r,`warning`):process.emitWarning(r)},Ue=e=>(v.cordis?(0,le.readDoomReadinessCoordinator)(v.cordis):void 0)||(Be??=(0,le.createDoomReadinessCoordinator)({notify:He}),Be),j=async e=>{e?.throwIfAborted();let t=O;if(!t)throw Error(`Workflow session initialization has not started.`);let n=await t;if(e?.throwIfAborted(),await n.wait(e?{signal:e}:void 0),!A()||t!==O)throw Error(`Workflow readiness belongs to a stale extension generation.`)},We=(e,t)=>{let n=Reflect.get(e,t,e);return typeof n==`function`?n.bind(e):n},Ge=new Proxy(y,{get(e,t){return t===`registerTool`?t=>{e.registerTool({...t,execute:async(e,n,r,i,a)=>(await j(r),t.execute(e,n,r,i,a))})}:We(e,t)}}),{parser:Ke,recoverService:qe,registry:M,runService:Je,runTool:Ye}=b,Xe=v.spawnDetached??Le,Ze=v.monitorIntervalMs??3e4,Qe=v.followIntervalMs??2e3,N,$e=!1,P,et=!1,F,tt=new Map,I=new Map,nt=new Set,rt=0,it=v.cordis?n.registerRunProvider(v.cordis):void 0,at=!1,L=0,R=!1,ot,z;v.cordis?.inject([se.DOOM_MINOR_MODE_CATALOG_SERVICE],e=>{let n=he(R,L),r=(0,se.registerMinorModeOwner)((0,se.requireMinorModeCatalog)(e),{descriptor:{source:t.PACKAGE_SOURCE,id:`workflow`,label:`Workflow`,description:`Workflow discovery, launch, inspection, control, and recovery tools.`,order:20,actions:[{id:pe,label:`Activate`,description:`Enable workflow tools for this session.`,contexts:[`tui`,`headless`],parameters:[]},{id:me,label:`Deactivate`,description:`Disable workflow tools without stopping active runs.`,contexts:[`tui`,`headless`],parameters:[]}]},initialState:n,async handleAction(e,t,n){if(await j(),e===pe)return await on(!0,n.context),{message:`Workflow mode activated.`};if(e===me)return await on(!1,n.context),{message:`Workflow mode deactivated.`};throw Error(`Unknown workflow mode action: ${e}`)}});return z=r,ot=JSON.stringify(n),()=>{r.dispose(),z===r&&(z=void 0,ot=void 0)}});let B,V,H,st=!1,ct=new Map,U,lt=new Set,W=new Map,ut=[],G=new Map,dt=0,ft=new l.WorkflowProgressOverlay,pt,mt,K=e=>(mt??=(0,ue.createDoomTelemetry)({serviceName:`doom-workflow`,packageName:`@agimon-ai/doompi-workflow`,cwd:e?.cwd,env:process.env,enableLogs:!0,enableTraces:!0}),mt),ht,gt=e=>{K(B).recordWarning(`doom_workflow.narration_failed`,e).catch(e=>{process.emitWarning(`Doom-workflow could not record a narration failure: ${String(e)}`)})},_t={narrate(e){let t=ht,n=(0,ce.createNarrationRequest)(e);if(!(!t||!n))try{Promise.resolve(t.request(n)).catch(gt)}catch(e){gt(e)}}};v.cordis?.inject([ce.DOOM_NARRATION_SERVICE],e=>{let t=(0,ce.requireDoomNarrationService)(e);return ht=t,()=>{ht===t&&(ht=void 0)}});let vt=e=>{e&&A()&&(pt=(0,_.resolveRootSessionId)(e))},yt=()=>{let e=pt??B?.sessionManager.getSessionId();return e?(0,_.resolveRootSessionId)(e):void 0},bt=(e,t)=>e.sessionManager.getSessionId().trim()===t,xt=b.createRecoverTool({ownerSessionId:yt}),St=b.createControlTool(),q=new Set,Ct=e=>{let t=Date.now(),n=K();return q.add(e),n.recordEvent(`doom_workflow.run_started`,{outcome:`started`}),e.then(()=>(q.delete(e),n.recordEvent(`doom_workflow.run_finished`,{duration_ms:Date.now()-t,outcome:`completed`})),r=>(q.delete(e),n.recordError(`doom_workflow.run_failed`,r,{duration_ms:Date.now()-t}))),e},wt=(e,t)=>{let n=Re(Ke.parseWorkflowFile(e));if(!(!n||n.includes(t)))return`Runner ${JSON.stringify(t)} is not available across this workflow. Compatible runners: ${n.join(`, `)||`none`}.`},Tt=p.createWorkflowLaunchExecutor({activeRunCount:async()=>L,observeSession:vt,rejectRunner:wt,runTool:Ye,trackPendingRun:Ct,...v.launchAckPollMs===void 0?{}:{launchAckPollMs:v.launchAckPollMs},...v.launchAckTimeoutMs===void 0?{}:{launchAckTimeoutMs:v.launchAckTimeoutMs},findLaunchedRun:async({sessionId:e,since:t,workflowPath:n})=>{let r=Me(n),i=n=>{if(!f.isSessionRun(n,e)||n.stale||n.workflowId&&n.workflowId!==r)return!1;let i=Date.parse(n.startedAt);return Number.isFinite(i)&&i>=t-2e3};return U?(await U.refresh(),ut.find(i)):(await k(M)).find(i)},onLateFailure:(e,t)=>{let n=e instanceof Error?e.message:String(e);t.ui.notify(f.launchNotice(`Workflow launch failed after it was reported started.\n${n}`),`warning`)},onLaunch:async e=>(await K(e).recordEvent(be,{outcome:`requested`}),X(e,!1))}),Et=()=>{let e=[...G.values()].sort((e,t)=>Date.parse(e.startedAt)-Date.parse(t.startedAt)||Y(e).localeCompare(Y(t)));ft.update(e.map(e=>l.workflowProgressRow(e,W.get(Y(e))??[])))},Dt=e=>{dt+=1;let t=Y(e);e.stage===w&&!e.stale?G.set(t,e):G.delete(t),Et()},Ot=e=>{G.clear();for(let t of e)G.set(Y(t),t);Et()},kt=(e,t)=>{let n=W.get(e)??[];n.push(t),W.set(e,n)},J,At=e=>{!A()||e!==B||J||(J=setTimeout(()=>{J=void 0,A()&&e===B&&X(e,!0)},120),J.unref?.())},jt=e=>{W.delete(e)},Mt=async e=>{let t=(0,_.resolveRootSessionId)(e.sessionManager.getSessionId()),n=b.createRunControl({recordFilter:e=>f.isSessionRun(e,t)});U=n;let r=()=>A()&&e===B&&U===n,i=[n.on(`step`,t=>{if(!r())return;let n=Y(t.record);kt(n,{at:t.at,job:t.job,status:t.status,step:t.step,type:`step`,...t.reason===void 0?{}:{reason:t.reason}}),Dt(t.record),At(e)}),n.on(`job`,t=>{if(!r())return;let n=Y(t.record);kt(n,{at:t.at,job:t.job,status:t.status,type:`job`,...t.index===void 0?{}:{index:t.index},...t.reason===void 0?{}:{reason:t.reason},...t.total===void 0?{}:{total:t.total}}),Dt(t.record),At(e)}),n.on(`runStarted`,t=>{r()&&(ut.unshift(t.record),ut.length>32&&(ut.length=32),Dt(t.record),At(e))}),n.on(`runUpdated`,t=>{r()&&(Dt(t.record),X(e,!0))}),n.on(`runFinished`,t=>{r()&&(Dt(t.record),X(e,!0))})];for(let e of i)lt.add(e);try{await n.start()}catch(e){for(let e of i)lt.delete(e),e();throw n.dispose(),U===n&&(U=void 0),e}if(!A()||e!==B||U!==n){for(let e of i)lt.delete(e),e();n.dispose(),U===n&&(U=void 0)}},Nt=()=>{J&&clearTimeout(J),J=void 0;for(let e of lt)e();lt.clear(),U?.dispose(),U=void 0,W.clear(),dt+=1,G.clear(),Et()},Pt=()=>{V?.teardown(),V?.handle?.hide(),V=void 0},Y=e=>e.runId??`${e.workspace}/${e.runKey}`,Ft=()=>{let e=z;if(!e)return;let t=he(R,L),n=JSON.stringify(t);n!==ot&&(ot=n,e.publish(t))},X=async(e,t)=>{if(!A()||e!==B)return;let n=K(e);if($e){n.recordEvent(`doom_workflow.monitor_skipped`,{outcome:`already_running`});return}let i=Date.now(),a=dt;$e=!0;try{let s=await k(M);if(!A()||e!==B)return;let c=(0,_.resolveRootSessionId)(e.sessionManager.getSessionId()),l=bt(e,c),u=s.filter(e=>f.isSessionRun(e,c)),ee=u.filter(e=>e.stage===w&&!e.stale),d=u.filter(e=>e.stage===ve);a===dt&&Ot(ee),n.recordEvent(`doom_workflow.monitor_counts`,{"workflow.run_count":u.length,"workflow.running_count":ee.length,"workflow.failed_count":d.length,mode:R?`on`:`off`});let p=f.runsForSession(s,c).filter(e=>!e.stale);L=p.length,Ft(),it?.update(p.map(e=>({id:e.runId??e.runKey,sessionId:c}))),Vt(new Set(u.map(e=>Y(e))));let m=new Map(u.map(e=>[Y(e),e.stage]));for(let e of u){let n=Y(e),i=tt.get(n),a=Date.parse(e.startedAt),o=i===void 0&&(rt===0||!Number.isFinite(a)||a>=rt);at&&r.narrateWorkflowTransition(_t,e,i===w||i===T||i===ve?i:void 0,o),!(!t||!l||e.stage===w)&&!nt.has(n)&&(i===w||o)&&I.set(n,e)}let te=new Set([...u.filter(e=>e.stage===w&&!e.stale).map(e=>Y(e)),...I.keys()]);for(let e of W.keys())te.has(e)||jt(e);if(t)for(let t of u){if(tt.get(Y(t))!==w||t.stage===w)continue;let r=t.stage===T,i=t.failedJob?` at ${t.failedJob}`:``;e.ui.notify(r?`${D.completed} ${t.runKey} completed`:`${D.failed} ${t.runKey} ${De(t)}${i}`,r?`info`:`warning`),n.recordEvent(`doom_workflow.run_transition`,{outcome:r?`completed`:De(t)})}if(l&&I.size>0)try{let e=[...I.values()],t=await Promise.all(e.map(async e=>{if(e.stage===T)return f.finishedRunSummary(e,[]);let t=Y(e),n=W.get(t)??Ee(e,await(0,g.readWorkflowProgress)(M.runDirectoryFor(e)));return f.finishedRunSummary(e,(0,g.summarizeWorkflowProgress)(n))}));y.sendMessage({customType:o.WORKFLOW_FINISHED_MESSAGE,content:t.join(`
|
|
2
|
+
|
|
3
|
+
`),display:!0,details:{runIds:e.map(e=>e.runId??Y(e)),runs:e.map(e=>({runKey:e.runKey,workspace:e.workspace,stage:e.stage,...e.workflowId?{workflowId:e.workflowId}:{},...e.failedJob?{failedJob:e.failedJob}:{},...e.errorMessage?{error:e.errorMessage}:{}}))}},{triggerTurn:!0,deliverAs:`steer`});for(let t of e){let e=Y(t);nt.add(e),I.delete(e),jt(e)}}catch(e){await n.recordError(`doom_workflow.terminal_delivery_failed`,e,{"workflow.pending_terminal_count":I.size})}tt=m,n.recordEvent(`doom_workflow.monitor_finished`,{duration_ms:Date.now()-i,outcome:`completed`})}catch(t){await n.recordError(`doom_workflow.monitor_failed`,t,{duration_ms:Date.now()-i}),e.ui.notify(`Workflow status refresh failed: ${t instanceof Error?t.message:String(t)}`,`warning`)}finally{$e=!1}},It=e=>{P&&clearInterval(P),P=void 0,F=void 0,e.ui.setWidget(fe,void 0)},Z=new g.WorkflowTerminalService({run:async(e,t,n)=>{let r=await y.exec(e,[...t],{timeout:n.timeoutMs});return{code:r.code,stdout:r.stdout,stderr:r.stderr}},lines:24,timeoutMs:_e}),Lt=e.createWorkflowTerminalService({terminal:Z,now:()=>Date.now(),refreshMs:750}),Rt=new Map,zt=(e,t,n)=>{let r=Y(e),i=`${t}x${n}`;Rt.get(r)!==i&&(Rt.set(r,i),Z.resize(e,t,n))},Bt=e=>Z.targetsCurrentTerminal(e)?Promise.resolve([je]):Lt.screen(Y(e),e,24),Vt=e=>{Lt.forget(e);for(let t of Rt.keys())e.has(t)||Rt.delete(t)},Ht=async e=>{let t=e.launcher;if(!t)return`No durable launcher identity is recorded for this run.`;if(Z.targetsCurrentTerminal(e))return je;if(t.type===`native`)return`This run is hosted natively rather than in a multiplexer, so there is no separate window to bring forward.`;if(t.type===Ae)return await y.exec(Ae,[`select-workspace`,`--workspace`,t.workspaceId],{timeout:_e}),`Opened ${e.runKey} in cmux.`;if(!process.env.TMUX)return`Pi is not attached to tmux. Follow the output instead, or attach to the recorded tmux session manually.`;let n=t.sessionId??t.sessionName,r=await y.exec(ke,[`switch-client`,`-t`,n],{timeout:_e});return r.code===0?(t.paneId&&await y.exec(ke,[`select-pane`,`-t`,t.paneId],{timeout:_e}),`Opened ${e.runKey} in tmux.`):r.stderr.trim()||`Unable to open tmux session ${n}.`},Ut=async(e,t)=>{if(!et){et=!0;try{let n=(0,g.summarizeWorkflowProgress)(Ee(e,await(0,g.readWorkflowProgress)(M.runDirectoryFor(e)))),r=n.length>0?void 0:await Bt(e);t.ui.setWidget(fe,(t,i)=>({render:t=>we(e,r??Te(n,i,t),i,t),invalidate:()=>{}}),{placement:`aboveEditor`})}finally{et=!1}}},Wt=async(e,t)=>{It(t),F=e,await Ut(e,t),P=setInterval(()=>{F&&Ut(F,t)},Qe),P.unref?.()},Gt=async(e,t)=>{Z.capabilities(e).writable&&await Z.write(e,t)},Kt=async(e,t)=>{Pt();let n=Z.capabilities(e).writable,r=new a.TerminalInputBatcher(t=>Gt(e,t)),i=[],o=[],s,c=!1,l=async()=>{i=(0,g.summarizeWorkflowProgress)(Ee(e,await(0,g.readWorkflowProgress)(M.runDirectoryFor(e)))),o=await Bt(e)};await l();let u=()=>{s&&clearInterval(s),s=void 0,r.dispose()},d={interactive:n,runKey:e.runKey,teardown:u};V=d;let f=()=>{Pt(),t.ui.notify(`Closed the ${e.runKey} view. The run keeps going.`,`info`)};return t.ui.custom((a,p,m,te)=>(s=setInterval(()=>{c||(c=!0,l().finally(()=>{c=!1,a.requestRender()}))},200),s.unref?.(),new ee.WorkflowRunPanelComponent(a,p,{runKey:e.runKey,label:`${D.running} ${ze(e)}`,breadcrumb:`SPC › w / workflows › run`,interactive:n,footer:Se(n),hints:Ce(n),snapshot:e=>({progress:Te(i,p,e),output:o}),onViewport:(t,n)=>zt(e,t,n),onUnfollow:()=>{d.handle?.unfocus(),t.ui.notify(`Typing goes to this session. The run keeps going.`,`info`)},onClose:f,sendInput:e=>r.write(e),flushInput:()=>void r.flush(),unfollowShortcut:x,closeShortcut:S,onDispose:()=>{u(),V===d&&(V=void 0),te()}})),{...ee.runPanelUiOptions(n),onHandle:e=>{d.handle=e}}),t.ui.notify(n?`${e.runKey}: typing goes to the run. Press Esc twice to close, ${C(x)} to type here instead.`:`${e.runKey}: view only, because this run is hosted natively. ${C(S)} closes it.`,`info`),n?[`Showing ${e.runKey} over Pi. Typing goes to the run.`,`Pressing Escape twice quickly closes the view, and a single Escape still reaches the run.`,`${C(x)} moves typing between the run and this session,`,`and ${C(S)} closes the view. The run keeps going either way.`].join(` `):[`Showing ${e.runKey} over Pi, as a view only:`,`the run is hosted natively rather than in a multiplexer, so there is no terminal to type into.`,`Typing stays with this session, and ${C(S)} closes the view.`].join(` `)},qt=async(e,t=!1)=>{if(!(st||V||F)){st=!0;try{let n=await e.ui.custom((e,t,n,r)=>new i.WorkflowInspectorComponent(e,t,{list:async()=>{let e=yt(),t=(await k(M)).filter(t=>t.stage===w&&!t.stale&&f.isSessionRun(t,e));return ct=new Map(t.map(e=>[Y(e),e])),Promise.all(t.map(async e=>({displayName:e.displayName,executionState:e.executionState,jobs:(0,g.summarizeWorkflowProgress)(Ee(e,await(0,g.readWorkflowProgress)(M.runDirectoryFor(e)))),key:Y(e),output:[],runKey:e.runKey,startedAt:e.startedAt,workspace:e.workspace})))},output:async e=>{let t=ct.get(e.key);return t?Bt(t):[`Workflow is no longer active.`]}},r),{...de,onHandle:e=>{H=e}});if(n){let r=await Q(n);t?await Qt(r,e):await Kt(r,e)}}finally{H=void 0,st=!1,ct.clear()}}},Q=async(e,t=yt())=>{vt(t);let n=(await k(M,e.workspace)).filter(n=>n.runKey===e.runKey&&f.isSessionRun(n,t));if(n.length>1)throw Error(f.withOptions(`Workflow run key ${JSON.stringify(e.runKey)} exists in more than one workspace in this session.`,[`Retry with the workspace from the run identity.`]));let r=n[0];if(!r)throw Error(f.withOptions(`No workflow run matches ${JSON.stringify(e.runKey)} in this session.`,[`workflow_run with action status: use a run key from this session before retrying.`,`Tell the user this session did not launch that run rather than guessing a similar key. A run launched by another Pi session, or from the command line, is managed there or with the workflow-mcp CLI.`]));return r},Jt=async e=>{let t=(await k(M,e.workspace)).filter(t=>t.runKey===e.runKey&&t.stage===ve);if(t.length>1)throw Error(f.withOptions(`Failed workflow run key ${JSON.stringify(e.runKey)} exists in more than one workspace.`,[`Retry with the workspace from the recovery picker or run identity.`]));let n=t[0];if(!n)throw Error(f.withOptions(`No failed workflow run matches ${JSON.stringify(e.runKey)}.`,[`Use the recovery picker to select an interrupted or failed run, or retry with its workspace.`,`Do not recover a running or completed workflow.`]));return n},Yt=async e=>{let t=M.runDirectoryFor(e),n=[(0,h.resolve)(t,`changelog.md`),(0,h.resolve)(t,`context.md`),(0,h.resolve)(t,`progress.ndjson`)],r=[];for(let e of n)try{let t=await(0,oe.readFile)(e,`utf-8`);r.push(`--- ${(0,h.basename)(e)} ---`,t.slice(-65536).trimEnd())}catch(e){if(e.code!==`ENOENT`)throw e}return r.length>0?r:[`No durable recovery evidence files are recorded for this run.`]},Xt=async(e,t)=>{let n=await Jt(e);return await K(t).recordEvent(`doom_workflow.recovery_evidence_requested`,{outcome:`requested`}),[`Workflow: ${ze(n)}`,`--- run.json ---`,JSON.stringify(n,null,2),...await Yt(n)].join(`
|
|
4
|
+
`)},Zt=async(e,t)=>{let n=Ie();if(!n)return;let r=await Jt(e),i;try{i=Ke.parseWorkflowFile(r.workflowPath)}catch{return}if(!i[`launch-command`])return;let a=(0,_.resolveRootSessionId)(t.sessionManager.getSessionId()),o=await M.claimRunRecovery(r.workspace,r.runKey,a),s=r.originalRepoPath??t.cwd,c=Fe([process.execPath,n,`recover-workflow`,r.runKey,`--workspace`,r.workspace,`--recovery-claim`,o.claimId,...e.runner?[`--runner`,e.runner]:[]]),l=Pe();try{await Xe(process.execPath,[n,`launch-process`,...l?[`--launcher`,l]:[],`--name`,`${r.displayName} recover`,`--cwd`,s,`--command`,c],{cwd:s,env:Ne()})}catch(e){throw await M.releaseRunRecoveryClaim(r.workspace,r.runKey,o.claimId),e}return await K(t).recordEvent(`doom_workflow.recover_delegated`,{launcher:l??`auto`,outcome:`delegated`}),`Recovering ${r.runKey} in a launcher of its own, so this session keeps its terminal. It reports back here when it ends.`},Qt=async(e,t)=>{let n=e;for(;;){let e=[`Open output`],r=n.executionState??w;r===w&&e.push(`Pause`),r===`paused`&&e.push(`Resume`),n.stage===w&&e.push(`Stop`),e.push(`Back`);let i=await u.openWorkflowChoice(t,{title:`Manage ${n.runKey}`,breadcrumb:`SPC › w / workflows › r / runs`,choices:e});if(!i||i===`Back`)return;if(n=await Q(n),n.stage!==w){t.ui.notify(`${n.runKey} is no longer running.`,`warning`);return}if(i===`Open output`){await Kt(n,t);return}if(i===`Stop`){if(!await t.ui.confirm(`Stop ${n.runKey}?`,`The workflow will be interrupted and will not be restarted automatically.`))continue;if(n=await Q(n),n.stage!==w){t.ui.notify(`${n.runKey} is no longer running.`,`warning`);return}}if(i!==`Pause`&&i!==`Resume`&&i!==`Stop`)continue;if(!n.runId)throw Error(`${n.runKey} has no controllable run generation.`);let a=await St.execute({action:i.toLowerCase(),expectedRunId:n.runId,...i===`Stop`?{reason:`Stopped from the workflow manager.`}:{},runKey:n.runKey,workspace:n.workspace});if(a.isError)throw Error(f.toolResultText(a)||`Unable to ${i.toLowerCase()} workflow.`);t.ui.notify(f.toolResultText(a)||`${i} requested for ${n.runKey}.`,`info`),await X(t,!1),n=await Q(n)}},$t=(e,t)=>({editor:(t,n)=>e.ui.editor(t,n),input:(n,r)=>u.openWorkflowInput(e,{title:n,breadcrumb:t,...r?{fallback:r}:{}}),notify:(t,n)=>e.ui.notify(t,n),select:(n,r)=>u.openWorkflowChoice(e,{title:n,breadcrumb:t,choices:r})}),en=async e=>{if(!e.hasUI){e.ui.notify(`The workflow list needs an interactive Pi session.`,`warning`);return}let t=await m.loadWorkflowCatalog(b.listWorkflowsTool,e.cwd),n=new Map(t.map(e=>[e.path,e])),r={compatibleRunners:Re,launch:(e,t)=>Tt.execute(e,t),parseWorkflow:e=>Ke.parseWorkflowFile(e),ui:$t(e,`SPC › w / workflows › l / list`)};await s.openWorkflowCatalogOverlay(e,t.map(e=>({key:e.path,name:e.name,relativePath:e.relativePath,description:e.description,tags:e.tags})),{loadDetail:e=>m.summarizeWorkflowFile(e.key,r),launchWorkflow:t=>{let i=n.get(t.key);i&&m.launchWorkflowEntry(r,i,e).then(t=>{t&&e.ui.notify(f.launchNotice(f.toolResultText(t)),`info`)},t=>{e.ui.notify(t instanceof Error?t.message:String(t),`error`)})}})},tn=async(e,t)=>{let n=te.parseWorkflowLaunchCommand(e);if(te.isLaunchParseFailure(n)){t.ui.notify(n.error,`error`);return}let r=await m.loadWorkflowCatalog(b.listWorkflowsTool,t.cwd),i=te.resolveWorkflowEntry(r,n.workflow);if(!i){t.ui.notify(`No workflow matches '${n.workflow}' under ${t.cwd}.`,`error`);return}let a=m.summarizeWorkflowFile(i.path,{compatibleRunners:Re,parseWorkflow:e=>Ke.parseWorkflowFile(e)});if(a.error!==void 0){t.ui.notify(`${i.name} could not be read: ${a.error}`,`error`);return}let o=te.validateWorkflowLaunch(a,n);if(o.length>0){t.ui.notify(o.join(` `),`error`);return}let s=Ke.parseWorkflowFile(i.path),c={workflowPath:i.path,...n.runner===void 0?{}:{runner:n.runner},...typeof s.workspace==`string`?{workspace:s.workspace}:{},...n.prompt===void 0?{}:{prompt:n.prompt},...Object.keys(n.inputs).length===0?{}:{inputs:n.inputs}},l=await Tt.execute(c,t);t.ui.notify(f.launchNotice(f.toolResultText(l)),`info`)};y.registerCommand(`workflow-launch`,{description:`Launch a workflow: /workflow-launch <workflow> [runner=x] [key=value …] [prompt]`,handler:async(e,t)=>{await j();try{await tn(e,t)}catch(e){t.ui.notify(e instanceof Error?e.message:String(e),`error`)}}});let nn=async e=>{let t=(await k(M)).filter(e=>e.stage===ve);if(t.length===0){e.ui.notify(`No failed workflows are available to recover.`,`info`);return}let n=await c.openWorkflowPickerOverlay(e,{title:`WORKFLOW RECOVERY`,breadcrumb:`SPC › w / workflows › c / recover`,unit:`failed runs`,action:`recover`,filterPlaceholder:`type to filter by name, run key or failed job`,emptyMessage:`No failed workflows are available to recover.`},t.map(e=>({key:`${e.workspace}/${e.runKey}`,name:e.displayName,detail:`${e.workspace}/${e.runKey}${e.failedJob?` · ${e.failedJob}`:``}`,...e.failedJob?{search:e.failedJob}:{},value:e})));if(!n)return;let r=await Jt(n);if(r.stage!==ve)throw Error(`${r.runKey} is no longer failed.`);let i=(0,h.resolve)((0,h.dirname)((0,ie.fileURLToPath)(require("url").pathToFileURL(__filename).href)),xe,`workflow-recovery`,`SKILL.md`);if(!(0,re.existsSync)(i))throw Error(`Workflow recovery skill is unavailable at ${i}.`);rn(!0),e.ui.notify(`Workflow tools enabled. The agent will investigate this failure and choose the safe next step.`,`info`),y.sendUserMessage([`Investigate recovery for this failed workflow run. This selection is permission to investigate, not permission to recover blindly.`,`Run identity: ${JSON.stringify({runKey:r.runKey,workspace:r.workspace})}`,`Read the package-owned recovery skill with the read tool at ${JSON.stringify(i)} before acting.`,`Inspect status, every relevant log source, process state, the staged run.json, and only the repair referenced by activeRepairId.`,`Choose exactly one outcome: recover, launch fresh, or defer. Never edit issue.md or repair.json, never scan historical repairs, and never pass recovery dryRun or a job override.`,`Do not recover terminal, approval-pending, blocked, or otherwise unsafe work. If evidence is incomplete, defer and explain what is missing.`,`If recovery is justified, preserve the recorded worktree and repair metadata, then verify real process and registry progress before reporting success.`].join(`
|
|
5
|
+
`),{deliverAs:`followUp`})},rn=e=>{if(!A())return;let t=new Set(y.getActiveTools());for(let n of p.WORKFLOW_PI_TOOL_NAMES)e?t.add(n):t.delete(n);y.setActiveTools([...t]),R=e,Ft(),v.onModeChange?.(e)},an=()=>R?[`${D.completed} Workflow mode on`,`Ask for workflows in plain language: the agent can list, launch, inspect, pause, resume, stop, and recover runs.`,`${C(x)} stops following a run without stopping it.`].join(`
|
|
6
|
+
`):[`Workflow mode off`,`Press SPC w e to give the agent its workflow tools. Runs already going are unaffected.`].join(`
|
|
7
|
+
`),on=async(e,t)=>{rn(e),R||It(t),t.ui.notify(an(),`info`),await X(t,!1)};y.registerShortcut(x,{description:`Open workflows or move typing between a workflow run and this session`,handler:async e=>{await j();let t=V?.handle;if(t){if(!V?.interactive){e.ui.notify(`This run is hosted natively, so the view takes no typing. Your keys stay here.`,`info`);return}t.isFocused()?(t.unfocus(),e.ui.notify(`Typing goes to this session. The run keeps going.`,`info`)):(t.focus(),e.ui.notify(`Typing goes to ${V?.runKey}.`,`info`));return}if(F){It(e),e.ui.notify(`Workflow continues in the background.`,`info`);return}await qt(e)}}),y.registerShortcut(S,{description:`Close the workflow run view`,handler:async e=>{if(await j(),!V)return;let t=V.runKey;Pt(),e.ui.notify(`Closed the ${t} view. The run keeps going.`,`info`)}}),y.on(`resources_discover`,()=>{if(!R)return{skillPaths:[]};let e=(0,h.resolve)((0,h.dirname)((0,ie.fileURLToPath)(require("url").pathToFileURL(__filename).href)),xe);return{skillPaths:(0,re.existsSync)(e)?[e]:[]}}),o.registerWorkflowFinishedRenderer(y),y.registerMessageRenderer(`workflow-step`,(e,{outputPad:t},n)=>{let r=d.isWorkflowStepMessageDetails(e.details)?e.details:void 0,i=typeof e.content==`string`?e.content:JSON.stringify(e.content);return d.renderWorkflowStepMessage(r,i,t,n)}),p.registerWorkflowPiTools(Ge,{runTool:Ye,recoverTool:xt,launchExecutor:Tt,controlTool:St,requireSessionRun:Q,requireRecoverableRun:Jt,readRecoveryEvidence:Xt,delegateRecovery:Zt,trackPendingRun:Ct,observeSession:vt,activeRunCount:async()=>L,onLaunch:async e=>(await K(e).recordEvent(be,{outcome:`requested`}),X(e,!1)),followRun:async(e,t)=>{let n=await Q(e,t.sessionManager.getSessionId());return await K(t).recordEvent(`doom_workflow.follow_started`,{outcome:`started`}),await Wt(n,t),`Following ${ze(n)}. Press ${C(x)} to stop following; the run keeps going.`},tailRun:async(e,t)=>{let n=await Q(e,t.sessionManager.getSessionId());return await K(t).recordEvent(`doom_workflow.tail_requested`,{outcome:`requested`}),[`Workflow: ${ze(n)}`,`Stage: ${De(n)}`,`Raw launcher output is hidden from chat. Use action follow or open to view it.`].join(`
|
|
8
|
+
`)},openRun:async(e,t)=>{let n=await Q(e,t.sessionManager.getSessionId());return await K(t).recordEvent(`doom_workflow.open_requested`,{outcome:`requested`}),t.hasUI?Kt(n,t):Ht(n)},rejectRunner:wt});let sn;v.cordis?.inject([ae.DOOM_UI_HUB_SERVICE],e=>{let n=(0,ae.requireDoomUiHub)(e).registerLeaderActions({source:t.PACKAGE_SOURCE,handlers:{[t.LEADER_ENABLE_ACTION]:async e=>(await j(),on(!0,e)),[t.LEADER_DISABLE_ACTION]:async e=>(await j(),on(!1,e)),[t.LEADER_MANAGE_ACTION]:async e=>(await j(),qt(e,!0)),[t.LEADER_CATALOG_ACTION]:async e=>(await j(),en(e)),[t.LEADER_RECOVER_ACTION]:async e=>(await j(),nn(e))},onError:(e,t,n)=>{n.ui.notify(e instanceof Error?e.message:String(e),`error`)}});return sn=n,()=>{n(),sn===n&&(sn=void 0)}}),y.on(`session_start`,(e,n)=>{if(!E||!Ve())return;let r=++ye,i=O;Oe?.abort();let a=new AbortController;Oe=a,B=n;let o=()=>E&&r===ye&&B===n&&Ve();Nt(),N&&clearInterval(N),N=void 0,it?.update([]),It(n),H?.hide(),H=void 0,st=!1,ct.clear(),Pt(),Lt.forget(new Set),ft.setUICtx(n.ui),K(n).recordEvent(`doom_workflow.session_started`,{mode:process.env.WORKFLOW_MCP_MODE===`on`?`on`:`off`,outcome:`started`});let s=n.sessionManager.getSessionId(),c=(0,_.resolveRootSessionId)(s);vt(c),rt=Date.now(),at=!1,tt=new Map,I.clear(),nt.clear(),rn(v.initialMode??process.env.WORKFLOW_MCP_MODE===`on`);let l=Ue(n);O=(async()=>{if(i&&await Promise.allSettled([i.then(e=>e.wait())]),!o())throw Error(`Workflow session initialization was superseded.`);return l.start(t.PACKAGE_SOURCE,`${ge}:${r}`,async e=>{let t=()=>a.signal.aborted||!o();return e.throwIfAborted(),t()||(await Mt(n),e.throwIfAborted(),t())||(await X(n,!1),e.throwIfAborted(),t())?{value:void 0}:(at=!0,N=setInterval(()=>{o()&&X(n,!0)},Ze),N.unref?.(),{value:void 0})})})(),Promise.allSettled([O.then(e=>e.wait())])});let $=async(e,t)=>{try{await t()}catch(t){process.emitWarning(`Doom-workflow cleanup could not ${e}: ${String(t)}`)}},cn;return{dispose:(e=B)=>(cn??=(async()=>{if(!E)return;E=!1,ye+=1;let t=O;O=void 0,Oe?.abort(),Oe=void 0,await $(`stop the workflow observer`,Nt);let n=Be;if(Be=void 0,n?await $(`dispose standalone workflow readiness`,()=>n.dispose()):t&&await Promise.allSettled([t.then(e=>e.wait())]),q.size>0){for(let e of[Je,qe])await $(`interrupt an inline workflow`,()=>e.interrupt(`SIGTERM`,{phase:`workflow`,source:`pi-session-shutdown`}));await Promise.race([Promise.allSettled(q),new Promise(e=>setTimeout(e,1e4).unref?.())])}N&&clearInterval(N),N=void 0,J&&clearTimeout(J),J=void 0;let r=it;it=void 0,r&&await $(`unregister the background-work provider`,()=>r.dispose()),at=!1,H?.hide(),H=void 0,st=!1,ct.clear(),Lt.forget(new Set),Pt(),L=0,e?It(e):P&&clearInterval(P),P=void 0,F=void 0,ft.dispose(),R=!1,ot=void 0;let i=z;z=void 0,i&&(await $(`publish the inactive workflow mode`,()=>i.publish(he(!1,0))),await $(`dispose the workflow mode owner`,()=>i.dispose()));let a=sn;sn=void 0,a&&await $(`dispose workflow leader actions`,a);let o=q.size,s=mt;mt=void 0,s&&(await $(`record the workflow session finish`,()=>s.recordEvent(`doom_workflow.session_finished`,{"workflow.pending_count":o,outcome:o===0?`completed`:`interrupted`})),await $(`stop workflow telemetry`,()=>s.shutdown())),q.clear(),I.clear(),nt.clear(),ut.length=0,pt=void 0,B=void 0})(),cn)}}}exports.compatibleRunners=Re,exports.installWorkflowPiRuntime=Be,exports.panelHint=Se,exports.panelHints=Ce,exports.shortcutLabel=C;
|
|
9
|
+
//# sourceMappingURL=piExtension.cjs.map
|