@pixelbyte-software/pixcode 1.35.0 → 1.35.1

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 (150) hide show
  1. package/LICENSE +718 -718
  2. package/README.de.md +248 -248
  3. package/README.ja.md +240 -240
  4. package/README.ko.md +240 -240
  5. package/README.md +303 -303
  6. package/README.ru.md +248 -248
  7. package/README.tr.md +250 -250
  8. package/README.zh-CN.md +240 -240
  9. package/dist/api-docs.html +548 -548
  10. package/dist/assets/{index-Djuh0wHV.js → index-CBdsvGSR.js} +133 -133
  11. package/dist/clear-cache.html +85 -85
  12. package/dist/convert-icons.md +52 -52
  13. package/dist/generate-icons.js +48 -48
  14. package/dist/icons/codex-white.svg +3 -3
  15. package/dist/icons/codex.svg +3 -3
  16. package/dist/icons/cursor-white.svg +11 -11
  17. package/dist/icons/qwen-logo.svg +14 -14
  18. package/dist/index.html +58 -58
  19. package/dist/manifest.json +60 -60
  20. package/dist/openapi.yaml +1693 -1693
  21. package/dist/sw.js +124 -124
  22. package/dist-server/server/cli.js +96 -96
  23. package/dist-server/server/daemon/manager.js +33 -33
  24. package/dist-server/server/daemon-manager.js +64 -64
  25. package/dist-server/server/modules/orchestration/preview/preview-proxy.js +3 -3
  26. package/dist-server/server/modules/orchestration/preview/preview-proxy.js.map +1 -1
  27. package/dist-server/server/routes/commands.js +25 -25
  28. package/dist-server/server/routes/git.js +17 -17
  29. package/dist-server/server/routes/taskmaster.js +419 -419
  30. package/package.json +180 -180
  31. package/scripts/fix-node-pty.js +67 -67
  32. package/scripts/smoke/a2a-roundtrip.mjs +167 -167
  33. package/scripts/smoke/orchestration-api.mjs +172 -172
  34. package/scripts/smoke/orchestration-live-run.mjs +176 -176
  35. package/server/claude-sdk.js +898 -898
  36. package/server/cli.js +935 -935
  37. package/server/constants/config.js +4 -4
  38. package/server/cursor-cli.js +342 -342
  39. package/server/daemon/manager.js +564 -564
  40. package/server/daemon-manager.js +959 -959
  41. package/server/database/json-store.js +197 -197
  42. package/server/gemini-cli.js +535 -535
  43. package/server/gemini-response-handler.js +79 -79
  44. package/server/index.js +3135 -3135
  45. package/server/load-env.js +34 -34
  46. package/server/middleware/auth.js +173 -173
  47. package/server/modules/orchestration/a2a/adapter-registry.ts +108 -108
  48. package/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.ts +55 -55
  49. package/server/modules/orchestration/a2a/adapters/claude-code.adapter.ts +284 -284
  50. package/server/modules/orchestration/a2a/adapters/codex.adapter.ts +244 -244
  51. package/server/modules/orchestration/a2a/adapters/cursor.adapter.ts +249 -249
  52. package/server/modules/orchestration/a2a/adapters/gemini.adapter.ts +248 -248
  53. package/server/modules/orchestration/a2a/adapters/opencode.adapter.ts +248 -248
  54. package/server/modules/orchestration/a2a/adapters/qwen.adapter.ts +248 -248
  55. package/server/modules/orchestration/a2a/agent-card.ts +55 -55
  56. package/server/modules/orchestration/a2a/auth.middleware.ts +29 -29
  57. package/server/modules/orchestration/a2a/bus.ts +46 -46
  58. package/server/modules/orchestration/a2a/routes.ts +577 -577
  59. package/server/modules/orchestration/a2a/task-store.ts +178 -178
  60. package/server/modules/orchestration/a2a/types.ts +125 -125
  61. package/server/modules/orchestration/a2a/validator.ts +113 -113
  62. package/server/modules/orchestration/index.ts +66 -66
  63. package/server/modules/orchestration/preview/port-watcher.ts +112 -112
  64. package/server/modules/orchestration/preview/preview-proxy.ts +60 -60
  65. package/server/modules/orchestration/preview/types.ts +19 -19
  66. package/server/modules/orchestration/tasks/orchestration-task-store.ts +45 -45
  67. package/server/modules/orchestration/tasks/orchestration-task.routes.ts +73 -73
  68. package/server/modules/orchestration/tasks/orchestration-task.service.ts +145 -145
  69. package/server/modules/orchestration/tasks/orchestration-task.types.ts +29 -29
  70. package/server/modules/orchestration/workflows/built-in-workflows.ts +127 -127
  71. package/server/modules/orchestration/workflows/workflow-runner.ts +1206 -1206
  72. package/server/modules/orchestration/workflows/workflow-store.ts +97 -97
  73. package/server/modules/orchestration/workflows/workflow.routes.ts +169 -169
  74. package/server/modules/orchestration/workflows/workflow.types.ts +70 -70
  75. package/server/modules/orchestration/workflows/workspace-target.ts +120 -120
  76. package/server/modules/orchestration/workspace/docker-workspace.ts +135 -135
  77. package/server/modules/orchestration/workspace/path-safety.ts +55 -55
  78. package/server/modules/orchestration/workspace/types.ts +52 -52
  79. package/server/modules/orchestration/workspace/workspace-manager.ts +97 -97
  80. package/server/modules/orchestration/workspace/worktree-workspace.ts +125 -125
  81. package/server/modules/providers/index.ts +2 -2
  82. package/server/modules/providers/list/claude/claude-auth.provider.ts +145 -145
  83. package/server/modules/providers/list/claude/claude-mcp.provider.ts +135 -135
  84. package/server/modules/providers/list/claude/claude-sessions.provider.ts +306 -306
  85. package/server/modules/providers/list/claude/claude.provider.ts +15 -15
  86. package/server/modules/providers/list/codex/codex-auth.provider.ts +115 -115
  87. package/server/modules/providers/list/codex/codex-mcp.provider.ts +135 -135
  88. package/server/modules/providers/list/codex/codex-sessions.provider.ts +319 -319
  89. package/server/modules/providers/list/codex/codex.provider.ts +15 -15
  90. package/server/modules/providers/list/cursor/cursor-auth.provider.ts +143 -143
  91. package/server/modules/providers/list/cursor/cursor-mcp.provider.ts +108 -108
  92. package/server/modules/providers/list/cursor/cursor-sessions.provider.ts +421 -421
  93. package/server/modules/providers/list/cursor/cursor.provider.ts +15 -15
  94. package/server/modules/providers/list/gemini/gemini-auth.provider.ts +163 -163
  95. package/server/modules/providers/list/gemini/gemini-mcp.provider.ts +110 -110
  96. package/server/modules/providers/list/gemini/gemini-sessions.provider.ts +227 -227
  97. package/server/modules/providers/list/gemini/gemini.provider.ts +15 -15
  98. package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +232 -232
  99. package/server/modules/providers/list/qwen/qwen-sessions.provider.ts +265 -265
  100. package/server/modules/providers/provider.registry.ts +40 -40
  101. package/server/modules/providers/provider.routes.ts +819 -819
  102. package/server/modules/providers/services/mcp.service.ts +86 -86
  103. package/server/modules/providers/services/provider-auth.service.ts +26 -26
  104. package/server/modules/providers/services/sessions.service.ts +45 -45
  105. package/server/modules/providers/shared/base/abstract.provider.ts +20 -20
  106. package/server/modules/providers/shared/mcp/mcp.provider.ts +151 -151
  107. package/server/modules/providers/tests/mcp.test.ts +293 -293
  108. package/server/openai-codex.js +462 -462
  109. package/server/opencode-cli.js +459 -459
  110. package/server/opencode-response-handler.js +107 -107
  111. package/server/projects.js +3105 -3105
  112. package/server/routes/agent.js +1365 -1365
  113. package/server/routes/auth.js +138 -138
  114. package/server/routes/codex.js +19 -19
  115. package/server/routes/commands.js +554 -554
  116. package/server/routes/cursor.js +52 -52
  117. package/server/routes/gemini.js +24 -24
  118. package/server/routes/git.js +1488 -1488
  119. package/server/routes/mcp-utils.js +31 -31
  120. package/server/routes/messages.js +61 -61
  121. package/server/routes/network.js +120 -120
  122. package/server/routes/plugins.js +318 -318
  123. package/server/routes/projects.js +915 -915
  124. package/server/routes/settings.js +286 -286
  125. package/server/routes/taskmaster.js +1496 -1496
  126. package/server/routes/telegram.js +125 -125
  127. package/server/routes/user.js +123 -123
  128. package/server/services/install-jobs.js +571 -571
  129. package/server/services/notification-orchestrator.js +242 -242
  130. package/server/services/provider-credentials.js +189 -189
  131. package/server/services/telegram/bot.js +279 -279
  132. package/server/services/telegram/translations.js +170 -170
  133. package/server/sessionManager.js +225 -225
  134. package/server/shared/interfaces.ts +54 -54
  135. package/server/shared/types.ts +172 -172
  136. package/server/shared/utils.ts +193 -193
  137. package/server/tsconfig.json +36 -36
  138. package/server/utils/colors.js +21 -21
  139. package/server/utils/commandParser.js +303 -303
  140. package/server/utils/frontmatter.js +18 -18
  141. package/server/utils/gitConfig.js +34 -34
  142. package/server/utils/mcp-detector.js +147 -147
  143. package/server/utils/plugin-loader.js +457 -457
  144. package/server/utils/plugin-process-manager.js +184 -184
  145. package/server/utils/runtime-paths.js +37 -37
  146. package/server/utils/taskmaster-websocket.js +128 -128
  147. package/server/utils/url-detection.js +71 -71
  148. package/server/vite-daemon.js +78 -78
  149. package/shared/modelConstants.js +162 -162
  150. package/shared/networkHosts.js +22 -22
@@ -1,577 +1,577 @@
1
- // server/modules/orchestration/a2a/routes.ts
2
- // HTTP surface for A2A v0.2. Mounted at /a2a in server/index.js.
3
-
4
- import crypto from 'node:crypto';
5
-
6
- import type { Request, Response, Router } from 'express';
7
- import express from 'express';
8
-
9
- import { adapterRegistry } from '@/modules/orchestration/a2a/adapter-registry.js';
10
- import { buildPixcodeAgentCard } from '@/modules/orchestration/a2a/agent-card.js';
11
- import { a2aAuth } from '@/modules/orchestration/a2a/auth.middleware.js';
12
- import { a2aBus } from '@/modules/orchestration/a2a/bus.js';
13
- import { A2ATaskStore } from '@/modules/orchestration/a2a/task-store.js';
14
- import type {
15
- BusEvent,
16
- Message,
17
- Task,
18
- TaskState,
19
- } from '@/modules/orchestration/a2a/types.js';
20
- import {
21
- A2AValidationError,
22
- assertMessage,
23
- assertSubmitTaskInput,
24
- } from '@/modules/orchestration/a2a/validator.js';
25
- import { portWatcher } from '@/modules/orchestration/preview/port-watcher.js';
26
- import type { PreviewArtifactData } from '@/modules/orchestration/preview/types.js';
27
- import { workspaceManager } from '@/modules/orchestration/workspace/workspace-manager.js';
28
- import type {
29
- WorkspaceHandle,
30
- WorkspaceKind,
31
- WorkspaceMetadata,
32
- } from '@/modules/orchestration/workspace/types.js';
33
- import { WorkspaceError } from '@/modules/orchestration/workspace/types.js';
34
-
35
- type RoutingHints = {
36
- preferredAdapterId?: string;
37
- preferredProvider?: string;
38
- preferredSkillId?: string;
39
- };
40
-
41
- function readRoutingHints(value: unknown): RoutingHints {
42
- if (!value || typeof value !== 'object') {
43
- return {};
44
- }
45
-
46
- const source = value as Record<string, unknown>;
47
- return {
48
- preferredAdapterId:
49
- typeof source.preferredAdapterId === 'string' ? source.preferredAdapterId : undefined,
50
- preferredProvider:
51
- typeof source.preferredProvider === 'string' ? source.preferredProvider : undefined,
52
- preferredSkillId:
53
- typeof source.preferredSkillId === 'string' ? source.preferredSkillId : undefined,
54
- };
55
- }
56
-
57
- const TERMINAL: TaskState[] = ['completed', 'canceled', 'failed'];
58
- // Per-task bus unsubscribe handles; called on terminal state.
59
- const taskUnsubs = new Map<string, () => void>();
60
- // Eviction timeouts (terminal tasks live for 1 hour before being purged).
61
- const taskEvictions = new Map<string, NodeJS.Timeout>();
62
- const TERMINAL_TASK_TTL_MS = 60 * 60 * 1000; // 1 hour
63
- const MAX_TASKS = 1000;
64
- const taskStore = new A2ATaskStore({ terminalTaskTtlMs: TERMINAL_TASK_TTL_MS });
65
- const activeWorkspaces = new Map<string, WorkspaceHandle>();
66
- const previewStops = new Map<string, () => void>();
67
- const finalizingTasks = new Set<string>();
68
-
69
- function newId(prefix: string): string {
70
- return `${prefix}_${crypto.randomBytes(8).toString('hex')}`;
71
- }
72
-
73
- function isTerminalTaskState(state: TaskState): boolean {
74
- return TERMINAL.includes(state);
75
- }
76
-
77
- function getBaseUrl(req: Request): string {
78
- // TODO: this trusts X-Forwarded-Proto/Host without checking app's
79
- // trust-proxy setting. Same posture as auth.middleware.ts; revisit
80
- // when project-wide trust-proxy decision lands.
81
- const proto = req.header('x-forwarded-proto') ?? req.protocol;
82
- const host = req.header('x-forwarded-host') ?? req.get('host');
83
- return `${proto}://${host}`;
84
- }
85
-
86
- function scheduleTaskEviction(taskId: string): void {
87
- const existingTimeout = taskEvictions.get(taskId);
88
- if (existingTimeout) {
89
- clearTimeout(existingTimeout);
90
- }
91
-
92
- const task = taskStore.get(taskId);
93
- if (!task) {
94
- taskEvictions.delete(taskId);
95
- return;
96
- }
97
-
98
- const remainingMs = Math.max(0, task.updatedAt + TERMINAL_TASK_TTL_MS - Date.now());
99
- taskEvictions.set(
100
- taskId,
101
- setTimeout(() => {
102
- taskStore.delete(taskId);
103
- taskEvictions.delete(taskId);
104
- }, remainingMs),
105
- );
106
- }
107
-
108
- function parseTaskState(value: unknown): TaskState | undefined {
109
- if (typeof value !== 'string') {
110
- return undefined;
111
- }
112
-
113
- const normalized = value.trim();
114
- if (
115
- normalized === 'submitted' ||
116
- normalized === 'working' ||
117
- normalized === 'input-required' ||
118
- normalized === 'completed' ||
119
- normalized === 'canceled' ||
120
- normalized === 'failed'
121
- ) {
122
- return normalized;
123
- }
124
-
125
- return undefined;
126
- }
127
-
128
- function parsePositiveInt(value: unknown, fallback: number): number {
129
- if (typeof value !== 'string') {
130
- return fallback;
131
- }
132
-
133
- const parsed = Number.parseInt(value, 10);
134
- if (!Number.isFinite(parsed) || parsed < 0) {
135
- return fallback;
136
- }
137
-
138
- return parsed;
139
- }
140
-
141
- function readString(value: unknown): string | undefined {
142
- return typeof value === 'string' && value.trim() ? value : undefined;
143
- }
144
-
145
- function readBoolean(value: unknown): boolean | undefined {
146
- return typeof value === 'boolean' ? value : undefined;
147
- }
148
-
149
- function readObject(value: unknown): Record<string, unknown> | undefined {
150
- return value && typeof value === 'object' ? value as Record<string, unknown> : undefined;
151
- }
152
-
153
- function readWorkspaceKind(value: unknown): WorkspaceKind | undefined {
154
- return value === 'host' || value === 'worktree' || value === 'docker' ? value : undefined;
155
- }
156
-
157
- function workspaceMetadata(workspace: WorkspaceHandle, keepAfterCompletion?: boolean): WorkspaceMetadata {
158
- return {
159
- id: workspace.id,
160
- kind: workspace.kind,
161
- path: workspace.path,
162
- baseRef: workspace.baseRef,
163
- branchName: workspace.branchName,
164
- keepAfterCompletion,
165
- };
166
- }
167
-
168
- async function finalizeTerminalTask(task: Task): Promise<void> {
169
- if (finalizingTasks.has(task.id)) return;
170
- finalizingTasks.add(task.id);
171
-
172
- const stopPreview = previewStops.get(task.id);
173
- if (stopPreview) {
174
- stopPreview();
175
- previewStops.delete(task.id);
176
- }
177
-
178
- const workspace = activeWorkspaces.get(task.id);
179
- try {
180
- if (workspace) {
181
- const diff = await workspace.diff();
182
- a2aBus.publish({
183
- kind: 'artifact',
184
- taskId: task.id,
185
- artifact: {
186
- artifactId: newId('art'),
187
- type: 'file-diff',
188
- parts: [{ kind: 'text', text: diff }],
189
- metadata: {
190
- source: 'workspace-diff',
191
- workspaceId: workspace.id,
192
- workspaceKind: workspace.kind,
193
- baseRef: workspace.baseRef,
194
- },
195
- },
196
- });
197
-
198
- const keepAfterCompletion = task.metadata?.workspace &&
199
- typeof task.metadata.workspace === 'object' &&
200
- readBoolean((task.metadata.workspace as Record<string, unknown>).keepAfterCompletion);
201
- if (workspace.kind !== 'host' && keepAfterCompletion !== true) {
202
- await workspace.destroy();
203
- }
204
- }
205
- } catch (error) {
206
- const message = error instanceof Error ? error.message : String(error);
207
- task.metadata = {
208
- ...task.metadata,
209
- workspaceFinalizationError: message,
210
- };
211
- task.updatedAt = Date.now();
212
- taskStore.set(task);
213
- } finally {
214
- activeWorkspaces.delete(task.id);
215
- const unsub = taskUnsubs.get(task.id);
216
- if (unsub) {
217
- unsub();
218
- taskUnsubs.delete(task.id);
219
- }
220
- scheduleTaskEviction(task.id);
221
- finalizingTasks.delete(task.id);
222
- }
223
- }
224
-
225
- function attachBusToTask(task: Task): void {
226
- const unsubscribe = a2aBus.subscribe(task.id, (event: BusEvent) => {
227
- if (event.kind === 'task-state') {
228
- task.state = event.state;
229
- if (event.error) task.error = event.error;
230
- task.updatedAt = Date.now();
231
- taskStore.set(task);
232
- if (isTerminalTaskState(event.state)) {
233
- void finalizeTerminalTask(task);
234
- }
235
- } else if (event.kind === 'message') {
236
- task.history.push(event.message);
237
- task.updatedAt = Date.now();
238
- taskStore.set(task);
239
- } else if (event.kind === 'artifact') {
240
- task.artifacts.push(event.artifact);
241
- task.updatedAt = Date.now();
242
- taskStore.set(task);
243
- }
244
- });
245
- taskUnsubs.set(task.id, unsubscribe);
246
- }
247
-
248
- for (const task of taskStore.values()) {
249
- if (isTerminalTaskState(task.state)) {
250
- scheduleTaskEviction(task.id);
251
- }
252
- }
253
-
254
- export function createA2ARouter(): Router {
255
- const router: Router = express.Router();
256
-
257
- router.use(express.json({ limit: '5mb' }));
258
- router.use(a2aAuth);
259
-
260
- // Discovery
261
- router.get('/.well-known/agent-card.json', (req, res) => {
262
- res.json(buildPixcodeAgentCard(getBaseUrl(req)));
263
- });
264
-
265
- router.get('/agents', (_req, res) => {
266
- res.json({ agents: adapterRegistry.agentCards() });
267
- });
268
-
269
- router.get('/agents/:id/agent-card', (req, res) => {
270
- const adapter = adapterRegistry.get(req.params.id);
271
- if (!adapter) {
272
- res.status(404).json({ error: { code: 'AGENT_NOT_FOUND', message: req.params.id } });
273
- return;
274
- }
275
- res.json(adapter.agentCard);
276
- });
277
-
278
- router.post('/adapters/resolve', (req, res) => {
279
- const selector = typeof req.body?.adapterId === 'string' ? req.body.adapterId : '';
280
- if (!selector.trim()) {
281
- res.status(400).json({
282
- error: { code: 'ADAPTER_ID_REQUIRED', message: 'adapterId is required.' },
283
- });
284
- return;
285
- }
286
-
287
- const routing = readRoutingHints(req.body?.routing);
288
- const adapter = adapterRegistry.resolve(selector, routing);
289
- if (!adapter) {
290
- res.status(404).json({
291
- error: {
292
- code: 'ADAPTER_NOT_FOUND',
293
- message: selector,
294
- availableAdapters: adapterRegistry.list().map((candidate) => candidate.id),
295
- },
296
- });
297
- return;
298
- }
299
-
300
- res.json({
301
- selector,
302
- resolvedAdapterId: adapter.id,
303
- agentCard: adapter.agentCard,
304
- });
305
- });
306
-
307
- router.get('/tasks', (req, res) => {
308
- const state = parseTaskState(req.query.state);
309
- const contextId = typeof req.query.contextId === 'string' ? req.query.contextId : undefined;
310
- const adapterId = typeof req.query.adapterId === 'string' ? req.query.adapterId : undefined;
311
- const limit = parsePositiveInt(req.query.limit, 50);
312
-
313
- const tasks = taskStore
314
- .list({ state, contextId, adapterId, limit })
315
- .map((task) => taskStore.summarize(task));
316
-
317
- res.json({
318
- tasks,
319
- count: tasks.length,
320
- filters: {
321
- state,
322
- contextId,
323
- adapterId,
324
- limit,
325
- },
326
- });
327
- });
328
-
329
- // Task lifecycle
330
- router.post('/tasks', async (req: Request, res: Response) => {
331
- try {
332
- assertSubmitTaskInput(req.body);
333
- } catch (err) {
334
- const e = err as A2AValidationError;
335
- res.status(400).json({ error: { code: 'INVALID_INPUT', message: e.message, path: e.path } });
336
- return;
337
- }
338
-
339
- const metadata = req.body.metadata as Record<string, unknown> | undefined;
340
- const routing = readRoutingHints(metadata?.routing);
341
-
342
- const adapter = adapterRegistry.resolve(req.body.adapterId, routing);
343
- if (!adapter) {
344
- res.status(404).json({
345
- error: {
346
- code: 'ADAPTER_NOT_FOUND',
347
- message: req.body.adapterId,
348
- availableAdapters: adapterRegistry.list().map((candidate) => candidate.id),
349
- },
350
- });
351
- return;
352
- }
353
-
354
- // Enforce MAX_TASKS cap. Evict the oldest terminal task first; if all
355
- // active, fail closed with 503.
356
- if (taskStore.size >= MAX_TASKS) {
357
- let evicted = false;
358
- for (const [tid, t] of taskStore.entries()) {
359
- if (isTerminalTaskState(t.state)) {
360
- const timeout = taskEvictions.get(tid);
361
- if (timeout) clearTimeout(timeout);
362
- taskEvictions.delete(tid);
363
- const unsub = taskUnsubs.get(tid);
364
- if (unsub) {
365
- unsub();
366
- taskUnsubs.delete(tid);
367
- }
368
- taskStore.delete(tid);
369
- evicted = true;
370
- break;
371
- }
372
- }
373
- if (!evicted) {
374
- res.status(503).json({
375
- error: { code: 'TASK_LIMIT', message: `task store at capacity (${MAX_TASKS})` },
376
- });
377
- return;
378
- }
379
- }
380
-
381
- const userMessage: Message = req.body.message;
382
- const task: Task = {
383
- id: newId('task'),
384
- contextId: req.body.contextId,
385
- state: 'submitted',
386
- history: [],
387
- artifacts: [],
388
- metadata: req.body.metadata,
389
- createdAt: Date.now(),
390
- updatedAt: Date.now(),
391
- };
392
- task.history.push({ ...userMessage, taskId: task.id });
393
- const workspaceOptions = (metadata?.workspace && typeof metadata.workspace === 'object'
394
- ? metadata.workspace
395
- : {}) as Record<string, unknown>;
396
- // Persist adapterId in metadata so cancel can resolve the owning adapter
397
- // even when the original request body is no longer available.
398
- task.metadata = {
399
- ...task.metadata,
400
- adapterId: adapter.id,
401
- adapterSelector: req.body.adapterId,
402
- };
403
- taskStore.set(task);
404
- attachBusToTask(task);
405
-
406
- let workspace: WorkspaceHandle;
407
- try {
408
- workspace = await workspaceManager.create({
409
- taskId: task.id,
410
- projectPath: readString(workspaceOptions.projectPath) ?? process.cwd(),
411
- kind: readWorkspaceKind(workspaceOptions.kind) ?? readWorkspaceKind(metadata?.isolation),
412
- baseRef: readString(workspaceOptions.baseRef) ?? readString(metadata?.baseRef) ?? 'HEAD',
413
- keepAfterCompletion: readBoolean(workspaceOptions.keepAfterCompletion),
414
- metadata: workspaceOptions,
415
- });
416
- } catch (err) {
417
- const workspaceError = err instanceof WorkspaceError ? err : undefined;
418
- a2aBus.publish({
419
- kind: 'task-state',
420
- taskId: task.id,
421
- state: 'failed',
422
- error: {
423
- code: workspaceError?.code ?? 'WORKSPACE_CREATE_FAILED',
424
- message: err instanceof Error ? err.message : String(err),
425
- details: workspaceError?.details,
426
- },
427
- });
428
- res.status(202).json(task);
429
- return;
430
- }
431
-
432
- activeWorkspaces.set(task.id, workspace);
433
- task.metadata = {
434
- ...task.metadata,
435
- workspace: workspaceMetadata(workspace, readBoolean(workspaceOptions.keepAfterCompletion)),
436
- };
437
- taskStore.set(task);
438
-
439
- previewStops.set(
440
- task.id,
441
- portWatcher.watch({
442
- taskId: task.id,
443
- workspace,
444
- onPort: (event) => {
445
- const data: PreviewArtifactData = {
446
- url: event.url,
447
- proxiedUrl: `/preview/${event.port}/`,
448
- port: event.port,
449
- host: event.host,
450
- processName: event.processName,
451
- confidence: event.confidence,
452
- };
453
- a2aBus.publish({
454
- kind: 'artifact',
455
- taskId: task.id,
456
- artifact: {
457
- artifactId: newId('art'),
458
- type: 'preview-url',
459
- parts: [{ kind: 'data', data: { ...data } }],
460
- metadata: {
461
- source: 'port-watcher',
462
- workspaceId: workspace.id,
463
- },
464
- },
465
- });
466
- },
467
- }),
468
- );
469
-
470
- try {
471
- await adapter.submitTask(task, {
472
- cwd: workspace.path,
473
- workspace,
474
- model: readString(metadata?.model),
475
- permissionMode: readString(metadata?.permissionMode),
476
- toolsSettings: readObject(metadata?.toolsSettings),
477
- });
478
- } catch (err) {
479
- // Publish to bus so SSE subscribers and the attachBusToTask listener
480
- // both see the failure transition. The listener mutates the stored
481
- // task in place, so the 202 body still reflects the failed state.
482
- a2aBus.publish({
483
- kind: 'task-state',
484
- taskId: task.id,
485
- state: 'failed',
486
- error: {
487
- code: 'ADAPTER_SUBMIT_FAILED',
488
- message: err instanceof Error ? err.message : String(err),
489
- },
490
- });
491
- }
492
-
493
- res.status(202).json(task);
494
- });
495
-
496
- router.get('/tasks/:id', (req, res) => {
497
- const task = taskStore.get(req.params.id);
498
- if (!task) {
499
- res.status(404).json({ error: { code: 'TASK_NOT_FOUND', message: req.params.id } });
500
- return;
501
- }
502
- res.json(task);
503
- });
504
-
505
- router.get('/tasks/:id/stream', (req, res) => {
506
- const task = taskStore.get(req.params.id);
507
- if (!task) {
508
- res.status(404).json({ error: { code: 'TASK_NOT_FOUND', message: req.params.id } });
509
- return;
510
- }
511
- res.setHeader('Content-Type', 'text/event-stream');
512
- res.setHeader('Cache-Control', 'no-cache, no-transform');
513
- res.setHeader('Connection', 'keep-alive');
514
- res.flushHeaders();
515
-
516
- // Replay current state once so late subscribers see history.
517
- const initial = { kind: 'task-snapshot' as const, task };
518
- res.write(`event: snapshot\ndata: ${JSON.stringify(initial)}\n\n`);
519
-
520
- const unsubscribe = a2aBus.subscribe(task.id, (event) => {
521
- res.write(`event: ${event.kind}\ndata: ${JSON.stringify(event)}\n\n`);
522
- if (event.kind === 'task-state' && TERMINAL.includes(event.state)) {
523
- setTimeout(() => res.end(), 1500);
524
- }
525
- });
526
-
527
- req.on('close', () => {
528
- unsubscribe();
529
- });
530
- });
531
-
532
- router.post('/tasks/:id/cancel', async (req, res) => {
533
- const task = taskStore.get(req.params.id);
534
- if (!task) {
535
- res.status(404).json({ error: { code: 'TASK_NOT_FOUND', message: req.params.id } });
536
- return;
537
- }
538
- // Look up the adapter that owns this task. We stored adapterId in metadata.
539
- const adapterId = req.body?.adapterId ?? task.metadata?.adapterId;
540
- const adapter = typeof adapterId === 'string' ? adapterRegistry.resolve(adapterId) : undefined;
541
- if (!adapter) {
542
- res.status(400).json({
543
- error: {
544
- code: 'ADAPTER_REQUIRED',
545
- message: 'Provide adapterId to cancel a task whose adapter is unknown',
546
- },
547
- });
548
- return;
549
- }
550
- await adapter.cancelTask(task.id);
551
- res.json(taskStore.get(task.id));
552
- });
553
-
554
- router.post('/messages', (req, res) => {
555
- try {
556
- assertMessage(req.body);
557
- } catch (err) {
558
- const e = err as A2AValidationError;
559
- res.status(400).json({ error: { code: 'INVALID_INPUT', message: e.message, path: e.path } });
560
- return;
561
- }
562
- if (typeof req.body.taskId === 'string' && !taskStore.get(req.body.taskId)) {
563
- res.status(404).json({
564
- error: { code: 'TASK_NOT_FOUND', message: req.body.taskId },
565
- });
566
- return;
567
- }
568
- a2aBus.publish({
569
- kind: 'message',
570
- taskId: req.body.taskId ?? 'broadcast',
571
- message: req.body,
572
- });
573
- res.status(202).json({ accepted: true });
574
- });
575
-
576
- return router;
577
- }
1
+ // server/modules/orchestration/a2a/routes.ts
2
+ // HTTP surface for A2A v0.2. Mounted at /a2a in server/index.js.
3
+
4
+ import crypto from 'node:crypto';
5
+
6
+ import type { Request, Response, Router } from 'express';
7
+ import express from 'express';
8
+
9
+ import { adapterRegistry } from '@/modules/orchestration/a2a/adapter-registry.js';
10
+ import { buildPixcodeAgentCard } from '@/modules/orchestration/a2a/agent-card.js';
11
+ import { a2aAuth } from '@/modules/orchestration/a2a/auth.middleware.js';
12
+ import { a2aBus } from '@/modules/orchestration/a2a/bus.js';
13
+ import { A2ATaskStore } from '@/modules/orchestration/a2a/task-store.js';
14
+ import type {
15
+ BusEvent,
16
+ Message,
17
+ Task,
18
+ TaskState,
19
+ } from '@/modules/orchestration/a2a/types.js';
20
+ import {
21
+ A2AValidationError,
22
+ assertMessage,
23
+ assertSubmitTaskInput,
24
+ } from '@/modules/orchestration/a2a/validator.js';
25
+ import { portWatcher } from '@/modules/orchestration/preview/port-watcher.js';
26
+ import type { PreviewArtifactData } from '@/modules/orchestration/preview/types.js';
27
+ import { workspaceManager } from '@/modules/orchestration/workspace/workspace-manager.js';
28
+ import type {
29
+ WorkspaceHandle,
30
+ WorkspaceKind,
31
+ WorkspaceMetadata,
32
+ } from '@/modules/orchestration/workspace/types.js';
33
+ import { WorkspaceError } from '@/modules/orchestration/workspace/types.js';
34
+
35
+ type RoutingHints = {
36
+ preferredAdapterId?: string;
37
+ preferredProvider?: string;
38
+ preferredSkillId?: string;
39
+ };
40
+
41
+ function readRoutingHints(value: unknown): RoutingHints {
42
+ if (!value || typeof value !== 'object') {
43
+ return {};
44
+ }
45
+
46
+ const source = value as Record<string, unknown>;
47
+ return {
48
+ preferredAdapterId:
49
+ typeof source.preferredAdapterId === 'string' ? source.preferredAdapterId : undefined,
50
+ preferredProvider:
51
+ typeof source.preferredProvider === 'string' ? source.preferredProvider : undefined,
52
+ preferredSkillId:
53
+ typeof source.preferredSkillId === 'string' ? source.preferredSkillId : undefined,
54
+ };
55
+ }
56
+
57
+ const TERMINAL: TaskState[] = ['completed', 'canceled', 'failed'];
58
+ // Per-task bus unsubscribe handles; called on terminal state.
59
+ const taskUnsubs = new Map<string, () => void>();
60
+ // Eviction timeouts (terminal tasks live for 1 hour before being purged).
61
+ const taskEvictions = new Map<string, NodeJS.Timeout>();
62
+ const TERMINAL_TASK_TTL_MS = 60 * 60 * 1000; // 1 hour
63
+ const MAX_TASKS = 1000;
64
+ const taskStore = new A2ATaskStore({ terminalTaskTtlMs: TERMINAL_TASK_TTL_MS });
65
+ const activeWorkspaces = new Map<string, WorkspaceHandle>();
66
+ const previewStops = new Map<string, () => void>();
67
+ const finalizingTasks = new Set<string>();
68
+
69
+ function newId(prefix: string): string {
70
+ return `${prefix}_${crypto.randomBytes(8).toString('hex')}`;
71
+ }
72
+
73
+ function isTerminalTaskState(state: TaskState): boolean {
74
+ return TERMINAL.includes(state);
75
+ }
76
+
77
+ function getBaseUrl(req: Request): string {
78
+ // TODO: this trusts X-Forwarded-Proto/Host without checking app's
79
+ // trust-proxy setting. Same posture as auth.middleware.ts; revisit
80
+ // when project-wide trust-proxy decision lands.
81
+ const proto = req.header('x-forwarded-proto') ?? req.protocol;
82
+ const host = req.header('x-forwarded-host') ?? req.get('host');
83
+ return `${proto}://${host}`;
84
+ }
85
+
86
+ function scheduleTaskEviction(taskId: string): void {
87
+ const existingTimeout = taskEvictions.get(taskId);
88
+ if (existingTimeout) {
89
+ clearTimeout(existingTimeout);
90
+ }
91
+
92
+ const task = taskStore.get(taskId);
93
+ if (!task) {
94
+ taskEvictions.delete(taskId);
95
+ return;
96
+ }
97
+
98
+ const remainingMs = Math.max(0, task.updatedAt + TERMINAL_TASK_TTL_MS - Date.now());
99
+ taskEvictions.set(
100
+ taskId,
101
+ setTimeout(() => {
102
+ taskStore.delete(taskId);
103
+ taskEvictions.delete(taskId);
104
+ }, remainingMs),
105
+ );
106
+ }
107
+
108
+ function parseTaskState(value: unknown): TaskState | undefined {
109
+ if (typeof value !== 'string') {
110
+ return undefined;
111
+ }
112
+
113
+ const normalized = value.trim();
114
+ if (
115
+ normalized === 'submitted' ||
116
+ normalized === 'working' ||
117
+ normalized === 'input-required' ||
118
+ normalized === 'completed' ||
119
+ normalized === 'canceled' ||
120
+ normalized === 'failed'
121
+ ) {
122
+ return normalized;
123
+ }
124
+
125
+ return undefined;
126
+ }
127
+
128
+ function parsePositiveInt(value: unknown, fallback: number): number {
129
+ if (typeof value !== 'string') {
130
+ return fallback;
131
+ }
132
+
133
+ const parsed = Number.parseInt(value, 10);
134
+ if (!Number.isFinite(parsed) || parsed < 0) {
135
+ return fallback;
136
+ }
137
+
138
+ return parsed;
139
+ }
140
+
141
+ function readString(value: unknown): string | undefined {
142
+ return typeof value === 'string' && value.trim() ? value : undefined;
143
+ }
144
+
145
+ function readBoolean(value: unknown): boolean | undefined {
146
+ return typeof value === 'boolean' ? value : undefined;
147
+ }
148
+
149
+ function readObject(value: unknown): Record<string, unknown> | undefined {
150
+ return value && typeof value === 'object' ? value as Record<string, unknown> : undefined;
151
+ }
152
+
153
+ function readWorkspaceKind(value: unknown): WorkspaceKind | undefined {
154
+ return value === 'host' || value === 'worktree' || value === 'docker' ? value : undefined;
155
+ }
156
+
157
+ function workspaceMetadata(workspace: WorkspaceHandle, keepAfterCompletion?: boolean): WorkspaceMetadata {
158
+ return {
159
+ id: workspace.id,
160
+ kind: workspace.kind,
161
+ path: workspace.path,
162
+ baseRef: workspace.baseRef,
163
+ branchName: workspace.branchName,
164
+ keepAfterCompletion,
165
+ };
166
+ }
167
+
168
+ async function finalizeTerminalTask(task: Task): Promise<void> {
169
+ if (finalizingTasks.has(task.id)) return;
170
+ finalizingTasks.add(task.id);
171
+
172
+ const stopPreview = previewStops.get(task.id);
173
+ if (stopPreview) {
174
+ stopPreview();
175
+ previewStops.delete(task.id);
176
+ }
177
+
178
+ const workspace = activeWorkspaces.get(task.id);
179
+ try {
180
+ if (workspace) {
181
+ const diff = await workspace.diff();
182
+ a2aBus.publish({
183
+ kind: 'artifact',
184
+ taskId: task.id,
185
+ artifact: {
186
+ artifactId: newId('art'),
187
+ type: 'file-diff',
188
+ parts: [{ kind: 'text', text: diff }],
189
+ metadata: {
190
+ source: 'workspace-diff',
191
+ workspaceId: workspace.id,
192
+ workspaceKind: workspace.kind,
193
+ baseRef: workspace.baseRef,
194
+ },
195
+ },
196
+ });
197
+
198
+ const keepAfterCompletion = task.metadata?.workspace &&
199
+ typeof task.metadata.workspace === 'object' &&
200
+ readBoolean((task.metadata.workspace as Record<string, unknown>).keepAfterCompletion);
201
+ if (workspace.kind !== 'host' && keepAfterCompletion !== true) {
202
+ await workspace.destroy();
203
+ }
204
+ }
205
+ } catch (error) {
206
+ const message = error instanceof Error ? error.message : String(error);
207
+ task.metadata = {
208
+ ...task.metadata,
209
+ workspaceFinalizationError: message,
210
+ };
211
+ task.updatedAt = Date.now();
212
+ taskStore.set(task);
213
+ } finally {
214
+ activeWorkspaces.delete(task.id);
215
+ const unsub = taskUnsubs.get(task.id);
216
+ if (unsub) {
217
+ unsub();
218
+ taskUnsubs.delete(task.id);
219
+ }
220
+ scheduleTaskEviction(task.id);
221
+ finalizingTasks.delete(task.id);
222
+ }
223
+ }
224
+
225
+ function attachBusToTask(task: Task): void {
226
+ const unsubscribe = a2aBus.subscribe(task.id, (event: BusEvent) => {
227
+ if (event.kind === 'task-state') {
228
+ task.state = event.state;
229
+ if (event.error) task.error = event.error;
230
+ task.updatedAt = Date.now();
231
+ taskStore.set(task);
232
+ if (isTerminalTaskState(event.state)) {
233
+ void finalizeTerminalTask(task);
234
+ }
235
+ } else if (event.kind === 'message') {
236
+ task.history.push(event.message);
237
+ task.updatedAt = Date.now();
238
+ taskStore.set(task);
239
+ } else if (event.kind === 'artifact') {
240
+ task.artifacts.push(event.artifact);
241
+ task.updatedAt = Date.now();
242
+ taskStore.set(task);
243
+ }
244
+ });
245
+ taskUnsubs.set(task.id, unsubscribe);
246
+ }
247
+
248
+ for (const task of taskStore.values()) {
249
+ if (isTerminalTaskState(task.state)) {
250
+ scheduleTaskEviction(task.id);
251
+ }
252
+ }
253
+
254
+ export function createA2ARouter(): Router {
255
+ const router: Router = express.Router();
256
+
257
+ router.use(express.json({ limit: '5mb' }));
258
+ router.use(a2aAuth);
259
+
260
+ // Discovery
261
+ router.get('/.well-known/agent-card.json', (req, res) => {
262
+ res.json(buildPixcodeAgentCard(getBaseUrl(req)));
263
+ });
264
+
265
+ router.get('/agents', (_req, res) => {
266
+ res.json({ agents: adapterRegistry.agentCards() });
267
+ });
268
+
269
+ router.get('/agents/:id/agent-card', (req, res) => {
270
+ const adapter = adapterRegistry.get(req.params.id);
271
+ if (!adapter) {
272
+ res.status(404).json({ error: { code: 'AGENT_NOT_FOUND', message: req.params.id } });
273
+ return;
274
+ }
275
+ res.json(adapter.agentCard);
276
+ });
277
+
278
+ router.post('/adapters/resolve', (req, res) => {
279
+ const selector = typeof req.body?.adapterId === 'string' ? req.body.adapterId : '';
280
+ if (!selector.trim()) {
281
+ res.status(400).json({
282
+ error: { code: 'ADAPTER_ID_REQUIRED', message: 'adapterId is required.' },
283
+ });
284
+ return;
285
+ }
286
+
287
+ const routing = readRoutingHints(req.body?.routing);
288
+ const adapter = adapterRegistry.resolve(selector, routing);
289
+ if (!adapter) {
290
+ res.status(404).json({
291
+ error: {
292
+ code: 'ADAPTER_NOT_FOUND',
293
+ message: selector,
294
+ availableAdapters: adapterRegistry.list().map((candidate) => candidate.id),
295
+ },
296
+ });
297
+ return;
298
+ }
299
+
300
+ res.json({
301
+ selector,
302
+ resolvedAdapterId: adapter.id,
303
+ agentCard: adapter.agentCard,
304
+ });
305
+ });
306
+
307
+ router.get('/tasks', (req, res) => {
308
+ const state = parseTaskState(req.query.state);
309
+ const contextId = typeof req.query.contextId === 'string' ? req.query.contextId : undefined;
310
+ const adapterId = typeof req.query.adapterId === 'string' ? req.query.adapterId : undefined;
311
+ const limit = parsePositiveInt(req.query.limit, 50);
312
+
313
+ const tasks = taskStore
314
+ .list({ state, contextId, adapterId, limit })
315
+ .map((task) => taskStore.summarize(task));
316
+
317
+ res.json({
318
+ tasks,
319
+ count: tasks.length,
320
+ filters: {
321
+ state,
322
+ contextId,
323
+ adapterId,
324
+ limit,
325
+ },
326
+ });
327
+ });
328
+
329
+ // Task lifecycle
330
+ router.post('/tasks', async (req: Request, res: Response) => {
331
+ try {
332
+ assertSubmitTaskInput(req.body);
333
+ } catch (err) {
334
+ const e = err as A2AValidationError;
335
+ res.status(400).json({ error: { code: 'INVALID_INPUT', message: e.message, path: e.path } });
336
+ return;
337
+ }
338
+
339
+ const metadata = req.body.metadata as Record<string, unknown> | undefined;
340
+ const routing = readRoutingHints(metadata?.routing);
341
+
342
+ const adapter = adapterRegistry.resolve(req.body.adapterId, routing);
343
+ if (!adapter) {
344
+ res.status(404).json({
345
+ error: {
346
+ code: 'ADAPTER_NOT_FOUND',
347
+ message: req.body.adapterId,
348
+ availableAdapters: adapterRegistry.list().map((candidate) => candidate.id),
349
+ },
350
+ });
351
+ return;
352
+ }
353
+
354
+ // Enforce MAX_TASKS cap. Evict the oldest terminal task first; if all
355
+ // active, fail closed with 503.
356
+ if (taskStore.size >= MAX_TASKS) {
357
+ let evicted = false;
358
+ for (const [tid, t] of taskStore.entries()) {
359
+ if (isTerminalTaskState(t.state)) {
360
+ const timeout = taskEvictions.get(tid);
361
+ if (timeout) clearTimeout(timeout);
362
+ taskEvictions.delete(tid);
363
+ const unsub = taskUnsubs.get(tid);
364
+ if (unsub) {
365
+ unsub();
366
+ taskUnsubs.delete(tid);
367
+ }
368
+ taskStore.delete(tid);
369
+ evicted = true;
370
+ break;
371
+ }
372
+ }
373
+ if (!evicted) {
374
+ res.status(503).json({
375
+ error: { code: 'TASK_LIMIT', message: `task store at capacity (${MAX_TASKS})` },
376
+ });
377
+ return;
378
+ }
379
+ }
380
+
381
+ const userMessage: Message = req.body.message;
382
+ const task: Task = {
383
+ id: newId('task'),
384
+ contextId: req.body.contextId,
385
+ state: 'submitted',
386
+ history: [],
387
+ artifacts: [],
388
+ metadata: req.body.metadata,
389
+ createdAt: Date.now(),
390
+ updatedAt: Date.now(),
391
+ };
392
+ task.history.push({ ...userMessage, taskId: task.id });
393
+ const workspaceOptions = (metadata?.workspace && typeof metadata.workspace === 'object'
394
+ ? metadata.workspace
395
+ : {}) as Record<string, unknown>;
396
+ // Persist adapterId in metadata so cancel can resolve the owning adapter
397
+ // even when the original request body is no longer available.
398
+ task.metadata = {
399
+ ...task.metadata,
400
+ adapterId: adapter.id,
401
+ adapterSelector: req.body.adapterId,
402
+ };
403
+ taskStore.set(task);
404
+ attachBusToTask(task);
405
+
406
+ let workspace: WorkspaceHandle;
407
+ try {
408
+ workspace = await workspaceManager.create({
409
+ taskId: task.id,
410
+ projectPath: readString(workspaceOptions.projectPath) ?? process.cwd(),
411
+ kind: readWorkspaceKind(workspaceOptions.kind) ?? readWorkspaceKind(metadata?.isolation),
412
+ baseRef: readString(workspaceOptions.baseRef) ?? readString(metadata?.baseRef) ?? 'HEAD',
413
+ keepAfterCompletion: readBoolean(workspaceOptions.keepAfterCompletion),
414
+ metadata: workspaceOptions,
415
+ });
416
+ } catch (err) {
417
+ const workspaceError = err instanceof WorkspaceError ? err : undefined;
418
+ a2aBus.publish({
419
+ kind: 'task-state',
420
+ taskId: task.id,
421
+ state: 'failed',
422
+ error: {
423
+ code: workspaceError?.code ?? 'WORKSPACE_CREATE_FAILED',
424
+ message: err instanceof Error ? err.message : String(err),
425
+ details: workspaceError?.details,
426
+ },
427
+ });
428
+ res.status(202).json(task);
429
+ return;
430
+ }
431
+
432
+ activeWorkspaces.set(task.id, workspace);
433
+ task.metadata = {
434
+ ...task.metadata,
435
+ workspace: workspaceMetadata(workspace, readBoolean(workspaceOptions.keepAfterCompletion)),
436
+ };
437
+ taskStore.set(task);
438
+
439
+ previewStops.set(
440
+ task.id,
441
+ portWatcher.watch({
442
+ taskId: task.id,
443
+ workspace,
444
+ onPort: (event) => {
445
+ const data: PreviewArtifactData = {
446
+ url: event.url,
447
+ proxiedUrl: `/preview/${event.port}/`,
448
+ port: event.port,
449
+ host: event.host,
450
+ processName: event.processName,
451
+ confidence: event.confidence,
452
+ };
453
+ a2aBus.publish({
454
+ kind: 'artifact',
455
+ taskId: task.id,
456
+ artifact: {
457
+ artifactId: newId('art'),
458
+ type: 'preview-url',
459
+ parts: [{ kind: 'data', data: { ...data } }],
460
+ metadata: {
461
+ source: 'port-watcher',
462
+ workspaceId: workspace.id,
463
+ },
464
+ },
465
+ });
466
+ },
467
+ }),
468
+ );
469
+
470
+ try {
471
+ await adapter.submitTask(task, {
472
+ cwd: workspace.path,
473
+ workspace,
474
+ model: readString(metadata?.model),
475
+ permissionMode: readString(metadata?.permissionMode),
476
+ toolsSettings: readObject(metadata?.toolsSettings),
477
+ });
478
+ } catch (err) {
479
+ // Publish to bus so SSE subscribers and the attachBusToTask listener
480
+ // both see the failure transition. The listener mutates the stored
481
+ // task in place, so the 202 body still reflects the failed state.
482
+ a2aBus.publish({
483
+ kind: 'task-state',
484
+ taskId: task.id,
485
+ state: 'failed',
486
+ error: {
487
+ code: 'ADAPTER_SUBMIT_FAILED',
488
+ message: err instanceof Error ? err.message : String(err),
489
+ },
490
+ });
491
+ }
492
+
493
+ res.status(202).json(task);
494
+ });
495
+
496
+ router.get('/tasks/:id', (req, res) => {
497
+ const task = taskStore.get(req.params.id);
498
+ if (!task) {
499
+ res.status(404).json({ error: { code: 'TASK_NOT_FOUND', message: req.params.id } });
500
+ return;
501
+ }
502
+ res.json(task);
503
+ });
504
+
505
+ router.get('/tasks/:id/stream', (req, res) => {
506
+ const task = taskStore.get(req.params.id);
507
+ if (!task) {
508
+ res.status(404).json({ error: { code: 'TASK_NOT_FOUND', message: req.params.id } });
509
+ return;
510
+ }
511
+ res.setHeader('Content-Type', 'text/event-stream');
512
+ res.setHeader('Cache-Control', 'no-cache, no-transform');
513
+ res.setHeader('Connection', 'keep-alive');
514
+ res.flushHeaders();
515
+
516
+ // Replay current state once so late subscribers see history.
517
+ const initial = { kind: 'task-snapshot' as const, task };
518
+ res.write(`event: snapshot\ndata: ${JSON.stringify(initial)}\n\n`);
519
+
520
+ const unsubscribe = a2aBus.subscribe(task.id, (event) => {
521
+ res.write(`event: ${event.kind}\ndata: ${JSON.stringify(event)}\n\n`);
522
+ if (event.kind === 'task-state' && TERMINAL.includes(event.state)) {
523
+ setTimeout(() => res.end(), 1500);
524
+ }
525
+ });
526
+
527
+ req.on('close', () => {
528
+ unsubscribe();
529
+ });
530
+ });
531
+
532
+ router.post('/tasks/:id/cancel', async (req, res) => {
533
+ const task = taskStore.get(req.params.id);
534
+ if (!task) {
535
+ res.status(404).json({ error: { code: 'TASK_NOT_FOUND', message: req.params.id } });
536
+ return;
537
+ }
538
+ // Look up the adapter that owns this task. We stored adapterId in metadata.
539
+ const adapterId = req.body?.adapterId ?? task.metadata?.adapterId;
540
+ const adapter = typeof adapterId === 'string' ? adapterRegistry.resolve(adapterId) : undefined;
541
+ if (!adapter) {
542
+ res.status(400).json({
543
+ error: {
544
+ code: 'ADAPTER_REQUIRED',
545
+ message: 'Provide adapterId to cancel a task whose adapter is unknown',
546
+ },
547
+ });
548
+ return;
549
+ }
550
+ await adapter.cancelTask(task.id);
551
+ res.json(taskStore.get(task.id));
552
+ });
553
+
554
+ router.post('/messages', (req, res) => {
555
+ try {
556
+ assertMessage(req.body);
557
+ } catch (err) {
558
+ const e = err as A2AValidationError;
559
+ res.status(400).json({ error: { code: 'INVALID_INPUT', message: e.message, path: e.path } });
560
+ return;
561
+ }
562
+ if (typeof req.body.taskId === 'string' && !taskStore.get(req.body.taskId)) {
563
+ res.status(404).json({
564
+ error: { code: 'TASK_NOT_FOUND', message: req.body.taskId },
565
+ });
566
+ return;
567
+ }
568
+ a2aBus.publish({
569
+ kind: 'message',
570
+ taskId: req.body.taskId ?? 'broadcast',
571
+ message: req.body,
572
+ });
573
+ res.status(202).json({ accepted: true });
574
+ });
575
+
576
+ return router;
577
+ }