@pixelbyte-software/pixcode 1.54.7 → 1.54.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (288) hide show
  1. package/CODE_OF_CONDUCT.md +41 -41
  2. package/CONTRIBUTING.md +155 -155
  3. package/LICENSE +718 -718
  4. package/README.de.md +169 -169
  5. package/README.ja.md +167 -167
  6. package/README.ko.md +167 -167
  7. package/README.md +418 -418
  8. package/README.ru.md +169 -169
  9. package/README.tr.md +298 -298
  10. package/README.zh-CN.md +167 -167
  11. package/SECURITY.md +46 -46
  12. package/dist/api-automation.html +110 -110
  13. package/dist/api-docs.html +548 -548
  14. package/dist/assets/{index-D-4VRH1a.js → index-BU3Z3zrh.js} +186 -184
  15. package/dist/assets/index-Dz1luE0u.css +32 -0
  16. package/dist/clear-cache.html +85 -85
  17. package/dist/convert-icons.md +52 -52
  18. package/dist/docs.html +308 -308
  19. package/dist/features.html +133 -133
  20. package/dist/generate-icons.js +48 -48
  21. package/dist/humans.txt +15 -15
  22. package/dist/icons/codex-white.svg +3 -3
  23. package/dist/icons/codex.svg +3 -3
  24. package/dist/icons/cursor-white.svg +11 -11
  25. package/dist/icons/qwen-logo.svg +14 -14
  26. package/dist/index.html +59 -59
  27. package/dist/landing.html +268 -268
  28. package/dist/llms-full.txt +119 -119
  29. package/dist/llms.txt +53 -53
  30. package/dist/manifest.json +60 -60
  31. package/dist/openapi.yaml +1696 -1696
  32. package/dist/orchestration.html +125 -125
  33. package/dist/robots.txt +4 -4
  34. package/dist/site.css +692 -692
  35. package/dist/sitemap.xml +51 -51
  36. package/dist/sw.js +132 -132
  37. package/dist-server/server/cli.js +100 -100
  38. package/dist-server/server/daemon/manager.js +33 -33
  39. package/dist-server/server/daemon-manager.js +64 -64
  40. package/dist-server/server/index.js +109 -12
  41. package/dist-server/server/index.js.map +1 -1
  42. package/dist-server/server/routes/auth.js +17 -5
  43. package/dist-server/server/routes/auth.js.map +1 -1
  44. package/dist-server/server/routes/commands.js +25 -25
  45. package/dist-server/server/routes/git.js +17 -17
  46. package/dist-server/server/routes/live-view.js +46 -46
  47. package/dist-server/server/services/public-api-manifest.js +51 -51
  48. package/package.json +224 -224
  49. package/scripts/fix-node-pty.js +67 -67
  50. package/scripts/github/create-v1.38-issues.mjs +351 -351
  51. package/scripts/github/create-vscode-workbench-issues.mjs +121 -121
  52. package/scripts/smoke/backend-resource-bounds.mjs +152 -152
  53. package/scripts/smoke/changes-panel-layout.mjs +48 -48
  54. package/scripts/smoke/chat-composer-fixed-layout.mjs +55 -55
  55. package/scripts/smoke/chat-message-timeline-order.mjs +41 -41
  56. package/scripts/smoke/chat-realtime-hydration.mjs +44 -44
  57. package/scripts/smoke/chat-session-provider-pools.mjs +35 -35
  58. package/scripts/smoke/chat-session-state.mjs +19 -19
  59. package/scripts/smoke/code-editor-theme.mjs +55 -55
  60. package/scripts/smoke/code-editor-vscode-engine.mjs +91 -91
  61. package/scripts/smoke/command-center-agent-writes.mjs +79 -79
  62. package/scripts/smoke/command-center-non-git.mjs +46 -46
  63. package/scripts/smoke/context-packet.mjs +43 -43
  64. package/scripts/smoke/control-room-ux-redesign.mjs +91 -91
  65. package/scripts/smoke/daemon-entrypoint.mjs +20 -20
  66. package/scripts/smoke/default-landing-routing.mjs +33 -33
  67. package/scripts/smoke/desktop-native-notifications.mjs +30 -30
  68. package/scripts/smoke/desktop-tray-icon.mjs +33 -33
  69. package/scripts/smoke/discord-release-workflow.mjs +24 -24
  70. package/scripts/smoke/git-install-update.mjs +255 -255
  71. package/scripts/smoke/handoff-artifact-protocol.mjs +50 -50
  72. package/scripts/smoke/live-view-diagnostics.mjs +53 -53
  73. package/scripts/smoke/live-view-environment.mjs +92 -92
  74. package/scripts/smoke/live-view-integration.mjs +450 -450
  75. package/scripts/smoke/mac-desktop-runtime.mjs +37 -37
  76. package/scripts/smoke/mobile-tunnel-guidance.mjs +29 -29
  77. package/scripts/smoke/mobile-ux.mjs +76 -76
  78. package/scripts/smoke/model-registry.mjs +36 -36
  79. package/scripts/smoke/multi-project-ui.mjs +45 -45
  80. package/scripts/smoke/multi-worker-slots.mjs +42 -42
  81. package/scripts/smoke/notification-center.mjs +87 -87
  82. package/scripts/smoke/notification-inapp-preference.mjs +23 -23
  83. package/scripts/smoke/notification-taxonomy.mjs +58 -58
  84. package/scripts/smoke/orchestration-api.mjs +172 -172
  85. package/scripts/smoke/orchestration-execution-dashboard.mjs +33 -33
  86. package/scripts/smoke/orchestration-live-run.mjs +176 -176
  87. package/scripts/smoke/orchestration-mobile-scroll.mjs +29 -29
  88. package/scripts/smoke/orchestration-model-sync.mjs +30 -30
  89. package/scripts/smoke/orchestration-permission-fallback.mjs +34 -34
  90. package/scripts/smoke/orchestration-runtime-guards.mjs +48 -48
  91. package/scripts/smoke/orchestration-user-facing-output.mjs +25 -25
  92. package/scripts/smoke/permission-policy.mjs +50 -50
  93. package/scripts/smoke/pixcode-workbench-1-48.mjs +167 -167
  94. package/scripts/smoke/provider-models-opencode-live.mjs +66 -66
  95. package/scripts/smoke/provider-rest-api.mjs +124 -124
  96. package/scripts/smoke/provider-selection-status.mjs +52 -52
  97. package/scripts/smoke/run-state-refresh.mjs +52 -52
  98. package/scripts/smoke/runtime-manager.mjs +99 -99
  99. package/scripts/smoke/shell-manual-disconnect.mjs +30 -30
  100. package/scripts/smoke/side-panel-editor-layout.mjs +34 -34
  101. package/scripts/smoke/static-root-routing.mjs +21 -21
  102. package/scripts/smoke/strict-handoff-compact.mjs +60 -60
  103. package/scripts/smoke/taskmaster-config.mjs +24 -24
  104. package/scripts/smoke/taskmaster-execution-telegram.mjs +3 -3
  105. package/scripts/smoke/taskmaster-onboarding.mjs +3 -3
  106. package/scripts/smoke/taskmaster-run-graph.mjs +3 -3
  107. package/scripts/smoke/telegram-control.mjs +331 -331
  108. package/scripts/smoke/tunnel-persistence.mjs +56 -56
  109. package/scripts/smoke/update-issue-progress.mjs +69 -69
  110. package/scripts/smoke/update-ux.mjs +55 -55
  111. package/scripts/smoke/v138-completion.mjs +132 -132
  112. package/scripts/smoke/v138-desktop-release-hardening.mjs +69 -69
  113. package/scripts/smoke/v138-diagnostics.mjs +63 -63
  114. package/scripts/smoke/v138-issue-planner.mjs +33 -33
  115. package/scripts/smoke/v143-remote-control.mjs +76 -76
  116. package/scripts/smoke/v144-production-loop.mjs +47 -47
  117. package/scripts/smoke/v145-platformization.mjs +46 -46
  118. package/scripts/smoke/v146-control-room-ui.mjs +150 -150
  119. package/scripts/smoke/version-modal-autoshow.mjs +29 -29
  120. package/scripts/smoke/vscode-workbench-layout.mjs +63 -63
  121. package/scripts/smoke/vscode-workbench-polish.mjs +461 -461
  122. package/scripts/smoke/workflow-fallback-replay.mjs +56 -56
  123. package/scripts/smoke/workflow-templates.mjs +43 -43
  124. package/scripts/smoke/workflow-trace-timeline.mjs +46 -46
  125. package/scripts/update-git-install.mjs +298 -298
  126. package/server/claude-sdk.js +927 -927
  127. package/server/cli.js +1106 -1106
  128. package/server/constants/config.js +4 -4
  129. package/server/cursor-cli.js +344 -344
  130. package/server/daemon/manager.js +563 -563
  131. package/server/daemon-manager.js +964 -964
  132. package/server/database/db.js +988 -988
  133. package/server/database/json-store.js +197 -197
  134. package/server/gemini-cli.js +550 -550
  135. package/server/gemini-response-handler.js +79 -79
  136. package/server/index.js +5620 -5529
  137. package/server/load-env.js +35 -35
  138. package/server/middleware/account-lockout.js +112 -112
  139. package/server/middleware/auth.js +277 -277
  140. package/server/middleware/rate-limiter.js +87 -87
  141. package/server/modules/orchestration/a2a/adapter-registry.ts +108 -108
  142. package/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.ts +63 -63
  143. package/server/modules/orchestration/a2a/adapters/claude-code.adapter.ts +286 -286
  144. package/server/modules/orchestration/a2a/adapters/codex.adapter.ts +244 -244
  145. package/server/modules/orchestration/a2a/adapters/cursor.adapter.ts +249 -249
  146. package/server/modules/orchestration/a2a/adapters/gemini.adapter.ts +248 -248
  147. package/server/modules/orchestration/a2a/adapters/json-event.adapter.test.ts +60 -60
  148. package/server/modules/orchestration/a2a/adapters/json-event.adapter.ts +101 -101
  149. package/server/modules/orchestration/a2a/adapters/opencode.adapter.ts +248 -248
  150. package/server/modules/orchestration/a2a/adapters/qwen.adapter.ts +248 -248
  151. package/server/modules/orchestration/a2a/agent-card.ts +55 -55
  152. package/server/modules/orchestration/a2a/auth.middleware.ts +29 -29
  153. package/server/modules/orchestration/a2a/bus.ts +46 -46
  154. package/server/modules/orchestration/a2a/routes.ts +586 -586
  155. package/server/modules/orchestration/a2a/task-dispatcher.ts +345 -345
  156. package/server/modules/orchestration/a2a/task-store.ts +178 -178
  157. package/server/modules/orchestration/a2a/types.ts +126 -126
  158. package/server/modules/orchestration/a2a/validator.ts +113 -113
  159. package/server/modules/orchestration/index.ts +99 -99
  160. package/server/modules/orchestration/preview/port-watcher.ts +112 -112
  161. package/server/modules/orchestration/preview/preview-proxy.ts +60 -60
  162. package/server/modules/orchestration/preview/types.ts +19 -19
  163. package/server/modules/orchestration/security/permission-policy.ts +401 -401
  164. package/server/modules/orchestration/tasks/orchestration-task-store.ts +41 -41
  165. package/server/modules/orchestration/tasks/orchestration-task.routes.ts +81 -81
  166. package/server/modules/orchestration/tasks/orchestration-task.service.ts +201 -201
  167. package/server/modules/orchestration/tasks/orchestration-task.types.ts +40 -40
  168. package/server/modules/orchestration/tasks/task-run-graph.ts +155 -155
  169. package/server/modules/orchestration/workflows/approval-queue.ts +106 -106
  170. package/server/modules/orchestration/workflows/built-in-workflows.ts +127 -127
  171. package/server/modules/orchestration/workflows/context-packet.ts +186 -186
  172. package/server/modules/orchestration/workflows/handoff-artifact.ts +175 -175
  173. package/server/modules/orchestration/workflows/workflow-fallback-policy.ts +161 -161
  174. package/server/modules/orchestration/workflows/workflow-replay.ts +254 -254
  175. package/server/modules/orchestration/workflows/workflow-runner.ts +2062 -2062
  176. package/server/modules/orchestration/workflows/workflow-store.ts +97 -97
  177. package/server/modules/orchestration/workflows/workflow-templates.ts +272 -272
  178. package/server/modules/orchestration/workflows/workflow-trace.ts +424 -424
  179. package/server/modules/orchestration/workflows/workflow.routes.ts +586 -586
  180. package/server/modules/orchestration/workflows/workflow.types.ts +111 -111
  181. package/server/modules/orchestration/workflows/workspace-target.ts +122 -122
  182. package/server/modules/orchestration/workspace/docker-workspace.ts +136 -136
  183. package/server/modules/orchestration/workspace/path-safety.ts +55 -55
  184. package/server/modules/orchestration/workspace/types.ts +52 -52
  185. package/server/modules/orchestration/workspace/workspace-manager.ts +102 -102
  186. package/server/modules/orchestration/workspace/worktree-workspace.ts +126 -126
  187. package/server/modules/providers/index.ts +2 -2
  188. package/server/modules/providers/list/claude/claude-auth.provider.ts +146 -146
  189. package/server/modules/providers/list/claude/claude-mcp.provider.ts +135 -135
  190. package/server/modules/providers/list/claude/claude-sessions.provider.ts +306 -306
  191. package/server/modules/providers/list/claude/claude.provider.ts +15 -15
  192. package/server/modules/providers/list/codex/codex-auth.provider.ts +117 -117
  193. package/server/modules/providers/list/codex/codex-mcp.provider.ts +135 -135
  194. package/server/modules/providers/list/codex/codex-sessions.provider.ts +319 -319
  195. package/server/modules/providers/list/codex/codex.provider.ts +15 -15
  196. package/server/modules/providers/list/cursor/cursor-auth.provider.ts +147 -147
  197. package/server/modules/providers/list/cursor/cursor-mcp.provider.ts +108 -108
  198. package/server/modules/providers/list/cursor/cursor-sessions.provider.ts +421 -421
  199. package/server/modules/providers/list/cursor/cursor.provider.ts +15 -15
  200. package/server/modules/providers/list/gemini/gemini-auth.provider.ts +173 -173
  201. package/server/modules/providers/list/gemini/gemini-mcp.provider.ts +110 -110
  202. package/server/modules/providers/list/gemini/gemini-sessions.provider.ts +227 -227
  203. package/server/modules/providers/list/gemini/gemini.provider.ts +15 -15
  204. package/server/modules/providers/list/opencode/opencode-auth.provider.ts +131 -131
  205. package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +286 -286
  206. package/server/modules/providers/list/qwen/qwen-auth.provider.ts +146 -146
  207. package/server/modules/providers/list/qwen/qwen-sessions.provider.ts +265 -265
  208. package/server/modules/providers/provider.registry.ts +40 -40
  209. package/server/modules/providers/provider.routes.ts +982 -982
  210. package/server/modules/providers/services/mcp.service.ts +86 -86
  211. package/server/modules/providers/services/provider-auth.service.ts +26 -26
  212. package/server/modules/providers/services/sessions.service.ts +45 -45
  213. package/server/modules/providers/shared/base/abstract.provider.ts +20 -20
  214. package/server/modules/providers/shared/mcp/mcp.provider.ts +151 -151
  215. package/server/modules/providers/tests/mcp.test.ts +293 -293
  216. package/server/openai-codex.js +468 -468
  217. package/server/opencode-cli.js +491 -491
  218. package/server/opencode-response-handler.js +111 -111
  219. package/server/projects.js +3125 -3125
  220. package/server/qwen-code-cli.js +410 -410
  221. package/server/routes/agent.js +1451 -1451
  222. package/server/routes/auth.js +298 -286
  223. package/server/routes/codex.js +20 -20
  224. package/server/routes/commands.js +581 -581
  225. package/server/routes/cursor.js +61 -61
  226. package/server/routes/diagnostics.js +44 -44
  227. package/server/routes/gemini.js +25 -25
  228. package/server/routes/git.js +1822 -1822
  229. package/server/routes/live-view.js +434 -434
  230. package/server/routes/mcp-utils.js +13 -13
  231. package/server/routes/messages.js +97 -97
  232. package/server/routes/network.js +143 -143
  233. package/server/routes/platformization.js +231 -231
  234. package/server/routes/plugins.js +690 -690
  235. package/server/routes/production-agent-loop.js +90 -90
  236. package/server/routes/projects.js +918 -918
  237. package/server/routes/public-api.js +34 -34
  238. package/server/routes/qwen.js +27 -27
  239. package/server/routes/remote.js +56 -56
  240. package/server/routes/settings.js +321 -321
  241. package/server/routes/telegram.js +163 -163
  242. package/server/routes/user.js +125 -125
  243. package/server/routes/webhooks.js +63 -63
  244. package/server/services/control-room.js +102 -102
  245. package/server/services/diagnostics.js +165 -165
  246. package/server/services/external-access.js +403 -403
  247. package/server/services/install-jobs.js +715 -715
  248. package/server/services/live-view.js +956 -956
  249. package/server/services/managed-runtimes.js +493 -493
  250. package/server/services/model-registry.js +144 -144
  251. package/server/services/notification-orchestrator.js +365 -365
  252. package/server/services/notification-taxonomy.js +204 -204
  253. package/server/services/platformization.js +1052 -1052
  254. package/server/services/production-agent-loop.js +248 -248
  255. package/server/services/provider-cli-versions.js +149 -149
  256. package/server/services/provider-credentials.js +189 -189
  257. package/server/services/provider-models.js +396 -396
  258. package/server/services/public-api-manifest.js +181 -181
  259. package/server/services/qr-login.js +126 -126
  260. package/server/services/remote-connection.js +127 -127
  261. package/server/services/runtime-manager.js +323 -323
  262. package/server/services/startup-update.js +259 -259
  263. package/server/services/telegram/bot.js +393 -393
  264. package/server/services/telegram/control-center.js +2453 -2453
  265. package/server/services/telegram/telegram-gateway.js +314 -314
  266. package/server/services/telegram/telegram-http-client.js +201 -201
  267. package/server/services/telegram/translations.js +470 -470
  268. package/server/services/webhooks.js +216 -216
  269. package/server/sessionManager.js +225 -225
  270. package/server/setup-wizard.js +283 -283
  271. package/server/shared/interfaces.ts +54 -54
  272. package/server/shared/types.ts +172 -172
  273. package/server/shared/utils.ts +193 -193
  274. package/server/tsconfig.json +36 -36
  275. package/server/utils/colors.js +21 -21
  276. package/server/utils/commandParser.js +305 -305
  277. package/server/utils/frontmatter.js +18 -18
  278. package/server/utils/gitConfig.js +34 -34
  279. package/server/utils/plugin-loader.js +461 -461
  280. package/server/utils/plugin-process-manager.js +185 -185
  281. package/server/utils/port-access.js +227 -227
  282. package/server/utils/runtime-paths.js +37 -37
  283. package/server/utils/security-log.js +84 -84
  284. package/server/utils/url-detection.js +71 -71
  285. package/server/vite-daemon.js +79 -79
  286. package/shared/modelConstants.js +161 -161
  287. package/shared/networkHosts.js +22 -22
  288. package/dist/assets/index-DvudRU5X.css +0 -32
@@ -1,2062 +1,2062 @@
1
- import crypto from 'node:crypto';
2
-
3
- import type {
4
- Workflow,
5
- WorkflowNode,
6
- WorkflowNodeRun,
7
- WorkflowRun,
8
- } from '@/modules/orchestration/workflows/workflow.types.js';
9
- import {
10
- PIXCODE_HANDOFF_PROTOCOL,
11
- formatHandoffArtifactForContext,
12
- handoffArtifactToWorkflowArtifact,
13
- parseHandoffArtifact,
14
- } from '@/modules/orchestration/workflows/handoff-artifact.js';
15
- import {
16
- buildWorkflowContextPacket,
17
- formatContextPacketForPrompt,
18
- } from '@/modules/orchestration/workflows/context-packet.js';
19
- import {
20
- type WorkflowFallbackTrigger,
21
- classifyWorkflowFailure,
22
- resolveWorkflowFallbackDecision,
23
- } from '@/modules/orchestration/workflows/workflow-fallback-policy.js';
24
- import {
25
- evaluatePermissionRequest,
26
- resolvePermissionPolicyFromMetadata,
27
- type PermissionDecision,
28
- type PermissionPolicy,
29
- type PermissionPolicyEvent,
30
- } from '@/modules/orchestration/security/permission-policy.js';
31
- import {
32
- type ResolvedWorkspaceTarget,
33
- resolveWorkflowWorkspace,
34
- workspaceContextPrompt,
35
- workspaceTargetMetadata,
36
- } from '@/modules/orchestration/workflows/workspace-target.js';
37
- import { workflowStore } from '@/modules/orchestration/workflows/workflow-store.js';
38
- import { orchestrationTaskService } from '@/modules/orchestration/tasks/orchestration-task.service.js';
39
- import {
40
- cancelA2ATask,
41
- getA2ATask,
42
- submitA2ATask,
43
- } from '@/modules/orchestration/a2a/task-dispatcher.js';
44
- // @ts-ignore — plain-JS service
45
- import {
46
- getDefaultProviderModel,
47
- getProviderModelRegistryEntry,
48
- getStaticProviderModels,
49
- } from '@/services/model-registry.js';
50
- // @ts-ignore — plain-JS service
51
- import {
52
- createNotificationEvent,
53
- notifyRunFailed,
54
- notifyRunStopped,
55
- notifyUserIfEnabled,
56
- } from '@/services/notification-orchestrator.js';
57
- // @ts-ignore — plain-JS service
58
- import { dispatchWebhookEvent } from '@/services/webhooks.js';
59
-
60
- const TERMINAL = new Set(['completed', 'failed', 'canceled']);
61
- const SKIPPED = 'skipped';
62
- const BACKEND_HANDOFF_TIMEOUT_MS = 120_000;
63
- const MAX_OUTPUT_CONTEXT_CHARS = 12_000;
64
- const DEFAULT_MAX_REPAIR_CYCLES = 1;
65
- const MAX_REPAIR_CYCLES = 5;
66
- const HANDOFF_ARTIFACT_EXAMPLE = [
67
- '{',
68
- ' "protocol": "pixcode.handoff.v1",',
69
- ' "taskStatus": "ready | completed | blocked | failed | needs-review",',
70
- ' "contextSummary": "Compacted context the next agent needs.",',
71
- ' "taskResult": "What was decided or completed in this step.",',
72
- ' "changedFiles": [],',
73
- ' "blockers": [],',
74
- ' "risks": [],',
75
- ' "nextAction": "The requested next action.",',
76
- ' "nextInstructions": "Specific instructions for the next agent."',
77
- '}',
78
- ].join('\n');
79
- const KNOWN_AGENT_ROLES = [
80
- 'backend',
81
- 'frontend',
82
- 'review',
83
- 'implementation',
84
- 'proposal',
85
- 'critique',
86
- 'response',
87
- 'decision',
88
- 'report',
89
- ] as const;
90
-
91
- class WorkflowCanceledError extends Error {
92
- constructor() {
93
- super('Workflow canceled.');
94
- this.name = 'WorkflowCanceledError';
95
- }
96
- }
97
-
98
- class WorkflowNodeTimeoutError extends Error {
99
- constructor(readonly timeoutMs: number) {
100
- super(`Workflow node timed out after ${Math.round(timeoutMs / 1000)}s.`);
101
- this.name = 'WorkflowNodeTimeoutError';
102
- }
103
- }
104
-
105
- function newId(prefix: string): string {
106
- return `${prefix}_${crypto.randomBytes(8).toString('hex')}`;
107
- }
108
-
109
- function validateWorkflow(workflow: Workflow): void {
110
- if (workflow.nodes.length > 64) {
111
- throw new Error('Workflow node limit exceeded.');
112
- }
113
- const ids = new Set(workflow.nodes.map((node) => node.id));
114
- for (const node of workflow.nodes) {
115
- for (const input of node.inputs) {
116
- if (!ids.has(input)) {
117
- throw new Error(`Workflow node ${node.id} references missing input ${input}.`);
118
- }
119
- }
120
- }
121
- }
122
-
123
- type TaskResult = {
124
- state: string;
125
- text: string;
126
- error?: string;
127
- messages: Array<{ role: string; text: string }>;
128
- artifacts: Array<{
129
- type: string;
130
- text?: string;
131
- data?: Record<string, unknown>;
132
- metadata?: Record<string, unknown>;
133
- }>;
134
- };
135
-
136
- type RawTask = {
137
- id: string;
138
- state?: string;
139
- error?: { code?: string; message?: string };
140
- history?: Array<{ role?: string; parts?: Array<{ kind?: string; text?: string; data?: Record<string, unknown> }> }>;
141
- artifacts?: Array<{
142
- type?: string;
143
- parts?: Array<{ kind?: string; text?: string; data?: Record<string, unknown> }>;
144
- metadata?: Record<string, unknown>;
145
- }>;
146
- };
147
-
148
- type AgentAssignment = {
149
- instanceId: string;
150
- adapterId: string;
151
- label: string;
152
- role?: AgentRole;
153
- instruction?: string;
154
- model?: string;
155
- permissionMode?: string;
156
- toolsSettings?: Record<string, unknown>;
157
- order: number;
158
- };
159
-
160
- type KnownAgentRole = typeof KNOWN_AGENT_ROLES[number];
161
- type AgentRole = string;
162
- type ProviderId = 'claude' | 'cursor' | 'codex' | 'gemini' | 'qwen' | 'opencode';
163
- type ProviderModel = {
164
- value: string;
165
- label?: string;
166
- source?: 'static' | 'api';
167
- free?: boolean;
168
- };
169
- type RunStoppedNotifier = (payload: {
170
- userId: string | number;
171
- provider: string;
172
- sessionId?: string | null;
173
- stopReason?: string;
174
- sessionName?: string | null;
175
- }) => void;
176
- type RunFailedNotifier = (payload: {
177
- userId: string | number;
178
- provider: string;
179
- sessionId?: string | null;
180
- error: unknown;
181
- sessionName?: string | null;
182
- }) => void;
183
-
184
- const sendRunStoppedNotification = notifyRunStopped as RunStoppedNotifier;
185
- const sendRunFailedNotification = notifyRunFailed as RunFailedNotifier;
186
-
187
- const adapterProviderMap: Record<string, ProviderId | undefined> = {
188
- 'claude-code': 'claude',
189
- cursor: 'cursor',
190
- codex: 'codex',
191
- gemini: 'gemini',
192
- qwen: 'qwen',
193
- opencode: 'opencode',
194
- };
195
-
196
- function readAgentRole(value: unknown): AgentRole | undefined {
197
- return typeof value === 'string' && value.trim() && value.trim() !== 'auto'
198
- ? value.trim()
199
- : undefined;
200
- }
201
-
202
- function isKnownAgentRole(value: string | undefined): value is KnownAgentRole {
203
- return Boolean(value && (KNOWN_AGENT_ROLES as readonly string[]).includes(value));
204
- }
205
-
206
- function getMetadataRecord(metadata: Record<string, unknown> | undefined, key: string): Record<string, unknown> {
207
- return readRecord(metadata?.[key]) ?? {};
208
- }
209
-
210
- function readRecord(value: unknown): Record<string, unknown> | undefined {
211
- return value && typeof value === 'object' ? value as Record<string, unknown> : undefined;
212
- }
213
-
214
- function readString(value: unknown): string | undefined {
215
- return typeof value === 'string' && value.trim() ? value : undefined;
216
- }
217
-
218
- function readNotificationUserId(metadata?: Record<string, unknown>): string | number | null {
219
- const value = metadata?.userId;
220
- return typeof value === 'string' || typeof value === 'number' ? value : null;
221
- }
222
-
223
- function workflowNotificationTitle(run: WorkflowRun): string {
224
- return readString(run.metadata?.workflowName) ?? run.workflowId;
225
- }
226
-
227
- function notifyWorkflowRunFinished(run: WorkflowRun): void {
228
- const userId = readNotificationUserId(run.metadata);
229
- if (!userId) return;
230
-
231
- if (run.status === 'completed') {
232
- sendRunStoppedNotification({
233
- userId,
234
- provider: 'system',
235
- sessionId: run.id,
236
- sessionName: workflowNotificationTitle(run),
237
- stopReason: 'Orchestration completed',
238
- });
239
- return;
240
- }
241
-
242
- if (run.status === 'canceled') {
243
- sendRunStoppedNotification({
244
- userId,
245
- provider: 'system',
246
- sessionId: run.id,
247
- sessionName: workflowNotificationTitle(run),
248
- stopReason: 'Orchestration canceled',
249
- });
250
- return;
251
- }
252
-
253
- if (run.status === 'failed') {
254
- sendRunFailedNotification({
255
- userId,
256
- provider: 'system',
257
- sessionId: run.id,
258
- sessionName: workflowNotificationTitle(run),
259
- error: readString(run.metadata?.error) ?? 'Orchestration failed',
260
- });
261
- }
262
- }
263
-
264
- function permissionPolicyFromRun(run: WorkflowRun): PermissionPolicy {
265
- return resolvePermissionPolicyFromMetadata(run.metadata);
266
- }
267
-
268
- function permissionPolicyEvents(run: WorkflowRun): PermissionPolicyEvent[] {
269
- return Array.isArray(run.metadata?.permissionPolicyEvents)
270
- ? run.metadata.permissionPolicyEvents.filter((event): event is PermissionPolicyEvent =>
271
- Boolean(event && typeof event === 'object'),
272
- )
273
- : [];
274
- }
275
-
276
- function permissionApprovalRequests(run: WorkflowRun): Array<Record<string, unknown>> {
277
- return Array.isArray(run.metadata?.pendingPermissionApprovals)
278
- ? run.metadata.pendingPermissionApprovals.filter((event): event is Record<string, unknown> =>
279
- Boolean(event && typeof event === 'object'),
280
- )
281
- : [];
282
- }
283
-
284
- function notifyPermissionApprovalRequested(run: WorkflowRun, decision: PermissionDecision): void {
285
- const userId = readNotificationUserId(run.metadata);
286
- if (!userId || !decision.approvalRequest) return;
287
-
288
- const event = (createNotificationEvent as unknown as (payload: Record<string, unknown>) => unknown)({
289
- provider: 'system',
290
- sessionId: run.id,
291
- kind: 'action_required',
292
- code: 'permission.required',
293
- meta: {
294
- toolName: decision.capabilities.join(', '),
295
- sessionName: workflowNotificationTitle(run),
296
- },
297
- severity: 'warning',
298
- requiresUserAction: true,
299
- dedupeKey: `workflow:permission:${run.id}:${decision.requestId}`,
300
- });
301
- (notifyUserIfEnabled as (payload: { userId: string | number; event: unknown }) => void)({
302
- userId,
303
- event,
304
- });
305
- }
306
-
307
- function readBoolean(value: unknown): boolean | undefined {
308
- return typeof value === 'boolean' ? value : undefined;
309
- }
310
-
311
- function modelValueSet(models: ProviderModel[]): Set<string> {
312
- return new Set(models.map((model) => model.value).filter(Boolean));
313
- }
314
-
315
- function preferredFallbackModel(models: ProviderModel[], defaultModel?: string): string | undefined {
316
- const values = modelValueSet(models);
317
- if (defaultModel && values.has(defaultModel)) return defaultModel;
318
- return models.find((model) => model.source === 'api' && model.free)?.value
319
- ?? models.find((model) => model.source === 'api')?.value
320
- ?? models.find((model) => model.free)?.value
321
- ?? models[0]?.value
322
- ?? defaultModel;
323
- }
324
-
325
- async function resolveWorkflowModel(adapterId: string, requestedModel?: string): Promise<string | undefined> {
326
- const provider = adapterProviderMap[adapterId];
327
- if (!provider) return requestedModel;
328
-
329
- const defaultModel = getDefaultProviderModel(provider);
330
- if (!requestedModel) return defaultModel;
331
-
332
- try {
333
- const result = await getProviderModelRegistryEntry(provider);
334
- const models = Array.isArray(result?.models) ? result.models as ProviderModel[] : [];
335
- if (modelValueSet(models).has(requestedModel)) {
336
- return requestedModel;
337
- }
338
- return preferredFallbackModel(models, defaultModel) ?? requestedModel;
339
- } catch {
340
- const staticModels = getStaticProviderModels(provider) as ProviderModel[];
341
- const staticValues = modelValueSet(staticModels);
342
- return staticValues.has(requestedModel)
343
- ? requestedModel
344
- : preferredFallbackModel(staticModels, defaultModel) ?? requestedModel;
345
- }
346
- }
347
-
348
- function readIsolation(value: unknown): 'host' | 'worktree' | 'docker' | undefined {
349
- return value === 'host' || value === 'worktree' || value === 'docker' ? value : undefined;
350
- }
351
-
352
- function readLegacyEnabledAdapters(metadata?: Record<string, unknown>): string[] {
353
- return Array.isArray(metadata?.enabledAdapters)
354
- ? metadata.enabledAdapters.filter((value): value is string => typeof value === 'string' && value.trim().length > 0)
355
- : [];
356
- }
357
-
358
- function readMetadataAgents(metadata?: Record<string, unknown>): AgentAssignment[] {
359
- if (!Array.isArray(metadata?.agents)) return [];
360
-
361
- return metadata.agents
362
- .map((value, index): AgentAssignment | null => {
363
- if (!value || typeof value !== 'object') return null;
364
- const record = value as Record<string, unknown>;
365
- const adapterId = readString(record.adapterId);
366
- if (!adapterId) return null;
367
- if (readBoolean(record.enabled) === false) return null;
368
-
369
- return {
370
- instanceId: readString(record.instanceId) ?? `${adapterId}-${index + 1}`,
371
- adapterId,
372
- label: readString(record.label) ?? `${adapterId} #${index + 1}`,
373
- role: readAgentRole(record.role),
374
- instruction: readString(record.instruction),
375
- model: readString(record.model),
376
- permissionMode: readString(record.permissionMode),
377
- toolsSettings: readRecord(record.toolsSettings),
378
- order: index,
379
- };
380
- })
381
- .filter((value): value is AgentAssignment => Boolean(value))
382
- .slice(0, 16);
383
- }
384
-
385
- function readAgentAssignments(metadata?: Record<string, unknown>): AgentAssignment[] {
386
- const agents = readMetadataAgents(metadata);
387
- if (agents.length > 0) return agents;
388
-
389
- return readLegacyEnabledAdapters(metadata).map((adapterId, index) => ({
390
- instanceId: `${adapterId}-${index + 1}`,
391
- adapterId,
392
- label: `${adapterId} #${index + 1}`,
393
- order: index,
394
- }));
395
- }
396
-
397
- function readEnabledAdapters(metadata?: Record<string, unknown>): string[] {
398
- return [...new Set(readAgentAssignments(metadata).map((agent) => agent.adapterId))];
399
- }
400
-
401
- function readMaxParallelAgents(metadata?: Record<string, unknown>): number {
402
- const settings = getMetadataRecord(metadata, 'settings');
403
- const value = settings.maxParallelAgents;
404
- return typeof value === 'number' && Number.isFinite(value)
405
- ? Math.max(1, Math.min(12, Math.round(value)))
406
- : 3;
407
- }
408
-
409
- function readMaxRepairCycles(metadata?: Record<string, unknown>): number {
410
- const settings = getMetadataRecord(metadata, 'settings');
411
- const value = settings.maxRepairCycles;
412
- return typeof value === 'number' && Number.isFinite(value)
413
- ? Math.max(0, Math.min(MAX_REPAIR_CYCLES, Math.round(value)))
414
- : DEFAULT_MAX_REPAIR_CYCLES;
415
- }
416
-
417
- function safeNodeId(adapterId: string, suffix: string): string {
418
- return `${adapterId.replace(/[^a-zA-Z0-9_]+/g, '_')}_${suffix}`;
419
- }
420
-
421
- function safeAgentNodeId(agent: AgentAssignment, index: number, suffix: string): string {
422
- return `agent_${index + 1}_${safeNodeId(agent.adapterId, suffix)}`;
423
- }
424
-
425
- function agentRoster(agents: AgentAssignment[]): string {
426
- return agents
427
- .map((agent, index) => {
428
- const instruction = agent.instruction
429
- ? `\n User assignment: ${agent.instruction}`
430
- : '';
431
- const role = agent.role ? `\n API role: ${agent.role}` : '';
432
- return `${index + 1}. ${agent.label} (${agent.adapterId})${role}${instruction}`;
433
- })
434
- .join('\n');
435
- }
436
-
437
- function inferAgentRole(agent: AgentAssignment): AgentRole {
438
- if (isKnownAgentRole(agent.role)) return agent.role;
439
-
440
- const text = `${agent.label} ${agent.adapterId} ${agent.role ?? ''} ${agent.instruction ?? ''}`.toLocaleLowerCase('tr');
441
- if (/(test|tester|qa|review|code review|hata|kontrol|onay|incele|doğrula|dogrula)/u.test(text)) {
442
- return 'review';
443
- }
444
- if (/(backend|back-end|api|server|veri|database|db|fapi|endpoint|websocket|ws)/u.test(text)) {
445
- return 'backend';
446
- }
447
- if (/(frontend|front-end|ui|ux|tailwind|tasarım|tasarim|design|chart|tradingview|arayüz|arayuz)/u.test(text)) {
448
- return 'frontend';
449
- }
450
- return 'implementation';
451
- }
452
-
453
- function inferImplementationRole(agent: AgentAssignment): 'backend' | 'frontend' | 'review' | 'implementation' {
454
- const role = inferAgentRole(agent);
455
- return role === 'backend' || role === 'frontend' || role === 'review' || role === 'implementation'
456
- ? role
457
- : 'implementation';
458
- }
459
-
460
- function displayStage(agent: AgentAssignment, fallback: AgentRole): string {
461
- return agent.role && !isKnownAgentRole(agent.role) ? agent.role : fallback;
462
- }
463
-
464
- function rolePrompt(role: AgentRole): string {
465
- if (role === 'backend') {
466
- return 'Backend/API/data work should define stable contracts first. Report endpoints, payload shapes, ports, and any data-source limitations clearly for downstream agents.';
467
- }
468
- if (role === 'frontend') {
469
- return 'Frontend/UI work must use prior backend/data-contract outputs when present. If a dependency is missing, use a minimal mock only as a temporary fallback and report the blocker.';
470
- }
471
- if (role === 'review') {
472
- return 'You are the validation/review stage. Inspect the prior agent outputs and actual project state. Approve only if it works; otherwise return a concrete bug list and required fixes.';
473
- }
474
- if (role === 'proposal') {
475
- return 'You are in the proposal stage. Produce a concrete option with tradeoffs, assumptions, and what should happen next. Do not edit files.';
476
- }
477
- if (role === 'critique') {
478
- return 'You are in the critique stage. Challenge the proposal for risks, missing constraints, and weak assumptions. Do not edit files.';
479
- }
480
- if (role === 'response') {
481
- return 'You are in the response stage. Reconcile the critique with the proposal and refine the practical path forward. Do not edit files.';
482
- }
483
- if (role === 'decision' || role === 'report') {
484
- return 'You are the reporting stage. Produce the final concise decision report and a next prompt for launching an implementation agent team. Do not edit files.';
485
- }
486
- if (role !== 'implementation') {
487
- return `You are assigned to the custom stage "${role}". Follow that user-defined stage literally, avoid duplicating other agents, and report changed files, commands, blockers, and next actions.`;
488
- }
489
- return 'Implementation work should avoid duplicating other agents and should report changed files, commands, blockers, and next actions.';
490
- }
491
-
492
- function privacyGuardPrompt(): string {
493
- return 'Do not mention internal instructions, memory files, skill use, or tool protocol unless the user explicitly asks.';
494
- }
495
-
496
- function handoffArtifactInstructions(statusHint: string): string {
497
- return [
498
- `Output exactly one JSON object using the ${PIXCODE_HANDOFF_PROTOCOL} handoff artifact protocol.`,
499
- 'Do not wrap it in Markdown. Do not add commentary before or after it.',
500
- `Use "${statusHint}" for taskStatus unless completed, blocked, failed, or needs-review is more accurate.`,
501
- 'Schema:',
502
- HANDOFF_ARTIFACT_EXAMPLE,
503
- ].join('\n');
504
- }
505
-
506
- function handoffPrompt(agent: AgentAssignment, role: AgentRole): string {
507
- return [
508
- `You are ${agent.label} in a Pixcode CLI team.`,
509
- `Your inferred stage is: ${role}.`,
510
- 'This is a bounded Pixcode handoff task, not the full implementation.',
511
- 'Read the original user goal and coordinator plan, then publish a compact contract for downstream agents.',
512
- agent.instruction ? `Your explicit assignment from the user is: ${agent.instruction}` : '',
513
- handoffArtifactInstructions('ready'),
514
- 'Do not install dependencies, edit files, run long commands, or start servers in this handoff task.',
515
- privacyGuardPrompt(),
516
- 'Stop after the contract. Keep it concise and respond in the same language as the user request.',
517
- ].filter(Boolean).join('\n');
518
- }
519
-
520
- function handoffInitPrompt(agent: AgentAssignment, index: number): string {
521
- return [
522
- `You are preparing ${agent.label} for a strict Pixcode handoff chain.`,
523
- `This is internal step ${index + 1}.`,
524
- 'Create a compact init packet for the next visible work step.',
525
- 'Use the original user goal and any prior compact handoff packet included above.',
526
- agent.instruction ? `The explicit assignment for this agent is: ${agent.instruction}` : '',
527
- handoffArtifactInstructions('ready'),
528
- privacyGuardPrompt(),
529
- 'Do not perform the task yet. Do not mention that this is hidden from the user.',
530
- 'Respond in the same language as the user request.',
531
- ].filter(Boolean).join('\n');
532
- }
533
-
534
- function handoffWorkPrompt(agent: AgentAssignment, index: number): string {
535
- return [
536
- `You are ${agent.label} in a strict Pixcode handoff chain.`,
537
- `This is visible work step ${index + 1}.`,
538
- 'The internal init packet above is your starting context. Do the assigned work now.',
539
- agent.instruction
540
- ? `Your explicit assignment from the user is: ${agent.instruction}`
541
- : 'Use the init packet and original user goal to choose the next useful work for this step.',
542
- rolePrompt(agent.role ?? 'implementation'),
543
- privacyGuardPrompt(),
544
- 'Report only user-facing progress, changed files, commands, verification, blockers, and next actions.',
545
- 'Respond in the same language as the user request.',
546
- ].filter(Boolean).join('\n');
547
- }
548
-
549
- function handoffCompactPrompt(agent: AgentAssignment, index: number): string {
550
- return [
551
- `You are compacting ${agent.label}'s strict handoff output for the next Pixcode agent.`,
552
- `This is internal compact step ${index + 1}.`,
553
- 'Read the prior visible work output included above and create a compact handoff packet.',
554
- handoffArtifactInstructions('completed'),
555
- privacyGuardPrompt(),
556
- 'Do not include raw logs unless they are essential. Keep it concise and actionable.',
557
- 'Respond in the same language as the user request.',
558
- ].join('\n');
559
- }
560
-
561
- function compactOutputForContext(text: string): string {
562
- if (text.length <= MAX_OUTPUT_CONTEXT_CHARS) {
563
- return text;
564
- }
565
-
566
- const edge = Math.floor(MAX_OUTPUT_CONTEXT_CHARS / 2);
567
- return [
568
- text.slice(0, edge),
569
- `\n\n[...${text.length - MAX_OUTPUT_CONTEXT_CHARS} characters omitted from prior agent output...]\n\n`,
570
- text.slice(-edge),
571
- ].join('');
572
- }
573
-
574
- function requiresHandoffArtifact(node: WorkflowNode): boolean {
575
- return node.stage === 'handoff' || node.stage === 'handoff_init' || node.stage === 'handoff_compact';
576
- }
577
-
578
- function handoffArtifactSource(result: TaskResult): string {
579
- const structured = result.artifacts.find((artifact) => artifact.type === 'handoff-artifact' && artifact.data);
580
- if (structured?.data) {
581
- return JSON.stringify(structured.data);
582
- }
583
- return result.text;
584
- }
585
-
586
- function isExternalDirectoryPermissionError(value: unknown): boolean {
587
- const text = String(value ?? '').toLocaleLowerCase('en');
588
- return (
589
- text.includes('external_directory') ||
590
- /permission requested:.*auto-rejecting/u.test(text) ||
591
- /auto-rejecting.*permission/u.test(text) ||
592
- /outside (the )?(workspace|working directory)/u.test(text) ||
593
- /permission.*external/u.test(text)
594
- );
595
- }
596
-
597
- function isFinalReportNode(node: WorkflowNode): boolean {
598
- return node.id === 'final_report' || node.stage === 'final_report' || node.stage === 'report';
599
- }
600
-
601
- function workspaceNeedsHostPermissionBypass(target: ResolvedWorkspaceTarget): boolean {
602
- return (target.kind === 'selected_project' || target.kind === 'custom') && target.projectPath !== target.appRoot;
603
- }
604
-
605
- function resolveNodePermissionMode(node: WorkflowNode, target: ResolvedWorkspaceTarget): string | undefined {
606
- if (node.permissionMode && node.permissionMode !== 'default') {
607
- return node.permissionMode;
608
- }
609
-
610
- if (workspaceNeedsHostPermissionBypass(target)) {
611
- return 'bypassPermissions';
612
- }
613
-
614
- return node.permissionMode;
615
- }
616
-
617
- function buildPermissionFallbackOutput(
618
- node: WorkflowNode,
619
- reason: string,
620
- target: ResolvedWorkspaceTarget,
621
- ): string {
622
- return [
623
- 'Bu adım çalışma alanı izin sınırına takıldı.',
624
- '',
625
- `Ajan: ${node.agentLabel || node.id}`,
626
- `Hedef çalışma alanı: ${target.projectPath}`,
627
- `Hata: ${reason}`,
628
- '',
629
- 'Pixcode bu adımı workflow dışına taşırmadan devam ettirdi. Ajan aynı dış dizin yoluna tekrar tekrar erişmek yerine mevcut bağlamla ilerlemeli.',
630
- ].join('\n');
631
- }
632
-
633
- function buildFallbackFinalReport(
634
- outputs: Map<string, string>,
635
- reason: string,
636
- target: ResolvedWorkspaceTarget,
637
- ): string {
638
- const completedOutputs = [...outputs.entries()]
639
- .map(([nodeId, output]) => [`## ${nodeId}`, output || '(çıktı yok)'].join('\n'))
640
- .join('\n\n');
641
-
642
- return [
643
- 'Final rapor aracı çalışma alanı izin sınırına takıldı, bu yüzden Pixcode tamamlanan ajan çıktılarından güvenli bir özet üretti.',
644
- '',
645
- `Hedef çalışma alanı: ${target.projectPath}`,
646
- `İzin hatası: ${reason}`,
647
- '',
648
- completedOutputs || 'Bu turda final rapora aktarılabilecek tamamlanmış ajan çıktısı yok.',
649
- ].join('\n');
650
- }
651
-
652
- function completeNodeWithPermissionFallback(
653
- nodeRun: WorkflowNodeRun,
654
- node: WorkflowNode,
655
- outputs: Map<string, string>,
656
- completed: Set<string>,
657
- reason: string,
658
- target: ResolvedWorkspaceTarget,
659
- ): void {
660
- const outputText = isFinalReportNode(node)
661
- ? buildFallbackFinalReport(outputs, reason, target)
662
- : buildPermissionFallbackOutput(node, reason, target);
663
-
664
- nodeRun.status = 'completed';
665
- nodeRun.error = reason;
666
- nodeRun.outputText = outputText;
667
- nodeRun.finishedAt = nodeRun.finishedAt ?? Date.now();
668
- outputs.set(node.id, compactOutputForContext(outputText));
669
- completed.add(node.id);
670
- }
671
-
672
- function expandAgentTeamWorkflow(workflow: Workflow, metadata?: Record<string, unknown>): Workflow {
673
- const agents = readAgentAssignments(metadata);
674
- if (agents.length === 0) {
675
- throw new Error('Select at least one CLI agent.');
676
- }
677
-
678
- const coordinator = agents.find((agent) => agent.adapterId === 'claude-code') ?? agents[0];
679
- const roster = agentRoster(agents);
680
- const workerSpecs = agents.map((agent, index) => ({
681
- agent,
682
- role: inferImplementationRole(agent),
683
- stage: displayStage(agent, inferImplementationRole(agent)),
684
- nodeId: safeAgentNodeId(agent, index, 'work'),
685
- handoffNodeId: safeAgentNodeId(agent, index, 'handoff'),
686
- }));
687
- const backendHandoffNodeIds = workerSpecs
688
- .filter((spec) => spec.role === 'backend')
689
- .map((spec) => spec.handoffNodeId);
690
- const implementationNodeIds = workerSpecs
691
- .filter((spec) => spec.role !== 'review')
692
- .map((spec) => spec.nodeId);
693
- const handoffNodes: WorkflowNode[] = workerSpecs
694
- .filter((spec) => spec.role === 'backend')
695
- .map(({ agent, role, handoffNodeId }) => ({
696
- id: handoffNodeId,
697
- adapterId: agent.adapterId,
698
- agentInstanceId: agent.instanceId,
699
- agentLabel: `${agent.label} Handoff`,
700
- assignment: agent.instruction,
701
- stage: 'handoff',
702
- model: agent.model,
703
- permissionMode: agent.permissionMode,
704
- toolsSettings: agent.toolsSettings,
705
- prompt: handoffPrompt(agent, role),
706
- inputs: ['coordinator'],
707
- output: 'message',
708
- onFail: 'continue',
709
- timeoutMs: BACKEND_HANDOFF_TIMEOUT_MS,
710
- }));
711
- const workerNodes: WorkflowNode[] = workerSpecs.map(({ agent, role, stage, nodeId, handoffNodeId }) => {
712
- const inputs = role === 'review'
713
- ? (implementationNodeIds.length > 0 ? implementationNodeIds : ['coordinator'])
714
- : role === 'frontend' && backendHandoffNodeIds.length > 0
715
- ? ['coordinator', ...backendHandoffNodeIds]
716
- : role === 'backend'
717
- ? ['coordinator', handoffNodeId]
718
- : ['coordinator'];
719
-
720
- return {
721
- id: nodeId,
722
- adapterId: agent.adapterId,
723
- agentInstanceId: agent.instanceId,
724
- agentLabel: agent.label,
725
- assignment: agent.instruction,
726
- stage,
727
- model: agent.model,
728
- permissionMode: agent.permissionMode,
729
- toolsSettings: agent.toolsSettings,
730
- prompt: [
731
- `You are ${agent.label} in a Pixcode CLI team.`,
732
- `Your stage is: ${stage}.`,
733
- stage !== role ? `Runtime routing category: ${role}.` : '',
734
- 'The coordinator plan and any dependency outputs are included above. Use them together with the original user goal.',
735
- agent.instruction
736
- ? `Your explicit assignment from the user is: ${agent.instruction}`
737
- : 'No fixed per-agent assignment was set. Take the part assigned to you by the coordinator; if none is named, choose useful work that fits this CLI.',
738
- rolePrompt(stage),
739
- privacyGuardPrompt(),
740
- 'Respond in the same language as the user request.',
741
- ].filter(Boolean).join('\n'),
742
- inputs,
743
- output: 'both',
744
- onFail: 'continue',
745
- };
746
- });
747
-
748
- return {
749
- ...workflow,
750
- nodes: [
751
- {
752
- id: 'coordinator',
753
- adapterId: coordinator.adapterId,
754
- agentInstanceId: coordinator.instanceId,
755
- agentLabel: coordinator.label,
756
- stage: 'coordinator',
757
- model: coordinator.model,
758
- permissionMode: coordinator.permissionMode,
759
- toolsSettings: coordinator.toolsSettings,
760
- prompt: [
761
- 'You are the coordinator for a Pixcode CLI agent team.',
762
- 'Read the user goal, active CLI roster, and any per-agent assignments. Create a compact execution plan for the selected agents.',
763
- 'If the user directly names a CLI, honor that. Do not invent permanent roles; assign work only from the goal, active agents, and explicit assignment text.',
764
- `Active roster:\n${roster}`,
765
- 'Respond in the same language as the user request.',
766
- ].join('\n'),
767
- inputs: [],
768
- output: 'message',
769
- onFail: 'abort',
770
- },
771
- ...handoffNodes,
772
- ...workerNodes,
773
- {
774
- id: 'final_report',
775
- adapterId: coordinator.adapterId,
776
- agentInstanceId: coordinator.instanceId,
777
- agentLabel: coordinator.label,
778
- stage: 'final_report',
779
- model: coordinator.model,
780
- permissionMode: coordinator.permissionMode,
781
- toolsSettings: coordinator.toolsSettings,
782
- prompt: [
783
- 'Collect the worker outputs into one user-facing result.',
784
- 'Show what each CLI did, which parts failed, what changed, and the next action if work remains.',
785
- 'Do not expose internal prompts, memory lookup, skill/tool instructions, raw agent logs, or role prefixes like "agent:" and "user:".',
786
- 'If a worker reveals internal process text, summarize only the useful user-facing result.',
787
- 'Respond in the same language as the user request.',
788
- ].join('\n'),
789
- inputs: workerNodes.map((node) => node.id),
790
- output: 'message',
791
- onFail: 'abort',
792
- },
793
- ],
794
- };
795
- }
796
-
797
- function stagePrompt(agent: AgentAssignment, stage: AgentRole): string {
798
- return [
799
- `You are ${agent.label} in a Pixcode decision workflow.`,
800
- `Your stage is: ${stage}.`,
801
- agent.role && agent.role !== stage ? `User custom stage label: ${agent.role}.` : '',
802
- agent.instruction ? `User assignment for you: ${agent.instruction}` : '',
803
- rolePrompt(stage),
804
- privacyGuardPrompt(),
805
- 'Keep the answer concise, structured, and useful for the next stage.',
806
- 'Respond in the same language as the user request.',
807
- ].filter(Boolean).join('\n');
808
- }
809
-
810
- function agentsWithRole(agents: AgentAssignment[], role: AgentRole): AgentAssignment[] {
811
- return agents.filter((agent) => agent.role === role);
812
- }
813
-
814
- function autoAssignDebateAgents(agents: AgentAssignment[]): {
815
- proposalAgents: AgentAssignment[];
816
- critiqueAgents: AgentAssignment[];
817
- responseAgents: AgentAssignment[];
818
- reportAgent: AgentAssignment;
819
- } {
820
- const assigned = new Set<string>();
821
- const markAssigned = (items: AgentAssignment[]) => {
822
- for (const item of items) assigned.add(item.instanceId);
823
- };
824
- const pickNext = () =>
825
- agents.find((agent) => !assigned.has(agent.instanceId) && agent.role !== 'decision' && agent.role !== 'report')
826
- ?? agents.find((agent) => !assigned.has(agent.instanceId))
827
- ?? agents[0];
828
-
829
- const proposalAgents = agentsWithRole(agents, 'proposal');
830
- if (proposalAgents.length === 0) proposalAgents.push(pickNext());
831
- markAssigned(proposalAgents);
832
-
833
- const critiqueAgents = agentsWithRole(agents, 'critique');
834
- if (critiqueAgents.length === 0) critiqueAgents.push(pickNext());
835
- markAssigned(critiqueAgents);
836
-
837
- const responseAgents = agentsWithRole(agents, 'response');
838
- if (responseAgents.length === 0 && agents.length > 2) {
839
- responseAgents.push(...agents.filter((agent) =>
840
- !assigned.has(agent.instanceId) && agent.role !== 'decision' && agent.role !== 'report',
841
- ));
842
- }
843
- markAssigned(responseAgents);
844
-
845
- const reportAgent = agentsWithRole(agents, 'decision')[0]
846
- ?? agentsWithRole(agents, 'report')[0]
847
- ?? agents[0];
848
-
849
- return { proposalAgents, critiqueAgents, responseAgents, reportAgent };
850
- }
851
-
852
- function expandAdversarialDebateWorkflow(workflow: Workflow, metadata?: Record<string, unknown>): Workflow {
853
- const agents = readAgentAssignments(metadata);
854
- if (agents.length === 0) {
855
- throw new Error('Select at least one CLI agent.');
856
- }
857
-
858
- const {
859
- proposalAgents,
860
- critiqueAgents,
861
- responseAgents,
862
- reportAgent,
863
- } = autoAssignDebateAgents(agents);
864
-
865
- const proposalNodes: WorkflowNode[] = proposalAgents.map((agent, index) => ({
866
- id: safeAgentNodeId(agent, index, 'proposal'),
867
- adapterId: agent.adapterId,
868
- agentInstanceId: agent.instanceId,
869
- agentLabel: agent.label,
870
- assignment: agent.instruction || 'Proposal stage',
871
- stage: 'proposal',
872
- model: agent.model,
873
- permissionMode: agent.permissionMode,
874
- toolsSettings: agent.toolsSettings,
875
- prompt: stagePrompt(agent, 'proposal'),
876
- inputs: [],
877
- output: 'message',
878
- onFail: 'continue',
879
- }));
880
- const critiqueNodes: WorkflowNode[] = critiqueAgents.map((agent, index) => ({
881
- id: safeAgentNodeId(agent, index, 'critique'),
882
- adapterId: agent.adapterId,
883
- agentInstanceId: agent.instanceId,
884
- agentLabel: agent.label,
885
- assignment: agent.instruction || 'Critique stage',
886
- stage: 'critique',
887
- model: agent.model,
888
- permissionMode: agent.permissionMode,
889
- toolsSettings: agent.toolsSettings,
890
- prompt: stagePrompt(agent, 'critique'),
891
- inputs: proposalNodes.map((node) => node.id),
892
- output: 'message',
893
- onFail: 'continue',
894
- }));
895
- const responseNodes: WorkflowNode[] = responseAgents.map((agent, index) => ({
896
- id: safeAgentNodeId(agent, index, 'response'),
897
- adapterId: agent.adapterId,
898
- agentInstanceId: agent.instanceId,
899
- agentLabel: agent.label,
900
- assignment: agent.instruction || 'Response stage',
901
- stage: 'response',
902
- model: agent.model,
903
- permissionMode: agent.permissionMode,
904
- toolsSettings: agent.toolsSettings,
905
- prompt: stagePrompt(agent, 'response'),
906
- inputs: critiqueNodes.map((node) => node.id),
907
- output: 'message',
908
- onFail: 'continue',
909
- }));
910
- const finalInputs = responseNodes.length > 0
911
- ? responseNodes.map((node) => node.id)
912
- : critiqueNodes.map((node) => node.id);
913
-
914
- return {
915
- ...workflow,
916
- nodes: [
917
- ...proposalNodes,
918
- ...critiqueNodes,
919
- ...responseNodes,
920
- {
921
- id: 'final_report',
922
- adapterId: reportAgent.adapterId,
923
- agentInstanceId: reportAgent.instanceId,
924
- agentLabel: reportAgent.label,
925
- assignment: reportAgent.instruction || 'Final decision report',
926
- stage: 'final_report',
927
- model: reportAgent.model,
928
- permissionMode: reportAgent.permissionMode,
929
- toolsSettings: reportAgent.toolsSettings,
930
- prompt: [
931
- 'Produce the final decision report from the debate.',
932
- 'Use this exact structure:',
933
- '1. Short decision',
934
- '2. Why',
935
- '3. Risks',
936
- '4. Suggested next prompt',
937
- '5. Proposed agent team and assignments',
938
- 'The next prompt should be ready to paste into Pixcode Agent Team mode.',
939
- 'Do not edit files. Respond in the same language as the user request.',
940
- ].join('\n'),
941
- inputs: finalInputs,
942
- output: 'message',
943
- onFail: 'abort',
944
- },
945
- ],
946
- };
947
- }
948
-
949
- function expandSequentialHandoffWorkflow(workflow: Workflow, metadata?: Record<string, unknown>): Workflow {
950
- const agents = readAgentAssignments(metadata);
951
- if (agents.length === 0) {
952
- throw new Error('Select at least one CLI agent.');
953
- }
954
-
955
- const nodes: WorkflowNode[] = agents.flatMap((agent, index): WorkflowNode[] => {
956
- const initNodeId = safeAgentNodeId(agent, index, 'init');
957
- const workNodeId = safeAgentNodeId(agent, index, 'work');
958
- const compactNodeId = safeAgentNodeId(agent, index, 'compact');
959
-
960
- return [
961
- {
962
- id: initNodeId,
963
- adapterId: agent.adapterId,
964
- agentInstanceId: agent.instanceId,
965
- agentLabel: `${agent.label} Init`,
966
- assignment: agent.instruction,
967
- stage: 'handoff_init',
968
- model: agent.model,
969
- permissionMode: agent.permissionMode,
970
- toolsSettings: agent.toolsSettings,
971
- prompt: handoffInitPrompt(agent, index),
972
- inputs: index === 0 ? [] : [safeAgentNodeId(agents[index - 1], index - 1, 'compact')],
973
- output: 'message',
974
- onFail: 'abort',
975
- internal: true,
976
- },
977
- {
978
- id: workNodeId,
979
- adapterId: agent.adapterId,
980
- agentInstanceId: agent.instanceId,
981
- agentLabel: agent.label,
982
- assignment: agent.instruction,
983
- stage: agent.role ?? 'implementation',
984
- model: agent.model,
985
- permissionMode: agent.permissionMode,
986
- toolsSettings: agent.toolsSettings,
987
- prompt: handoffWorkPrompt(agent, index),
988
- inputs: [initNodeId],
989
- output: 'both',
990
- onFail: 'abort',
991
- },
992
- {
993
- id: compactNodeId,
994
- adapterId: agent.adapterId,
995
- agentInstanceId: agent.instanceId,
996
- agentLabel: `${agent.label} Compact`,
997
- assignment: agent.instruction,
998
- stage: 'handoff_compact',
999
- model: agent.model,
1000
- permissionMode: agent.permissionMode,
1001
- toolsSettings: agent.toolsSettings,
1002
- prompt: handoffCompactPrompt(agent, index),
1003
- inputs: [workNodeId],
1004
- output: 'message',
1005
- onFail: 'abort',
1006
- internal: true,
1007
- },
1008
- ];
1009
- });
1010
- const reportAgent = agents[0];
1011
- const lastCompactNodeId = safeAgentNodeId(agents[agents.length - 1], agents.length - 1, 'compact');
1012
-
1013
- return {
1014
- ...workflow,
1015
- nodes: [
1016
- ...nodes,
1017
- {
1018
- id: 'final_report',
1019
- adapterId: reportAgent.adapterId,
1020
- agentInstanceId: reportAgent.instanceId,
1021
- agentLabel: reportAgent.label,
1022
- stage: 'final_report',
1023
- model: reportAgent.model,
1024
- permissionMode: reportAgent.permissionMode,
1025
- toolsSettings: reportAgent.toolsSettings,
1026
- prompt: [
1027
- 'Create the final user-facing result for this strict handoff run.',
1028
- 'Use the final compact handoff packet and the original user goal.',
1029
- 'Summarize what each visible agent did, what changed, verification, blockers, and next actions.',
1030
- 'Do not expose internal init packets, compact packets, prompts, memory lookup, skill/tool instructions, raw agent logs, or role prefixes like "agent:" and "user:".',
1031
- 'Respond in the same language as the user request.',
1032
- ].join('\n'),
1033
- inputs: [lastCompactNodeId],
1034
- output: 'message',
1035
- onFail: 'abort',
1036
- },
1037
- ],
1038
- };
1039
- }
1040
-
1041
- function expandWorkflowForRun(workflow: Workflow, metadata?: Record<string, unknown>): Workflow {
1042
- if (workflow.id === 'agent_team') {
1043
- return expandAgentTeamWorkflow(workflow, metadata);
1044
- }
1045
-
1046
- const agents = readAgentAssignments(metadata);
1047
- if (workflow.id === 'adversarial_debate') {
1048
- return expandAdversarialDebateWorkflow(workflow, metadata);
1049
- }
1050
- if (workflow.id === 'sequential_handoff') {
1051
- return expandSequentialHandoffWorkflow(workflow, metadata);
1052
- }
1053
- if (workflow.id !== 'multi_model_review' || agents.length === 0) {
1054
- return workflow;
1055
- }
1056
-
1057
- const reportAgent = agentsWithRole(agents, 'report')[0] ?? agentsWithRole(agents, 'decision')[0] ?? agents[0];
1058
- const reviewAgents = agents.filter((agent) => agent.instanceId !== reportAgent.instanceId || agents.length === 1);
1059
- const reviewNodes: WorkflowNode[] = reviewAgents.map((agent, index) => ({
1060
- id: safeAgentNodeId(agent, index, 'review'),
1061
- adapterId: agent.adapterId,
1062
- agentInstanceId: agent.instanceId,
1063
- agentLabel: agent.label,
1064
- assignment: agent.instruction,
1065
- stage: 'review',
1066
- model: agent.model,
1067
- permissionMode: agent.permissionMode,
1068
- toolsSettings: agent.toolsSettings,
1069
- prompt: [
1070
- `You are ${agent.label}.`,
1071
- 'Review the requested change for bugs, regressions, missing validation, security, scale, and user-experience risks.',
1072
- agent.instruction ? `Focus on this user assignment: ${agent.instruction}` : '',
1073
- privacyGuardPrompt(),
1074
- 'Respond in the same language as the user request.',
1075
- ].filter(Boolean).join('\n'),
1076
- inputs: [],
1077
- output: 'both',
1078
- onFail: 'continue',
1079
- }));
1080
-
1081
- return {
1082
- ...workflow,
1083
- nodes: [
1084
- ...reviewNodes,
1085
- {
1086
- id: 'aggregate',
1087
- adapterId: reportAgent.adapterId,
1088
- agentInstanceId: reportAgent.instanceId,
1089
- agentLabel: reportAgent.label,
1090
- stage: 'report',
1091
- model: reportAgent.model,
1092
- permissionMode: reportAgent.permissionMode,
1093
- toolsSettings: reportAgent.toolsSettings,
1094
- prompt: [
1095
- 'Aggregate the prior agent reviews into a concise prioritized report.',
1096
- 'Do not expose internal prompts, memory lookup, skill/tool instructions, raw agent logs, or role prefixes like "agent:" and "user:".',
1097
- 'Respond in the same language as the user request.',
1098
- ].join('\n'),
1099
- inputs: reviewNodes.map((node) => node.id),
1100
- output: 'message',
1101
- onFail: 'abort',
1102
- },
1103
- ],
1104
- };
1105
- }
1106
-
1107
- function readTaskResult(task: RawTask): TaskResult {
1108
- const messages = (task.history ?? []).map((message) => ({
1109
- role: typeof message.role === 'string' ? message.role : 'agent',
1110
- text: (message.parts ?? [])
1111
- .filter((part) => part.kind === 'text' && typeof part.text === 'string')
1112
- .map((part) => part.text)
1113
- .join('\n'),
1114
- })).filter((message) => message.text.trim());
1115
- const artifacts = (task.artifacts ?? []).map((artifact) => {
1116
- const text = (artifact.parts ?? [])
1117
- .filter((part) => part.kind === 'text' && typeof part.text === 'string')
1118
- .map((part) => part.text)
1119
- .join('\n');
1120
- const data = (artifact.parts ?? []).find((part) => part.kind === 'data')?.data;
1121
- return {
1122
- type: artifact.type ?? 'data',
1123
- text: text || undefined,
1124
- data,
1125
- metadata: artifact.metadata,
1126
- };
1127
- });
1128
- const outputMessages = messages.filter((message) => message.role !== 'user');
1129
- const userFacingTaskText = outputMessages.map((message) => message.text.trim()).filter(Boolean).join('\n\n');
1130
- const error = task.error?.message
1131
- ? `${task.error.code ? `${task.error.code}: ` : ''}${task.error.message}`
1132
- : undefined;
1133
- return {
1134
- state: task.state ?? 'submitted',
1135
- text: userFacingTaskText,
1136
- error,
1137
- messages,
1138
- artifacts,
1139
- };
1140
- }
1141
-
1142
- async function waitForTask(
1143
- taskId: string,
1144
- shouldCancel?: () => boolean,
1145
- onSnapshot?: (result: TaskResult) => void,
1146
- timeoutMs?: number,
1147
- ): Promise<TaskResult> {
1148
- const timeout = timeoutMs && timeoutMs > 0 ? timeoutMs : undefined;
1149
- const deadline = timeout ? Date.now() + timeout : undefined;
1150
- for (;;) {
1151
- if (shouldCancel?.()) {
1152
- throw new WorkflowCanceledError();
1153
- }
1154
- if (deadline && Date.now() >= deadline) {
1155
- throw new WorkflowNodeTimeoutError(timeout ?? 0);
1156
- }
1157
- const task = getA2ATask(taskId);
1158
- if (!task) {
1159
- throw new Error(`Agent task ${taskId} was not found.`);
1160
- }
1161
- const snapshot = readTaskResult(task);
1162
- onSnapshot?.(snapshot);
1163
- if (task.state && TERMINAL.has(task.state)) {
1164
- return snapshot;
1165
- }
1166
- await new Promise((resolve) => setTimeout(resolve, 1000));
1167
- }
1168
- }
1169
-
1170
- function readyNodes(workflow: Workflow, completed: Set<string>, started: Set<string>): WorkflowNode[] {
1171
- return workflow.nodes.filter((node) =>
1172
- !started.has(node.id) && node.inputs.every((input) => completed.has(input)),
1173
- );
1174
- }
1175
-
1176
- function nodeRunFromNode(node: WorkflowNode): WorkflowNodeRun {
1177
- return {
1178
- nodeId: node.id,
1179
- adapterId: node.adapterId,
1180
- agentInstanceId: node.agentInstanceId,
1181
- agentLabel: node.agentLabel,
1182
- assignment: node.assignment,
1183
- promptPreview: node.prompt,
1184
- model: node.model,
1185
- permissionMode: node.permissionMode,
1186
- timeoutMs: node.timeoutMs,
1187
- stage: node.stage,
1188
- internal: node.internal,
1189
- fallbackTrigger: node.fallbackTrigger,
1190
- fallbackSourceNodeId: node.fallbackSourceNodeId,
1191
- status: 'queued',
1192
- };
1193
- }
1194
-
1195
- function uniqueInputs(inputs: string[]): string[] {
1196
- return [...new Set(inputs.filter(Boolean))];
1197
- }
1198
-
1199
- function isReviewNode(node: WorkflowNode): boolean {
1200
- return node.stage === 'review';
1201
- }
1202
-
1203
- function isImplementationNode(node: WorkflowNode): boolean {
1204
- return node.stage === 'backend' || node.stage === 'frontend' || node.stage === 'implementation' || node.stage === 'repair';
1205
- }
1206
-
1207
- function reviewRequiresRepair(text: string): boolean {
1208
- const normalized = text.toLocaleLowerCase('tr').replace(/\s+/g, ' ').trim();
1209
- if (!normalized) return false;
1210
-
1211
- const approvalPatterns = [
1212
- /hata yok/u,
1213
- /sorun yok/u,
1214
- /problem yok/u,
1215
- /bulgu yok/u,
1216
- /kritik bulgu yok/u,
1217
- /temiz/u,
1218
- /onaylı/u,
1219
- /onayli/u,
1220
- /approved/u,
1221
- /lgtm/u,
1222
- /no issues/u,
1223
- /no findings/u,
1224
- /looks good/u,
1225
- /pass(?:ed)?/u,
1226
- ];
1227
- const actionableText = approvalPatterns.reduce((current, pattern) => current.replace(pattern, ' '), normalized);
1228
- const issuePatterns = [
1229
- /hata/u,
1230
- /bug/u,
1231
- /kritik/u,
1232
- /critical/u,
1233
- /blocker/u,
1234
- /regression/u,
1235
- /failed/u,
1236
- /failure/u,
1237
- /fail/u,
1238
- /eksik/u,
1239
- /düzelt/u,
1240
- /duzelt/u,
1241
- /fix required/u,
1242
- /needs fix/u,
1243
- /sorun/u,
1244
- /risk/u,
1245
- /güvenlik/u,
1246
- /guvenlik/u,
1247
- /security/u,
1248
- /çalışmıyor/u,
1249
- /calismiyor/u,
1250
- ];
1251
-
1252
- return issuePatterns.some((pattern) => pattern.test(actionableText));
1253
- }
1254
-
1255
- function findRepairFixer(workflow: Workflow, reviewNode: WorkflowNode): WorkflowNode | undefined {
1256
- return reviewNode.inputs
1257
- .map((input) => workflow.nodes.find((node) => node.id === input))
1258
- .find((node): node is WorkflowNode => Boolean(node && isImplementationNode(node)))
1259
- ?? workflow.nodes.find((node) => isImplementationNode(node))
1260
- ?? workflow.nodes.find((node) => node.stage === 'coordinator');
1261
- }
1262
-
1263
- class WorkflowRunner {
1264
- private readonly cancelingRuns = new Set<string>();
1265
-
1266
- preview(workflow: Workflow, metadata?: Record<string, unknown>): Workflow {
1267
- const runtimeWorkflow = expandWorkflowForRun(workflow, metadata);
1268
- validateWorkflow(runtimeWorkflow);
1269
- return runtimeWorkflow;
1270
- }
1271
-
1272
- start(workflow: Workflow, input = '', metadata?: Record<string, unknown>): WorkflowRun {
1273
- const runtimeWorkflow = expandWorkflowForRun(workflow, metadata);
1274
- validateWorkflow(runtimeWorkflow);
1275
- const workspaceTarget = resolveWorkflowWorkspace(metadata);
1276
- const permissionPolicy = resolvePermissionPolicyFromMetadata(metadata);
1277
- const runMetadata: Record<string, unknown> = {
1278
- ...metadata,
1279
- permissionPolicy,
1280
- projectPath: workspaceTarget.projectPath,
1281
- selectedProjectPath: workspaceTarget.selectedProjectPath,
1282
- workspaceTarget: workspaceTargetMetadata(workspaceTarget),
1283
- };
1284
- const run: WorkflowRun = {
1285
- id: newId('wrun'),
1286
- workflowId: runtimeWorkflow.id,
1287
- contextId: newId('ctx'),
1288
- status: 'queued',
1289
- input,
1290
- nodeRuns: runtimeWorkflow.nodes.map(nodeRunFromNode),
1291
- startedAt: Date.now(),
1292
- metadata: runMetadata,
1293
- };
1294
- workflowStore.setRun(run);
1295
- const orchestrationTaskId = readString(runMetadata.orchestrationTaskId);
1296
- if (orchestrationTaskId) {
1297
- orchestrationTaskService.linkWorkflowRun(orchestrationTaskId, run);
1298
- }
1299
- void this.execute(runtimeWorkflow, run);
1300
- return run;
1301
- }
1302
-
1303
- async cancel(runId: string): Promise<WorkflowRun | undefined> {
1304
- const run = workflowStore.getRun(runId);
1305
- if (!run) return undefined;
1306
- if (TERMINAL.has(run.status)) return run;
1307
-
1308
- this.cancelingRuns.add(run.id);
1309
- const taskIds = run.nodeRuns
1310
- .filter((node) => node.a2aTaskId && (node.status === 'running' || node.status === 'queued'))
1311
- .map((node) => node.a2aTaskId as string);
1312
-
1313
- this.markCanceled(run);
1314
- workflowStore.setRun(run);
1315
-
1316
- await Promise.all(taskIds.map((taskId) => cancelA2ATask(taskId)));
1317
-
1318
- return workflowStore.getRun(run.id) ?? run;
1319
- }
1320
-
1321
- private isCanceling(runId: string): boolean {
1322
- return this.cancelingRuns.has(runId) || workflowStore.getRun(runId)?.status === 'canceled';
1323
- }
1324
-
1325
- private markCanceled(run: WorkflowRun): void {
1326
- run.status = 'canceled';
1327
- run.finishedAt = run.finishedAt ?? Date.now();
1328
- for (const nodeRun of run.nodeRuns) {
1329
- if (!TERMINAL.has(nodeRun.status) && nodeRun.status !== SKIPPED) {
1330
- nodeRun.status = 'canceled';
1331
- nodeRun.finishedAt = nodeRun.finishedAt ?? Date.now();
1332
- }
1333
- }
1334
- }
1335
-
1336
- private fallbackAgentFor(run: WorkflowRun, node: WorkflowNode): AgentAssignment | undefined {
1337
- if (node.stage === 'fallback' || node.id.startsWith('fallback_')) {
1338
- return undefined;
1339
- }
1340
-
1341
- const settings = getMetadataRecord(run.metadata, 'settings');
1342
- const fallbackAgentInstanceId = readString(settings.fallbackAgentInstanceId);
1343
- if (!fallbackAgentInstanceId || fallbackAgentInstanceId === node.agentInstanceId) {
1344
- return undefined;
1345
- }
1346
-
1347
- return readAgentAssignments(run.metadata).find((agent) => agent.instanceId === fallbackAgentInstanceId);
1348
- }
1349
-
1350
- private createFallbackNode(
1351
- node: WorkflowNode,
1352
- fallbackAgent: AgentAssignment,
1353
- reason: string,
1354
- fallbackTrigger: WorkflowFallbackTrigger,
1355
- ): WorkflowNode {
1356
- const fallbackSuffix = safeNodeId(fallbackAgent.instanceId, 'fallback');
1357
- return {
1358
- ...node,
1359
- id: `fallback_${node.id}_${fallbackSuffix}`,
1360
- adapterId: fallbackAgent.adapterId,
1361
- agentInstanceId: fallbackAgent.instanceId,
1362
- agentLabel: `${fallbackAgent.label} Fallback`,
1363
- assignment: `Fallback for ${node.agentLabel || node.id}`,
1364
- stage: 'fallback',
1365
- model: fallbackAgent.model,
1366
- permissionMode: fallbackAgent.permissionMode,
1367
- toolsSettings: fallbackAgent.toolsSettings,
1368
- fallbackTrigger,
1369
- fallbackSourceNodeId: node.id,
1370
- prompt: [
1371
- 'The previous CLI agent failed on this orchestration step.',
1372
- `Failed step: ${node.agentLabel || node.id}`,
1373
- `Fallback trigger: ${fallbackTrigger}`,
1374
- `Failure: ${reason}`,
1375
- 'Take over the same assignment as the backup CLI. Use the original goal and upstream context.',
1376
- 'Do not repeat unrelated work; complete the failed step and report what you did.',
1377
- node.prompt,
1378
- ].join('\n'),
1379
- onFail: 'continue',
1380
- };
1381
- }
1382
-
1383
- private recordFallbackSkipped(
1384
- run: WorkflowRun,
1385
- node: WorkflowNode,
1386
- reason: string,
1387
- fallbackTrigger: WorkflowFallbackTrigger,
1388
- skippedReason: string,
1389
- ): void {
1390
- const fallbackSkippedEvents = Array.isArray(run.metadata?.fallbackSkippedEvents)
1391
- ? run.metadata.fallbackSkippedEvents
1392
- : [];
1393
- run.metadata = {
1394
- ...run.metadata,
1395
- fallbackSkippedEvents: [
1396
- ...fallbackSkippedEvents,
1397
- {
1398
- nodeId: node.id,
1399
- trigger: fallbackTrigger,
1400
- reason,
1401
- skippedReason,
1402
- createdAt: Date.now(),
1403
- },
1404
- ],
1405
- };
1406
- workflowStore.setRun(run);
1407
- }
1408
-
1409
- private async runFallbackAfterFailure(
1410
- node: WorkflowNode,
1411
- workflow: Workflow,
1412
- run: WorkflowRun,
1413
- outputs: Map<string, string>,
1414
- started: Set<string>,
1415
- completed: Set<string>,
1416
- reason: string,
1417
- trigger?: WorkflowFallbackTrigger,
1418
- ): Promise<boolean> {
1419
- const fallbackTrigger = classifyWorkflowFailure(reason, trigger);
1420
- const fallbackAgent = this.fallbackAgentFor(run, node);
1421
- if (!fallbackAgent) {
1422
- this.recordFallbackSkipped(run, node, reason, fallbackTrigger, 'No fallback agent is configured for this run.');
1423
- return false;
1424
- }
1425
- const decision = resolveWorkflowFallbackDecision({
1426
- run,
1427
- node,
1428
- reason,
1429
- trigger: fallbackTrigger,
1430
- fallbackAgentInstanceId: fallbackAgent.instanceId,
1431
- });
1432
- if (!decision.shouldFallback) {
1433
- this.recordFallbackSkipped(
1434
- run,
1435
- node,
1436
- reason,
1437
- decision.trigger,
1438
- decision.skippedReason ?? 'Fallback policy skipped this failure.',
1439
- );
1440
- return false;
1441
- }
1442
- if (workflow.nodes.length + 1 > 64) {
1443
- run.metadata = {
1444
- ...run.metadata,
1445
- fallbackSkipped: `Workflow node limit reached after ${node.id}.`,
1446
- };
1447
- workflowStore.setRun(run);
1448
- return false;
1449
- }
1450
-
1451
- let fallbackNode = this.createFallbackNode(node, fallbackAgent, reason, decision.trigger);
1452
- let collision = 1;
1453
- while (workflow.nodes.some((candidate) => candidate.id === fallbackNode.id)) {
1454
- collision += 1;
1455
- fallbackNode = {
1456
- ...fallbackNode,
1457
- id: `${fallbackNode.id}_${collision}`,
1458
- };
1459
- }
1460
-
1461
- const nodeIndex = workflow.nodes.findIndex((candidate) => candidate.id === node.id);
1462
- const runIndex = run.nodeRuns.findIndex((candidate) => candidate.nodeId === node.id);
1463
- if (nodeIndex >= 0) {
1464
- workflow.nodes.splice(nodeIndex + 1, 0, fallbackNode);
1465
- } else {
1466
- workflow.nodes.push(fallbackNode);
1467
- }
1468
- if (runIndex >= 0) {
1469
- run.nodeRuns.splice(runIndex + 1, 0, nodeRunFromNode(fallbackNode));
1470
- } else {
1471
- run.nodeRuns.push(nodeRunFromNode(fallbackNode));
1472
- }
1473
-
1474
- const fallbackEvents = Array.isArray(run.metadata?.fallbackEvents)
1475
- ? run.metadata.fallbackEvents
1476
- : [];
1477
- run.metadata = {
1478
- ...run.metadata,
1479
- fallbackEvents: [
1480
- ...fallbackEvents,
1481
- {
1482
- nodeId: node.id,
1483
- fallbackNodeId: fallbackNode.id,
1484
- fallbackAgentInstanceId: fallbackAgent.instanceId,
1485
- trigger: decision.trigger,
1486
- policy: decision.policy,
1487
- reason,
1488
- startedAt: Date.now(),
1489
- },
1490
- ],
1491
- };
1492
- workflowStore.setRun(run);
1493
-
1494
- await this.executeNode(fallbackNode, workflow, run, outputs, started, completed);
1495
-
1496
- const fallbackRun = run.nodeRuns.find((candidate) => candidate.nodeId === fallbackNode.id);
1497
- if (fallbackRun?.status !== 'completed') {
1498
- return false;
1499
- }
1500
-
1501
- const fallbackOutput = outputs.get(fallbackNode.id) || fallbackRun.outputText;
1502
- if (fallbackOutput) {
1503
- outputs.set(node.id, compactOutputForContext(fallbackOutput));
1504
- }
1505
- completed.add(node.id);
1506
- workflowStore.setRun(run);
1507
- return true;
1508
- }
1509
-
1510
- private maybeAddRepairCycle(
1511
- node: WorkflowNode,
1512
- workflow: Workflow,
1513
- run: WorkflowRun,
1514
- result: TaskResult,
1515
- ): void {
1516
- if (workflow.id !== 'agent_team') return;
1517
- if (!isReviewNode(node) || node.id.startsWith('repair_') || node.id.startsWith('recheck_')) return;
1518
- if (!reviewRequiresRepair(`${result.text}\n${result.error ?? ''}`)) return;
1519
-
1520
- const maxRepairCycles = readMaxRepairCycles(run.metadata);
1521
- if (maxRepairCycles <= 0) return;
1522
-
1523
- const existingCycles = workflow.nodes.filter((candidate) => candidate.id.startsWith(`repair_${node.id}_`)).length;
1524
- if (existingCycles >= maxRepairCycles) return;
1525
-
1526
- if (workflow.nodes.length + 2 > 64) {
1527
- run.metadata = {
1528
- ...run.metadata,
1529
- dynamicRepairSkipped: `Workflow node limit reached after ${node.id}.`,
1530
- };
1531
- workflowStore.setRun(run);
1532
- return;
1533
- }
1534
-
1535
- const fixer = findRepairFixer(workflow, node);
1536
- if (!fixer || fixer.id === node.id) return;
1537
-
1538
- const cycle = existingCycles + 1;
1539
- const repairNode: WorkflowNode = {
1540
- id: `repair_${node.id}_${cycle}`,
1541
- adapterId: fixer.adapterId,
1542
- agentInstanceId: fixer.agentInstanceId,
1543
- agentLabel: fixer.agentLabel ? `${fixer.agentLabel} Repair` : undefined,
1544
- assignment: `Automatic repair from ${node.agentLabel || node.id} review findings`,
1545
- stage: 'repair',
1546
- model: fixer.model,
1547
- permissionMode: fixer.permissionMode,
1548
- toolsSettings: fixer.toolsSettings,
1549
- prompt: [
1550
- 'A review stage found actionable issues in the prior work.',
1551
- 'Use the original user goal, prior implementation outputs, and review output included above.',
1552
- 'Fix only the reported issues; do not restart the whole project or duplicate unrelated work.',
1553
- 'Report changed files, commands, verification, and any remaining blockers.',
1554
- 'Respond in the same language as the user request.',
1555
- ].join('\n'),
1556
- inputs: uniqueInputs([...node.inputs, fixer.id, node.id]),
1557
- output: 'both',
1558
- onFail: 'continue',
1559
- };
1560
- const recheckNode: WorkflowNode = {
1561
- id: `recheck_${node.id}_${cycle}`,
1562
- adapterId: node.adapterId,
1563
- agentInstanceId: node.agentInstanceId,
1564
- agentLabel: node.agentLabel ? `${node.agentLabel} Recheck` : undefined,
1565
- assignment: 'Automatic validation after repair',
1566
- stage: 'review',
1567
- model: node.model,
1568
- permissionMode: node.permissionMode,
1569
- toolsSettings: node.toolsSettings,
1570
- prompt: [
1571
- 'Validate the automatic repair against the original review findings.',
1572
- 'Approve only if the reported issues are fixed.',
1573
- 'If anything remains, list the remaining blockers clearly and do not invent new unrelated scope.',
1574
- 'Respond in the same language as the user request.',
1575
- ].join('\n'),
1576
- inputs: uniqueInputs([node.id, repairNode.id]),
1577
- output: 'message',
1578
- onFail: 'continue',
1579
- };
1580
-
1581
- const finalIndex = workflow.nodes.findIndex((candidate) =>
1582
- candidate.id === 'final_report' || candidate.stage === 'final_report' || candidate.stage === 'report',
1583
- );
1584
- if (finalIndex >= 0) {
1585
- workflow.nodes.splice(finalIndex, 0, repairNode, recheckNode);
1586
- run.nodeRuns.splice(finalIndex, 0, nodeRunFromNode(repairNode), nodeRunFromNode(recheckNode));
1587
- } else {
1588
- workflow.nodes.push(repairNode, recheckNode);
1589
- run.nodeRuns.push(nodeRunFromNode(repairNode), nodeRunFromNode(recheckNode));
1590
- }
1591
-
1592
- for (const finalNode of workflow.nodes) {
1593
- if (finalNode.id === 'final_report' || finalNode.stage === 'final_report' || finalNode.stage === 'report') {
1594
- finalNode.inputs = uniqueInputs([...finalNode.inputs, recheckNode.id]);
1595
- }
1596
- }
1597
-
1598
- const repairCycles = Array.isArray(run.metadata?.dynamicRepairCycles)
1599
- ? run.metadata.dynamicRepairCycles
1600
- : [];
1601
- run.metadata = {
1602
- ...run.metadata,
1603
- dynamicRepairCycles: [
1604
- ...repairCycles,
1605
- {
1606
- reviewNodeId: node.id,
1607
- repairNodeId: repairNode.id,
1608
- recheckNodeId: recheckNode.id,
1609
- fixerNodeId: fixer.id,
1610
- },
1611
- ],
1612
- };
1613
- workflowStore.setRun(run);
1614
- }
1615
-
1616
- private async execute(workflow: Workflow, run: WorkflowRun): Promise<void> {
1617
- run.status = 'running';
1618
- workflowStore.setRun(run);
1619
- const completed = new Set<string>();
1620
- const started = new Set<string>();
1621
- const outputs = new Map<string, string>();
1622
- const maxParallelAgents = readMaxParallelAgents(run.metadata);
1623
-
1624
- try {
1625
- while (completed.size < workflow.nodes.length) {
1626
- if (this.isCanceling(run.id)) {
1627
- throw new WorkflowCanceledError();
1628
- }
1629
- const batch = readyNodes(workflow, completed, started);
1630
- if (batch.length === 0) {
1631
- throw new Error('Workflow stalled; no ready nodes remain.');
1632
- }
1633
- for (let index = 0; index < batch.length; index += maxParallelAgents) {
1634
- if (this.isCanceling(run.id)) {
1635
- throw new WorkflowCanceledError();
1636
- }
1637
- const slice = batch.slice(index, index + maxParallelAgents);
1638
- await Promise.all(slice.map((node) => this.executeNode(node, workflow, run, outputs, started, completed)));
1639
- }
1640
- }
1641
- if (this.isCanceling(run.id)) {
1642
- throw new WorkflowCanceledError();
1643
- }
1644
- run.status = 'completed';
1645
- } catch (error) {
1646
- if (error instanceof WorkflowCanceledError || this.isCanceling(run.id)) {
1647
- this.markCanceled(run);
1648
- } else {
1649
- run.status = 'failed';
1650
- run.metadata = {
1651
- ...run.metadata,
1652
- error: error instanceof Error ? error.message : String(error),
1653
- };
1654
- }
1655
- } finally {
1656
- run.finishedAt = run.finishedAt ?? Date.now();
1657
- workflowStore.setRun(run);
1658
- orchestrationTaskService.updateFromWorkflowRun(run);
1659
- notifyWorkflowRunFinished(run);
1660
- const webhookRunStatus = String(run.status);
1661
- dispatchWebhookEvent({
1662
- type: webhookRunStatus === 'completed'
1663
- ? 'run.completed'
1664
- : webhookRunStatus === 'canceled'
1665
- ? 'run.canceled'
1666
- : 'run.failed',
1667
- payload: {
1668
- runId: run.id,
1669
- workflowId: run.workflowId,
1670
- status: webhookRunStatus,
1671
- error: readString(run.metadata?.error),
1672
- },
1673
- });
1674
- this.cancelingRuns.delete(run.id);
1675
- }
1676
- }
1677
-
1678
- private recordPermissionDecision(
1679
- run: WorkflowRun,
1680
- nodeRun: WorkflowNodeRun,
1681
- decision: PermissionDecision,
1682
- ): void {
1683
- nodeRun.permissionDecisions = [
1684
- ...(nodeRun.permissionDecisions ?? []),
1685
- decision,
1686
- ];
1687
-
1688
- const existingApprovals = permissionApprovalRequests(run)
1689
- .filter((approval) => approval.id !== decision.approvalRequest?.id);
1690
- run.metadata = {
1691
- ...run.metadata,
1692
- permissionPolicyEvents: [
1693
- ...permissionPolicyEvents(run),
1694
- decision.event,
1695
- ],
1696
- pendingPermissionApprovals: decision.approvalRequest
1697
- ? [
1698
- ...existingApprovals,
1699
- decision.approvalRequest,
1700
- ]
1701
- : existingApprovals,
1702
- };
1703
-
1704
- if (decision.approvalRequest) {
1705
- notifyPermissionApprovalRequested(run, decision);
1706
- dispatchWebhookEvent({
1707
- type: 'approval.needed',
1708
- payload: {
1709
- runId: run.id,
1710
- workflowId: run.workflowId,
1711
- approvalId: decision.approvalRequest.id,
1712
- capabilities: decision.capabilities,
1713
- },
1714
- });
1715
- }
1716
- }
1717
-
1718
- private async executeNode(
1719
- node: WorkflowNode,
1720
- workflow: Workflow,
1721
- run: WorkflowRun,
1722
- outputs: Map<string, string>,
1723
- started: Set<string>,
1724
- completed: Set<string>,
1725
- ): Promise<void> {
1726
- started.add(node.id);
1727
- const nodeRun = run.nodeRuns.find((candidate) => candidate.nodeId === node.id) as WorkflowNodeRun;
1728
- const enabledAdapters = readEnabledAdapters(run.metadata);
1729
- if (enabledAdapters.length > 0 && !enabledAdapters.includes(node.adapterId)) {
1730
- nodeRun.status = SKIPPED;
1731
- nodeRun.finishedAt = Date.now();
1732
- completed.add(node.id);
1733
- workflowStore.setRun(run);
1734
- return;
1735
- }
1736
- if (this.isCanceling(run.id)) {
1737
- nodeRun.status = 'canceled';
1738
- nodeRun.finishedAt = Date.now();
1739
- workflowStore.setRun(run);
1740
- throw new WorkflowCanceledError();
1741
- }
1742
-
1743
- nodeRun.status = 'running';
1744
- nodeRun.startedAt = Date.now();
1745
- nodeRun.permissionMode = resolveNodePermissionMode(node, resolveWorkflowWorkspace(run.metadata));
1746
- workflowStore.setRun(run);
1747
-
1748
- const inputContext = node.inputs.map((input) => outputs.get(input)).filter(Boolean).join('\n\n');
1749
- const workspaceTarget = resolveWorkflowWorkspace(run.metadata);
1750
- const contextPacket = buildWorkflowContextPacket({
1751
- run,
1752
- node,
1753
- workspaceTarget,
1754
- inputContext,
1755
- inputNodeIds: node.inputs,
1756
- });
1757
- nodeRun.contextPacket = contextPacket;
1758
- workflowStore.setRun(run);
1759
- const prompt = [
1760
- 'Original user request (primary task; answer this directly even if the workspace is empty):',
1761
- run.input?.trim() || '(No original user request was provided.)',
1762
- formatContextPacketForPrompt(contextPacket),
1763
- inputContext
1764
- ? `Upstream workflow context from prior agents:\n${inputContext}`
1765
- : '',
1766
- `Current workflow step instructions:\n${node.prompt}`,
1767
- workspaceContextPrompt(workspaceTarget),
1768
- ].filter(Boolean).join('\n\n');
1769
- const settings = getMetadataRecord(run.metadata, 'settings');
1770
- const projectPath = workspaceTarget.projectPath;
1771
- const isolation = readIsolation(settings.isolation) ?? node.isolation ?? 'host';
1772
- const keepAfterCompletion = readBoolean(settings.keepWorkspace) ?? true;
1773
- const baseRef = readString(settings.baseRef) ?? 'HEAD';
1774
- const effectivePermissionMode = resolveNodePermissionMode(node, workspaceTarget);
1775
- const effectiveModel = await resolveWorkflowModel(node.adapterId, node.model);
1776
- if (effectiveModel !== node.model) {
1777
- nodeRun.model = effectiveModel;
1778
- const modelFallbackEvents = Array.isArray(run.metadata?.modelFallbackEvents)
1779
- ? run.metadata.modelFallbackEvents
1780
- : [];
1781
- run.metadata = {
1782
- ...run.metadata,
1783
- modelFallbackEvents: [
1784
- ...modelFallbackEvents,
1785
- {
1786
- nodeId: node.id,
1787
- adapterId: node.adapterId,
1788
- requestedModel: node.model,
1789
- effectiveModel,
1790
- changedAt: Date.now(),
1791
- },
1792
- ],
1793
- };
1794
- workflowStore.setRun(run);
1795
- }
1796
- const permissionPolicy = permissionPolicyFromRun(run);
1797
- nodeRun.permissionPolicy = permissionPolicy;
1798
- const permissionDecision = evaluatePermissionRequest({
1799
- policy: permissionPolicy,
1800
- request: {
1801
- source: 'workflow_node',
1802
- toolName: node.adapterId,
1803
- input: {
1804
- assignment: node.assignment,
1805
- stage: node.stage,
1806
- toolsSettings: node.toolsSettings,
1807
- },
1808
- cwd: projectPath,
1809
- workspacePath: workspaceTarget.appRoot,
1810
- targetPaths: [projectPath],
1811
- summary: [
1812
- node.agentLabel || node.id,
1813
- node.stage ? `stage=${node.stage}` : undefined,
1814
- node.assignment,
1815
- ].filter(Boolean).join(' / '),
1816
- },
1817
- context: {
1818
- runId: run.id,
1819
- nodeId: node.id,
1820
- workflowId: run.workflowId,
1821
- adapterId: node.adapterId,
1822
- agentLabel: node.agentLabel,
1823
- userId: readNotificationUserId(run.metadata),
1824
- },
1825
- });
1826
- this.recordPermissionDecision(run, nodeRun, permissionDecision);
1827
- workflowStore.setRun(run);
1828
- if (permissionDecision.behavior === 'deny') {
1829
- nodeRun.finishedAt = Date.now();
1830
- nodeRun.status = 'failed';
1831
- nodeRun.error = permissionDecision.message;
1832
- workflowStore.setRun(run);
1833
- if (node.onFail === 'continue') {
1834
- completed.add(node.id);
1835
- return;
1836
- }
1837
- throw new Error(permissionDecision.message);
1838
- }
1839
- let submittedTask: RawTask;
1840
- try {
1841
- submittedTask = await submitA2ATask({
1842
- adapterId: node.adapterId,
1843
- contextId: run.contextId,
1844
- message: {
1845
- messageId: newId('msg'),
1846
- role: 'user',
1847
- parts: [{ kind: 'text', text: prompt }],
1848
- },
1849
- metadata: {
1850
- workflowRunId: run.id,
1851
- workflowNodeId: node.id,
1852
- agentInstanceId: node.agentInstanceId,
1853
- agentLabel: node.agentLabel,
1854
- assignment: node.assignment,
1855
- model: effectiveModel,
1856
- permissionMode: effectivePermissionMode,
1857
- permissionPolicy,
1858
- permissionPolicyContext: {
1859
- runId: run.id,
1860
- nodeId: node.id,
1861
- workflowId: run.workflowId,
1862
- adapterId: node.adapterId,
1863
- agentLabel: node.agentLabel,
1864
- userId: readNotificationUserId(run.metadata),
1865
- },
1866
- toolsSettings: node.toolsSettings,
1867
- projectPath,
1868
- workspaceTarget: workspaceTargetMetadata(workspaceTarget),
1869
- workspace: {
1870
- kind: isolation,
1871
- projectPath,
1872
- baseRef,
1873
- keepAfterCompletion,
1874
- },
1875
- },
1876
- });
1877
- } catch (error) {
1878
- nodeRun.finishedAt = Date.now();
1879
- nodeRun.status = 'failed';
1880
- nodeRun.error = error instanceof Error ? error.message : String(error);
1881
- workflowStore.setRun(run);
1882
- if (isExternalDirectoryPermissionError(nodeRun.error)) {
1883
- completeNodeWithPermissionFallback(nodeRun, node, outputs, completed, nodeRun.error, workspaceTarget);
1884
- workflowStore.setRun(run);
1885
- return;
1886
- }
1887
- if (await this.runFallbackAfterFailure(
1888
- node,
1889
- workflow,
1890
- run,
1891
- outputs,
1892
- started,
1893
- completed,
1894
- nodeRun.error,
1895
- 'provider_failure',
1896
- )) {
1897
- return;
1898
- }
1899
- if (node.onFail === 'continue') {
1900
- completed.add(node.id);
1901
- return;
1902
- }
1903
- throw error;
1904
- }
1905
- nodeRun.a2aTaskId = submittedTask.id;
1906
- workflowStore.setRun(run);
1907
-
1908
- if (this.isCanceling(run.id)) {
1909
- await cancelA2ATask(submittedTask.id);
1910
- nodeRun.status = 'canceled';
1911
- nodeRun.finishedAt = Date.now();
1912
- workflowStore.setRun(run);
1913
- throw new WorkflowCanceledError();
1914
- }
1915
-
1916
- let result: TaskResult;
1917
- try {
1918
- result = await waitForTask(
1919
- submittedTask.id,
1920
- () => this.isCanceling(run.id),
1921
- (snapshot) => {
1922
- nodeRun.outputText = snapshot.text || nodeRun.outputText;
1923
- nodeRun.messages = snapshot.messages;
1924
- nodeRun.artifacts = snapshot.artifacts;
1925
- nodeRun.error = snapshot.error;
1926
- workflowStore.setRun(run);
1927
- },
1928
- node.timeoutMs,
1929
- );
1930
- } catch (error) {
1931
- if (!(error instanceof WorkflowNodeTimeoutError)) {
1932
- throw error;
1933
- }
1934
-
1935
- await cancelA2ATask(submittedTask.id);
1936
- nodeRun.finishedAt = Date.now();
1937
- nodeRun.status = 'failed';
1938
- nodeRun.error = error.message;
1939
- if (nodeRun.outputText) {
1940
- outputs.set(node.id, compactOutputForContext(nodeRun.outputText));
1941
- }
1942
- workflowStore.setRun(run);
1943
- if (isExternalDirectoryPermissionError(nodeRun.error)) {
1944
- completeNodeWithPermissionFallback(nodeRun, node, outputs, completed, nodeRun.error, workspaceTarget);
1945
- workflowStore.setRun(run);
1946
- return;
1947
- }
1948
- if (await this.runFallbackAfterFailure(
1949
- node,
1950
- workflow,
1951
- run,
1952
- outputs,
1953
- started,
1954
- completed,
1955
- nodeRun.error,
1956
- 'timeout',
1957
- )) {
1958
- return;
1959
- }
1960
- if (node.onFail === 'continue') {
1961
- completed.add(node.id);
1962
- return;
1963
- }
1964
- throw error;
1965
- }
1966
- nodeRun.finishedAt = Date.now();
1967
- nodeRun.outputText = result.text;
1968
- nodeRun.messages = result.messages;
1969
- nodeRun.artifacts = result.artifacts;
1970
- if (this.isCanceling(run.id)) {
1971
- nodeRun.status = 'canceled';
1972
- workflowStore.setRun(run);
1973
- throw new WorkflowCanceledError();
1974
- }
1975
- if (result.state === 'completed') {
1976
- let outputForContext = result.text;
1977
- if (requiresHandoffArtifact(node)) {
1978
- const handoffParse = parseHandoffArtifact(handoffArtifactSource(result), {
1979
- workflowRunId: run.id,
1980
- nodeId: node.id,
1981
- agentLabel: node.agentLabel,
1982
- stage: node.stage,
1983
- });
1984
- if (!handoffParse.ok) {
1985
- const visibleHandoffError = handoffParse.error.startsWith('Invalid handoff artifact')
1986
- ? handoffParse.error
1987
- : `Invalid handoff artifact: ${handoffParse.error}`;
1988
- nodeRun.status = 'failed';
1989
- nodeRun.error = visibleHandoffError;
1990
- workflowStore.setRun(run);
1991
- if (await this.runFallbackAfterFailure(
1992
- node,
1993
- workflow,
1994
- run,
1995
- outputs,
1996
- started,
1997
- completed,
1998
- visibleHandoffError,
1999
- 'invalid_output',
2000
- )) {
2001
- return;
2002
- }
2003
- if (node.onFail === 'continue') {
2004
- completed.add(node.id);
2005
- return;
2006
- }
2007
- throw new Error(visibleHandoffError);
2008
- }
2009
-
2010
- nodeRun.handoffArtifact = handoffParse.artifact;
2011
- nodeRun.artifacts = [
2012
- ...(nodeRun.artifacts ?? []).filter((artifact) => artifact.type !== 'handoff-artifact'),
2013
- handoffArtifactToWorkflowArtifact(handoffParse.artifact),
2014
- ];
2015
- outputForContext = formatHandoffArtifactForContext(handoffParse.artifact);
2016
- }
2017
-
2018
- outputs.set(node.id, compactOutputForContext(outputForContext));
2019
- completed.add(node.id);
2020
- nodeRun.status = 'completed';
2021
- workflowStore.setRun(run);
2022
- this.maybeAddRepairCycle(node, workflow, run, result);
2023
- return;
2024
- }
2025
- if (result.state === 'canceled') {
2026
- nodeRun.status = 'canceled';
2027
- workflowStore.setRun(run);
2028
- throw new WorkflowCanceledError();
2029
- }
2030
-
2031
- nodeRun.status = 'failed';
2032
- nodeRun.error = result.error ?? `Agent task ended with ${result.state}`;
2033
- workflowStore.setRun(run);
2034
- if (isExternalDirectoryPermissionError(`${nodeRun.error}\n${nodeRun.outputText ?? ''}`)) {
2035
- completeNodeWithPermissionFallback(nodeRun, node, outputs, completed, nodeRun.error, workspaceTarget);
2036
- workflowStore.setRun(run);
2037
- return;
2038
- }
2039
- if (await this.runFallbackAfterFailure(
2040
- node,
2041
- workflow,
2042
- run,
2043
- outputs,
2044
- started,
2045
- completed,
2046
- nodeRun.error,
2047
- classifyWorkflowFailure(`${nodeRun.error}\n${nodeRun.outputText ?? ''}`),
2048
- )) {
2049
- return;
2050
- }
2051
- if (node.onFail === 'continue') {
2052
- if (nodeRun.outputText) {
2053
- outputs.set(node.id, compactOutputForContext(nodeRun.outputText));
2054
- }
2055
- completed.add(node.id);
2056
- return;
2057
- }
2058
- throw new Error(nodeRun.error);
2059
- }
2060
- }
2061
-
2062
- export const workflowRunner = new WorkflowRunner();
1
+ import crypto from 'node:crypto';
2
+
3
+ import type {
4
+ Workflow,
5
+ WorkflowNode,
6
+ WorkflowNodeRun,
7
+ WorkflowRun,
8
+ } from '@/modules/orchestration/workflows/workflow.types.js';
9
+ import {
10
+ PIXCODE_HANDOFF_PROTOCOL,
11
+ formatHandoffArtifactForContext,
12
+ handoffArtifactToWorkflowArtifact,
13
+ parseHandoffArtifact,
14
+ } from '@/modules/orchestration/workflows/handoff-artifact.js';
15
+ import {
16
+ buildWorkflowContextPacket,
17
+ formatContextPacketForPrompt,
18
+ } from '@/modules/orchestration/workflows/context-packet.js';
19
+ import {
20
+ type WorkflowFallbackTrigger,
21
+ classifyWorkflowFailure,
22
+ resolveWorkflowFallbackDecision,
23
+ } from '@/modules/orchestration/workflows/workflow-fallback-policy.js';
24
+ import {
25
+ evaluatePermissionRequest,
26
+ resolvePermissionPolicyFromMetadata,
27
+ type PermissionDecision,
28
+ type PermissionPolicy,
29
+ type PermissionPolicyEvent,
30
+ } from '@/modules/orchestration/security/permission-policy.js';
31
+ import {
32
+ type ResolvedWorkspaceTarget,
33
+ resolveWorkflowWorkspace,
34
+ workspaceContextPrompt,
35
+ workspaceTargetMetadata,
36
+ } from '@/modules/orchestration/workflows/workspace-target.js';
37
+ import { workflowStore } from '@/modules/orchestration/workflows/workflow-store.js';
38
+ import { orchestrationTaskService } from '@/modules/orchestration/tasks/orchestration-task.service.js';
39
+ import {
40
+ cancelA2ATask,
41
+ getA2ATask,
42
+ submitA2ATask,
43
+ } from '@/modules/orchestration/a2a/task-dispatcher.js';
44
+ // @ts-ignore — plain-JS service
45
+ import {
46
+ getDefaultProviderModel,
47
+ getProviderModelRegistryEntry,
48
+ getStaticProviderModels,
49
+ } from '@/services/model-registry.js';
50
+ // @ts-ignore — plain-JS service
51
+ import {
52
+ createNotificationEvent,
53
+ notifyRunFailed,
54
+ notifyRunStopped,
55
+ notifyUserIfEnabled,
56
+ } from '@/services/notification-orchestrator.js';
57
+ // @ts-ignore — plain-JS service
58
+ import { dispatchWebhookEvent } from '@/services/webhooks.js';
59
+
60
+ const TERMINAL = new Set(['completed', 'failed', 'canceled']);
61
+ const SKIPPED = 'skipped';
62
+ const BACKEND_HANDOFF_TIMEOUT_MS = 120_000;
63
+ const MAX_OUTPUT_CONTEXT_CHARS = 12_000;
64
+ const DEFAULT_MAX_REPAIR_CYCLES = 1;
65
+ const MAX_REPAIR_CYCLES = 5;
66
+ const HANDOFF_ARTIFACT_EXAMPLE = [
67
+ '{',
68
+ ' "protocol": "pixcode.handoff.v1",',
69
+ ' "taskStatus": "ready | completed | blocked | failed | needs-review",',
70
+ ' "contextSummary": "Compacted context the next agent needs.",',
71
+ ' "taskResult": "What was decided or completed in this step.",',
72
+ ' "changedFiles": [],',
73
+ ' "blockers": [],',
74
+ ' "risks": [],',
75
+ ' "nextAction": "The requested next action.",',
76
+ ' "nextInstructions": "Specific instructions for the next agent."',
77
+ '}',
78
+ ].join('\n');
79
+ const KNOWN_AGENT_ROLES = [
80
+ 'backend',
81
+ 'frontend',
82
+ 'review',
83
+ 'implementation',
84
+ 'proposal',
85
+ 'critique',
86
+ 'response',
87
+ 'decision',
88
+ 'report',
89
+ ] as const;
90
+
91
+ class WorkflowCanceledError extends Error {
92
+ constructor() {
93
+ super('Workflow canceled.');
94
+ this.name = 'WorkflowCanceledError';
95
+ }
96
+ }
97
+
98
+ class WorkflowNodeTimeoutError extends Error {
99
+ constructor(readonly timeoutMs: number) {
100
+ super(`Workflow node timed out after ${Math.round(timeoutMs / 1000)}s.`);
101
+ this.name = 'WorkflowNodeTimeoutError';
102
+ }
103
+ }
104
+
105
+ function newId(prefix: string): string {
106
+ return `${prefix}_${crypto.randomBytes(8).toString('hex')}`;
107
+ }
108
+
109
+ function validateWorkflow(workflow: Workflow): void {
110
+ if (workflow.nodes.length > 64) {
111
+ throw new Error('Workflow node limit exceeded.');
112
+ }
113
+ const ids = new Set(workflow.nodes.map((node) => node.id));
114
+ for (const node of workflow.nodes) {
115
+ for (const input of node.inputs) {
116
+ if (!ids.has(input)) {
117
+ throw new Error(`Workflow node ${node.id} references missing input ${input}.`);
118
+ }
119
+ }
120
+ }
121
+ }
122
+
123
+ type TaskResult = {
124
+ state: string;
125
+ text: string;
126
+ error?: string;
127
+ messages: Array<{ role: string; text: string }>;
128
+ artifacts: Array<{
129
+ type: string;
130
+ text?: string;
131
+ data?: Record<string, unknown>;
132
+ metadata?: Record<string, unknown>;
133
+ }>;
134
+ };
135
+
136
+ type RawTask = {
137
+ id: string;
138
+ state?: string;
139
+ error?: { code?: string; message?: string };
140
+ history?: Array<{ role?: string; parts?: Array<{ kind?: string; text?: string; data?: Record<string, unknown> }> }>;
141
+ artifacts?: Array<{
142
+ type?: string;
143
+ parts?: Array<{ kind?: string; text?: string; data?: Record<string, unknown> }>;
144
+ metadata?: Record<string, unknown>;
145
+ }>;
146
+ };
147
+
148
+ type AgentAssignment = {
149
+ instanceId: string;
150
+ adapterId: string;
151
+ label: string;
152
+ role?: AgentRole;
153
+ instruction?: string;
154
+ model?: string;
155
+ permissionMode?: string;
156
+ toolsSettings?: Record<string, unknown>;
157
+ order: number;
158
+ };
159
+
160
+ type KnownAgentRole = typeof KNOWN_AGENT_ROLES[number];
161
+ type AgentRole = string;
162
+ type ProviderId = 'claude' | 'cursor' | 'codex' | 'gemini' | 'qwen' | 'opencode';
163
+ type ProviderModel = {
164
+ value: string;
165
+ label?: string;
166
+ source?: 'static' | 'api';
167
+ free?: boolean;
168
+ };
169
+ type RunStoppedNotifier = (payload: {
170
+ userId: string | number;
171
+ provider: string;
172
+ sessionId?: string | null;
173
+ stopReason?: string;
174
+ sessionName?: string | null;
175
+ }) => void;
176
+ type RunFailedNotifier = (payload: {
177
+ userId: string | number;
178
+ provider: string;
179
+ sessionId?: string | null;
180
+ error: unknown;
181
+ sessionName?: string | null;
182
+ }) => void;
183
+
184
+ const sendRunStoppedNotification = notifyRunStopped as RunStoppedNotifier;
185
+ const sendRunFailedNotification = notifyRunFailed as RunFailedNotifier;
186
+
187
+ const adapterProviderMap: Record<string, ProviderId | undefined> = {
188
+ 'claude-code': 'claude',
189
+ cursor: 'cursor',
190
+ codex: 'codex',
191
+ gemini: 'gemini',
192
+ qwen: 'qwen',
193
+ opencode: 'opencode',
194
+ };
195
+
196
+ function readAgentRole(value: unknown): AgentRole | undefined {
197
+ return typeof value === 'string' && value.trim() && value.trim() !== 'auto'
198
+ ? value.trim()
199
+ : undefined;
200
+ }
201
+
202
+ function isKnownAgentRole(value: string | undefined): value is KnownAgentRole {
203
+ return Boolean(value && (KNOWN_AGENT_ROLES as readonly string[]).includes(value));
204
+ }
205
+
206
+ function getMetadataRecord(metadata: Record<string, unknown> | undefined, key: string): Record<string, unknown> {
207
+ return readRecord(metadata?.[key]) ?? {};
208
+ }
209
+
210
+ function readRecord(value: unknown): Record<string, unknown> | undefined {
211
+ return value && typeof value === 'object' ? value as Record<string, unknown> : undefined;
212
+ }
213
+
214
+ function readString(value: unknown): string | undefined {
215
+ return typeof value === 'string' && value.trim() ? value : undefined;
216
+ }
217
+
218
+ function readNotificationUserId(metadata?: Record<string, unknown>): string | number | null {
219
+ const value = metadata?.userId;
220
+ return typeof value === 'string' || typeof value === 'number' ? value : null;
221
+ }
222
+
223
+ function workflowNotificationTitle(run: WorkflowRun): string {
224
+ return readString(run.metadata?.workflowName) ?? run.workflowId;
225
+ }
226
+
227
+ function notifyWorkflowRunFinished(run: WorkflowRun): void {
228
+ const userId = readNotificationUserId(run.metadata);
229
+ if (!userId) return;
230
+
231
+ if (run.status === 'completed') {
232
+ sendRunStoppedNotification({
233
+ userId,
234
+ provider: 'system',
235
+ sessionId: run.id,
236
+ sessionName: workflowNotificationTitle(run),
237
+ stopReason: 'Orchestration completed',
238
+ });
239
+ return;
240
+ }
241
+
242
+ if (run.status === 'canceled') {
243
+ sendRunStoppedNotification({
244
+ userId,
245
+ provider: 'system',
246
+ sessionId: run.id,
247
+ sessionName: workflowNotificationTitle(run),
248
+ stopReason: 'Orchestration canceled',
249
+ });
250
+ return;
251
+ }
252
+
253
+ if (run.status === 'failed') {
254
+ sendRunFailedNotification({
255
+ userId,
256
+ provider: 'system',
257
+ sessionId: run.id,
258
+ sessionName: workflowNotificationTitle(run),
259
+ error: readString(run.metadata?.error) ?? 'Orchestration failed',
260
+ });
261
+ }
262
+ }
263
+
264
+ function permissionPolicyFromRun(run: WorkflowRun): PermissionPolicy {
265
+ return resolvePermissionPolicyFromMetadata(run.metadata);
266
+ }
267
+
268
+ function permissionPolicyEvents(run: WorkflowRun): PermissionPolicyEvent[] {
269
+ return Array.isArray(run.metadata?.permissionPolicyEvents)
270
+ ? run.metadata.permissionPolicyEvents.filter((event): event is PermissionPolicyEvent =>
271
+ Boolean(event && typeof event === 'object'),
272
+ )
273
+ : [];
274
+ }
275
+
276
+ function permissionApprovalRequests(run: WorkflowRun): Array<Record<string, unknown>> {
277
+ return Array.isArray(run.metadata?.pendingPermissionApprovals)
278
+ ? run.metadata.pendingPermissionApprovals.filter((event): event is Record<string, unknown> =>
279
+ Boolean(event && typeof event === 'object'),
280
+ )
281
+ : [];
282
+ }
283
+
284
+ function notifyPermissionApprovalRequested(run: WorkflowRun, decision: PermissionDecision): void {
285
+ const userId = readNotificationUserId(run.metadata);
286
+ if (!userId || !decision.approvalRequest) return;
287
+
288
+ const event = (createNotificationEvent as unknown as (payload: Record<string, unknown>) => unknown)({
289
+ provider: 'system',
290
+ sessionId: run.id,
291
+ kind: 'action_required',
292
+ code: 'permission.required',
293
+ meta: {
294
+ toolName: decision.capabilities.join(', '),
295
+ sessionName: workflowNotificationTitle(run),
296
+ },
297
+ severity: 'warning',
298
+ requiresUserAction: true,
299
+ dedupeKey: `workflow:permission:${run.id}:${decision.requestId}`,
300
+ });
301
+ (notifyUserIfEnabled as (payload: { userId: string | number; event: unknown }) => void)({
302
+ userId,
303
+ event,
304
+ });
305
+ }
306
+
307
+ function readBoolean(value: unknown): boolean | undefined {
308
+ return typeof value === 'boolean' ? value : undefined;
309
+ }
310
+
311
+ function modelValueSet(models: ProviderModel[]): Set<string> {
312
+ return new Set(models.map((model) => model.value).filter(Boolean));
313
+ }
314
+
315
+ function preferredFallbackModel(models: ProviderModel[], defaultModel?: string): string | undefined {
316
+ const values = modelValueSet(models);
317
+ if (defaultModel && values.has(defaultModel)) return defaultModel;
318
+ return models.find((model) => model.source === 'api' && model.free)?.value
319
+ ?? models.find((model) => model.source === 'api')?.value
320
+ ?? models.find((model) => model.free)?.value
321
+ ?? models[0]?.value
322
+ ?? defaultModel;
323
+ }
324
+
325
+ async function resolveWorkflowModel(adapterId: string, requestedModel?: string): Promise<string | undefined> {
326
+ const provider = adapterProviderMap[adapterId];
327
+ if (!provider) return requestedModel;
328
+
329
+ const defaultModel = getDefaultProviderModel(provider);
330
+ if (!requestedModel) return defaultModel;
331
+
332
+ try {
333
+ const result = await getProviderModelRegistryEntry(provider);
334
+ const models = Array.isArray(result?.models) ? result.models as ProviderModel[] : [];
335
+ if (modelValueSet(models).has(requestedModel)) {
336
+ return requestedModel;
337
+ }
338
+ return preferredFallbackModel(models, defaultModel) ?? requestedModel;
339
+ } catch {
340
+ const staticModels = getStaticProviderModels(provider) as ProviderModel[];
341
+ const staticValues = modelValueSet(staticModels);
342
+ return staticValues.has(requestedModel)
343
+ ? requestedModel
344
+ : preferredFallbackModel(staticModels, defaultModel) ?? requestedModel;
345
+ }
346
+ }
347
+
348
+ function readIsolation(value: unknown): 'host' | 'worktree' | 'docker' | undefined {
349
+ return value === 'host' || value === 'worktree' || value === 'docker' ? value : undefined;
350
+ }
351
+
352
+ function readLegacyEnabledAdapters(metadata?: Record<string, unknown>): string[] {
353
+ return Array.isArray(metadata?.enabledAdapters)
354
+ ? metadata.enabledAdapters.filter((value): value is string => typeof value === 'string' && value.trim().length > 0)
355
+ : [];
356
+ }
357
+
358
+ function readMetadataAgents(metadata?: Record<string, unknown>): AgentAssignment[] {
359
+ if (!Array.isArray(metadata?.agents)) return [];
360
+
361
+ return metadata.agents
362
+ .map((value, index): AgentAssignment | null => {
363
+ if (!value || typeof value !== 'object') return null;
364
+ const record = value as Record<string, unknown>;
365
+ const adapterId = readString(record.adapterId);
366
+ if (!adapterId) return null;
367
+ if (readBoolean(record.enabled) === false) return null;
368
+
369
+ return {
370
+ instanceId: readString(record.instanceId) ?? `${adapterId}-${index + 1}`,
371
+ adapterId,
372
+ label: readString(record.label) ?? `${adapterId} #${index + 1}`,
373
+ role: readAgentRole(record.role),
374
+ instruction: readString(record.instruction),
375
+ model: readString(record.model),
376
+ permissionMode: readString(record.permissionMode),
377
+ toolsSettings: readRecord(record.toolsSettings),
378
+ order: index,
379
+ };
380
+ })
381
+ .filter((value): value is AgentAssignment => Boolean(value))
382
+ .slice(0, 16);
383
+ }
384
+
385
+ function readAgentAssignments(metadata?: Record<string, unknown>): AgentAssignment[] {
386
+ const agents = readMetadataAgents(metadata);
387
+ if (agents.length > 0) return agents;
388
+
389
+ return readLegacyEnabledAdapters(metadata).map((adapterId, index) => ({
390
+ instanceId: `${adapterId}-${index + 1}`,
391
+ adapterId,
392
+ label: `${adapterId} #${index + 1}`,
393
+ order: index,
394
+ }));
395
+ }
396
+
397
+ function readEnabledAdapters(metadata?: Record<string, unknown>): string[] {
398
+ return [...new Set(readAgentAssignments(metadata).map((agent) => agent.adapterId))];
399
+ }
400
+
401
+ function readMaxParallelAgents(metadata?: Record<string, unknown>): number {
402
+ const settings = getMetadataRecord(metadata, 'settings');
403
+ const value = settings.maxParallelAgents;
404
+ return typeof value === 'number' && Number.isFinite(value)
405
+ ? Math.max(1, Math.min(12, Math.round(value)))
406
+ : 3;
407
+ }
408
+
409
+ function readMaxRepairCycles(metadata?: Record<string, unknown>): number {
410
+ const settings = getMetadataRecord(metadata, 'settings');
411
+ const value = settings.maxRepairCycles;
412
+ return typeof value === 'number' && Number.isFinite(value)
413
+ ? Math.max(0, Math.min(MAX_REPAIR_CYCLES, Math.round(value)))
414
+ : DEFAULT_MAX_REPAIR_CYCLES;
415
+ }
416
+
417
+ function safeNodeId(adapterId: string, suffix: string): string {
418
+ return `${adapterId.replace(/[^a-zA-Z0-9_]+/g, '_')}_${suffix}`;
419
+ }
420
+
421
+ function safeAgentNodeId(agent: AgentAssignment, index: number, suffix: string): string {
422
+ return `agent_${index + 1}_${safeNodeId(agent.adapterId, suffix)}`;
423
+ }
424
+
425
+ function agentRoster(agents: AgentAssignment[]): string {
426
+ return agents
427
+ .map((agent, index) => {
428
+ const instruction = agent.instruction
429
+ ? `\n User assignment: ${agent.instruction}`
430
+ : '';
431
+ const role = agent.role ? `\n API role: ${agent.role}` : '';
432
+ return `${index + 1}. ${agent.label} (${agent.adapterId})${role}${instruction}`;
433
+ })
434
+ .join('\n');
435
+ }
436
+
437
+ function inferAgentRole(agent: AgentAssignment): AgentRole {
438
+ if (isKnownAgentRole(agent.role)) return agent.role;
439
+
440
+ const text = `${agent.label} ${agent.adapterId} ${agent.role ?? ''} ${agent.instruction ?? ''}`.toLocaleLowerCase('tr');
441
+ if (/(test|tester|qa|review|code review|hata|kontrol|onay|incele|doğrula|dogrula)/u.test(text)) {
442
+ return 'review';
443
+ }
444
+ if (/(backend|back-end|api|server|veri|database|db|fapi|endpoint|websocket|ws)/u.test(text)) {
445
+ return 'backend';
446
+ }
447
+ if (/(frontend|front-end|ui|ux|tailwind|tasarım|tasarim|design|chart|tradingview|arayüz|arayuz)/u.test(text)) {
448
+ return 'frontend';
449
+ }
450
+ return 'implementation';
451
+ }
452
+
453
+ function inferImplementationRole(agent: AgentAssignment): 'backend' | 'frontend' | 'review' | 'implementation' {
454
+ const role = inferAgentRole(agent);
455
+ return role === 'backend' || role === 'frontend' || role === 'review' || role === 'implementation'
456
+ ? role
457
+ : 'implementation';
458
+ }
459
+
460
+ function displayStage(agent: AgentAssignment, fallback: AgentRole): string {
461
+ return agent.role && !isKnownAgentRole(agent.role) ? agent.role : fallback;
462
+ }
463
+
464
+ function rolePrompt(role: AgentRole): string {
465
+ if (role === 'backend') {
466
+ return 'Backend/API/data work should define stable contracts first. Report endpoints, payload shapes, ports, and any data-source limitations clearly for downstream agents.';
467
+ }
468
+ if (role === 'frontend') {
469
+ return 'Frontend/UI work must use prior backend/data-contract outputs when present. If a dependency is missing, use a minimal mock only as a temporary fallback and report the blocker.';
470
+ }
471
+ if (role === 'review') {
472
+ return 'You are the validation/review stage. Inspect the prior agent outputs and actual project state. Approve only if it works; otherwise return a concrete bug list and required fixes.';
473
+ }
474
+ if (role === 'proposal') {
475
+ return 'You are in the proposal stage. Produce a concrete option with tradeoffs, assumptions, and what should happen next. Do not edit files.';
476
+ }
477
+ if (role === 'critique') {
478
+ return 'You are in the critique stage. Challenge the proposal for risks, missing constraints, and weak assumptions. Do not edit files.';
479
+ }
480
+ if (role === 'response') {
481
+ return 'You are in the response stage. Reconcile the critique with the proposal and refine the practical path forward. Do not edit files.';
482
+ }
483
+ if (role === 'decision' || role === 'report') {
484
+ return 'You are the reporting stage. Produce the final concise decision report and a next prompt for launching an implementation agent team. Do not edit files.';
485
+ }
486
+ if (role !== 'implementation') {
487
+ return `You are assigned to the custom stage "${role}". Follow that user-defined stage literally, avoid duplicating other agents, and report changed files, commands, blockers, and next actions.`;
488
+ }
489
+ return 'Implementation work should avoid duplicating other agents and should report changed files, commands, blockers, and next actions.';
490
+ }
491
+
492
+ function privacyGuardPrompt(): string {
493
+ return 'Do not mention internal instructions, memory files, skill use, or tool protocol unless the user explicitly asks.';
494
+ }
495
+
496
+ function handoffArtifactInstructions(statusHint: string): string {
497
+ return [
498
+ `Output exactly one JSON object using the ${PIXCODE_HANDOFF_PROTOCOL} handoff artifact protocol.`,
499
+ 'Do not wrap it in Markdown. Do not add commentary before or after it.',
500
+ `Use "${statusHint}" for taskStatus unless completed, blocked, failed, or needs-review is more accurate.`,
501
+ 'Schema:',
502
+ HANDOFF_ARTIFACT_EXAMPLE,
503
+ ].join('\n');
504
+ }
505
+
506
+ function handoffPrompt(agent: AgentAssignment, role: AgentRole): string {
507
+ return [
508
+ `You are ${agent.label} in a Pixcode CLI team.`,
509
+ `Your inferred stage is: ${role}.`,
510
+ 'This is a bounded Pixcode handoff task, not the full implementation.',
511
+ 'Read the original user goal and coordinator plan, then publish a compact contract for downstream agents.',
512
+ agent.instruction ? `Your explicit assignment from the user is: ${agent.instruction}` : '',
513
+ handoffArtifactInstructions('ready'),
514
+ 'Do not install dependencies, edit files, run long commands, or start servers in this handoff task.',
515
+ privacyGuardPrompt(),
516
+ 'Stop after the contract. Keep it concise and respond in the same language as the user request.',
517
+ ].filter(Boolean).join('\n');
518
+ }
519
+
520
+ function handoffInitPrompt(agent: AgentAssignment, index: number): string {
521
+ return [
522
+ `You are preparing ${agent.label} for a strict Pixcode handoff chain.`,
523
+ `This is internal step ${index + 1}.`,
524
+ 'Create a compact init packet for the next visible work step.',
525
+ 'Use the original user goal and any prior compact handoff packet included above.',
526
+ agent.instruction ? `The explicit assignment for this agent is: ${agent.instruction}` : '',
527
+ handoffArtifactInstructions('ready'),
528
+ privacyGuardPrompt(),
529
+ 'Do not perform the task yet. Do not mention that this is hidden from the user.',
530
+ 'Respond in the same language as the user request.',
531
+ ].filter(Boolean).join('\n');
532
+ }
533
+
534
+ function handoffWorkPrompt(agent: AgentAssignment, index: number): string {
535
+ return [
536
+ `You are ${agent.label} in a strict Pixcode handoff chain.`,
537
+ `This is visible work step ${index + 1}.`,
538
+ 'The internal init packet above is your starting context. Do the assigned work now.',
539
+ agent.instruction
540
+ ? `Your explicit assignment from the user is: ${agent.instruction}`
541
+ : 'Use the init packet and original user goal to choose the next useful work for this step.',
542
+ rolePrompt(agent.role ?? 'implementation'),
543
+ privacyGuardPrompt(),
544
+ 'Report only user-facing progress, changed files, commands, verification, blockers, and next actions.',
545
+ 'Respond in the same language as the user request.',
546
+ ].filter(Boolean).join('\n');
547
+ }
548
+
549
+ function handoffCompactPrompt(agent: AgentAssignment, index: number): string {
550
+ return [
551
+ `You are compacting ${agent.label}'s strict handoff output for the next Pixcode agent.`,
552
+ `This is internal compact step ${index + 1}.`,
553
+ 'Read the prior visible work output included above and create a compact handoff packet.',
554
+ handoffArtifactInstructions('completed'),
555
+ privacyGuardPrompt(),
556
+ 'Do not include raw logs unless they are essential. Keep it concise and actionable.',
557
+ 'Respond in the same language as the user request.',
558
+ ].join('\n');
559
+ }
560
+
561
+ function compactOutputForContext(text: string): string {
562
+ if (text.length <= MAX_OUTPUT_CONTEXT_CHARS) {
563
+ return text;
564
+ }
565
+
566
+ const edge = Math.floor(MAX_OUTPUT_CONTEXT_CHARS / 2);
567
+ return [
568
+ text.slice(0, edge),
569
+ `\n\n[...${text.length - MAX_OUTPUT_CONTEXT_CHARS} characters omitted from prior agent output...]\n\n`,
570
+ text.slice(-edge),
571
+ ].join('');
572
+ }
573
+
574
+ function requiresHandoffArtifact(node: WorkflowNode): boolean {
575
+ return node.stage === 'handoff' || node.stage === 'handoff_init' || node.stage === 'handoff_compact';
576
+ }
577
+
578
+ function handoffArtifactSource(result: TaskResult): string {
579
+ const structured = result.artifacts.find((artifact) => artifact.type === 'handoff-artifact' && artifact.data);
580
+ if (structured?.data) {
581
+ return JSON.stringify(structured.data);
582
+ }
583
+ return result.text;
584
+ }
585
+
586
+ function isExternalDirectoryPermissionError(value: unknown): boolean {
587
+ const text = String(value ?? '').toLocaleLowerCase('en');
588
+ return (
589
+ text.includes('external_directory') ||
590
+ /permission requested:.*auto-rejecting/u.test(text) ||
591
+ /auto-rejecting.*permission/u.test(text) ||
592
+ /outside (the )?(workspace|working directory)/u.test(text) ||
593
+ /permission.*external/u.test(text)
594
+ );
595
+ }
596
+
597
+ function isFinalReportNode(node: WorkflowNode): boolean {
598
+ return node.id === 'final_report' || node.stage === 'final_report' || node.stage === 'report';
599
+ }
600
+
601
+ function workspaceNeedsHostPermissionBypass(target: ResolvedWorkspaceTarget): boolean {
602
+ return (target.kind === 'selected_project' || target.kind === 'custom') && target.projectPath !== target.appRoot;
603
+ }
604
+
605
+ function resolveNodePermissionMode(node: WorkflowNode, target: ResolvedWorkspaceTarget): string | undefined {
606
+ if (node.permissionMode && node.permissionMode !== 'default') {
607
+ return node.permissionMode;
608
+ }
609
+
610
+ if (workspaceNeedsHostPermissionBypass(target)) {
611
+ return 'bypassPermissions';
612
+ }
613
+
614
+ return node.permissionMode;
615
+ }
616
+
617
+ function buildPermissionFallbackOutput(
618
+ node: WorkflowNode,
619
+ reason: string,
620
+ target: ResolvedWorkspaceTarget,
621
+ ): string {
622
+ return [
623
+ 'Bu adım çalışma alanı izin sınırına takıldı.',
624
+ '',
625
+ `Ajan: ${node.agentLabel || node.id}`,
626
+ `Hedef çalışma alanı: ${target.projectPath}`,
627
+ `Hata: ${reason}`,
628
+ '',
629
+ 'Pixcode bu adımı workflow dışına taşırmadan devam ettirdi. Ajan aynı dış dizin yoluna tekrar tekrar erişmek yerine mevcut bağlamla ilerlemeli.',
630
+ ].join('\n');
631
+ }
632
+
633
+ function buildFallbackFinalReport(
634
+ outputs: Map<string, string>,
635
+ reason: string,
636
+ target: ResolvedWorkspaceTarget,
637
+ ): string {
638
+ const completedOutputs = [...outputs.entries()]
639
+ .map(([nodeId, output]) => [`## ${nodeId}`, output || '(çıktı yok)'].join('\n'))
640
+ .join('\n\n');
641
+
642
+ return [
643
+ 'Final rapor aracı çalışma alanı izin sınırına takıldı, bu yüzden Pixcode tamamlanan ajan çıktılarından güvenli bir özet üretti.',
644
+ '',
645
+ `Hedef çalışma alanı: ${target.projectPath}`,
646
+ `İzin hatası: ${reason}`,
647
+ '',
648
+ completedOutputs || 'Bu turda final rapora aktarılabilecek tamamlanmış ajan çıktısı yok.',
649
+ ].join('\n');
650
+ }
651
+
652
+ function completeNodeWithPermissionFallback(
653
+ nodeRun: WorkflowNodeRun,
654
+ node: WorkflowNode,
655
+ outputs: Map<string, string>,
656
+ completed: Set<string>,
657
+ reason: string,
658
+ target: ResolvedWorkspaceTarget,
659
+ ): void {
660
+ const outputText = isFinalReportNode(node)
661
+ ? buildFallbackFinalReport(outputs, reason, target)
662
+ : buildPermissionFallbackOutput(node, reason, target);
663
+
664
+ nodeRun.status = 'completed';
665
+ nodeRun.error = reason;
666
+ nodeRun.outputText = outputText;
667
+ nodeRun.finishedAt = nodeRun.finishedAt ?? Date.now();
668
+ outputs.set(node.id, compactOutputForContext(outputText));
669
+ completed.add(node.id);
670
+ }
671
+
672
+ function expandAgentTeamWorkflow(workflow: Workflow, metadata?: Record<string, unknown>): Workflow {
673
+ const agents = readAgentAssignments(metadata);
674
+ if (agents.length === 0) {
675
+ throw new Error('Select at least one CLI agent.');
676
+ }
677
+
678
+ const coordinator = agents.find((agent) => agent.adapterId === 'claude-code') ?? agents[0];
679
+ const roster = agentRoster(agents);
680
+ const workerSpecs = agents.map((agent, index) => ({
681
+ agent,
682
+ role: inferImplementationRole(agent),
683
+ stage: displayStage(agent, inferImplementationRole(agent)),
684
+ nodeId: safeAgentNodeId(agent, index, 'work'),
685
+ handoffNodeId: safeAgentNodeId(agent, index, 'handoff'),
686
+ }));
687
+ const backendHandoffNodeIds = workerSpecs
688
+ .filter((spec) => spec.role === 'backend')
689
+ .map((spec) => spec.handoffNodeId);
690
+ const implementationNodeIds = workerSpecs
691
+ .filter((spec) => spec.role !== 'review')
692
+ .map((spec) => spec.nodeId);
693
+ const handoffNodes: WorkflowNode[] = workerSpecs
694
+ .filter((spec) => spec.role === 'backend')
695
+ .map(({ agent, role, handoffNodeId }) => ({
696
+ id: handoffNodeId,
697
+ adapterId: agent.adapterId,
698
+ agentInstanceId: agent.instanceId,
699
+ agentLabel: `${agent.label} Handoff`,
700
+ assignment: agent.instruction,
701
+ stage: 'handoff',
702
+ model: agent.model,
703
+ permissionMode: agent.permissionMode,
704
+ toolsSettings: agent.toolsSettings,
705
+ prompt: handoffPrompt(agent, role),
706
+ inputs: ['coordinator'],
707
+ output: 'message',
708
+ onFail: 'continue',
709
+ timeoutMs: BACKEND_HANDOFF_TIMEOUT_MS,
710
+ }));
711
+ const workerNodes: WorkflowNode[] = workerSpecs.map(({ agent, role, stage, nodeId, handoffNodeId }) => {
712
+ const inputs = role === 'review'
713
+ ? (implementationNodeIds.length > 0 ? implementationNodeIds : ['coordinator'])
714
+ : role === 'frontend' && backendHandoffNodeIds.length > 0
715
+ ? ['coordinator', ...backendHandoffNodeIds]
716
+ : role === 'backend'
717
+ ? ['coordinator', handoffNodeId]
718
+ : ['coordinator'];
719
+
720
+ return {
721
+ id: nodeId,
722
+ adapterId: agent.adapterId,
723
+ agentInstanceId: agent.instanceId,
724
+ agentLabel: agent.label,
725
+ assignment: agent.instruction,
726
+ stage,
727
+ model: agent.model,
728
+ permissionMode: agent.permissionMode,
729
+ toolsSettings: agent.toolsSettings,
730
+ prompt: [
731
+ `You are ${agent.label} in a Pixcode CLI team.`,
732
+ `Your stage is: ${stage}.`,
733
+ stage !== role ? `Runtime routing category: ${role}.` : '',
734
+ 'The coordinator plan and any dependency outputs are included above. Use them together with the original user goal.',
735
+ agent.instruction
736
+ ? `Your explicit assignment from the user is: ${agent.instruction}`
737
+ : 'No fixed per-agent assignment was set. Take the part assigned to you by the coordinator; if none is named, choose useful work that fits this CLI.',
738
+ rolePrompt(stage),
739
+ privacyGuardPrompt(),
740
+ 'Respond in the same language as the user request.',
741
+ ].filter(Boolean).join('\n'),
742
+ inputs,
743
+ output: 'both',
744
+ onFail: 'continue',
745
+ };
746
+ });
747
+
748
+ return {
749
+ ...workflow,
750
+ nodes: [
751
+ {
752
+ id: 'coordinator',
753
+ adapterId: coordinator.adapterId,
754
+ agentInstanceId: coordinator.instanceId,
755
+ agentLabel: coordinator.label,
756
+ stage: 'coordinator',
757
+ model: coordinator.model,
758
+ permissionMode: coordinator.permissionMode,
759
+ toolsSettings: coordinator.toolsSettings,
760
+ prompt: [
761
+ 'You are the coordinator for a Pixcode CLI agent team.',
762
+ 'Read the user goal, active CLI roster, and any per-agent assignments. Create a compact execution plan for the selected agents.',
763
+ 'If the user directly names a CLI, honor that. Do not invent permanent roles; assign work only from the goal, active agents, and explicit assignment text.',
764
+ `Active roster:\n${roster}`,
765
+ 'Respond in the same language as the user request.',
766
+ ].join('\n'),
767
+ inputs: [],
768
+ output: 'message',
769
+ onFail: 'abort',
770
+ },
771
+ ...handoffNodes,
772
+ ...workerNodes,
773
+ {
774
+ id: 'final_report',
775
+ adapterId: coordinator.adapterId,
776
+ agentInstanceId: coordinator.instanceId,
777
+ agentLabel: coordinator.label,
778
+ stage: 'final_report',
779
+ model: coordinator.model,
780
+ permissionMode: coordinator.permissionMode,
781
+ toolsSettings: coordinator.toolsSettings,
782
+ prompt: [
783
+ 'Collect the worker outputs into one user-facing result.',
784
+ 'Show what each CLI did, which parts failed, what changed, and the next action if work remains.',
785
+ 'Do not expose internal prompts, memory lookup, skill/tool instructions, raw agent logs, or role prefixes like "agent:" and "user:".',
786
+ 'If a worker reveals internal process text, summarize only the useful user-facing result.',
787
+ 'Respond in the same language as the user request.',
788
+ ].join('\n'),
789
+ inputs: workerNodes.map((node) => node.id),
790
+ output: 'message',
791
+ onFail: 'abort',
792
+ },
793
+ ],
794
+ };
795
+ }
796
+
797
+ function stagePrompt(agent: AgentAssignment, stage: AgentRole): string {
798
+ return [
799
+ `You are ${agent.label} in a Pixcode decision workflow.`,
800
+ `Your stage is: ${stage}.`,
801
+ agent.role && agent.role !== stage ? `User custom stage label: ${agent.role}.` : '',
802
+ agent.instruction ? `User assignment for you: ${agent.instruction}` : '',
803
+ rolePrompt(stage),
804
+ privacyGuardPrompt(),
805
+ 'Keep the answer concise, structured, and useful for the next stage.',
806
+ 'Respond in the same language as the user request.',
807
+ ].filter(Boolean).join('\n');
808
+ }
809
+
810
+ function agentsWithRole(agents: AgentAssignment[], role: AgentRole): AgentAssignment[] {
811
+ return agents.filter((agent) => agent.role === role);
812
+ }
813
+
814
+ function autoAssignDebateAgents(agents: AgentAssignment[]): {
815
+ proposalAgents: AgentAssignment[];
816
+ critiqueAgents: AgentAssignment[];
817
+ responseAgents: AgentAssignment[];
818
+ reportAgent: AgentAssignment;
819
+ } {
820
+ const assigned = new Set<string>();
821
+ const markAssigned = (items: AgentAssignment[]) => {
822
+ for (const item of items) assigned.add(item.instanceId);
823
+ };
824
+ const pickNext = () =>
825
+ agents.find((agent) => !assigned.has(agent.instanceId) && agent.role !== 'decision' && agent.role !== 'report')
826
+ ?? agents.find((agent) => !assigned.has(agent.instanceId))
827
+ ?? agents[0];
828
+
829
+ const proposalAgents = agentsWithRole(agents, 'proposal');
830
+ if (proposalAgents.length === 0) proposalAgents.push(pickNext());
831
+ markAssigned(proposalAgents);
832
+
833
+ const critiqueAgents = agentsWithRole(agents, 'critique');
834
+ if (critiqueAgents.length === 0) critiqueAgents.push(pickNext());
835
+ markAssigned(critiqueAgents);
836
+
837
+ const responseAgents = agentsWithRole(agents, 'response');
838
+ if (responseAgents.length === 0 && agents.length > 2) {
839
+ responseAgents.push(...agents.filter((agent) =>
840
+ !assigned.has(agent.instanceId) && agent.role !== 'decision' && agent.role !== 'report',
841
+ ));
842
+ }
843
+ markAssigned(responseAgents);
844
+
845
+ const reportAgent = agentsWithRole(agents, 'decision')[0]
846
+ ?? agentsWithRole(agents, 'report')[0]
847
+ ?? agents[0];
848
+
849
+ return { proposalAgents, critiqueAgents, responseAgents, reportAgent };
850
+ }
851
+
852
+ function expandAdversarialDebateWorkflow(workflow: Workflow, metadata?: Record<string, unknown>): Workflow {
853
+ const agents = readAgentAssignments(metadata);
854
+ if (agents.length === 0) {
855
+ throw new Error('Select at least one CLI agent.');
856
+ }
857
+
858
+ const {
859
+ proposalAgents,
860
+ critiqueAgents,
861
+ responseAgents,
862
+ reportAgent,
863
+ } = autoAssignDebateAgents(agents);
864
+
865
+ const proposalNodes: WorkflowNode[] = proposalAgents.map((agent, index) => ({
866
+ id: safeAgentNodeId(agent, index, 'proposal'),
867
+ adapterId: agent.adapterId,
868
+ agentInstanceId: agent.instanceId,
869
+ agentLabel: agent.label,
870
+ assignment: agent.instruction || 'Proposal stage',
871
+ stage: 'proposal',
872
+ model: agent.model,
873
+ permissionMode: agent.permissionMode,
874
+ toolsSettings: agent.toolsSettings,
875
+ prompt: stagePrompt(agent, 'proposal'),
876
+ inputs: [],
877
+ output: 'message',
878
+ onFail: 'continue',
879
+ }));
880
+ const critiqueNodes: WorkflowNode[] = critiqueAgents.map((agent, index) => ({
881
+ id: safeAgentNodeId(agent, index, 'critique'),
882
+ adapterId: agent.adapterId,
883
+ agentInstanceId: agent.instanceId,
884
+ agentLabel: agent.label,
885
+ assignment: agent.instruction || 'Critique stage',
886
+ stage: 'critique',
887
+ model: agent.model,
888
+ permissionMode: agent.permissionMode,
889
+ toolsSettings: agent.toolsSettings,
890
+ prompt: stagePrompt(agent, 'critique'),
891
+ inputs: proposalNodes.map((node) => node.id),
892
+ output: 'message',
893
+ onFail: 'continue',
894
+ }));
895
+ const responseNodes: WorkflowNode[] = responseAgents.map((agent, index) => ({
896
+ id: safeAgentNodeId(agent, index, 'response'),
897
+ adapterId: agent.adapterId,
898
+ agentInstanceId: agent.instanceId,
899
+ agentLabel: agent.label,
900
+ assignment: agent.instruction || 'Response stage',
901
+ stage: 'response',
902
+ model: agent.model,
903
+ permissionMode: agent.permissionMode,
904
+ toolsSettings: agent.toolsSettings,
905
+ prompt: stagePrompt(agent, 'response'),
906
+ inputs: critiqueNodes.map((node) => node.id),
907
+ output: 'message',
908
+ onFail: 'continue',
909
+ }));
910
+ const finalInputs = responseNodes.length > 0
911
+ ? responseNodes.map((node) => node.id)
912
+ : critiqueNodes.map((node) => node.id);
913
+
914
+ return {
915
+ ...workflow,
916
+ nodes: [
917
+ ...proposalNodes,
918
+ ...critiqueNodes,
919
+ ...responseNodes,
920
+ {
921
+ id: 'final_report',
922
+ adapterId: reportAgent.adapterId,
923
+ agentInstanceId: reportAgent.instanceId,
924
+ agentLabel: reportAgent.label,
925
+ assignment: reportAgent.instruction || 'Final decision report',
926
+ stage: 'final_report',
927
+ model: reportAgent.model,
928
+ permissionMode: reportAgent.permissionMode,
929
+ toolsSettings: reportAgent.toolsSettings,
930
+ prompt: [
931
+ 'Produce the final decision report from the debate.',
932
+ 'Use this exact structure:',
933
+ '1. Short decision',
934
+ '2. Why',
935
+ '3. Risks',
936
+ '4. Suggested next prompt',
937
+ '5. Proposed agent team and assignments',
938
+ 'The next prompt should be ready to paste into Pixcode Agent Team mode.',
939
+ 'Do not edit files. Respond in the same language as the user request.',
940
+ ].join('\n'),
941
+ inputs: finalInputs,
942
+ output: 'message',
943
+ onFail: 'abort',
944
+ },
945
+ ],
946
+ };
947
+ }
948
+
949
+ function expandSequentialHandoffWorkflow(workflow: Workflow, metadata?: Record<string, unknown>): Workflow {
950
+ const agents = readAgentAssignments(metadata);
951
+ if (agents.length === 0) {
952
+ throw new Error('Select at least one CLI agent.');
953
+ }
954
+
955
+ const nodes: WorkflowNode[] = agents.flatMap((agent, index): WorkflowNode[] => {
956
+ const initNodeId = safeAgentNodeId(agent, index, 'init');
957
+ const workNodeId = safeAgentNodeId(agent, index, 'work');
958
+ const compactNodeId = safeAgentNodeId(agent, index, 'compact');
959
+
960
+ return [
961
+ {
962
+ id: initNodeId,
963
+ adapterId: agent.adapterId,
964
+ agentInstanceId: agent.instanceId,
965
+ agentLabel: `${agent.label} Init`,
966
+ assignment: agent.instruction,
967
+ stage: 'handoff_init',
968
+ model: agent.model,
969
+ permissionMode: agent.permissionMode,
970
+ toolsSettings: agent.toolsSettings,
971
+ prompt: handoffInitPrompt(agent, index),
972
+ inputs: index === 0 ? [] : [safeAgentNodeId(agents[index - 1], index - 1, 'compact')],
973
+ output: 'message',
974
+ onFail: 'abort',
975
+ internal: true,
976
+ },
977
+ {
978
+ id: workNodeId,
979
+ adapterId: agent.adapterId,
980
+ agentInstanceId: agent.instanceId,
981
+ agentLabel: agent.label,
982
+ assignment: agent.instruction,
983
+ stage: agent.role ?? 'implementation',
984
+ model: agent.model,
985
+ permissionMode: agent.permissionMode,
986
+ toolsSettings: agent.toolsSettings,
987
+ prompt: handoffWorkPrompt(agent, index),
988
+ inputs: [initNodeId],
989
+ output: 'both',
990
+ onFail: 'abort',
991
+ },
992
+ {
993
+ id: compactNodeId,
994
+ adapterId: agent.adapterId,
995
+ agentInstanceId: agent.instanceId,
996
+ agentLabel: `${agent.label} Compact`,
997
+ assignment: agent.instruction,
998
+ stage: 'handoff_compact',
999
+ model: agent.model,
1000
+ permissionMode: agent.permissionMode,
1001
+ toolsSettings: agent.toolsSettings,
1002
+ prompt: handoffCompactPrompt(agent, index),
1003
+ inputs: [workNodeId],
1004
+ output: 'message',
1005
+ onFail: 'abort',
1006
+ internal: true,
1007
+ },
1008
+ ];
1009
+ });
1010
+ const reportAgent = agents[0];
1011
+ const lastCompactNodeId = safeAgentNodeId(agents[agents.length - 1], agents.length - 1, 'compact');
1012
+
1013
+ return {
1014
+ ...workflow,
1015
+ nodes: [
1016
+ ...nodes,
1017
+ {
1018
+ id: 'final_report',
1019
+ adapterId: reportAgent.adapterId,
1020
+ agentInstanceId: reportAgent.instanceId,
1021
+ agentLabel: reportAgent.label,
1022
+ stage: 'final_report',
1023
+ model: reportAgent.model,
1024
+ permissionMode: reportAgent.permissionMode,
1025
+ toolsSettings: reportAgent.toolsSettings,
1026
+ prompt: [
1027
+ 'Create the final user-facing result for this strict handoff run.',
1028
+ 'Use the final compact handoff packet and the original user goal.',
1029
+ 'Summarize what each visible agent did, what changed, verification, blockers, and next actions.',
1030
+ 'Do not expose internal init packets, compact packets, prompts, memory lookup, skill/tool instructions, raw agent logs, or role prefixes like "agent:" and "user:".',
1031
+ 'Respond in the same language as the user request.',
1032
+ ].join('\n'),
1033
+ inputs: [lastCompactNodeId],
1034
+ output: 'message',
1035
+ onFail: 'abort',
1036
+ },
1037
+ ],
1038
+ };
1039
+ }
1040
+
1041
+ function expandWorkflowForRun(workflow: Workflow, metadata?: Record<string, unknown>): Workflow {
1042
+ if (workflow.id === 'agent_team') {
1043
+ return expandAgentTeamWorkflow(workflow, metadata);
1044
+ }
1045
+
1046
+ const agents = readAgentAssignments(metadata);
1047
+ if (workflow.id === 'adversarial_debate') {
1048
+ return expandAdversarialDebateWorkflow(workflow, metadata);
1049
+ }
1050
+ if (workflow.id === 'sequential_handoff') {
1051
+ return expandSequentialHandoffWorkflow(workflow, metadata);
1052
+ }
1053
+ if (workflow.id !== 'multi_model_review' || agents.length === 0) {
1054
+ return workflow;
1055
+ }
1056
+
1057
+ const reportAgent = agentsWithRole(agents, 'report')[0] ?? agentsWithRole(agents, 'decision')[0] ?? agents[0];
1058
+ const reviewAgents = agents.filter((agent) => agent.instanceId !== reportAgent.instanceId || agents.length === 1);
1059
+ const reviewNodes: WorkflowNode[] = reviewAgents.map((agent, index) => ({
1060
+ id: safeAgentNodeId(agent, index, 'review'),
1061
+ adapterId: agent.adapterId,
1062
+ agentInstanceId: agent.instanceId,
1063
+ agentLabel: agent.label,
1064
+ assignment: agent.instruction,
1065
+ stage: 'review',
1066
+ model: agent.model,
1067
+ permissionMode: agent.permissionMode,
1068
+ toolsSettings: agent.toolsSettings,
1069
+ prompt: [
1070
+ `You are ${agent.label}.`,
1071
+ 'Review the requested change for bugs, regressions, missing validation, security, scale, and user-experience risks.',
1072
+ agent.instruction ? `Focus on this user assignment: ${agent.instruction}` : '',
1073
+ privacyGuardPrompt(),
1074
+ 'Respond in the same language as the user request.',
1075
+ ].filter(Boolean).join('\n'),
1076
+ inputs: [],
1077
+ output: 'both',
1078
+ onFail: 'continue',
1079
+ }));
1080
+
1081
+ return {
1082
+ ...workflow,
1083
+ nodes: [
1084
+ ...reviewNodes,
1085
+ {
1086
+ id: 'aggregate',
1087
+ adapterId: reportAgent.adapterId,
1088
+ agentInstanceId: reportAgent.instanceId,
1089
+ agentLabel: reportAgent.label,
1090
+ stage: 'report',
1091
+ model: reportAgent.model,
1092
+ permissionMode: reportAgent.permissionMode,
1093
+ toolsSettings: reportAgent.toolsSettings,
1094
+ prompt: [
1095
+ 'Aggregate the prior agent reviews into a concise prioritized report.',
1096
+ 'Do not expose internal prompts, memory lookup, skill/tool instructions, raw agent logs, or role prefixes like "agent:" and "user:".',
1097
+ 'Respond in the same language as the user request.',
1098
+ ].join('\n'),
1099
+ inputs: reviewNodes.map((node) => node.id),
1100
+ output: 'message',
1101
+ onFail: 'abort',
1102
+ },
1103
+ ],
1104
+ };
1105
+ }
1106
+
1107
+ function readTaskResult(task: RawTask): TaskResult {
1108
+ const messages = (task.history ?? []).map((message) => ({
1109
+ role: typeof message.role === 'string' ? message.role : 'agent',
1110
+ text: (message.parts ?? [])
1111
+ .filter((part) => part.kind === 'text' && typeof part.text === 'string')
1112
+ .map((part) => part.text)
1113
+ .join('\n'),
1114
+ })).filter((message) => message.text.trim());
1115
+ const artifacts = (task.artifacts ?? []).map((artifact) => {
1116
+ const text = (artifact.parts ?? [])
1117
+ .filter((part) => part.kind === 'text' && typeof part.text === 'string')
1118
+ .map((part) => part.text)
1119
+ .join('\n');
1120
+ const data = (artifact.parts ?? []).find((part) => part.kind === 'data')?.data;
1121
+ return {
1122
+ type: artifact.type ?? 'data',
1123
+ text: text || undefined,
1124
+ data,
1125
+ metadata: artifact.metadata,
1126
+ };
1127
+ });
1128
+ const outputMessages = messages.filter((message) => message.role !== 'user');
1129
+ const userFacingTaskText = outputMessages.map((message) => message.text.trim()).filter(Boolean).join('\n\n');
1130
+ const error = task.error?.message
1131
+ ? `${task.error.code ? `${task.error.code}: ` : ''}${task.error.message}`
1132
+ : undefined;
1133
+ return {
1134
+ state: task.state ?? 'submitted',
1135
+ text: userFacingTaskText,
1136
+ error,
1137
+ messages,
1138
+ artifacts,
1139
+ };
1140
+ }
1141
+
1142
+ async function waitForTask(
1143
+ taskId: string,
1144
+ shouldCancel?: () => boolean,
1145
+ onSnapshot?: (result: TaskResult) => void,
1146
+ timeoutMs?: number,
1147
+ ): Promise<TaskResult> {
1148
+ const timeout = timeoutMs && timeoutMs > 0 ? timeoutMs : undefined;
1149
+ const deadline = timeout ? Date.now() + timeout : undefined;
1150
+ for (;;) {
1151
+ if (shouldCancel?.()) {
1152
+ throw new WorkflowCanceledError();
1153
+ }
1154
+ if (deadline && Date.now() >= deadline) {
1155
+ throw new WorkflowNodeTimeoutError(timeout ?? 0);
1156
+ }
1157
+ const task = getA2ATask(taskId);
1158
+ if (!task) {
1159
+ throw new Error(`Agent task ${taskId} was not found.`);
1160
+ }
1161
+ const snapshot = readTaskResult(task);
1162
+ onSnapshot?.(snapshot);
1163
+ if (task.state && TERMINAL.has(task.state)) {
1164
+ return snapshot;
1165
+ }
1166
+ await new Promise((resolve) => setTimeout(resolve, 1000));
1167
+ }
1168
+ }
1169
+
1170
+ function readyNodes(workflow: Workflow, completed: Set<string>, started: Set<string>): WorkflowNode[] {
1171
+ return workflow.nodes.filter((node) =>
1172
+ !started.has(node.id) && node.inputs.every((input) => completed.has(input)),
1173
+ );
1174
+ }
1175
+
1176
+ function nodeRunFromNode(node: WorkflowNode): WorkflowNodeRun {
1177
+ return {
1178
+ nodeId: node.id,
1179
+ adapterId: node.adapterId,
1180
+ agentInstanceId: node.agentInstanceId,
1181
+ agentLabel: node.agentLabel,
1182
+ assignment: node.assignment,
1183
+ promptPreview: node.prompt,
1184
+ model: node.model,
1185
+ permissionMode: node.permissionMode,
1186
+ timeoutMs: node.timeoutMs,
1187
+ stage: node.stage,
1188
+ internal: node.internal,
1189
+ fallbackTrigger: node.fallbackTrigger,
1190
+ fallbackSourceNodeId: node.fallbackSourceNodeId,
1191
+ status: 'queued',
1192
+ };
1193
+ }
1194
+
1195
+ function uniqueInputs(inputs: string[]): string[] {
1196
+ return [...new Set(inputs.filter(Boolean))];
1197
+ }
1198
+
1199
+ function isReviewNode(node: WorkflowNode): boolean {
1200
+ return node.stage === 'review';
1201
+ }
1202
+
1203
+ function isImplementationNode(node: WorkflowNode): boolean {
1204
+ return node.stage === 'backend' || node.stage === 'frontend' || node.stage === 'implementation' || node.stage === 'repair';
1205
+ }
1206
+
1207
+ function reviewRequiresRepair(text: string): boolean {
1208
+ const normalized = text.toLocaleLowerCase('tr').replace(/\s+/g, ' ').trim();
1209
+ if (!normalized) return false;
1210
+
1211
+ const approvalPatterns = [
1212
+ /hata yok/u,
1213
+ /sorun yok/u,
1214
+ /problem yok/u,
1215
+ /bulgu yok/u,
1216
+ /kritik bulgu yok/u,
1217
+ /temiz/u,
1218
+ /onaylı/u,
1219
+ /onayli/u,
1220
+ /approved/u,
1221
+ /lgtm/u,
1222
+ /no issues/u,
1223
+ /no findings/u,
1224
+ /looks good/u,
1225
+ /pass(?:ed)?/u,
1226
+ ];
1227
+ const actionableText = approvalPatterns.reduce((current, pattern) => current.replace(pattern, ' '), normalized);
1228
+ const issuePatterns = [
1229
+ /hata/u,
1230
+ /bug/u,
1231
+ /kritik/u,
1232
+ /critical/u,
1233
+ /blocker/u,
1234
+ /regression/u,
1235
+ /failed/u,
1236
+ /failure/u,
1237
+ /fail/u,
1238
+ /eksik/u,
1239
+ /düzelt/u,
1240
+ /duzelt/u,
1241
+ /fix required/u,
1242
+ /needs fix/u,
1243
+ /sorun/u,
1244
+ /risk/u,
1245
+ /güvenlik/u,
1246
+ /guvenlik/u,
1247
+ /security/u,
1248
+ /çalışmıyor/u,
1249
+ /calismiyor/u,
1250
+ ];
1251
+
1252
+ return issuePatterns.some((pattern) => pattern.test(actionableText));
1253
+ }
1254
+
1255
+ function findRepairFixer(workflow: Workflow, reviewNode: WorkflowNode): WorkflowNode | undefined {
1256
+ return reviewNode.inputs
1257
+ .map((input) => workflow.nodes.find((node) => node.id === input))
1258
+ .find((node): node is WorkflowNode => Boolean(node && isImplementationNode(node)))
1259
+ ?? workflow.nodes.find((node) => isImplementationNode(node))
1260
+ ?? workflow.nodes.find((node) => node.stage === 'coordinator');
1261
+ }
1262
+
1263
+ class WorkflowRunner {
1264
+ private readonly cancelingRuns = new Set<string>();
1265
+
1266
+ preview(workflow: Workflow, metadata?: Record<string, unknown>): Workflow {
1267
+ const runtimeWorkflow = expandWorkflowForRun(workflow, metadata);
1268
+ validateWorkflow(runtimeWorkflow);
1269
+ return runtimeWorkflow;
1270
+ }
1271
+
1272
+ start(workflow: Workflow, input = '', metadata?: Record<string, unknown>): WorkflowRun {
1273
+ const runtimeWorkflow = expandWorkflowForRun(workflow, metadata);
1274
+ validateWorkflow(runtimeWorkflow);
1275
+ const workspaceTarget = resolveWorkflowWorkspace(metadata);
1276
+ const permissionPolicy = resolvePermissionPolicyFromMetadata(metadata);
1277
+ const runMetadata: Record<string, unknown> = {
1278
+ ...metadata,
1279
+ permissionPolicy,
1280
+ projectPath: workspaceTarget.projectPath,
1281
+ selectedProjectPath: workspaceTarget.selectedProjectPath,
1282
+ workspaceTarget: workspaceTargetMetadata(workspaceTarget),
1283
+ };
1284
+ const run: WorkflowRun = {
1285
+ id: newId('wrun'),
1286
+ workflowId: runtimeWorkflow.id,
1287
+ contextId: newId('ctx'),
1288
+ status: 'queued',
1289
+ input,
1290
+ nodeRuns: runtimeWorkflow.nodes.map(nodeRunFromNode),
1291
+ startedAt: Date.now(),
1292
+ metadata: runMetadata,
1293
+ };
1294
+ workflowStore.setRun(run);
1295
+ const orchestrationTaskId = readString(runMetadata.orchestrationTaskId);
1296
+ if (orchestrationTaskId) {
1297
+ orchestrationTaskService.linkWorkflowRun(orchestrationTaskId, run);
1298
+ }
1299
+ void this.execute(runtimeWorkflow, run);
1300
+ return run;
1301
+ }
1302
+
1303
+ async cancel(runId: string): Promise<WorkflowRun | undefined> {
1304
+ const run = workflowStore.getRun(runId);
1305
+ if (!run) return undefined;
1306
+ if (TERMINAL.has(run.status)) return run;
1307
+
1308
+ this.cancelingRuns.add(run.id);
1309
+ const taskIds = run.nodeRuns
1310
+ .filter((node) => node.a2aTaskId && (node.status === 'running' || node.status === 'queued'))
1311
+ .map((node) => node.a2aTaskId as string);
1312
+
1313
+ this.markCanceled(run);
1314
+ workflowStore.setRun(run);
1315
+
1316
+ await Promise.all(taskIds.map((taskId) => cancelA2ATask(taskId)));
1317
+
1318
+ return workflowStore.getRun(run.id) ?? run;
1319
+ }
1320
+
1321
+ private isCanceling(runId: string): boolean {
1322
+ return this.cancelingRuns.has(runId) || workflowStore.getRun(runId)?.status === 'canceled';
1323
+ }
1324
+
1325
+ private markCanceled(run: WorkflowRun): void {
1326
+ run.status = 'canceled';
1327
+ run.finishedAt = run.finishedAt ?? Date.now();
1328
+ for (const nodeRun of run.nodeRuns) {
1329
+ if (!TERMINAL.has(nodeRun.status) && nodeRun.status !== SKIPPED) {
1330
+ nodeRun.status = 'canceled';
1331
+ nodeRun.finishedAt = nodeRun.finishedAt ?? Date.now();
1332
+ }
1333
+ }
1334
+ }
1335
+
1336
+ private fallbackAgentFor(run: WorkflowRun, node: WorkflowNode): AgentAssignment | undefined {
1337
+ if (node.stage === 'fallback' || node.id.startsWith('fallback_')) {
1338
+ return undefined;
1339
+ }
1340
+
1341
+ const settings = getMetadataRecord(run.metadata, 'settings');
1342
+ const fallbackAgentInstanceId = readString(settings.fallbackAgentInstanceId);
1343
+ if (!fallbackAgentInstanceId || fallbackAgentInstanceId === node.agentInstanceId) {
1344
+ return undefined;
1345
+ }
1346
+
1347
+ return readAgentAssignments(run.metadata).find((agent) => agent.instanceId === fallbackAgentInstanceId);
1348
+ }
1349
+
1350
+ private createFallbackNode(
1351
+ node: WorkflowNode,
1352
+ fallbackAgent: AgentAssignment,
1353
+ reason: string,
1354
+ fallbackTrigger: WorkflowFallbackTrigger,
1355
+ ): WorkflowNode {
1356
+ const fallbackSuffix = safeNodeId(fallbackAgent.instanceId, 'fallback');
1357
+ return {
1358
+ ...node,
1359
+ id: `fallback_${node.id}_${fallbackSuffix}`,
1360
+ adapterId: fallbackAgent.adapterId,
1361
+ agentInstanceId: fallbackAgent.instanceId,
1362
+ agentLabel: `${fallbackAgent.label} Fallback`,
1363
+ assignment: `Fallback for ${node.agentLabel || node.id}`,
1364
+ stage: 'fallback',
1365
+ model: fallbackAgent.model,
1366
+ permissionMode: fallbackAgent.permissionMode,
1367
+ toolsSettings: fallbackAgent.toolsSettings,
1368
+ fallbackTrigger,
1369
+ fallbackSourceNodeId: node.id,
1370
+ prompt: [
1371
+ 'The previous CLI agent failed on this orchestration step.',
1372
+ `Failed step: ${node.agentLabel || node.id}`,
1373
+ `Fallback trigger: ${fallbackTrigger}`,
1374
+ `Failure: ${reason}`,
1375
+ 'Take over the same assignment as the backup CLI. Use the original goal and upstream context.',
1376
+ 'Do not repeat unrelated work; complete the failed step and report what you did.',
1377
+ node.prompt,
1378
+ ].join('\n'),
1379
+ onFail: 'continue',
1380
+ };
1381
+ }
1382
+
1383
+ private recordFallbackSkipped(
1384
+ run: WorkflowRun,
1385
+ node: WorkflowNode,
1386
+ reason: string,
1387
+ fallbackTrigger: WorkflowFallbackTrigger,
1388
+ skippedReason: string,
1389
+ ): void {
1390
+ const fallbackSkippedEvents = Array.isArray(run.metadata?.fallbackSkippedEvents)
1391
+ ? run.metadata.fallbackSkippedEvents
1392
+ : [];
1393
+ run.metadata = {
1394
+ ...run.metadata,
1395
+ fallbackSkippedEvents: [
1396
+ ...fallbackSkippedEvents,
1397
+ {
1398
+ nodeId: node.id,
1399
+ trigger: fallbackTrigger,
1400
+ reason,
1401
+ skippedReason,
1402
+ createdAt: Date.now(),
1403
+ },
1404
+ ],
1405
+ };
1406
+ workflowStore.setRun(run);
1407
+ }
1408
+
1409
+ private async runFallbackAfterFailure(
1410
+ node: WorkflowNode,
1411
+ workflow: Workflow,
1412
+ run: WorkflowRun,
1413
+ outputs: Map<string, string>,
1414
+ started: Set<string>,
1415
+ completed: Set<string>,
1416
+ reason: string,
1417
+ trigger?: WorkflowFallbackTrigger,
1418
+ ): Promise<boolean> {
1419
+ const fallbackTrigger = classifyWorkflowFailure(reason, trigger);
1420
+ const fallbackAgent = this.fallbackAgentFor(run, node);
1421
+ if (!fallbackAgent) {
1422
+ this.recordFallbackSkipped(run, node, reason, fallbackTrigger, 'No fallback agent is configured for this run.');
1423
+ return false;
1424
+ }
1425
+ const decision = resolveWorkflowFallbackDecision({
1426
+ run,
1427
+ node,
1428
+ reason,
1429
+ trigger: fallbackTrigger,
1430
+ fallbackAgentInstanceId: fallbackAgent.instanceId,
1431
+ });
1432
+ if (!decision.shouldFallback) {
1433
+ this.recordFallbackSkipped(
1434
+ run,
1435
+ node,
1436
+ reason,
1437
+ decision.trigger,
1438
+ decision.skippedReason ?? 'Fallback policy skipped this failure.',
1439
+ );
1440
+ return false;
1441
+ }
1442
+ if (workflow.nodes.length + 1 > 64) {
1443
+ run.metadata = {
1444
+ ...run.metadata,
1445
+ fallbackSkipped: `Workflow node limit reached after ${node.id}.`,
1446
+ };
1447
+ workflowStore.setRun(run);
1448
+ return false;
1449
+ }
1450
+
1451
+ let fallbackNode = this.createFallbackNode(node, fallbackAgent, reason, decision.trigger);
1452
+ let collision = 1;
1453
+ while (workflow.nodes.some((candidate) => candidate.id === fallbackNode.id)) {
1454
+ collision += 1;
1455
+ fallbackNode = {
1456
+ ...fallbackNode,
1457
+ id: `${fallbackNode.id}_${collision}`,
1458
+ };
1459
+ }
1460
+
1461
+ const nodeIndex = workflow.nodes.findIndex((candidate) => candidate.id === node.id);
1462
+ const runIndex = run.nodeRuns.findIndex((candidate) => candidate.nodeId === node.id);
1463
+ if (nodeIndex >= 0) {
1464
+ workflow.nodes.splice(nodeIndex + 1, 0, fallbackNode);
1465
+ } else {
1466
+ workflow.nodes.push(fallbackNode);
1467
+ }
1468
+ if (runIndex >= 0) {
1469
+ run.nodeRuns.splice(runIndex + 1, 0, nodeRunFromNode(fallbackNode));
1470
+ } else {
1471
+ run.nodeRuns.push(nodeRunFromNode(fallbackNode));
1472
+ }
1473
+
1474
+ const fallbackEvents = Array.isArray(run.metadata?.fallbackEvents)
1475
+ ? run.metadata.fallbackEvents
1476
+ : [];
1477
+ run.metadata = {
1478
+ ...run.metadata,
1479
+ fallbackEvents: [
1480
+ ...fallbackEvents,
1481
+ {
1482
+ nodeId: node.id,
1483
+ fallbackNodeId: fallbackNode.id,
1484
+ fallbackAgentInstanceId: fallbackAgent.instanceId,
1485
+ trigger: decision.trigger,
1486
+ policy: decision.policy,
1487
+ reason,
1488
+ startedAt: Date.now(),
1489
+ },
1490
+ ],
1491
+ };
1492
+ workflowStore.setRun(run);
1493
+
1494
+ await this.executeNode(fallbackNode, workflow, run, outputs, started, completed);
1495
+
1496
+ const fallbackRun = run.nodeRuns.find((candidate) => candidate.nodeId === fallbackNode.id);
1497
+ if (fallbackRun?.status !== 'completed') {
1498
+ return false;
1499
+ }
1500
+
1501
+ const fallbackOutput = outputs.get(fallbackNode.id) || fallbackRun.outputText;
1502
+ if (fallbackOutput) {
1503
+ outputs.set(node.id, compactOutputForContext(fallbackOutput));
1504
+ }
1505
+ completed.add(node.id);
1506
+ workflowStore.setRun(run);
1507
+ return true;
1508
+ }
1509
+
1510
+ private maybeAddRepairCycle(
1511
+ node: WorkflowNode,
1512
+ workflow: Workflow,
1513
+ run: WorkflowRun,
1514
+ result: TaskResult,
1515
+ ): void {
1516
+ if (workflow.id !== 'agent_team') return;
1517
+ if (!isReviewNode(node) || node.id.startsWith('repair_') || node.id.startsWith('recheck_')) return;
1518
+ if (!reviewRequiresRepair(`${result.text}\n${result.error ?? ''}`)) return;
1519
+
1520
+ const maxRepairCycles = readMaxRepairCycles(run.metadata);
1521
+ if (maxRepairCycles <= 0) return;
1522
+
1523
+ const existingCycles = workflow.nodes.filter((candidate) => candidate.id.startsWith(`repair_${node.id}_`)).length;
1524
+ if (existingCycles >= maxRepairCycles) return;
1525
+
1526
+ if (workflow.nodes.length + 2 > 64) {
1527
+ run.metadata = {
1528
+ ...run.metadata,
1529
+ dynamicRepairSkipped: `Workflow node limit reached after ${node.id}.`,
1530
+ };
1531
+ workflowStore.setRun(run);
1532
+ return;
1533
+ }
1534
+
1535
+ const fixer = findRepairFixer(workflow, node);
1536
+ if (!fixer || fixer.id === node.id) return;
1537
+
1538
+ const cycle = existingCycles + 1;
1539
+ const repairNode: WorkflowNode = {
1540
+ id: `repair_${node.id}_${cycle}`,
1541
+ adapterId: fixer.adapterId,
1542
+ agentInstanceId: fixer.agentInstanceId,
1543
+ agentLabel: fixer.agentLabel ? `${fixer.agentLabel} Repair` : undefined,
1544
+ assignment: `Automatic repair from ${node.agentLabel || node.id} review findings`,
1545
+ stage: 'repair',
1546
+ model: fixer.model,
1547
+ permissionMode: fixer.permissionMode,
1548
+ toolsSettings: fixer.toolsSettings,
1549
+ prompt: [
1550
+ 'A review stage found actionable issues in the prior work.',
1551
+ 'Use the original user goal, prior implementation outputs, and review output included above.',
1552
+ 'Fix only the reported issues; do not restart the whole project or duplicate unrelated work.',
1553
+ 'Report changed files, commands, verification, and any remaining blockers.',
1554
+ 'Respond in the same language as the user request.',
1555
+ ].join('\n'),
1556
+ inputs: uniqueInputs([...node.inputs, fixer.id, node.id]),
1557
+ output: 'both',
1558
+ onFail: 'continue',
1559
+ };
1560
+ const recheckNode: WorkflowNode = {
1561
+ id: `recheck_${node.id}_${cycle}`,
1562
+ adapterId: node.adapterId,
1563
+ agentInstanceId: node.agentInstanceId,
1564
+ agentLabel: node.agentLabel ? `${node.agentLabel} Recheck` : undefined,
1565
+ assignment: 'Automatic validation after repair',
1566
+ stage: 'review',
1567
+ model: node.model,
1568
+ permissionMode: node.permissionMode,
1569
+ toolsSettings: node.toolsSettings,
1570
+ prompt: [
1571
+ 'Validate the automatic repair against the original review findings.',
1572
+ 'Approve only if the reported issues are fixed.',
1573
+ 'If anything remains, list the remaining blockers clearly and do not invent new unrelated scope.',
1574
+ 'Respond in the same language as the user request.',
1575
+ ].join('\n'),
1576
+ inputs: uniqueInputs([node.id, repairNode.id]),
1577
+ output: 'message',
1578
+ onFail: 'continue',
1579
+ };
1580
+
1581
+ const finalIndex = workflow.nodes.findIndex((candidate) =>
1582
+ candidate.id === 'final_report' || candidate.stage === 'final_report' || candidate.stage === 'report',
1583
+ );
1584
+ if (finalIndex >= 0) {
1585
+ workflow.nodes.splice(finalIndex, 0, repairNode, recheckNode);
1586
+ run.nodeRuns.splice(finalIndex, 0, nodeRunFromNode(repairNode), nodeRunFromNode(recheckNode));
1587
+ } else {
1588
+ workflow.nodes.push(repairNode, recheckNode);
1589
+ run.nodeRuns.push(nodeRunFromNode(repairNode), nodeRunFromNode(recheckNode));
1590
+ }
1591
+
1592
+ for (const finalNode of workflow.nodes) {
1593
+ if (finalNode.id === 'final_report' || finalNode.stage === 'final_report' || finalNode.stage === 'report') {
1594
+ finalNode.inputs = uniqueInputs([...finalNode.inputs, recheckNode.id]);
1595
+ }
1596
+ }
1597
+
1598
+ const repairCycles = Array.isArray(run.metadata?.dynamicRepairCycles)
1599
+ ? run.metadata.dynamicRepairCycles
1600
+ : [];
1601
+ run.metadata = {
1602
+ ...run.metadata,
1603
+ dynamicRepairCycles: [
1604
+ ...repairCycles,
1605
+ {
1606
+ reviewNodeId: node.id,
1607
+ repairNodeId: repairNode.id,
1608
+ recheckNodeId: recheckNode.id,
1609
+ fixerNodeId: fixer.id,
1610
+ },
1611
+ ],
1612
+ };
1613
+ workflowStore.setRun(run);
1614
+ }
1615
+
1616
+ private async execute(workflow: Workflow, run: WorkflowRun): Promise<void> {
1617
+ run.status = 'running';
1618
+ workflowStore.setRun(run);
1619
+ const completed = new Set<string>();
1620
+ const started = new Set<string>();
1621
+ const outputs = new Map<string, string>();
1622
+ const maxParallelAgents = readMaxParallelAgents(run.metadata);
1623
+
1624
+ try {
1625
+ while (completed.size < workflow.nodes.length) {
1626
+ if (this.isCanceling(run.id)) {
1627
+ throw new WorkflowCanceledError();
1628
+ }
1629
+ const batch = readyNodes(workflow, completed, started);
1630
+ if (batch.length === 0) {
1631
+ throw new Error('Workflow stalled; no ready nodes remain.');
1632
+ }
1633
+ for (let index = 0; index < batch.length; index += maxParallelAgents) {
1634
+ if (this.isCanceling(run.id)) {
1635
+ throw new WorkflowCanceledError();
1636
+ }
1637
+ const slice = batch.slice(index, index + maxParallelAgents);
1638
+ await Promise.all(slice.map((node) => this.executeNode(node, workflow, run, outputs, started, completed)));
1639
+ }
1640
+ }
1641
+ if (this.isCanceling(run.id)) {
1642
+ throw new WorkflowCanceledError();
1643
+ }
1644
+ run.status = 'completed';
1645
+ } catch (error) {
1646
+ if (error instanceof WorkflowCanceledError || this.isCanceling(run.id)) {
1647
+ this.markCanceled(run);
1648
+ } else {
1649
+ run.status = 'failed';
1650
+ run.metadata = {
1651
+ ...run.metadata,
1652
+ error: error instanceof Error ? error.message : String(error),
1653
+ };
1654
+ }
1655
+ } finally {
1656
+ run.finishedAt = run.finishedAt ?? Date.now();
1657
+ workflowStore.setRun(run);
1658
+ orchestrationTaskService.updateFromWorkflowRun(run);
1659
+ notifyWorkflowRunFinished(run);
1660
+ const webhookRunStatus = String(run.status);
1661
+ dispatchWebhookEvent({
1662
+ type: webhookRunStatus === 'completed'
1663
+ ? 'run.completed'
1664
+ : webhookRunStatus === 'canceled'
1665
+ ? 'run.canceled'
1666
+ : 'run.failed',
1667
+ payload: {
1668
+ runId: run.id,
1669
+ workflowId: run.workflowId,
1670
+ status: webhookRunStatus,
1671
+ error: readString(run.metadata?.error),
1672
+ },
1673
+ });
1674
+ this.cancelingRuns.delete(run.id);
1675
+ }
1676
+ }
1677
+
1678
+ private recordPermissionDecision(
1679
+ run: WorkflowRun,
1680
+ nodeRun: WorkflowNodeRun,
1681
+ decision: PermissionDecision,
1682
+ ): void {
1683
+ nodeRun.permissionDecisions = [
1684
+ ...(nodeRun.permissionDecisions ?? []),
1685
+ decision,
1686
+ ];
1687
+
1688
+ const existingApprovals = permissionApprovalRequests(run)
1689
+ .filter((approval) => approval.id !== decision.approvalRequest?.id);
1690
+ run.metadata = {
1691
+ ...run.metadata,
1692
+ permissionPolicyEvents: [
1693
+ ...permissionPolicyEvents(run),
1694
+ decision.event,
1695
+ ],
1696
+ pendingPermissionApprovals: decision.approvalRequest
1697
+ ? [
1698
+ ...existingApprovals,
1699
+ decision.approvalRequest,
1700
+ ]
1701
+ : existingApprovals,
1702
+ };
1703
+
1704
+ if (decision.approvalRequest) {
1705
+ notifyPermissionApprovalRequested(run, decision);
1706
+ dispatchWebhookEvent({
1707
+ type: 'approval.needed',
1708
+ payload: {
1709
+ runId: run.id,
1710
+ workflowId: run.workflowId,
1711
+ approvalId: decision.approvalRequest.id,
1712
+ capabilities: decision.capabilities,
1713
+ },
1714
+ });
1715
+ }
1716
+ }
1717
+
1718
+ private async executeNode(
1719
+ node: WorkflowNode,
1720
+ workflow: Workflow,
1721
+ run: WorkflowRun,
1722
+ outputs: Map<string, string>,
1723
+ started: Set<string>,
1724
+ completed: Set<string>,
1725
+ ): Promise<void> {
1726
+ started.add(node.id);
1727
+ const nodeRun = run.nodeRuns.find((candidate) => candidate.nodeId === node.id) as WorkflowNodeRun;
1728
+ const enabledAdapters = readEnabledAdapters(run.metadata);
1729
+ if (enabledAdapters.length > 0 && !enabledAdapters.includes(node.adapterId)) {
1730
+ nodeRun.status = SKIPPED;
1731
+ nodeRun.finishedAt = Date.now();
1732
+ completed.add(node.id);
1733
+ workflowStore.setRun(run);
1734
+ return;
1735
+ }
1736
+ if (this.isCanceling(run.id)) {
1737
+ nodeRun.status = 'canceled';
1738
+ nodeRun.finishedAt = Date.now();
1739
+ workflowStore.setRun(run);
1740
+ throw new WorkflowCanceledError();
1741
+ }
1742
+
1743
+ nodeRun.status = 'running';
1744
+ nodeRun.startedAt = Date.now();
1745
+ nodeRun.permissionMode = resolveNodePermissionMode(node, resolveWorkflowWorkspace(run.metadata));
1746
+ workflowStore.setRun(run);
1747
+
1748
+ const inputContext = node.inputs.map((input) => outputs.get(input)).filter(Boolean).join('\n\n');
1749
+ const workspaceTarget = resolveWorkflowWorkspace(run.metadata);
1750
+ const contextPacket = buildWorkflowContextPacket({
1751
+ run,
1752
+ node,
1753
+ workspaceTarget,
1754
+ inputContext,
1755
+ inputNodeIds: node.inputs,
1756
+ });
1757
+ nodeRun.contextPacket = contextPacket;
1758
+ workflowStore.setRun(run);
1759
+ const prompt = [
1760
+ 'Original user request (primary task; answer this directly even if the workspace is empty):',
1761
+ run.input?.trim() || '(No original user request was provided.)',
1762
+ formatContextPacketForPrompt(contextPacket),
1763
+ inputContext
1764
+ ? `Upstream workflow context from prior agents:\n${inputContext}`
1765
+ : '',
1766
+ `Current workflow step instructions:\n${node.prompt}`,
1767
+ workspaceContextPrompt(workspaceTarget),
1768
+ ].filter(Boolean).join('\n\n');
1769
+ const settings = getMetadataRecord(run.metadata, 'settings');
1770
+ const projectPath = workspaceTarget.projectPath;
1771
+ const isolation = readIsolation(settings.isolation) ?? node.isolation ?? 'host';
1772
+ const keepAfterCompletion = readBoolean(settings.keepWorkspace) ?? true;
1773
+ const baseRef = readString(settings.baseRef) ?? 'HEAD';
1774
+ const effectivePermissionMode = resolveNodePermissionMode(node, workspaceTarget);
1775
+ const effectiveModel = await resolveWorkflowModel(node.adapterId, node.model);
1776
+ if (effectiveModel !== node.model) {
1777
+ nodeRun.model = effectiveModel;
1778
+ const modelFallbackEvents = Array.isArray(run.metadata?.modelFallbackEvents)
1779
+ ? run.metadata.modelFallbackEvents
1780
+ : [];
1781
+ run.metadata = {
1782
+ ...run.metadata,
1783
+ modelFallbackEvents: [
1784
+ ...modelFallbackEvents,
1785
+ {
1786
+ nodeId: node.id,
1787
+ adapterId: node.adapterId,
1788
+ requestedModel: node.model,
1789
+ effectiveModel,
1790
+ changedAt: Date.now(),
1791
+ },
1792
+ ],
1793
+ };
1794
+ workflowStore.setRun(run);
1795
+ }
1796
+ const permissionPolicy = permissionPolicyFromRun(run);
1797
+ nodeRun.permissionPolicy = permissionPolicy;
1798
+ const permissionDecision = evaluatePermissionRequest({
1799
+ policy: permissionPolicy,
1800
+ request: {
1801
+ source: 'workflow_node',
1802
+ toolName: node.adapterId,
1803
+ input: {
1804
+ assignment: node.assignment,
1805
+ stage: node.stage,
1806
+ toolsSettings: node.toolsSettings,
1807
+ },
1808
+ cwd: projectPath,
1809
+ workspacePath: workspaceTarget.appRoot,
1810
+ targetPaths: [projectPath],
1811
+ summary: [
1812
+ node.agentLabel || node.id,
1813
+ node.stage ? `stage=${node.stage}` : undefined,
1814
+ node.assignment,
1815
+ ].filter(Boolean).join(' / '),
1816
+ },
1817
+ context: {
1818
+ runId: run.id,
1819
+ nodeId: node.id,
1820
+ workflowId: run.workflowId,
1821
+ adapterId: node.adapterId,
1822
+ agentLabel: node.agentLabel,
1823
+ userId: readNotificationUserId(run.metadata),
1824
+ },
1825
+ });
1826
+ this.recordPermissionDecision(run, nodeRun, permissionDecision);
1827
+ workflowStore.setRun(run);
1828
+ if (permissionDecision.behavior === 'deny') {
1829
+ nodeRun.finishedAt = Date.now();
1830
+ nodeRun.status = 'failed';
1831
+ nodeRun.error = permissionDecision.message;
1832
+ workflowStore.setRun(run);
1833
+ if (node.onFail === 'continue') {
1834
+ completed.add(node.id);
1835
+ return;
1836
+ }
1837
+ throw new Error(permissionDecision.message);
1838
+ }
1839
+ let submittedTask: RawTask;
1840
+ try {
1841
+ submittedTask = await submitA2ATask({
1842
+ adapterId: node.adapterId,
1843
+ contextId: run.contextId,
1844
+ message: {
1845
+ messageId: newId('msg'),
1846
+ role: 'user',
1847
+ parts: [{ kind: 'text', text: prompt }],
1848
+ },
1849
+ metadata: {
1850
+ workflowRunId: run.id,
1851
+ workflowNodeId: node.id,
1852
+ agentInstanceId: node.agentInstanceId,
1853
+ agentLabel: node.agentLabel,
1854
+ assignment: node.assignment,
1855
+ model: effectiveModel,
1856
+ permissionMode: effectivePermissionMode,
1857
+ permissionPolicy,
1858
+ permissionPolicyContext: {
1859
+ runId: run.id,
1860
+ nodeId: node.id,
1861
+ workflowId: run.workflowId,
1862
+ adapterId: node.adapterId,
1863
+ agentLabel: node.agentLabel,
1864
+ userId: readNotificationUserId(run.metadata),
1865
+ },
1866
+ toolsSettings: node.toolsSettings,
1867
+ projectPath,
1868
+ workspaceTarget: workspaceTargetMetadata(workspaceTarget),
1869
+ workspace: {
1870
+ kind: isolation,
1871
+ projectPath,
1872
+ baseRef,
1873
+ keepAfterCompletion,
1874
+ },
1875
+ },
1876
+ });
1877
+ } catch (error) {
1878
+ nodeRun.finishedAt = Date.now();
1879
+ nodeRun.status = 'failed';
1880
+ nodeRun.error = error instanceof Error ? error.message : String(error);
1881
+ workflowStore.setRun(run);
1882
+ if (isExternalDirectoryPermissionError(nodeRun.error)) {
1883
+ completeNodeWithPermissionFallback(nodeRun, node, outputs, completed, nodeRun.error, workspaceTarget);
1884
+ workflowStore.setRun(run);
1885
+ return;
1886
+ }
1887
+ if (await this.runFallbackAfterFailure(
1888
+ node,
1889
+ workflow,
1890
+ run,
1891
+ outputs,
1892
+ started,
1893
+ completed,
1894
+ nodeRun.error,
1895
+ 'provider_failure',
1896
+ )) {
1897
+ return;
1898
+ }
1899
+ if (node.onFail === 'continue') {
1900
+ completed.add(node.id);
1901
+ return;
1902
+ }
1903
+ throw error;
1904
+ }
1905
+ nodeRun.a2aTaskId = submittedTask.id;
1906
+ workflowStore.setRun(run);
1907
+
1908
+ if (this.isCanceling(run.id)) {
1909
+ await cancelA2ATask(submittedTask.id);
1910
+ nodeRun.status = 'canceled';
1911
+ nodeRun.finishedAt = Date.now();
1912
+ workflowStore.setRun(run);
1913
+ throw new WorkflowCanceledError();
1914
+ }
1915
+
1916
+ let result: TaskResult;
1917
+ try {
1918
+ result = await waitForTask(
1919
+ submittedTask.id,
1920
+ () => this.isCanceling(run.id),
1921
+ (snapshot) => {
1922
+ nodeRun.outputText = snapshot.text || nodeRun.outputText;
1923
+ nodeRun.messages = snapshot.messages;
1924
+ nodeRun.artifacts = snapshot.artifacts;
1925
+ nodeRun.error = snapshot.error;
1926
+ workflowStore.setRun(run);
1927
+ },
1928
+ node.timeoutMs,
1929
+ );
1930
+ } catch (error) {
1931
+ if (!(error instanceof WorkflowNodeTimeoutError)) {
1932
+ throw error;
1933
+ }
1934
+
1935
+ await cancelA2ATask(submittedTask.id);
1936
+ nodeRun.finishedAt = Date.now();
1937
+ nodeRun.status = 'failed';
1938
+ nodeRun.error = error.message;
1939
+ if (nodeRun.outputText) {
1940
+ outputs.set(node.id, compactOutputForContext(nodeRun.outputText));
1941
+ }
1942
+ workflowStore.setRun(run);
1943
+ if (isExternalDirectoryPermissionError(nodeRun.error)) {
1944
+ completeNodeWithPermissionFallback(nodeRun, node, outputs, completed, nodeRun.error, workspaceTarget);
1945
+ workflowStore.setRun(run);
1946
+ return;
1947
+ }
1948
+ if (await this.runFallbackAfterFailure(
1949
+ node,
1950
+ workflow,
1951
+ run,
1952
+ outputs,
1953
+ started,
1954
+ completed,
1955
+ nodeRun.error,
1956
+ 'timeout',
1957
+ )) {
1958
+ return;
1959
+ }
1960
+ if (node.onFail === 'continue') {
1961
+ completed.add(node.id);
1962
+ return;
1963
+ }
1964
+ throw error;
1965
+ }
1966
+ nodeRun.finishedAt = Date.now();
1967
+ nodeRun.outputText = result.text;
1968
+ nodeRun.messages = result.messages;
1969
+ nodeRun.artifacts = result.artifacts;
1970
+ if (this.isCanceling(run.id)) {
1971
+ nodeRun.status = 'canceled';
1972
+ workflowStore.setRun(run);
1973
+ throw new WorkflowCanceledError();
1974
+ }
1975
+ if (result.state === 'completed') {
1976
+ let outputForContext = result.text;
1977
+ if (requiresHandoffArtifact(node)) {
1978
+ const handoffParse = parseHandoffArtifact(handoffArtifactSource(result), {
1979
+ workflowRunId: run.id,
1980
+ nodeId: node.id,
1981
+ agentLabel: node.agentLabel,
1982
+ stage: node.stage,
1983
+ });
1984
+ if (!handoffParse.ok) {
1985
+ const visibleHandoffError = handoffParse.error.startsWith('Invalid handoff artifact')
1986
+ ? handoffParse.error
1987
+ : `Invalid handoff artifact: ${handoffParse.error}`;
1988
+ nodeRun.status = 'failed';
1989
+ nodeRun.error = visibleHandoffError;
1990
+ workflowStore.setRun(run);
1991
+ if (await this.runFallbackAfterFailure(
1992
+ node,
1993
+ workflow,
1994
+ run,
1995
+ outputs,
1996
+ started,
1997
+ completed,
1998
+ visibleHandoffError,
1999
+ 'invalid_output',
2000
+ )) {
2001
+ return;
2002
+ }
2003
+ if (node.onFail === 'continue') {
2004
+ completed.add(node.id);
2005
+ return;
2006
+ }
2007
+ throw new Error(visibleHandoffError);
2008
+ }
2009
+
2010
+ nodeRun.handoffArtifact = handoffParse.artifact;
2011
+ nodeRun.artifacts = [
2012
+ ...(nodeRun.artifacts ?? []).filter((artifact) => artifact.type !== 'handoff-artifact'),
2013
+ handoffArtifactToWorkflowArtifact(handoffParse.artifact),
2014
+ ];
2015
+ outputForContext = formatHandoffArtifactForContext(handoffParse.artifact);
2016
+ }
2017
+
2018
+ outputs.set(node.id, compactOutputForContext(outputForContext));
2019
+ completed.add(node.id);
2020
+ nodeRun.status = 'completed';
2021
+ workflowStore.setRun(run);
2022
+ this.maybeAddRepairCycle(node, workflow, run, result);
2023
+ return;
2024
+ }
2025
+ if (result.state === 'canceled') {
2026
+ nodeRun.status = 'canceled';
2027
+ workflowStore.setRun(run);
2028
+ throw new WorkflowCanceledError();
2029
+ }
2030
+
2031
+ nodeRun.status = 'failed';
2032
+ nodeRun.error = result.error ?? `Agent task ended with ${result.state}`;
2033
+ workflowStore.setRun(run);
2034
+ if (isExternalDirectoryPermissionError(`${nodeRun.error}\n${nodeRun.outputText ?? ''}`)) {
2035
+ completeNodeWithPermissionFallback(nodeRun, node, outputs, completed, nodeRun.error, workspaceTarget);
2036
+ workflowStore.setRun(run);
2037
+ return;
2038
+ }
2039
+ if (await this.runFallbackAfterFailure(
2040
+ node,
2041
+ workflow,
2042
+ run,
2043
+ outputs,
2044
+ started,
2045
+ completed,
2046
+ nodeRun.error,
2047
+ classifyWorkflowFailure(`${nodeRun.error}\n${nodeRun.outputText ?? ''}`),
2048
+ )) {
2049
+ return;
2050
+ }
2051
+ if (node.onFail === 'continue') {
2052
+ if (nodeRun.outputText) {
2053
+ outputs.set(node.id, compactOutputForContext(nodeRun.outputText));
2054
+ }
2055
+ completed.add(node.id);
2056
+ return;
2057
+ }
2058
+ throw new Error(nodeRun.error);
2059
+ }
2060
+ }
2061
+
2062
+ export const workflowRunner = new WorkflowRunner();