@1agents/acp-service 0.11.0 → 0.11.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.
@@ -18,6 +18,13 @@ function safeFailureEvent(event, trustedRuntimeErrors) {
18
18
  return { event: event.event ?? 'error', sessionId: event.sessionId, code: 'CAPACITY_PENDING',
19
19
  message: 'CAPACITY_PENDING', scope: 'control', terminal: false, data: { position: data.position, waitedMs: data.waitedMs } };
20
20
  }
21
+ // A capacity refusal is composed by this service from its own governor reading; it carries the
22
+ // occupancy a person needs and never provider text, so it keeps its message instead of a summary.
23
+ if (typeof event.code === 'string' && event.code.startsWith('ACP_CAPACITY_')) {
24
+ const data = event.data && typeof event.data === 'object' ? event.data : undefined;
25
+ return { event: 'error', sessionId: event.sessionId, code: event.code, message: String(event.message ?? ''),
26
+ scope: 'control', terminal: true, ...(data ? { data } : {}) };
27
+ }
21
28
  if (['tool_call', 'tool_call_update', 'tool_result'].includes(event.event)) {
22
29
  if (event.error === undefined && event.errorCode === undefined && event.errorText === undefined)
23
30
  return event;
@@ -143,6 +150,10 @@ export class RuntimePeer {
143
150
  if (failureEvent.code === 'CAPACITY_PENDING' || failureEvent.message === 'CAPACITY_PENDING') {
144
151
  throw new RequestError(-32010, 'CAPACITY_PENDING', failureEvent.data);
145
152
  }
153
+ // Occupancy messages are built from numeric readings only, so the client keeps the reason.
154
+ if (typeof failureEvent.code === 'string' && failureEvent.code.startsWith('ACP_CAPACITY_')) {
155
+ throw new RequestError(-32011, failureEvent.message, failureEvent.data);
156
+ }
146
157
  const safe = toSafeError(failureEvent.error ?? failureEvent, { origin: 'service', operationId: payload.requestId });
147
158
  throw new RequestError(-32000, safe.message, safe);
148
159
  }
@@ -652,6 +663,27 @@ export function attachAcpConnection(ws, req, backend = production, state = new A
652
663
  return {};
653
664
  });
654
665
  }
666
+ /**
667
+ * A dropped transport cannot own a live agent process forever. Sessions this connection
668
+ * attached are released after a grace window so a reconnecting client keeps its live
669
+ * session (session/load repoints it) while an abandoned one stops holding a capacity slot
670
+ * until the daemon restarts.
671
+ */
672
+ function releaseOrphanedSessions() {
673
+ const parsed = Number(process.env.ACP_DISCONNECT_GRACE_MS);
674
+ const grace = Number.isFinite(parsed) && parsed >= 0 ? parsed : 30_000;
675
+ for (const [sessionId, session] of [...backend.sessions]) {
676
+ if (session?.ws !== peer)
677
+ continue;
678
+ const timer = setTimeout(() => {
679
+ // Reattachment repoints the session; another connection owns it now.
680
+ if (backend.sessions.get(sessionId)?.ws !== peer)
681
+ return;
682
+ void peer.command(backend, { action: 'close_session', sessionId }).catch(() => undefined);
683
+ }, grace);
684
+ timer.unref?.();
685
+ }
686
+ }
655
687
  ws.once('close', () => {
656
688
  connected = false;
657
689
  for (const item of interactive.values())
@@ -659,6 +691,7 @@ export function attachAcpConnection(ws, req, backend = production, state = new A
659
691
  for (const pending of prompts.values())
660
692
  pending.reject(failure(undefined, { origin: 'transport', operationId: pending.requestId, outcomeUnknown: true }));
661
693
  prompts.clear();
694
+ releaseOrphanedSessions();
662
695
  });
663
696
  const connection = app.connect(webSocketStream(ws));
664
697
  client = connection.client;
@@ -1554,7 +1554,19 @@ export async function dispatchCommand(ws, payload) {
1554
1554
  console.timeEnd(`ensure_session_${sessionId}`);
1555
1555
  break;
1556
1556
  }
1557
- const admission = await processCapacity.tryAdmit({ kind: "process", source: "automatic", id: capacityId, origin: capacityId.startsWith("a2a-") ? "job" : "user-opened" }, { signal: initializationSignal });
1557
+ const origin = capacityId.startsWith("a2a-") ? "job" : "user-opened";
1558
+ // A person opening a session must be told why it cannot start instead of joining an
1559
+ // unbounded queue behind other work and failing much later with a transport error.
1560
+ // Background jobs (origin "job") keep waiting in FIFO order.
1561
+ if (origin === "user-opened") {
1562
+ const capacity = await processCapacity.snapshot("process");
1563
+ if (capacity.availableAutomatic < 1) {
1564
+ sendCapacityExhausted(ws, sessionId, capacity);
1565
+ console.timeEnd(`ensure_session_${sessionId}`);
1566
+ break;
1567
+ }
1568
+ }
1569
+ const admission = await processCapacity.tryAdmit({ kind: "process", source: "automatic", id: capacityId, origin }, { signal: initializationSignal });
1558
1570
  if (admission?.pending === true) {
1559
1571
  sendCapacityPending(ws, sessionId, admission);
1560
1572
  console.timeEnd(`ensure_session_${sessionId}`);
@@ -2549,6 +2561,37 @@ function notifySessionTakenOver(previousWs, nextWs, sessionId) {
2549
2561
  console.warn(`[acpx-server] Failed to notify taken-over ws for ${sessionId}:`, err.message);
2550
2562
  }
2551
2563
  }
2564
+ /**
2565
+ * A capacity refusal is a control-plane answer, not a turn failure: it is composed here
2566
+ * from the live governor reading so the person sees the reason and the way out immediately.
2567
+ */
2568
+ function sendCapacityExhausted(ws, sessionId, snapshot) {
2569
+ const gib = value => `${(value / (1024 ** 3)).toFixed(1)} GB`;
2570
+ const memoryBound = snapshot.memory.availableSlots < 1;
2571
+ const code = memoryBound
2572
+ ? "ACP_CAPACITY_MEMORY_LIMIT"
2573
+ : snapshot.used >= snapshot.limits.hard
2574
+ ? "ACP_CAPACITY_HARD_LIMIT"
2575
+ : "ACP_CAPACITY_SOFT_LIMIT";
2576
+ const message = memoryBound
2577
+ ? `ACP capacity is unavailable: ${gib(snapshot.memory.availableBytes)} of reclaimable memory is below the ${gib(snapshot.memory.reserveBytes)} startup reserve. Close an idle ACP session or free memory, then retry.`
2578
+ : `ACP capacity is full: ${snapshot.used} of ${snapshot.used >= snapshot.limits.hard ? snapshot.limits.hard : snapshot.limits.soft} process slots are in use. Archive or close an ACP session, then retry.`;
2579
+ ws.send(JSON.stringify({
2580
+ event: "error",
2581
+ sessionId,
2582
+ code,
2583
+ message,
2584
+ scope: "control",
2585
+ terminal: true,
2586
+ data: {
2587
+ used: snapshot.used,
2588
+ limit: snapshot.limits.soft,
2589
+ hardLimit: snapshot.limits.hard,
2590
+ availableSlots: snapshot.memory.availableSlots,
2591
+ availableBytes: snapshot.memory.availableBytes,
2592
+ },
2593
+ }));
2594
+ }
2552
2595
  function sendCapacityPending(ws, sessionId, pending) {
2553
2596
  ws.send(JSON.stringify({
2554
2597
  event: "error",
@@ -1,4 +1,4 @@
1
- import { type CapacityLease, type CapacityOptions, type CapacityRequest } from './capacity.js';
1
+ import { type CapacityKind, type CapacityLease, type CapacityOptions, type CapacityRequest, type CapacitySnapshot } from './capacity.js';
2
2
  export interface CapacityQueueWaitOptions {
3
3
  signal?: AbortSignal;
4
4
  /** Called once only when admission actually has to wait. */
@@ -18,6 +18,8 @@ export declare class CapacityQueue {
18
18
  private readonly governor;
19
19
  private readonly pollIntervalMs;
20
20
  constructor(options?: CapacityOptions, timing?: CapacityQueueTimingOptions);
21
+ /** Read-only occupancy, so a caller can refuse an interactive open without queueing it. */
22
+ snapshot(kind: CapacityKind): Promise<CapacitySnapshot>;
21
23
  acquire(request: CapacityRequest, { signal, onPending }?: CapacityQueueWaitOptions): Promise<CapacityLease>;
22
24
  /**
23
25
  * Enqueue if needed and return immediately.
@@ -35,6 +35,10 @@ export class CapacityQueue {
35
35
  if (!isPositiveInteger(this.pollIntervalMs))
36
36
  throw new Error('ACP capacity queue poll interval must be a positive safe integer');
37
37
  }
38
+ /** Read-only occupancy, so a caller can refuse an interactive open without queueing it. */
39
+ async snapshot(kind) {
40
+ return this.governor.snapshot(kind);
41
+ }
38
42
  async acquire(request, { signal, onPending } = {}) {
39
43
  if (!validRequest(request))
40
44
  throw new Error('Invalid ACP capacity request');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@1agents/acp-service",
3
- "version": "0.11.0",
3
+ "version": "0.11.1",
4
4
  "description": "agent-workflow ACP runtime, CLI, HTTP/WebSocket service and DeepSeek Harness ACP/A2A plugins in one package. Part of 一芥天地 (DreamMate World).",
5
5
  "keywords": [
6
6
  "dreammate",
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: acp-service
3
- version: 0.11.0
3
+ version: 0.11.1
4
4
  description: 使用 @1agents/acp-service 管理 ACP 会话与 DSH 插件,通过 A2A 调用固定角色、派发临时任务、查询父子任务和执行轮次、记录业务验收及处理通知,并回投 Codex/DSH 原会话。也用于把已记录产物交给另一个角色(handoff_propose、handoff_decide、handoff_offer)、登记共享产物空间、项目/角色候选探查、目标登记和网络技能更新。用户说交接、下一跳、交给另一个角色、共享产物或 caseId 时使用。不用于无关的系统巡检或模型配置;执行中的 ACP 会话没有 handoff 工具。
5
5
  ---
6
6
 
@@ -119,6 +119,12 @@ export declare class AcpAdapter implements LlmAdapter {
119
119
  processReleased: true | 'pending';
120
120
  acp: boolean;
121
121
  }>;
122
+ /**
123
+ * Reclaim the agent process of every Session the Host archived. Archiving stops the session's
124
+ * work in DSH, but the ACP process and its device capacity slot belong to the service daemon,
125
+ * so the archive has to close them explicitly instead of leaving them to time out.
126
+ */
127
+ releaseArchivedSessions(archived: ReadonlySet<string>): Promise<void>;
122
128
  /**
123
129
  * Controlled delete. ACP session/delete closes the process and marks the record deleted.
124
130
  * The DSH session and its history stay. A detached session gets a bare link, so no agent process starts.
@@ -535,6 +535,29 @@ export class AcpAdapter {
535
535
  }
536
536
  return { processReleased, acp: true };
537
537
  }
538
+ /**
539
+ * Reclaim the agent process of every Session the Host archived. Archiving stops the session's
540
+ * work in DSH, but the ACP process and its device capacity slot belong to the service daemon,
541
+ * so the archive has to close them explicitly instead of leaving them to time out.
542
+ */
543
+ async releaseArchivedSessions(archived) {
544
+ for (const sessionId of archived) {
545
+ const pending = this.links.get(sessionId);
546
+ if (!pending)
547
+ continue;
548
+ try {
549
+ await this.releaseSession(sessionId);
550
+ continue;
551
+ }
552
+ catch { /* Not found (the agent was already gone) or the daemon is unreachable; retry locally. */ }
553
+ try {
554
+ (await pending)?.close();
555
+ }
556
+ catch { /* Connection setup already failed. */ }
557
+ if (this.links.get(sessionId) === pending)
558
+ this.links.delete(sessionId);
559
+ }
560
+ }
538
561
  /**
539
562
  * Controlled delete. ACP session/delete closes the process and marks the record deleted.
540
563
  * The DSH session and its history stay. A detached session gets a bare link, so no agent process starts.
@@ -45,6 +45,25 @@ export async function apply(ctx, input = {}) {
45
45
  const processRequests = input.a2a?.workbench ? createWorkbenchProcessClient(input.a2a.workbench) : undefined;
46
46
  const adapter = new AcpAdapter(ctx, config, diagnostics, processRequests);
47
47
  ctx.effect(() => ctx.llm.registerAdapter(['1agents-acp'], adapter));
48
+ // Archiving a Session in DSH stops its work but never reaches the service daemon, where the
49
+ // ACP process and its device capacity slot live. Sweep the Host's archive set so an archived
50
+ // session gives its slot back at once instead of holding it until the daemon restarts.
51
+ ctx.effect(() => {
52
+ const interval = Number(process.env.DSH_ACP_ARCHIVE_SWEEP_MS);
53
+ const every = Number.isFinite(interval) && interval >= 0 ? interval : 2000;
54
+ if (every === 0)
55
+ return () => undefined;
56
+ const timer = setInterval(() => {
57
+ // Read the live archive set rather than a captured copy; the registry mutates it in place.
58
+ const registry = ctx.get('workspaceRegistry');
59
+ const archived = registry?.archivedSessionIds ?? [];
60
+ if (archived.length === 0)
61
+ return;
62
+ void adapter.releaseArchivedSessions(new Set(archived.map(String)));
63
+ }, every);
64
+ timer.unref?.();
65
+ return () => clearInterval(timer);
66
+ });
48
67
  // A Cordis listener is released with this plugin's fiber.
49
68
  if (processRequests)
50
69
  registerNativeApprovals(ctx, processRequests);