@1agents/acp-service 0.11.2 → 0.11.4

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 (45) hide show
  1. package/README.md +1 -1
  2. package/dist/src/a2a/executor.js +9 -6
  3. package/dist/src/acp-connection.js +7 -0
  4. package/dist/src/bridge.d.ts +3 -0
  5. package/dist/src/bridge.js +361 -31
  6. package/dist/src/catalog-descriptors.js +2 -2
  7. package/dist/src/catalog.js +26 -7
  8. package/package.json +1 -1
  9. package/skills/acp-service/SKILL.md +8 -4
  10. package/skills/acp-service/references/a2a.md +15 -2
  11. package/skills/acp-service/references/acp.md +2 -0
  12. package/skills/acp-service/references/roles-and-tasks.md +1 -1
  13. package/vendor/dsh/README.md +1 -1
  14. package/vendor/dsh/adapter.js +23 -0
  15. package/vendor/dsh/client.js +1827 -280
  16. package/vendor/dsh/session-settings.js +22 -3
  17. package/vendor/dsh/transport.d.ts +1 -0
  18. package/vendor/dsh/transport.js +4 -0
  19. package/vendor/runtime/dist/{agent-registry-CsdsVpJb.js → agent-registry-C6ejwCZj.js} +2 -2
  20. package/vendor/runtime/dist/agent-registry-C6ejwCZj.js.map +1 -0
  21. package/vendor/runtime/dist/agent-registry.d.ts.map +1 -1
  22. package/vendor/runtime/dist/agent-registry.js +1 -1
  23. package/vendor/runtime/dist/{cli-B5gQOSDl.js → cli-tuiWjPY4.js} +4 -4
  24. package/vendor/runtime/dist/{cli-B5gQOSDl.js.map → cli-tuiWjPY4.js.map} +1 -1
  25. package/vendor/runtime/dist/cli.js +10 -10
  26. package/vendor/runtime/dist/client-D5y4RXME.d.ts.map +1 -1
  27. package/vendor/runtime/dist/{flows-CDj5YcTh.js → flows-7g_AQzTI.js} +5 -5
  28. package/vendor/runtime/dist/{flows-CDj5YcTh.js.map → flows-7g_AQzTI.js.map} +1 -1
  29. package/vendor/runtime/dist/flows.js +1 -1
  30. package/vendor/runtime/dist/{input-file-BsfVGZgn.js → input-file-CtXEzLxj.js} +5 -5
  31. package/vendor/runtime/dist/{input-file-BsfVGZgn.js.map → input-file-CtXEzLxj.js.map} +1 -1
  32. package/vendor/runtime/dist/{ipc-DfqJsbk6.js → ipc-CcrTSAL7.js} +7 -2
  33. package/vendor/runtime/dist/ipc-CcrTSAL7.js.map +1 -0
  34. package/vendor/runtime/dist/{output-DOIF4iFc.js → output-CQBC8OMR.js} +3 -3
  35. package/vendor/runtime/dist/{output-DOIF4iFc.js.map → output-CQBC8OMR.js.map} +1 -1
  36. package/vendor/runtime/dist/{queue-owner-runtime-DHBQbjXo.js → queue-owner-runtime-BnqiTiN1.js} +5 -4
  37. package/vendor/runtime/dist/queue-owner-runtime-BnqiTiN1.js.map +1 -0
  38. package/vendor/runtime/dist/runtime.js +4 -4
  39. package/vendor/runtime/dist/{session-watch-DRwFHcWw.js → session-watch-BYRZyCfk.js} +4 -4
  40. package/vendor/runtime/dist/{session-watch-DRwFHcWw.js.map → session-watch-BYRZyCfk.js.map} +1 -1
  41. package/vendor/runtime/dist/{watch-CUDGkljG.js → watch-DltPDEQ0.js} +2 -2
  42. package/vendor/runtime/dist/{watch-CUDGkljG.js.map → watch-DltPDEQ0.js.map} +1 -1
  43. package/vendor/runtime/dist/agent-registry-CsdsVpJb.js.map +0 -1
  44. package/vendor/runtime/dist/ipc-DfqJsbk6.js.map +0 -1
  45. package/vendor/runtime/dist/queue-owner-runtime-DHBQbjXo.js.map +0 -1
package/README.md CHANGED
@@ -312,7 +312,7 @@ Tests use the official ACP SDK over real WebSockets, cover session lifecycle and
312
312
 
313
313
  `GET /agents` returns `{ "agents": [...] }`, a fresh local filesystem inventory shared by DSH and 1agents_app. Each entry includes the canonical ACP registry `id`, display `label`, native CLI `installed`, and `chat_ready`. Legacy app fields (`type`, capabilities, cc-connect transport, integration status and install guidance) remain available; `claude` uses the legacy app type `claudecode`.
314
314
 
315
- Discovery checks PATH, `~/.local/bin`, `~/.grok/bin`, and installed adapter package launch files. A registered native ACP command is ready when its executable exists. Adapter-backed harnesses are ready when the adapter is installed, or when their native CLI and `npx` are installed; the latter uses the runtime's existing adapter download behavior when a session launches. Having `npx` or `uvx` alone does not expose uninstalled harnesses. Scanning neither executes agents nor downloads packages, and readiness does not verify credentials or model access. Detection-only frameworks remain in the inventory with `chat_ready: false`. Antigravity is ready only when its official ACP runtime is installed (`agy_acp_server.par`, or `agy_acp_server.exe` on Windows), not when the separate `agy` CLI is present. Keep `localharness_external` from the same release beside that runtime, or set `ANTIGRAVITY_HARNESS_PATH` to the helper. Antigravity's fixed-choice questions are still cancelled by the runtime and have to be answered in an interactive client.
315
+ Discovery checks PATH, `~/.local/bin`, `~/.grok/bin`, and installed adapter package launch files. A registered native ACP command is ready when its executable exists. Adapter-backed harnesses are ready when the adapter is installed, or when their native CLI and `npx` are installed; the latter uses the runtime's existing adapter download behavior when a session launches. Having `npx` or `uvx` alone does not expose uninstalled harnesses. Scanning neither executes agents nor downloads packages, and readiness does not verify credentials or model access. Detection-only frameworks remain in the inventory with `chat_ready: false`. Antigravity prefers the `agy` CLI's built-in ACP server (`agy acp`, which exposes the full CLI model catalog including Claude and GPT models), and falls back to the standalone `agy_acp_server.par` (`agy_acp_server.exe` on Windows) with `localharness_external` only when `agy` is not installed. Antigravity's fixed-choice questions are still cancelled by the runtime and have to be answered in an interactive client.
316
316
 
317
317
  The service launcher uses the same local command resolution, including absolute paths to user-local binaries. The catalog originates from 1agents_app's former Go detector; consumers no longer probe their own host or maintain separate detection tables. `discoverAgents()` is also exported for embedded service consumers and includes local executable paths; the HTTP response omits these paths.
318
318
 
@@ -40,11 +40,11 @@ export function validateA2AExecutionOptions(options) {
40
40
  class RoleSkillLoadingError extends Error {
41
41
  constructor(cause) { super('Role skills could not be loaded or verified; the model was not started', { cause }); }
42
42
  }
43
- const sessionFailureCodes = new Set(['SESSION_NOT_FOUND', 'SESSION_DELETED', 'SESSION_CLOSED', 'SESSION_CONFLICT', 'SESSION_ATTACH_IN_PROGRESS', 'MODEL_UNAVAILABLE', 'MODEL_SELECTION_UNSUPPORTED', 'UNKNOWN_MODEL_OR_GROUP']);
44
- /** Host-authored model ids only. A mismatch keeps the static sentence and drops whatever else the error carried. */
45
- const MODEL_FAILURE_MESSAGE = /^(?:Unknown model or routing group: [A-Za-z0-9][A-Za-z0-9._:/@+-]*(?:\. Available: [A-Za-z0-9][A-Za-z0-9._:/@+-]*(?:, [A-Za-z0-9][A-Za-z0-9._:/@+-]*)*)?|The requested model is not in the DSH model catalog\.|DSH did not select [A-Za-z0-9][A-Za-z0-9._:/@+-]*)$/;
43
+ const sessionFailureCodes = new Set(['SESSION_NOT_FOUND', 'SESSION_DELETED', 'SESSION_CLOSED', 'SESSION_CONFLICT', 'SESSION_ATTACH_IN_PROGRESS', 'MODEL_UNAVAILABLE', 'MODEL_SELECTION_UNSUPPORTED', 'PRESET_UNSUPPORTED', 'UNKNOWN_MODEL_OR_GROUP']);
44
+ /** Host-authored model/preset failure text only. A mismatch keeps the static sentence and drops whatever else the error carried. */
45
+ const MODEL_FAILURE_MESSAGE = /^(?:Unknown model or routing group: [A-Za-z0-9][A-Za-z0-9._:/@+-]*(?:\. Available: [A-Za-z0-9][A-Za-z0-9._:/@+-]*(?:, [A-Za-z0-9][A-Za-z0-9._:/@+-]*)*)?|The requested model is not in the DSH model catalog\.|DSH did not select [A-Za-z0-9][A-Za-z0-9._:/@+-]*|Configure the model on the DSH headless profile|provider and model apply only to standard presets|Only the configured DSH headless composition is supported)$/;
46
46
  function modelFailureMessage(error, code) {
47
- if (code !== 'UNKNOWN_MODEL_OR_GROUP' && code !== 'MODEL_UNAVAILABLE' && code !== 'MODEL_SELECTION_UNSUPPORTED')
47
+ if (code !== 'UNKNOWN_MODEL_OR_GROUP' && code !== 'MODEL_UNAVAILABLE' && code !== 'MODEL_SELECTION_UNSUPPORTED' && code !== 'PRESET_UNSUPPORTED')
48
48
  return undefined;
49
49
  const message = error && typeof error === 'object' && typeof error.message === 'string'
50
50
  ? error.message : '';
@@ -54,6 +54,8 @@ function modelFailureMessage(error, code) {
54
54
  return 'Unknown model or routing group.';
55
55
  if (code === 'MODEL_SELECTION_UNSUPPORTED')
56
56
  return 'provider and model apply only to standard presets';
57
+ if (code === 'PRESET_UNSUPPORTED')
58
+ return 'The requested agent preset is not supported by this host.';
57
59
  return 'The requested model is not in the DSH model catalog.';
58
60
  }
59
61
  function sessionFailureCode(error) {
@@ -326,9 +328,10 @@ export class A2ASessionExecutor {
326
328
  // ACP Agents publish their own model options through session/set_config_option.
327
329
  if (input.provider && agentPreset?.startsWith('oneagents-acp-'))
328
330
  throw Object.assign(new Error('provider and model apply only to standard presets'), { code: 'MODEL_SELECTION_UNSUPPORTED' });
329
- // ACP session preparation can itself wait in the process FIFO.
331
+ // ACP session preparation can wait in backend admission; publish early submission so
332
+ // returnImmediately callers do not block on prepare(), without falsely claiming a queue wait.
330
333
  if (agentPreset?.startsWith('oneagents-acp-'))
331
- pendingCapacity();
334
+ submitted();
332
335
  // Acquire only after context/role waits, immediately before session creation.
333
336
  capacityLease = await acquireCapacity();
334
337
  controller.signal.throwIfAborted();
@@ -331,6 +331,13 @@ export function attachAcpConnection(ws, req, backend = production, state = new A
331
331
  const { event: name, type, ...params } = event;
332
332
  notify(`${EXT}events/${name || type}`, { ...params, ...(name ? { type } : { _meta: { [NS]: { viewType: true } } }) });
333
333
  }
334
+ if (event.event === 'session_closed' && (event.reason === 'idle_timeout' || event.reason === 'capacity_evicted') && connected && attached.size === 0 && prompts.size === 0 && held.size === 0) {
335
+ void output.then(() => {
336
+ if (connected && attached.size === 0 && prompts.size === 0 && held.size === 0) {
337
+ ws.close(1000, event.reason === 'capacity_evicted' ? 'Idle session evicted for capacity' : 'Idle session released');
338
+ }
339
+ });
340
+ }
334
341
  const terminal = (event.event === 'turn_state' && ['completed', 'failed', 'cancelled'].includes(event.status)) || event.event === 'done' || event.event === 'turn_terminal' || (event.event === 'error' && event.terminal !== false && event.scope === 'turn');
335
342
  if (terminal) {
336
343
  if (summary && event.event !== 'turn_state') {
@@ -19,6 +19,9 @@ export const activeSessions: Map<any, any>;
19
19
  export const sessionBackgroundTasks: Map<any, any>;
20
20
  export function gracefulExit(source: any): Promise<void>;
21
21
  export function prewarmGrokSession(targetCwd: any): Promise<void>;
22
+ export function reapIdleSessions(): Promise<any>;
23
+ export function scheduleIdleReap(): void;
24
+ export function evictIdleSessionsForCapacity({ excludeSessionId, signal }?: {}): Promise<any[]>;
22
25
  export const pendingPermissions: Map<any, any>;
23
26
  export const pendingAskUserQuestions: Map<any, any>;
24
27
  export const pendingExitPlanModes: Map<any, any>;
@@ -106,6 +106,53 @@ function interactionTimeoutMs() {
106
106
  function interactionTimeoutText() {
107
107
  return `${Math.round(interactionTimeoutMs() / 60_000)}min`;
108
108
  }
109
+ // Idle process reclamation (Phase 1: tiered TTL + pressure-driven eviction + bg-task protection).
110
+ // Inactive sessions (no running turn, no queued prompt, no pending interactive prompt,
111
+ // no running background task) release their child process and capacity lease while
112
+ // keeping their durable session record on disk for fast session/load (~0.5-1.5s).
113
+ // Defaults: interactive (user-opened) 5min, background A2A job 60s, pressure eviction grace 15s.
114
+ // Set ACP_IDLE_SESSION_TTL_MS=0 to disable periodic idle reaping.
115
+ // Set ACP_PRESSURE_EVICT_ENABLED=0 to disable on-demand capacity eviction.
116
+ const DEFAULT_IDLE_SESSION_TTL_MS = 5 * 60 * 1000;
117
+ const DEFAULT_IDLE_JOB_TTL_MS = 60 * 1000;
118
+ const DEFAULT_PRESSURE_EVICT_GRACE_MS = 15 * 1000;
119
+ const RUNNING_BACKGROUND_TASK_STATUSES = new Set(["running", "in_progress", "pending"]);
120
+ function idleSessionTtlMs() {
121
+ const raw = process.env.ACP_IDLE_SESSION_TTL_MS;
122
+ if (raw === undefined || raw === "")
123
+ return DEFAULT_IDLE_SESSION_TTL_MS;
124
+ const value = Number(raw);
125
+ if (!Number.isFinite(value))
126
+ return DEFAULT_IDLE_SESSION_TTL_MS;
127
+ return value <= 0 ? 0 : value;
128
+ }
129
+ function idleJobTtlMs(baseTtlMs = idleSessionTtlMs()) {
130
+ const raw = process.env.ACP_IDLE_JOB_TTL_MS;
131
+ if (raw !== undefined && raw !== "") {
132
+ const value = Number(raw);
133
+ if (Number.isFinite(value))
134
+ return value <= 0 ? 0 : value;
135
+ }
136
+ if (baseTtlMs <= 0)
137
+ return 0;
138
+ return Math.min(baseTtlMs, DEFAULT_IDLE_JOB_TTL_MS);
139
+ }
140
+ function sessionIdleTtlMs(session) {
141
+ const base = idleSessionTtlMs();
142
+ return session?.origin === "job" ? idleJobTtlMs(base) : base;
143
+ }
144
+ function pressureEvictEnabled() {
145
+ return process.env.ACP_PRESSURE_EVICT_ENABLED !== "0";
146
+ }
147
+ function pressureEvictGraceMs() {
148
+ const raw = process.env.ACP_PRESSURE_EVICT_GRACE_MS;
149
+ if (raw === undefined || raw === "")
150
+ return DEFAULT_PRESSURE_EVICT_GRACE_MS;
151
+ const value = Number(raw);
152
+ if (!Number.isFinite(value))
153
+ return DEFAULT_PRESSURE_EVICT_GRACE_MS;
154
+ return value < 0 ? 0 : value;
155
+ }
109
156
  function clearHandshake(launchId) {
110
157
  const timer = handshakeTimers.get(launchId);
111
158
  if (timer)
@@ -153,6 +200,13 @@ const runtime = createAcpRuntime({
153
200
  : typeof sessionKey === "string" && sessionKey ? "user-opened" : undefined;
154
201
  if (origin)
155
202
  launchOrigins.set(launch.launchId, origin);
203
+ if (!preparedByLaunch.has(launch.launchId) && pressureEvictEnabled()) {
204
+ const snapshot = await processCapacity.snapshot("process");
205
+ if (snapshot.availableAutomatic < 1) {
206
+ await evictIdleSessionsForCapacity({ excludeSessionId: sessionKey, signal });
207
+ signal.throwIfAborted();
208
+ }
209
+ }
156
210
  await capacityLifecycle.onBeforeSpawn(launch);
157
211
  signal.throwIfAborted();
158
212
  // The 60s budget starts only after the process slot is held.
@@ -204,6 +258,9 @@ const runtime = createAcpRuntime({
204
258
  return;
205
259
  }
206
260
  if (updateTag === "background_task" && Array.isArray(update?.tasks)) {
261
+ sessionBackgroundTasks.set(sessionKey, update.tasks);
262
+ touchSessionActivity(session);
263
+ scheduleIdleReap();
207
264
  // Background-task snapshots can arrive between turns (a task finishing
208
265
  // long after the turn that started it). Forward the full snapshot so
209
266
  // the client's task panel stays live.
@@ -224,9 +281,9 @@ const runtime = createAcpRuntime({
224
281
  // to the history push below so the chat transcript updates too.
225
282
  const task = parseBackgroundTaskReminder(update);
226
283
  if (task) {
227
- const tasks = sessionBackgroundTasks.get(sessionKey) ?? [];
228
- tasks.push(task);
229
- sessionBackgroundTasks.set(sessionKey, tasks);
284
+ const tasks = upsertBackgroundTask(sessionKey, task);
285
+ touchSessionActivity(session);
286
+ scheduleIdleReap();
230
287
  const ws = session.ws;
231
288
  if (ws && ws.readyState === 1 /* OPEN */) {
232
289
  ws.send(JSON.stringify({
@@ -241,14 +298,227 @@ const runtime = createAcpRuntime({
241
298
  void sendSessionMeta(session.ws, sessionKey, session.handle);
242
299
  }
243
300
  if (HISTORY_UPDATE_TAGS.has(updateTag)) {
301
+ touchSessionActivity(session);
244
302
  scheduleSessionHistoryPush(sessionKey);
245
303
  }
246
304
  },
247
305
  });
248
306
  const turnJournal = createTurnJournal({ stateDir: DEFAULT_STATE_DIR });
249
307
  // Map of active session handles and turn contexts
250
- // sessionId -> { handle, activeTurn }
308
+ // sessionId -> { handle, activeTurn, lastActivityAt }
251
309
  const activeSessions = new Map();
310
+ let idleReapTimer = null;
311
+ let idleReapInFlight = null;
312
+ let pressureEvictChain = Promise.resolve();
313
+ function touchSessionActivity(session) {
314
+ if (session)
315
+ session.lastActivityAt = Date.now();
316
+ }
317
+ function upsertBackgroundTask(sessionId, task) {
318
+ const existing = sessionBackgroundTasks.get(sessionId) ?? [];
319
+ const next = [...existing];
320
+ const idx = task?.id ? next.findIndex((item) => item?.id === task.id) : -1;
321
+ if (idx >= 0)
322
+ next[idx] = { ...next[idx], ...task };
323
+ else
324
+ next.push(task);
325
+ sessionBackgroundTasks.set(sessionId, next);
326
+ return next;
327
+ }
328
+ function hasRunningBackgroundTask(sessionId) {
329
+ const tasks = sessionBackgroundTasks.get(sessionId);
330
+ if (!Array.isArray(tasks) || tasks.length === 0)
331
+ return false;
332
+ return tasks.some((task) => RUNNING_BACKGROUND_TASK_STATUSES.has(task?.status));
333
+ }
334
+ function hasPendingInteraction(sessionId) {
335
+ for (const pending of pendingPermissions.values()) {
336
+ if (pending.sessionId === sessionId)
337
+ return true;
338
+ }
339
+ for (const pending of pendingAskUserQuestions.values()) {
340
+ if (pending.sessionId === sessionId)
341
+ return true;
342
+ }
343
+ for (const pending of pendingExitPlanModes.values()) {
344
+ if (pending.sessionId === sessionId)
345
+ return true;
346
+ }
347
+ return false;
348
+ }
349
+ function isSessionBusy(sessionId, session) {
350
+ return Boolean(session.activeTurn ||
351
+ (Array.isArray(session.promptQueue) && session.promptQueue.length > 0) ||
352
+ initializingSessions.has(sessionId) ||
353
+ hasPendingInteraction(sessionId) ||
354
+ hasRunningBackgroundTask(sessionId));
355
+ }
356
+ function isSessionIdleEligible(sessionId, session, minIdleMs, now = Date.now()) {
357
+ if (!session || isSessionBusy(sessionId, session))
358
+ return false;
359
+ if (minIdleMs < 0)
360
+ return false;
361
+ const last = typeof session.lastActivityAt === "number" ? session.lastActivityAt : now;
362
+ return now - last >= minIdleMs;
363
+ }
364
+ function evictionPriorityTier(session) {
365
+ // Tier 0: disconnected/orphaned WS; Tier 1: background A2A job; Tier 2: interactive user session
366
+ if (!session?.ws || session.ws.readyState !== 1)
367
+ return 0;
368
+ if (session.origin === "job")
369
+ return 1;
370
+ return 2;
371
+ }
372
+ function stopIdleReaper() {
373
+ if (idleReapTimer) {
374
+ clearTimeout(idleReapTimer);
375
+ idleReapTimer = null;
376
+ }
377
+ }
378
+ function scheduleIdleReap() {
379
+ stopIdleReaper();
380
+ if (activeSessions.size === 0)
381
+ return;
382
+ const now = Date.now();
383
+ let earliestDue = Infinity;
384
+ let hasScheduledTarget = false;
385
+ for (const [sessionId, session] of activeSessions.entries()) {
386
+ const ttlMs = sessionIdleTtlMs(session);
387
+ if (ttlMs <= 0)
388
+ continue;
389
+ hasScheduledTarget = true;
390
+ if (isSessionBusy(sessionId, session)) {
391
+ if (ttlMs < earliestDue)
392
+ earliestDue = ttlMs;
393
+ continue;
394
+ }
395
+ const last = typeof session.lastActivityAt === "number" ? session.lastActivityAt : now;
396
+ const remaining = ttlMs - (now - last);
397
+ if (remaining < earliestDue)
398
+ earliestDue = remaining;
399
+ }
400
+ if (!hasScheduledTarget || !Number.isFinite(earliestDue))
401
+ return;
402
+ const overrideInterval = Number(process.env.ACP_IDLE_REAP_INTERVAL_MS);
403
+ const delayMs = Number.isFinite(overrideInterval) && overrideInterval > 0
404
+ ? overrideInterval
405
+ : Math.min(60_000, Math.max(25, earliestDue));
406
+ idleReapTimer = setTimeout(() => {
407
+ idleReapTimer = null;
408
+ void reapIdleSessions().finally(() => scheduleIdleReap());
409
+ }, delayMs);
410
+ idleReapTimer.unref?.();
411
+ }
412
+ async function reclaimIdleSession(sessionId, { minIdleMs, reason, closeLabel }) {
413
+ let reaped = false;
414
+ await withTurnDispatchLock(sessionId, async () => {
415
+ const now = Date.now();
416
+ const session = activeSessions.get(sessionId);
417
+ if (!isSessionIdleEligible(sessionId, session, minIdleMs, now))
418
+ return;
419
+ activeSessions.delete(sessionId);
420
+ sessionBackgroundTasks.delete(sessionId);
421
+ unregisterAgentSessionMapping(session.handle);
422
+ clearSessionHistoryPush(sessionId);
423
+ const owner = session.ws;
424
+ const idleSec = Math.round((now - (session.lastActivityAt ?? now)) / 1000);
425
+ console.log(`[acpx-server] Reclaiming idle session process: ${sessionId} (origin=${session.origin ?? "user-opened"}, reason=${reason}, idle ${idleSec}s)`);
426
+ try {
427
+ await runtime.close({ handle: session.handle, reason: closeLabel });
428
+ }
429
+ catch (err) {
430
+ console.warn(`[acpx-server] Error closing idle session ${sessionId}:`, err);
431
+ }
432
+ sessionMcpServers.delete(session.handle?.sessionKey);
433
+ reaped = true;
434
+ if (owner && owner.readyState === 1) {
435
+ try {
436
+ owner.send(JSON.stringify({ event: "session_closed", sessionId, reason }));
437
+ }
438
+ catch {
439
+ // ignore send errors on closed peer
440
+ }
441
+ }
442
+ });
443
+ return reaped;
444
+ }
445
+ async function reapIdleSessions() {
446
+ if (idleReapInFlight)
447
+ return idleReapInFlight;
448
+ if (activeSessions.size === 0)
449
+ return [];
450
+ idleReapInFlight = (async () => {
451
+ const now = Date.now();
452
+ const candidates = [];
453
+ for (const [sessionId, session] of activeSessions.entries()) {
454
+ const ttlMs = sessionIdleTtlMs(session);
455
+ if (ttlMs > 0 && isSessionIdleEligible(sessionId, session, ttlMs, now)) {
456
+ candidates.push({ sessionId, ttlMs });
457
+ }
458
+ }
459
+ const reaped = [];
460
+ for (const { sessionId, ttlMs } of candidates) {
461
+ if (await reclaimIdleSession(sessionId, {
462
+ minIdleMs: ttlMs,
463
+ reason: "idle_timeout",
464
+ closeLabel: "Idle session timeout",
465
+ })) {
466
+ reaped.push(sessionId);
467
+ }
468
+ }
469
+ return reaped;
470
+ })();
471
+ try {
472
+ return await idleReapInFlight;
473
+ }
474
+ finally {
475
+ idleReapInFlight = null;
476
+ }
477
+ }
478
+ async function evictIdleSessionsForCapacity({ excludeSessionId, signal } = {}) {
479
+ if (!pressureEvictEnabled() || activeSessions.size === 0)
480
+ return [];
481
+ const run = async () => {
482
+ signal?.throwIfAborted();
483
+ const graceMs = pressureEvictGraceMs();
484
+ const now = Date.now();
485
+ const candidates = [];
486
+ for (const [sessionId, session] of activeSessions.entries()) {
487
+ if (sessionId === excludeSessionId)
488
+ continue;
489
+ if (!isSessionIdleEligible(sessionId, session, graceMs, now))
490
+ continue;
491
+ candidates.push({
492
+ sessionId,
493
+ tier: evictionPriorityTier(session),
494
+ lastActivityAt: typeof session.lastActivityAt === "number" ? session.lastActivityAt : now,
495
+ });
496
+ }
497
+ if (candidates.length === 0)
498
+ return [];
499
+ candidates.sort((a, b) => a.tier - b.tier || a.lastActivityAt - b.lastActivityAt);
500
+ const evicted = [];
501
+ for (const candidate of candidates) {
502
+ signal?.throwIfAborted();
503
+ const snapshot = await processCapacity.snapshot("process");
504
+ if (snapshot.availableAutomatic >= 1)
505
+ break;
506
+ const reaped = await reclaimIdleSession(candidate.sessionId, {
507
+ minIdleMs: graceMs,
508
+ reason: "capacity_evicted",
509
+ closeLabel: "Evicted idle session for capacity",
510
+ });
511
+ if (reaped)
512
+ evicted.push(candidate.sessionId);
513
+ }
514
+ if (evicted.length > 0)
515
+ scheduleIdleReap();
516
+ return evicted;
517
+ };
518
+ const next = pressureEvictChain.then(run, run);
519
+ pressureEvictChain = next.then(() => undefined, () => undefined);
520
+ return next;
521
+ }
252
522
  // Phase 2 Pre-warm pool for grok-build (scoped to the most recent CWD)
253
523
  // Disabled: nothing schedules prewarmGrokSession. A spare starts without the
254
524
  // session's env, so adopting one silently dropped settings such as GROK_HOME.
@@ -1234,7 +1504,7 @@ export function attachBridgeServer(serverOrOptions = {}) {
1234
1504
  console.error("[acpx-server] WebSocketServer error:", err);
1235
1505
  });
1236
1506
  wss.on("connection", (ws, req) => attachAcpConnection(ws, req));
1237
- wss.on("close", () => { wss = null; });
1507
+ wss.on("close", () => { stopIdleReaper(); wss = null; });
1238
1508
  return {
1239
1509
  wss,
1240
1510
  runtime,
@@ -1250,6 +1520,14 @@ export async function dispatchCommand(ws, payload) {
1250
1520
  return;
1251
1521
  }
1252
1522
  console.log(`[acpx-server] Received action: ${action} for session: ${sessionId}`);
1523
+ if (sessionId &&
1524
+ action !== "list_sessions" &&
1525
+ action !== "get_history" &&
1526
+ action !== "close_session" &&
1527
+ action !== "delete_session" &&
1528
+ action !== "close_all_sessions") {
1529
+ touchSessionActivity(activeSessions.get(sessionId));
1530
+ }
1253
1531
  try {
1254
1532
  switch (action) {
1255
1533
  case "ensure_session": {
@@ -1416,6 +1694,8 @@ export async function dispatchCommand(ws, payload) {
1416
1694
  if (ws._acpxReqHost) {
1417
1695
  existingSession.reqHost = ws._acpxReqHost;
1418
1696
  }
1697
+ touchSessionActivity(existingSession);
1698
+ scheduleIdleReap();
1419
1699
  // Re-deliver any interactive prompts that were in-flight when the
1420
1700
  // previous WebSocket dropped. The ACP runtime is still blocked
1421
1701
  // waiting for the response; re-sending the event lets the newly
@@ -1516,11 +1796,16 @@ export async function dispatchCommand(ws, payload) {
1516
1796
  promptQueue: [],
1517
1797
  ws,
1518
1798
  agentType,
1799
+ origin: typeof payload.capacityId === "string" && payload.capacityId.trim().startsWith("a2a-")
1800
+ ? "job"
1801
+ : "user-opened",
1519
1802
  sessionMode: await resolveGrokPermissionMode(handle, agentType),
1520
1803
  permissionMode: seededMode ?? "approve-reads",
1521
1804
  responsePolicy: normalizedResponsePolicy,
1522
1805
  reqHost: ws._acpxReqHost,
1806
+ lastActivityAt: Date.now(),
1523
1807
  });
1808
+ scheduleIdleReap();
1524
1809
  registerAgentSessionMapping(sessionId, handle);
1525
1810
  if (normalizedResponsePolicy !== "summary") {
1526
1811
  await sendAuthoritativeTurnSync(ws, sessionId, activeSessions.get(sessionId), true);
@@ -1547,6 +1832,9 @@ export async function dispatchCommand(ws, payload) {
1547
1832
  prewarmedGrokCwd = null;
1548
1833
  }
1549
1834
  }
1835
+ const sessionOrigin = typeof payload.capacityId === "string" && payload.capacityId.trim().startsWith("a2a-")
1836
+ ? "job"
1837
+ : "user-opened";
1550
1838
  if (typeof payload.capacityId === "string" && payload.capacityId.trim()) {
1551
1839
  const capacityId = payload.capacityId.trim();
1552
1840
  if (capacityId.length > 4096) {
@@ -1554,19 +1842,38 @@ export async function dispatchCommand(ws, payload) {
1554
1842
  console.timeEnd(`ensure_session_${sessionId}`);
1555
1843
  break;
1556
1844
  }
1557
- const origin = capacityId.startsWith("a2a-") ? "job" : "user-opened";
1845
+ const origin = sessionOrigin;
1558
1846
  // A person opening a session must be told why it cannot start instead of joining an
1559
1847
  // unbounded queue behind other work and failing much later with a transport error.
1560
1848
  // Background jobs (origin "job") keep waiting in FIFO order.
1849
+ // Before rejecting or queueing, evict eligible idle sessions to free capacity on demand.
1561
1850
  if (origin === "user-opened") {
1562
- const capacity = await processCapacity.snapshot("process");
1851
+ let capacity = await processCapacity.snapshot("process");
1852
+ if (capacity.availableAutomatic < 1) {
1853
+ const evicted = await evictIdleSessionsForCapacity({
1854
+ excludeSessionId: sessionId,
1855
+ signal: initializationSignal,
1856
+ });
1857
+ if (evicted.length > 0) {
1858
+ capacity = await processCapacity.snapshot("process");
1859
+ }
1860
+ }
1563
1861
  if (capacity.availableAutomatic < 1) {
1564
1862
  sendCapacityExhausted(ws, sessionId, capacity);
1565
1863
  console.timeEnd(`ensure_session_${sessionId}`);
1566
1864
  break;
1567
1865
  }
1568
1866
  }
1569
- const admission = await processCapacity.tryAdmit({ kind: "process", source: "automatic", id: capacityId, origin }, { signal: initializationSignal });
1867
+ let admission = await processCapacity.tryAdmit({ kind: "process", source: "automatic", id: capacityId, origin }, { signal: initializationSignal });
1868
+ if (admission?.pending === true) {
1869
+ const evicted = await evictIdleSessionsForCapacity({
1870
+ excludeSessionId: sessionId,
1871
+ signal: initializationSignal,
1872
+ });
1873
+ if (evicted.length > 0) {
1874
+ admission = await processCapacity.tryAdmit({ kind: "process", source: "automatic", id: capacityId, origin }, { signal: initializationSignal });
1875
+ }
1876
+ }
1570
1877
  if (admission?.pending === true) {
1571
1878
  sendCapacityPending(ws, sessionId, admission);
1572
1879
  console.timeEnd(`ensure_session_${sessionId}`);
@@ -1636,6 +1943,7 @@ export async function dispatchCommand(ws, payload) {
1636
1943
  promptQueue: [],
1637
1944
  ws,
1638
1945
  agentType,
1946
+ origin: sessionOrigin,
1639
1947
  sessionMode,
1640
1948
  // permissionMode is per-session and overrides the runtime
1641
1949
  // default in handlePermissionRequestCallback. The Composer's
@@ -1648,7 +1956,9 @@ export async function dispatchCommand(ws, payload) {
1648
1956
  profileRevision,
1649
1957
  responsePolicy: normalizedResponsePolicy,
1650
1958
  reqHost: ws._acpxReqHost,
1959
+ lastActivityAt: Date.now(),
1651
1960
  });
1961
+ scheduleIdleReap();
1652
1962
  registerAgentSessionMapping(sessionId, handle);
1653
1963
  if (normalizedResponsePolicy !== "summary") {
1654
1964
  await sendAuthoritativeTurnSync(ws, sessionId, activeSessions.get(sessionId), true);
@@ -1733,6 +2043,11 @@ export async function dispatchCommand(ws, payload) {
1733
2043
  return;
1734
2044
  }
1735
2045
  await withTurnDispatchLock(sessionId, async () => {
2046
+ if (activeSessions.get(sessionId) !== session) {
2047
+ sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
2048
+ return;
2049
+ }
2050
+ touchSessionActivity(session);
1736
2051
  const snapshot = await turnJournal.snapshot(sessionId);
1737
2052
  const requestFingerprint = hostPromptFingerprint(text, attachments);
1738
2053
  const existing = snapshot.turns.find((turn) => turn.clientRequestId === requestedRuntimeId);
@@ -1785,32 +2100,39 @@ export async function dispatchCommand(ws, payload) {
1785
2100
  });
1786
2101
  break;
1787
2102
  }
1788
- if (session.activeTurn || session.promptQueue.length > 0) {
1789
- // Another prompt is already executing or waiting. Append to the
1790
- // per-session queue and ack the sender — the active turn's
1791
- // finally block will drain this when it finishes.
1792
- const queuedRequestId = `queued_${Date.now()}_${session.promptQueue.length}`;
1793
- session.promptQueue.push({
2103
+ await withTurnDispatchLock(sessionId, async () => {
2104
+ if (activeSessions.get(sessionId) !== session) {
2105
+ sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
2106
+ return;
2107
+ }
2108
+ touchSessionActivity(session);
2109
+ if (session.activeTurn || session.promptQueue.length > 0) {
2110
+ // Another prompt is already executing or waiting. Append to the
2111
+ // per-session queue and ack the sender — the active turn's
2112
+ // finally block will drain this when it finishes.
2113
+ const queuedRequestId = `queued_${Date.now()}_${session.promptQueue.length}`;
2114
+ session.promptQueue.push({
2115
+ text,
2116
+ attachments,
2117
+ queuedRequestId,
2118
+ ws,
2119
+ responsePolicy: parsedPromptPolicy,
2120
+ });
2121
+ ws.send(JSON.stringify({
2122
+ event: "prompt_queued",
2123
+ sessionId,
2124
+ requestId: queuedRequestId,
2125
+ queuePosition: session.promptQueue.length,
2126
+ text,
2127
+ }));
2128
+ console.log(`[acpx-server] Prompt queued for session ${sessionId} (queue depth=${session.promptQueue.length})`);
2129
+ return;
2130
+ }
2131
+ await runPromptTurn(session, sessionId, {
1794
2132
  text,
1795
2133
  attachments,
1796
- queuedRequestId,
1797
- ws,
1798
2134
  responsePolicy: parsedPromptPolicy,
1799
2135
  });
1800
- ws.send(JSON.stringify({
1801
- event: "prompt_queued",
1802
- sessionId,
1803
- requestId: queuedRequestId,
1804
- queuePosition: session.promptQueue.length,
1805
- text,
1806
- }));
1807
- console.log(`[acpx-server] Prompt queued for session ${sessionId} (queue depth=${session.promptQueue.length})`);
1808
- return;
1809
- }
1810
- await runPromptTurn(session, sessionId, {
1811
- text,
1812
- attachments,
1813
- responsePolicy: parsedPromptPolicy,
1814
2136
  });
1815
2137
  break;
1816
2138
  }
@@ -2758,6 +3080,7 @@ async function runPromptTurn(session, sessionId, promptItem) {
2758
3080
  turn.hostTurnId = promptItem.turnId || null;
2759
3081
  turn.eventSequence = 0;
2760
3082
  session.activeTurn = turn;
3083
+ touchSessionActivity(session);
2761
3084
  let terminalSent = false;
2762
3085
  let accumulatedAnswer = "";
2763
3086
  let hasMessagePhase = false;
@@ -2765,6 +3088,7 @@ async function runPromptTurn(session, sessionId, promptItem) {
2765
3088
  void (async () => {
2766
3089
  try {
2767
3090
  for await (const event of turn.events) {
3091
+ touchSessionActivity(activeSessions.get(sessionId) ?? session);
2768
3092
  if (event.type === "text_delta") {
2769
3093
  const streamType = event.stream || "output";
2770
3094
  if (streamType === "output") {
@@ -2898,6 +3222,7 @@ async function runPromptTurn(session, sessionId, promptItem) {
2898
3222
  });
2899
3223
  }
2900
3224
  else if (event.type === "background_task" && Array.isArray(event.tasks)) {
3225
+ sessionBackgroundTasks.set(sessionId, event.tasks);
2901
3226
  sendRuntimeTurnEvent(targetWs, sessionId, turn, {
2902
3227
  event: "background_task",
2903
3228
  payload: { tasks: event.tasks },
@@ -3089,10 +3414,14 @@ async function runPromptTurn(session, sessionId, promptItem) {
3089
3414
  const currentSession = activeSessions.get(sessionId);
3090
3415
  if (currentSession?.activeTurn === turn) {
3091
3416
  currentSession.activeTurn = null;
3417
+ touchSessionActivity(currentSession);
3092
3418
  if (currentSession.promptQueue.length > 0) {
3093
3419
  const next = currentSession.promptQueue.shift();
3094
3420
  await runPromptTurn(currentSession, sessionId, next);
3095
3421
  }
3422
+ else {
3423
+ scheduleIdleReap();
3424
+ }
3096
3425
  }
3097
3426
  });
3098
3427
  }
@@ -3382,6 +3711,7 @@ async function handlePermissionRequestCallback(req, ctx) {
3382
3711
  // Subprocess Cleanup / Orphan Prevention
3383
3712
  // ----------------------------------------------------
3384
3713
  async function killAllManagedAgents() {
3714
+ stopIdleReaper();
3385
3715
  console.log("[acpx-server] Cleaning up all active sessions and child processes...");
3386
3716
  const pendingLaunches = capacityLaunchAbort;
3387
3717
  capacityLaunchAbort = new AbortController();
@@ -3446,6 +3776,6 @@ export function attachProcessSignalHandlers() {
3446
3776
  void gracefulExit("SIGTERM");
3447
3777
  });
3448
3778
  }
3449
- export { runtime, activeSessions, sessionBackgroundTasks, killAllManagedAgents, gracefulExit, prewarmGrokSession, };
3779
+ export { runtime, activeSessions, sessionBackgroundTasks, killAllManagedAgents, gracefulExit, prewarmGrokSession, reapIdleSessions, scheduleIdleReap, evictIdleSessionsForCapacity, };
3450
3780
  export { pendingPermissions, pendingAskUserQuestions, pendingExitPlanModes, loadSessionHistory };
3451
3781
  export async function readRuntimeRecord(id) { return runtime.options.sessionStore.load(id); }
@@ -123,12 +123,12 @@ export const catalogDescriptors = [
123
123
  {
124
124
  "type": "antigravity",
125
125
  "label": "Antigravity",
126
- "binary": "agy_acp_server.par",
126
+ "binary": "agy",
127
127
  "acp_capable": true,
128
128
  "cli_capable": true,
129
129
  "cc_transport": "acp",
130
130
  "integrated": true,
131
- "install_command": "Install agy_acp_server and localharness_external from the same antigravity-acp release (https://github.com/agentclientprotocol/registry/blob/main/antigravity-acp/agent.json) onto PATH, and point ANTIGRAVITY_HARNESS_PATH at that helper"
131
+ "install_command": "Install Google Antigravity CLI (agy >= 1.5 with agy acp) onto PATH, or install agy_acp_server and localharness_external from an antigravity-acp release"
132
132
  },
133
133
  {
134
134
  "type": "openhands",