@1agents/acp-service 0.8.2 → 0.9.0

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 (76) hide show
  1. package/README.md +6 -0
  2. package/dist/bin/a2a.js +10 -2
  3. package/dist/bin/acp-service.js +6 -0
  4. package/dist/bin/roles.d.ts +1 -0
  5. package/dist/bin/roles.js +24 -0
  6. package/dist/src/a2a/executor.d.ts +16 -1
  7. package/dist/src/a2a/executor.js +205 -19
  8. package/dist/src/a2a/gateway.d.ts +77 -0
  9. package/dist/src/a2a/gateway.js +349 -27
  10. package/dist/src/a2a/index.d.ts +7 -1
  11. package/dist/src/a2a/index.js +4 -0
  12. package/dist/src/a2a/result-metadata.d.ts +3 -0
  13. package/dist/src/a2a/result-metadata.js +2 -1
  14. package/dist/src/a2a/server.js +2 -1
  15. package/dist/src/a2a/store.js +7 -1
  16. package/dist/src/a2a/types.d.ts +32 -1
  17. package/dist/src/a2a/types.js +11 -1
  18. package/dist/src/acp-connection.js +93 -12
  19. package/dist/src/bridge.js +127 -4
  20. package/dist/src/capacity-lifecycle.d.ts +5 -0
  21. package/dist/src/capacity-lifecycle.js +57 -0
  22. package/dist/src/capacity-queue.d.ts +23 -0
  23. package/dist/src/capacity-queue.js +251 -0
  24. package/dist/src/capacity.d.ts +76 -0
  25. package/dist/src/capacity.js +377 -0
  26. package/dist/src/execution/human-review.d.ts +103 -0
  27. package/dist/src/execution/human-review.js +87 -0
  28. package/dist/src/execution/ledger.d.ts +5 -0
  29. package/dist/src/execution/ledger.js +39 -8
  30. package/dist/src/execution/ppt-delivery.d.ts +36 -3
  31. package/dist/src/execution/ppt-delivery.js +243 -53
  32. package/dist/src/execution/project-discovery.d.ts +56 -0
  33. package/dist/src/execution/project-discovery.js +429 -0
  34. package/dist/src/execution/report-review.d.ts +60 -0
  35. package/dist/src/execution/report-review.js +173 -0
  36. package/dist/src/execution/targets.d.ts +5 -0
  37. package/dist/src/execution/targets.js +1 -0
  38. package/dist/src/execution/workbench.d.ts +131 -0
  39. package/dist/src/execution/workbench.js +265 -0
  40. package/dist/src/index.d.ts +4 -0
  41. package/dist/src/index.js +3 -0
  42. package/dist/src/roles/index.d.ts +1 -0
  43. package/dist/src/roles/index.js +1 -0
  44. package/dist/src/roles/skills.d.ts +71 -0
  45. package/dist/src/roles/skills.js +427 -0
  46. package/package.json +5 -1
  47. package/skills/acp-service/SKILL.md +21 -7
  48. package/skills/acp-service/references/a2a.md +9 -5
  49. package/skills/acp-service/references/async-caller.md +48 -0
  50. package/skills/acp-service/references/roles-and-tasks.md +120 -0
  51. package/skills/acp-service/scripts/a2a-caller.py +242 -0
  52. package/vendor/dsh/README.md +2 -0
  53. package/vendor/dsh/a2a-executor.d.ts +4 -1
  54. package/vendor/dsh/a2a-executor.js +46 -2
  55. package/vendor/dsh/adapter.d.ts +10 -0
  56. package/vendor/dsh/adapter.js +67 -3
  57. package/vendor/dsh/client.js +84 -24
  58. package/vendor/dsh/index.js +2 -1
  59. package/vendor/runtime/dist/{cli-DeOpE2Xz.js → cli-DXmYwv3U.js} +4 -4
  60. package/vendor/runtime/dist/{cli-DeOpE2Xz.js.map → cli-DXmYwv3U.js.map} +1 -1
  61. package/vendor/runtime/dist/cli.js +7 -7
  62. package/vendor/runtime/dist/client-VQsqcIOJ.d.ts.map +1 -1
  63. package/vendor/runtime/dist/docs-site/runtime-process-lifecycle.html +1 -0
  64. package/vendor/runtime/dist/{flows-oaBGn31w.js → flows-DJ17ajbw.js} +3 -3
  65. package/vendor/runtime/dist/{flows-oaBGn31w.js.map → flows-DJ17ajbw.js.map} +1 -1
  66. package/vendor/runtime/dist/flows.js +1 -1
  67. package/vendor/runtime/dist/{invocation-options-CUDEE8vW.js → invocation-options-PBfCgrdi.js} +3 -3
  68. package/vendor/runtime/dist/{invocation-options-CUDEE8vW.js.map → invocation-options-PBfCgrdi.js.map} +1 -1
  69. package/vendor/runtime/dist/{output-CFv3jcOQ.js → output-B3MDn7kv.js} +2 -2
  70. package/vendor/runtime/dist/{output-CFv3jcOQ.js.map → output-B3MDn7kv.js.map} +1 -1
  71. package/vendor/runtime/dist/{queue-owner-runtime-DvMJiGbP.js → queue-owner-runtime-DXCVngwU.js} +15 -8
  72. package/vendor/runtime/dist/queue-owner-runtime-DXCVngwU.js.map +1 -0
  73. package/vendor/runtime/dist/runtime.js +1 -1
  74. package/vendor/runtime/dist/{session-watch-Di-wIdCH.js → session-watch-DURyCw31.js} +2 -2
  75. package/vendor/runtime/dist/{session-watch-Di-wIdCH.js.map → session-watch-DURyCw31.js.map} +1 -1
  76. package/vendor/runtime/dist/queue-owner-runtime-DvMJiGbP.js.map +0 -1
@@ -2,15 +2,21 @@
2
2
  export { createA2AServer } from './server.js';
3
3
  export type { A2AServerOptions } from './server.js';
4
4
  export { FileA2AStore } from './store.js';
5
- export type { A2ABackend, A2APrepareInput, A2ARunResult, A2ATarget, A2APreflightInput, A2APreflightRequirements, A2APreflightReport } from './types.js';
5
+ export type { A2ABackend, A2APrepareInput, A2ARunResult, A2ATarget, A2APreflightInput, A2APreflightRequirements, A2APreflightReport, A2ARoleSkills } from './types.js';
6
+ export { a2aRoleSkillsSchema } from './types.js';
7
+ export type { A2AExecutionOptions } from './executor.js';
6
8
  export { a2aPreflightInputSchema, a2aPreflightRequirementsSchema, a2aPreflightReportSchema, A2APreflightError, runA2APreflight } from './preflight.js';
7
9
  export { a2aResultContractSchema, A2AResultValidationError, createA2AResultMetadata, saveA2AResultMetadata } from './result-metadata.js';
8
10
  export type { A2AResultContract, A2AVerifiedArtifact, A2AResultMetadata } from './result-metadata.js';
9
11
  export { RemoteAgentGateway, serveA2AGateway, REMOTE_AGENT_METHODS } from './gateway.js';
10
12
  export type { A2AGatewayConfig, RemoteAgentNotice } from './gateway.js';
13
+ export { ProjectRoleDiscovery, DISCOVERY_METHODS, projectDiscoveryConfigSchema } from '../execution/project-discovery.js';
11
14
  export { A2AAutomation } from './automation.js';
12
15
  export type { A2AAutomationConfig, AutomationRun, AutomationRunStatus } from './automation.js';
13
16
  export { DirectoryLease } from './lease.js';
17
+ export { CapacityGovernor, CapacityError } from '../capacity.js';
18
+ export { CapacityQueue } from '../capacity-queue.js';
19
+ export type { CapacityOptions, CapacityLease, CapacitySnapshot } from '../capacity.js';
14
20
  export { SessionDelivery } from './session-delivery.js';
15
21
  export type { SessionBinding, SessionDeliveryReceipt, SessionDeliveryStatus } from './session-delivery.js';
16
22
  export { sessionHostSchema, deliverSessionMessage, SessionDeliveryError } from './session-hosts.js';
@@ -1,10 +1,14 @@
1
1
  /** Shared A2A 1.0 server, persistent state and host-independent executor interfaces. */
2
2
  export { createA2AServer } from './server.js';
3
3
  export { FileA2AStore } from './store.js';
4
+ export { a2aRoleSkillsSchema } from './types.js';
4
5
  export { a2aPreflightInputSchema, a2aPreflightRequirementsSchema, a2aPreflightReportSchema, A2APreflightError, runA2APreflight } from './preflight.js';
5
6
  export { a2aResultContractSchema, A2AResultValidationError, createA2AResultMetadata, saveA2AResultMetadata } from './result-metadata.js';
6
7
  export { RemoteAgentGateway, serveA2AGateway, REMOTE_AGENT_METHODS } from './gateway.js';
8
+ export { ProjectRoleDiscovery, DISCOVERY_METHODS, projectDiscoveryConfigSchema } from '../execution/project-discovery.js';
7
9
  export { A2AAutomation } from './automation.js';
8
10
  export { DirectoryLease } from './lease.js';
11
+ export { CapacityGovernor, CapacityError } from '../capacity.js';
12
+ export { CapacityQueue } from '../capacity-queue.js';
9
13
  export { SessionDelivery } from './session-delivery.js';
10
14
  export { sessionHostSchema, deliverSessionMessage, SessionDeliveryError } from './session-hosts.js';
@@ -24,6 +24,9 @@ export interface A2AResultMetadata {
24
24
  sessionId?: string;
25
25
  cwd?: string;
26
26
  agentPreset?: string;
27
+ roleId?: string;
28
+ /** Resolved by the execution host, independently from caller-declared lineage. */
29
+ roleSkills?: A2ATarget['roleSkills'];
27
30
  startedAt: string;
28
31
  finishedAt: string;
29
32
  outcome: 'completed' | 'failed' | 'input-required' | 'canceled';
@@ -102,7 +102,8 @@ export async function createA2AResultMetadata(input) {
102
102
  const metadata = {
103
103
  version: 1, producer: '1agents/a2a-host', taskId: input.taskId, contextId: input.contextId,
104
104
  requestId: input.requestId, ...(target ? { sessionId: target.sessionId, cwd: target.cwd,
105
- ...(target.agentPreset ? { agentPreset: target.agentPreset } : {}) } : {}),
105
+ ...(target.agentPreset ? { agentPreset: target.agentPreset } : {}),
106
+ ...(target.roleSkills ? { roleId: target.roleId, roleSkills: structuredClone(target.roleSkills) } : {}) } : {}),
106
107
  startedAt: input.startedAt, finishedAt: new Date().toISOString(), outcome: input.outcome,
107
108
  ...(contract ? { lineage: { ...contract, source: 'caller-declared' } } : {}),
108
109
  ...(target?.preflight || input.preflight ? { preflight: target?.preflight ?? input.preflight } : {}), artifacts: [],
@@ -3,7 +3,7 @@ import { createHash, timingSafeEqual } from 'node:crypto';
3
3
  import { AgentCard, SSE_HEADERS, TaskState, formatSSEEvent } from '@a2a-js/sdk';
4
4
  import { PushNotificationNotSupportedError, RequestMalformedError, UnsupportedOperationError } from '@a2a-js/sdk/errors';
5
5
  import { DefaultExecutionEventBusManager, DefaultRequestHandler, JsonRpcTransportHandler, ServerCallContext, V1PushNotificationSerializer, resolveUserScope, validateVersion } from '@a2a-js/sdk/server';
6
- import { A2ASessionExecutor, parseA2AInput } from './executor.js';
6
+ import { A2ASessionExecutor, parseA2AInput, validateA2AExecutionOptions } from './executor.js';
7
7
  import { Role } from '@a2a-js/sdk';
8
8
  import { toSafeError } from '@1agents/acp-service/runtime';
9
9
  import { a2aRequestId } from './request-id.js';
@@ -174,6 +174,7 @@ class HostRequestHandler extends DefaultRequestHandler {
174
174
  export async function createA2AServer(options) {
175
175
  if (!options.token?.trim())
176
176
  throw new Error('A2A requires a bearer token');
177
+ validateA2AExecutionOptions(options);
177
178
  const path = options.path ?? '/a2a';
178
179
  if (!/^\/[a-z0-9/_-]+$/i.test(path) || path.endsWith('/'))
179
180
  throw new Error('Invalid A2A route path');
@@ -6,6 +6,7 @@ import { InMemoryTaskStore, resolveUserScope, ServerCallContext, } from '@a2a-js
6
6
  import { RequestMalformedError } from '@a2a-js/sdk/errors';
7
7
  import { toSafeError } from '@1agents/acp-service/runtime';
8
8
  import { DirectoryLease } from './lease.js';
9
+ import { a2aRoleSkillsSchema } from './types.js';
9
10
  import { a2aPreflightReportSchema } from './preflight.js';
10
11
  const terminalStates = new Set([
11
12
  TaskState.TASK_STATE_COMPLETED, TaskState.TASK_STATE_FAILED,
@@ -74,7 +75,12 @@ function parseTarget(value) {
74
75
  throw new Error('Invalid A2A working directory: expected an absolute path');
75
76
  const agentPreset = source.agentPreset === undefined ? undefined : text(source.agentPreset, 'agent preset');
76
77
  const preflight = source.preflight === undefined ? undefined : a2aPreflightReportSchema.parse(source.preflight);
77
- return { sessionId, cwd, ...(agentPreset === undefined ? {} : { agentPreset }), ...(preflight === undefined ? {} : { preflight }) };
78
+ const roleSkills = source.roleSkills === undefined ? undefined : a2aRoleSkillsSchema.parse(source.roleSkills);
79
+ const roleId = source.roleId === undefined ? undefined : text(source.roleId, 'role identity');
80
+ if ((roleId !== undefined) !== (roleSkills !== undefined))
81
+ throw new Error('A2A role identity and skill lock must be stored together');
82
+ return { sessionId, cwd, ...(agentPreset === undefined ? {} : { agentPreset }), ...(preflight === undefined ? {} : { preflight }),
83
+ ...(roleSkills === undefined ? {} : { roleId, roleSkills }) };
78
84
  }
79
85
  function validatePushUrl(value) {
80
86
  const url = text(value, 'push URL');
@@ -1,5 +1,24 @@
1
1
  /** Execution interfaces shared by DSH and future standalone A2A hosts. */
2
2
  import type { SafeError } from '@1agents/acp-service/runtime';
3
+ import { z } from 'zod';
4
+ /** Host-authored summary of a verified, immutable role/skill lock. */
5
+ export declare const a2aRoleSkillsSchema: z.ZodObject<{
6
+ roleId: z.ZodString;
7
+ roleVersion: z.ZodString;
8
+ lockPath: z.ZodString;
9
+ roleDirectory: z.ZodString;
10
+ entryGuidePath: z.ZodOptional<z.ZodString>;
11
+ skills: z.ZodArray<z.ZodObject<{
12
+ key: z.ZodString;
13
+ skillId: z.ZodString;
14
+ sourceId: z.ZodString;
15
+ name: z.ZodString;
16
+ revision: z.ZodString;
17
+ directory: z.ZodString;
18
+ guidePath: z.ZodString;
19
+ }, z.core.$strict>>;
20
+ }, z.core.$strict>;
21
+ export type A2ARoleSkills = z.infer<typeof a2aRoleSkillsSchema>;
3
22
  /** Explicit host-side requirements checked without creating an agent session. */
4
23
  export interface A2APreflightRequirements {
5
24
  allowedDirectories?: string[];
@@ -34,6 +53,9 @@ export interface A2ATarget {
34
53
  cwd: string;
35
54
  agentPreset?: string;
36
55
  preflight?: A2APreflightReport;
56
+ /** Logical host binding; several bindings may use one canonical skill profile. */
57
+ roleId?: string;
58
+ roleSkills?: A2ARoleSkills;
37
59
  }
38
60
  /** Omitted location and preset reuse a saved context or the host defaults. */
39
61
  export interface A2APrepareInput {
@@ -41,6 +63,10 @@ export interface A2APrepareInput {
41
63
  cwd?: string;
42
64
  agentPreset?: string;
43
65
  preflight?: A2APreflightRequirements;
66
+ /** Only selects a host-configured profile; clients cannot supply profile or cache configuration. */
67
+ roleId?: string;
68
+ /** Optional existing parent lock under the host cache's locks directory. */
69
+ roleLockPath?: string;
44
70
  }
45
71
  /** A single DSH turn's output, without transport or host dependencies. */
46
72
  export interface A2ARunResult {
@@ -60,9 +86,14 @@ export interface A2ABackend {
60
86
  recover?(target: A2ATarget, options: {
61
87
  requestId: string;
62
88
  }): Promise<SafeError | undefined>;
63
- prepare(input: A2APrepareInput): Promise<A2ATarget>;
89
+ /** Cancel pending admission and drain owned initialization before rejecting an aborted preparation. */
90
+ prepare(input: A2APrepareInput, options?: {
91
+ signal: AbortSignal;
92
+ }): Promise<A2ATarget>;
64
93
  run(target: A2ATarget, prompt: string, options: {
65
94
  requestId: string;
66
95
  signal: AbortSignal;
96
+ /** Hosts with a session queue call this again immediately before submitting the prompt. */
97
+ beforeStart?: (signal?: AbortSignal) => Promise<void>;
67
98
  }): Promise<A2ARunResult>;
68
99
  }
@@ -1 +1,11 @@
1
- export {};
1
+ import { isAbsolute } from 'node:path';
2
+ import { z } from 'zod';
3
+ const roleText = z.string().min(1).max(4096).refine(value => !value.includes('\0'));
4
+ const rolePath = roleText.refine(isAbsolute, 'Expected an absolute role cache path');
5
+ /** Host-authored summary of a verified, immutable role/skill lock. */
6
+ export const a2aRoleSkillsSchema = z.object({
7
+ roleId: roleText, roleVersion: roleText, lockPath: rolePath, roleDirectory: rolePath,
8
+ entryGuidePath: rolePath.optional(),
9
+ skills: z.array(z.object({ key: roleText, skillId: roleText, sourceId: roleText, name: roleText,
10
+ revision: z.string().regex(/^[a-f0-9]{64}$/), directory: rolePath, guidePath: rolePath }).strict()).min(1).max(100),
11
+ }).strict();
@@ -333,8 +333,27 @@ export function attachAcpConnection(ws, req, backend = production, state = new A
333
333
  });
334
334
  }
335
335
  }
336
- async function ensure(params, fresh, replay) {
336
+ async function ensure(params, fresh, replay, signal) {
337
337
  requireInitialized();
338
+ signal?.throwIfAborted();
339
+ // Read-only status/replay work may be abandoned after cancellation; the
340
+ // dispatch that owns process creation is always awaited and explicitly closed.
341
+ async function readWhileActive(operation) {
342
+ if (!signal)
343
+ return operation;
344
+ signal.throwIfAborted();
345
+ let abort;
346
+ const canceled = new Promise((_, reject) => {
347
+ abort = () => reject(signal.reason);
348
+ signal.addEventListener('abort', abort, { once: true });
349
+ });
350
+ try {
351
+ return await Promise.race([operation, canceled]);
352
+ }
353
+ finally {
354
+ signal.removeEventListener('abort', abort);
355
+ }
356
+ }
338
357
  if (typeof params.cwd !== 'string' || !isAbsolute(params.cwd))
339
358
  throw RequestError.invalidParams('cwd must be absolute');
340
359
  try {
@@ -346,7 +365,8 @@ export function attachAcpConnection(ws, req, backend = production, state = new A
346
365
  const id = fresh ? randomUUID() : params.sessionId;
347
366
  const custom = extensions ? metadata(params) : {};
348
367
  const stored = state.get(id);
349
- const record = fresh ? undefined : await backend.record(stored?.runtimeRecordId || id);
368
+ const record = fresh ? undefined : await readWhileActive(backend.record(stored?.runtimeRecordId || id));
369
+ signal?.throwIfAborted();
350
370
  if (!fresh) {
351
371
  const live = backend.sessions.get(id);
352
372
  const binding = state.get(id);
@@ -367,9 +387,44 @@ export function attachAcpConnection(ws, req, backend = production, state = new A
367
387
  }
368
388
  if (held.has(id))
369
389
  throw new RequestError(-32000, 'Session attachment is already in progress');
390
+ const previousSession = backend.sessions.get(id);
391
+ const previousPeer = previousSession?.ws;
392
+ const previousResponsePolicy = previousSession?.acpResponsePolicy;
393
+ const previouslyAttached = attached.has(id);
370
394
  held.set(id, []);
395
+ let dispatchStarted = false;
396
+ let abortCleanup;
397
+ let restoredExisting = false;
398
+ const closeOwnedStartup = async () => {
399
+ const current = backend.sessions.get(id);
400
+ if (previousSession && current === previousSession) {
401
+ // A canceled reattachment must preserve the user's original live turn.
402
+ if (current.ws === peer) {
403
+ current.ws = previousPeer;
404
+ current.acpResponsePolicy = previousResponsePolicy;
405
+ restoredExisting = true;
406
+ }
407
+ return;
408
+ }
409
+ // Ownership may have passed to another successful attachment while a
410
+ // canceled request was awaiting status. Never close that connection.
411
+ if (current && current.ws !== peer)
412
+ return;
413
+ await peer.command(backend, { action: 'close_session', sessionId: id, initializationSignal: signal });
414
+ };
415
+ const abort = () => {
416
+ if (!dispatchStarted)
417
+ return;
418
+ // The client does not know a fresh session's ID yet. Cancel its private
419
+ // initialization immediately, including while dispatch is awaiting capacity.
420
+ abortCleanup ??= closeOwnedStartup().catch(() => undefined);
421
+ };
422
+ signal?.addEventListener('abort', abort, { once: true });
371
423
  try {
372
- const events = await peer.command(backend, { ...custom, action: 'ensure_session', sessionId: id, workspacePath: params.cwd, agentType: agentName, mcpServers: params.mcpServers, runtimeSessionKey: stored?.runtimeRecordId, resumeSessionId: fresh ? custom.resumeSessionId : record?.acpSessionId, responsePolicy: 'stream' });
424
+ signal?.throwIfAborted();
425
+ dispatchStarted = true;
426
+ const events = await peer.command(backend, { ...custom, action: 'ensure_session', sessionId: id, workspacePath: params.cwd, agentType: agentName, mcpServers: params.mcpServers, runtimeSessionKey: stored?.runtimeRecordId, resumeSessionId: fresh ? custom.resumeSessionId : record?.acpSessionId, responsePolicy: 'stream', initializationSignal: signal });
427
+ signal?.throwIfAborted();
373
428
  state.create({ sessionId: id, agentType: agentName, cwd: params.cwd, completeHistory: fresh ? !custom.resumeSessionId : stored?.completeHistory === true, runtimeRecordId: backend.sessions.get(id)?.handle?.acpxRecordId });
374
429
  attached.add(id);
375
430
  const session = backend.sessions.get(id);
@@ -382,9 +437,11 @@ export function attachAcpConnection(ws, req, backend = production, state = new A
382
437
  for (const update of state.history(id)) {
383
438
  notify('session/update', { sessionId: id, update });
384
439
  }
385
- await output;
440
+ await readWhileActive(output);
441
+ signal?.throwIfAborted();
386
442
  }
387
- const status = await backend.status(id);
443
+ const status = await readWhileActive(backend.status(id));
444
+ signal?.throwIfAborted();
388
445
  if (backend.sessions.get(id)?.ws !== peer)
389
446
  throw new RequestError(-32000, 'Session taken over during attachment');
390
447
  if (status.availableCommands) {
@@ -392,15 +449,39 @@ export function attachAcpConnection(ws, req, backend = production, state = new A
392
449
  sessionUpdate: 'available_commands_update',
393
450
  availableCommands: status.availableCommands.map((c) => ({ name: c.name, description: c.description || '', ...(c.hasInput ? { input: { hint: c.inputHint || 'Arguments' } } : {}) })),
394
451
  } });
395
- await output;
452
+ await readWhileActive(output);
453
+ signal?.throwIfAborted();
396
454
  }
397
455
  const ready = events.find(e => e.event === 'session_ready') || {};
456
+ signal?.throwIfAborted();
457
+ if (previousSession && backend.sessions.get(id) === previousSession && previousSession.ws === peer &&
458
+ previousPeer && previousPeer !== peer && previousPeer.readyState === 1) {
459
+ previousPeer.send(JSON.stringify({ event: 'session_taken_over', sessionId: id }));
460
+ }
398
461
  return { ...(fresh ? { sessionId: id } : {}), ...(status.modes ? { modes: status.modes } : {}), configOptions: configOptions(status), _meta: { [NS]: { agentSessionId: ready.agentSessionId, turnProtocolVersion: 3, agentType: agentName } } };
399
462
  }
463
+ catch (error) {
464
+ if (signal?.aborted && dispatchStarted) {
465
+ if (!previouslyAttached)
466
+ attached.delete(id);
467
+ abort();
468
+ await abortCleanup;
469
+ // A backend may finish attachment after the first close was sent.
470
+ // Awaiting dispatch and then closing again retires that late handle too.
471
+ await closeOwnedStartup();
472
+ signal.throwIfAborted();
473
+ }
474
+ throw error;
475
+ }
400
476
  finally {
477
+ signal?.removeEventListener('abort', abort);
401
478
  const buffered = held.get(id) || [];
402
479
  held.delete(id);
403
- for (const event of buffered) {
480
+ if (signal?.aborted && restoredExisting && previousPeer && previousPeer !== peer && backend.sessions.get(id)?.ws === previousPeer) {
481
+ for (const event of buffered)
482
+ previousPeer.send(JSON.stringify(event));
483
+ }
484
+ for (const event of signal?.aborted && !previouslyAttached ? [] : buffered) {
404
485
  // The explicit load replay is the standard transcript; runtime history
405
486
  // snapshots are emitted only as negotiated application extensions.
406
487
  receive(event);
@@ -416,9 +497,9 @@ export function attachAcpConnection(ws, req, backend = production, state = new A
416
497
  return { protocolVersion: PROTOCOL_VERSION, agentInfo: { name: '1agents-acp-service', version: '0.2.0' }, authMethods: [], agentCapabilities: { promptCapabilities: { image: true, audio: true }, loadSession: true, sessionCapabilities: { resume: {}, close: {}, list: {}, delete: {} }, _meta: { [NS]: { version: 1, agentType: agentName, interactions: true, turnSync: true } } } };
417
498
  })
418
499
  .onRequest('authenticate', () => { requireInitialized(); throw RequestError.invalidParams('No connection authentication methods are configured'); })
419
- .onRequest('session/new', async ({ params }) => await ensure(params, true, false))
420
- .onRequest('session/load', ({ params }) => ensure(params, false, true))
421
- .onRequest('session/resume', ({ params }) => ensure(params, false, false))
500
+ .onRequest('session/new', async ({ params, signal }) => await ensure(params, true, false, signal))
501
+ .onRequest('session/load', ({ params, signal }) => ensure(params, false, true, signal))
502
+ .onRequest('session/resume', ({ params, signal }) => ensure(params, false, false, signal))
422
503
  .onRequest('session/prompt', async ({ params, signal }) => {
423
504
  requireSession(params.sessionId);
424
505
  const custom = extensions ? metadata(params) : {};
@@ -516,11 +597,11 @@ export function attachAcpConnection(ws, req, backend = production, state = new A
516
597
  if (!value || typeof value !== 'object' || Array.isArray(value))
517
598
  throw RequestError.invalidParams('Expected object');
518
599
  return value;
519
- }, async ({ params }) => {
600
+ }, async ({ params, signal }) => {
520
601
  requireInitialized();
521
602
  if (!extensions || typeof params.sessionId !== 'string' || !params.sessionId)
522
603
  throw RequestError.invalidParams('Native session ID required');
523
- return ensure({ ...params, _meta: { [NS]: { ...metadata(params), resumeSessionId: params.sessionId } } }, true, false);
604
+ return ensure({ ...params, _meta: { [NS]: { ...metadata(params), resumeSessionId: params.sessionId } } }, true, false, signal);
524
605
  });
525
606
  const controls = { 'session/history': 'get_history', 'session/permission_mode': 'set_permission_mode', 'session/cancel_queued': 'cancel_queued', 'session/fork': 'fork_session', 'session/authenticate': 'authenticate', 'session/logout': 'logout' };
526
607
  for (const [method, action] of Object.entries(controls)) {
@@ -5,6 +5,8 @@ import * as path from "node:path";
5
5
  import { WebSocketServer } from "ws";
6
6
  import { attachAcpConnection } from "./acp-connection.js";
7
7
  import { createServiceAgentRegistry } from "./catalog.js";
8
+ import { CapacityQueue } from "./capacity-queue.js";
9
+ import { createCapacityLifecycle } from "./capacity-lifecycle.js";
8
10
  import { createAcpRuntime, createRuntimeStore, createTurnJournal, toSafeError, } from "@1agents/acp-service/runtime";
9
11
  import { historyToolInput, resolveRuntimeTurnId, stampHistoryTurnIds, } from "./history-turn-ids.js";
10
12
  // ----------------------------------------------------
@@ -80,7 +82,47 @@ function parseBackgroundTaskReminder(update) {
80
82
  // this session instead of letting later completions wipe earlier ones.
81
83
  const sessionBackgroundTasks = new Map();
82
84
  // Setup session runtime manager options
85
+ const processCapacity = new CapacityQueue();
86
+ let capacityLaunchAbort = new AbortController();
87
+ const sessionLaunchControllers = new Map();
88
+ const initializingSessionControllers = new Map();
89
+ const capacityLaunchSignals = new Map();
90
+ const capacityLifecycle = createCapacityLifecycle({
91
+ acquire: request => processCapacity.acquire(request, {
92
+ signal: capacityLaunchSignals.get(request.id) || capacityLaunchAbort.signal,
93
+ }),
94
+ });
83
95
  const runtime = createAcpRuntime({
96
+ // Includes compatibility checks, probes and pre-warm launches. Native user
97
+ // processes outside this service are not admitted through this governor.
98
+ processLifecycle: {
99
+ async onBeforeSpawn(launch) {
100
+ const session = launch.scope.kind === "runtime-session"
101
+ ? sessionLaunchControllers.get(launch.scope.sessionKey)
102
+ : undefined;
103
+ // Capture the generation before the lifecycle's deferred acquire runs.
104
+ const signal = AbortSignal.any([
105
+ capacityLaunchAbort.signal,
106
+ ...(session ? [session.controller.signal] : []),
107
+ ]);
108
+ capacityLaunchSignals.set(launch.launchId, signal);
109
+ signal.throwIfAborted();
110
+ await capacityLifecycle.onBeforeSpawn(launch);
111
+ signal.throwIfAborted();
112
+ },
113
+ async onSpawned(started) {
114
+ await capacityLifecycle.onSpawned(started);
115
+ capacityLaunchSignals.delete(started.launchId);
116
+ },
117
+ onSpawnFailed(failure) {
118
+ capacityLaunchSignals.delete(failure.launchId);
119
+ return capacityLifecycle.onSpawnFailed(failure);
120
+ },
121
+ onExit(exit) {
122
+ capacityLaunchSignals.delete(exit.launchId);
123
+ return capacityLifecycle.onExit(exit);
124
+ },
125
+ },
84
126
  cwd: process.cwd(),
85
127
  sessionStore: createRuntimeStore({ stateDir: DEFAULT_STATE_DIR }),
86
128
  agentRegistry: createServiceAgentRegistry(),
@@ -200,6 +242,17 @@ const HISTORY_PUSH_INTERVAL_MS = 300;
200
242
  const historyPushStates = new Map();
201
243
  // Map of currently initializing sessions: sessionId -> Promise<handle>
202
244
  const initializingSessions = new Map();
245
+ async function cancelInitializingSession(sessionId, expectedSignal) {
246
+ const initialization = initializingSessionControllers.get(sessionId);
247
+ if (!initialization)
248
+ return false;
249
+ if (expectedSignal && initialization.signal !== expectedSignal)
250
+ return false;
251
+ initialization.controller.abort(new DOMException("ACP session initialization canceled", "AbortError"));
252
+ // Wait for late handles and bridge state to be retired, not just ensureSession().
253
+ await initialization.done;
254
+ return true;
255
+ }
203
256
  // Map of Agent UUID -> Client Session ID (for permission callbacks)
204
257
  const agentSessionToClientSession = new Map();
205
258
  function registerAgentSessionMapping(sessionId, handle) {
@@ -1111,6 +1164,11 @@ export async function dispatchCommand(ws, payload) {
1111
1164
  try {
1112
1165
  switch (action) {
1113
1166
  case "ensure_session": {
1167
+ // This object is supplied only by the process-local ACP adapter. JSON
1168
+ // extension metadata cannot manufacture an AbortSignal instance.
1169
+ const initializationSignal = payload.initializationSignal instanceof AbortSignal
1170
+ ? payload.initializationSignal : undefined;
1171
+ initializationSignal?.throwIfAborted();
1114
1172
  const { workspacePath, agentType, systemContext, mcpServers, resumeSessionId, acpSessionId, permissionMode, responsePolicy, env, launch, } = payload;
1115
1173
  const normalizedResponsePolicy = responsePolicy === "summary" ? "summary" : "stream";
1116
1174
  console.time(`ensure_session_${sessionId}`);
@@ -1237,7 +1295,10 @@ export async function dispatchCommand(ws, payload) {
1237
1295
  }
1238
1296
  if (existingSession) {
1239
1297
  console.log(`[acpx-server] Reconnecting to existing session: ${sessionId}`);
1240
- notifySessionTakenOver(existingSession.ws, ws, sessionId);
1298
+ // ACP attachment commits after its status read. A canceled attach
1299
+ // must not invalidate the original user's live request first.
1300
+ if (!initializationSignal)
1301
+ notifySessionTakenOver(existingSession.ws, ws, sessionId);
1241
1302
  existingSession.ws = ws;
1242
1303
  if (launchArgv.length > 0) {
1243
1304
  await runtime.ensureSession({
@@ -1302,11 +1363,14 @@ export async function dispatchCommand(ws, payload) {
1302
1363
  }
1303
1364
  if (initializingSessions.has(sessionId)) {
1304
1365
  console.log(`[acpx-server] Session ${sessionId} is currently initializing, awaiting...`);
1366
+ const initialization = initializingSessionControllers.get(sessionId);
1305
1367
  try {
1306
1368
  const handle = await initializingSessions.get(sessionId);
1369
+ initialization?.controller.signal.throwIfAborted();
1307
1370
  const sess = activeSessions.get(sessionId);
1308
1371
  if (sess) {
1309
- notifySessionTakenOver(sess.ws, ws, sessionId);
1372
+ if (!initializationSignal)
1373
+ notifySessionTakenOver(sess.ws, ws, sessionId);
1310
1374
  sess.ws = ws;
1311
1375
  sess.agentType = agentType;
1312
1376
  sess.sessionMode = await resolveGrokPermissionMode(handle, agentType);
@@ -1314,8 +1378,10 @@ export async function dispatchCommand(ws, payload) {
1314
1378
  sess.permissionMode = seededMode;
1315
1379
  }
1316
1380
  }
1381
+ initialization?.controller.signal.throwIfAborted();
1317
1382
  registerAgentSessionMapping(sessionId, handle);
1318
1383
  await sendAuthoritativeTurnSync(ws, sessionId, sess || { handle, agentType });
1384
+ initialization?.controller.signal.throwIfAborted();
1319
1385
  ws.send(JSON.stringify({
1320
1386
  event: "session_ready",
1321
1387
  sessionId,
@@ -1397,11 +1463,25 @@ export async function dispatchCommand(ws, payload) {
1397
1463
  agentArgv: launchArgv.length > 0 ? launchArgv : undefined,
1398
1464
  authCredentials: transientCredentials,
1399
1465
  };
1466
+ let finishInitialization;
1467
+ const initialization = {
1468
+ controller: new AbortController(),
1469
+ signal: initializationSignal,
1470
+ done: new Promise(resolve => { finishInitialization = resolve; }),
1471
+ };
1472
+ const forwardCancellation = () => initialization.controller.abort(initializationSignal.reason);
1473
+ initializationSignal?.addEventListener("abort", forwardCancellation, { once: true });
1474
+ if (initializationSignal?.aborted)
1475
+ forwardCancellation();
1476
+ initializingSessionControllers.set(sessionId, initialization);
1477
+ sessionLaunchControllers.set(runtimeSessionKey, initialization);
1400
1478
  const sessionPromise = (async () => {
1401
1479
  try {
1480
+ initialization.controller.signal.throwIfAborted();
1402
1481
  return await runtime.ensureSession(ensureInput);
1403
1482
  }
1404
1483
  catch (err) {
1484
+ initialization.controller.signal.throwIfAborted();
1405
1485
  if (!profileChanged || !resumeId) {
1406
1486
  throw err;
1407
1487
  }
@@ -1410,8 +1490,13 @@ export async function dispatchCommand(ws, payload) {
1410
1490
  }
1411
1491
  })();
1412
1492
  initializingSessions.set(sessionId, sessionPromise);
1493
+ let initializedHandle;
1413
1494
  try {
1414
1495
  const handle = await sessionPromise;
1496
+ initializedHandle = handle;
1497
+ initialization.controller.signal.throwIfAborted();
1498
+ const sessionMode = await resolveGrokPermissionMode(handle, agentType);
1499
+ initialization.controller.signal.throwIfAborted();
1415
1500
  console.timeEnd(`ensure_session_${sessionId}`);
1416
1501
  console.log(`[DEBUG] ensure_session finished for session=${sessionId}`);
1417
1502
  // Asynchronously trigger background pre-warm after a cold spawn using the new CWD
@@ -1424,7 +1509,7 @@ export async function dispatchCommand(ws, payload) {
1424
1509
  promptQueue: [],
1425
1510
  ws,
1426
1511
  agentType,
1427
- sessionMode: await resolveGrokPermissionMode(handle, agentType),
1512
+ sessionMode,
1428
1513
  // permissionMode is per-session and overrides the runtime
1429
1514
  // default in handlePermissionRequestCallback. The Composer's
1430
1515
  // mode toggle later updates this via set_permission_mode.
@@ -1441,6 +1526,7 @@ export async function dispatchCommand(ws, payload) {
1441
1526
  if (normalizedResponsePolicy !== "summary") {
1442
1527
  await sendAuthoritativeTurnSync(ws, sessionId, activeSessions.get(sessionId), true);
1443
1528
  }
1529
+ initialization.controller.signal.throwIfAborted();
1444
1530
  ws.send(JSON.stringify({
1445
1531
  event: "session_ready",
1446
1532
  sessionId,
@@ -1459,8 +1545,27 @@ export async function dispatchCommand(ws, payload) {
1459
1545
  }));
1460
1546
  }
1461
1547
  }
1548
+ catch (error) {
1549
+ if (initialization.controller.signal.aborted && initializedHandle) {
1550
+ const current = activeSessions.get(sessionId);
1551
+ if (current?.handle === initializedHandle) {
1552
+ activeSessions.delete(sessionId);
1553
+ sessionBackgroundTasks.delete(sessionId);
1554
+ }
1555
+ unregisterAgentSessionMapping(initializedHandle);
1556
+ await runtime.close({ handle: initializedHandle, reason: "Session initialization canceled" });
1557
+ }
1558
+ throw error;
1559
+ }
1462
1560
  finally {
1463
- initializingSessions.delete(sessionId);
1561
+ initializationSignal?.removeEventListener("abort", forwardCancellation);
1562
+ if (initializingSessions.get(sessionId) === sessionPromise)
1563
+ initializingSessions.delete(sessionId);
1564
+ if (initializingSessionControllers.get(sessionId) === initialization)
1565
+ initializingSessionControllers.delete(sessionId);
1566
+ if (sessionLaunchControllers.get(runtimeSessionKey) === initialization)
1567
+ sessionLaunchControllers.delete(runtimeSessionKey);
1568
+ finishInitialization();
1464
1569
  }
1465
1570
  break;
1466
1571
  }
@@ -1848,6 +1953,10 @@ export async function dispatchCommand(ws, payload) {
1848
1953
  }
1849
1954
  const session = activeSessions.get(sessionId);
1850
1955
  if (!session) {
1956
+ if (await cancelInitializingSession(sessionId)) {
1957
+ clearSessionHistoryPush(sessionId);
1958
+ break;
1959
+ }
1851
1960
  sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1852
1961
  return;
1853
1962
  }
@@ -1901,7 +2010,13 @@ export async function dispatchCommand(ws, payload) {
1901
2010
  sendError(ws, sessionId, "INVALID_PARAMS", "sessionId is required");
1902
2011
  return;
1903
2012
  }
2013
+ const expectedSignal = payload.initializationSignal instanceof AbortSignal ? payload.initializationSignal : undefined;
2014
+ if (expectedSignal && activeSessions.get(sessionId)?.ws && activeSessions.get(sessionId).ws !== ws)
2015
+ break;
2016
+ await cancelInitializingSession(sessionId, expectedSignal);
1904
2017
  const session = activeSessions.get(sessionId);
2018
+ if (expectedSignal && session && session.ws !== ws)
2019
+ break;
1905
2020
  if (session) {
1906
2021
  console.log(`[acpx-server] Closing session: ${sessionId}`);
1907
2022
  unregisterAgentSessionMapping(session.handle);
@@ -3073,7 +3188,15 @@ async function handlePermissionRequestCallback(req, ctx) {
3073
3188
  // ----------------------------------------------------
3074
3189
  async function killAllManagedAgents() {
3075
3190
  console.log("[acpx-server] Cleaning up all active sessions and child processes...");
3191
+ const pendingLaunches = capacityLaunchAbort;
3192
+ capacityLaunchAbort = new AbortController();
3193
+ pendingLaunches.abort(new Error("ACP service is closing pending launches"));
3194
+ const pendingInitializations = [...initializingSessionControllers.values()];
3195
+ for (const initialization of pendingInitializations) {
3196
+ initialization.controller.abort(new Error("ACP service is closing pending launches"));
3197
+ }
3076
3198
  const promises = [];
3199
+ promises.push(...pendingInitializations.map(initialization => initialization.done));
3077
3200
  for (const [sessionId, session] of activeSessions.entries()) {
3078
3201
  try {
3079
3202
  unregisterAgentSessionMapping(session.handle);
@@ -0,0 +1,5 @@
1
+ /** Bind runtime launch admission to durable device capacity reservations. */
2
+ import type { AcpProcessLifecycle } from '@1agents/acp-service/runtime';
3
+ import type { CapacityGovernor, CapacitySource } from './capacity.js';
4
+ /** The runtime owns child termination; capacity remains reserved until its exit is observed. */
5
+ export declare function createCapacityLifecycle(governor: Pick<CapacityGovernor, 'acquire'>, source?: CapacitySource): AcpProcessLifecycle;