maka-agent 0.2.0-dev.23.20260906 → 0.2.0-dev.24.20260907

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 (148) hide show
  1. package/dist/acp/maka-acp-agent.js +2 -1
  2. package/dist/acp/session-configuration.js +143 -0
  3. package/dist/acp/session-registry.js +90 -4
  4. package/dist/cli-core.js +2 -0
  5. package/dist/pi-transcript.js +5 -12
  6. package/dist/pi-tui-runner.js +74 -4
  7. package/dist/runtime-host-cli-context.js +167 -78
  8. package/dist/runtime-host-cli-installation.js +8 -2
  9. package/dist/runtime-host-cli.js +31 -1
  10. package/dist/runtime-host-handoff-surface.js +81 -0
  11. package/dist/runtime-host-installed-update-bootstrap.js +13 -0
  12. package/dist/runtime-host-installed-update-coordinator.js +33 -0
  13. package/dist/runtime-host-lifecycle-transaction.js +9 -1
  14. package/dist/runtime-host-local-handoff.js +37 -4
  15. package/dist/runtime-host-local-managed-activation.js +84 -0
  16. package/dist/runtime-host-local-source-retirement.js +18 -2
  17. package/dist/runtime-host-managed-lifecycle-manager.js +1 -0
  18. package/dist/runtime-host-operator-retirement.js +50 -0
  19. package/dist/runtime-host-service-manager.js +3 -0
  20. package/dist/runtime-host-session-driver.js +4 -25
  21. package/dist/runtime-host-session-update.js +62 -0
  22. package/dist/runtime-host-tui-command.js +38 -73
  23. package/dist/runtime-host-tui-context.js +1 -0
  24. package/dist/runtime-host-tui-owner.js +226 -0
  25. package/dist/tui-copy-catalog.js +140 -3
  26. package/dist/tui-host-owner-copy.js +24 -0
  27. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  28. package/node_modules/@maka/core/dist/canonical-runtime-event.js +3 -1
  29. package/node_modules/@maka/core/dist/model-failure.js +40 -0
  30. package/node_modules/@maka/core/dist/model-metadata.generated.js +4 -4
  31. package/node_modules/@maka/core/dist/model-metadata.js +3 -3
  32. package/node_modules/@maka/core/dist/model-web-search.js +5 -4
  33. package/node_modules/@maka/core/dist/provider-registry.js +45 -4
  34. package/node_modules/@maka/core/dist/record-schema.js +9 -2
  35. package/node_modules/@maka/core/dist/runtime-boundary.js +31 -11
  36. package/node_modules/@maka/core/dist/runtime-event.js +37 -6
  37. package/node_modules/@maka/core/dist/runtime-handoff.js +98 -0
  38. package/node_modules/@maka/core/dist/runtime-invocation.js +1 -1
  39. package/node_modules/@maka/core/dist/runtime-logical-execution.js +112 -0
  40. package/node_modules/@maka/core/dist/session.js +54 -52
  41. package/node_modules/@maka/core/dist/slash-command-catalog.js +2 -0
  42. package/node_modules/@maka/core/dist/tool-result-archive-evidence.js +20 -0
  43. package/node_modules/@maka/core/dist/usage-record-schema.js +26 -35
  44. package/node_modules/@maka/core/package.json +4 -0
  45. package/node_modules/@maka/mcp/dist/index.js +131 -1
  46. package/node_modules/@maka/runtime/dist/agent-run.js +272 -105
  47. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +13 -5
  48. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +109 -34
  49. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +127 -133
  50. package/node_modules/@maka/runtime/dist/context-budget.js +14 -9
  51. package/node_modules/@maka/runtime/dist/conversation-copy.js +5 -4
  52. package/node_modules/@maka/runtime/dist/goal-continuation.js +36 -4
  53. package/node_modules/@maka/runtime/dist/history-compact-checkpoint.js +18 -9
  54. package/node_modules/@maka/runtime/dist/history-compact-summarizer.js +30 -22
  55. package/node_modules/@maka/runtime/dist/history-compaction.js +29 -4
  56. package/node_modules/@maka/runtime/dist/ledger-tool-result-archive-reader.js +106 -0
  57. package/node_modules/@maka/runtime/dist/message-authority.js +9 -0
  58. package/node_modules/@maka/runtime/dist/model-adapter.js +19 -98
  59. package/node_modules/@maka/runtime/dist/model-factory.js +19 -81
  60. package/node_modules/@maka/runtime/dist/model-fetcher.js +7 -0
  61. package/node_modules/@maka/runtime/dist/model-runtime.js +85 -111
  62. package/node_modules/@maka/runtime/dist/native-web-search-tool.js +2 -1
  63. package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +2 -2
  64. package/node_modules/@maka/runtime/dist/opencode-session-header.js +4 -2
  65. package/node_modules/@maka/runtime/dist/provider-error-classification.js +84 -123
  66. package/node_modules/@maka/runtime/dist/provider-request-telemetry.js +68 -108
  67. package/node_modules/@maka/runtime/dist/run-handoff-gate.js +97 -0
  68. package/node_modules/@maka/runtime/dist/runtime-event-backfill.js +82 -54
  69. package/node_modules/@maka/runtime/dist/runtime-event-read-model.js +117 -159
  70. package/node_modules/@maka/runtime/dist/runtime-kernel.js +150 -112
  71. package/node_modules/@maka/runtime/dist/runtime-ledger-repair.js +160 -79
  72. package/node_modules/@maka/runtime/dist/runtime-read-model.js +30 -89
  73. package/node_modules/@maka/runtime/dist/runtime-resume.js +80 -4
  74. package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +5 -0
  75. package/node_modules/@maka/runtime/dist/session-manager.js +171 -288
  76. package/node_modules/@maka/runtime/dist/session-projection-helpers.js +0 -27
  77. package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +3 -4
  78. package/node_modules/@maka/runtime/dist/test-connection.js +16 -16
  79. package/node_modules/@maka/runtime/dist/tool-result-archive-encoding.js +38 -0
  80. package/node_modules/@maka/runtime/dist/tool-runtime.js +3 -61
  81. package/node_modules/@maka/runtime/package.json +1 -0
  82. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +35 -0
  83. package/node_modules/@maka/runtime-host/dist/client/connect-or-spawn.js +9 -1
  84. package/node_modules/@maka/runtime-host/dist/client/connection.js +3 -0
  85. package/node_modules/@maka/runtime-host/dist/client/host-handoff-copy.js +156 -0
  86. package/node_modules/@maka/runtime-host/dist/client/host-handoff.js +273 -0
  87. package/node_modules/@maka/runtime-host/dist/client/host-retirement.js +26 -5
  88. package/node_modules/@maka/runtime-host/dist/client/index.js +2 -0
  89. package/node_modules/@maka/runtime-host/dist/client/launcher.js +3 -0
  90. package/node_modules/@maka/runtime-host/dist/client/remote-compatibility-error.js +2 -0
  91. package/node_modules/@maka/runtime-host/dist/client/session-subscription.js +27 -5
  92. package/node_modules/@maka/runtime-host/dist/operator/index.js +2 -1
  93. package/node_modules/@maka/runtime-host/dist/operator/retirement-cancellation.js +20 -0
  94. package/node_modules/@maka/runtime-host/dist/protocol/host-status.js +21 -12
  95. package/node_modules/@maka/runtime-host/dist/protocol/index.js +25 -1
  96. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +1 -0
  97. package/node_modules/@maka/runtime-host/dist/protocol/session-continuity.js +40 -20
  98. package/node_modules/@maka/runtime-host/dist/protocol/session-transcript.js +0 -5
  99. package/node_modules/@maka/runtime-host/dist/protocol/session-turns.js +29 -58
  100. package/node_modules/@maka/runtime-host/dist/protocol/turn.js +11 -1
  101. package/node_modules/@maka/runtime-host/dist/server/access-credential-store.js +1 -0
  102. package/node_modules/@maka/runtime-host/dist/server/canonical-turn-snapshot.js +19 -4
  103. package/node_modules/@maka/runtime-host/dist/server/connection-session.js +7 -6
  104. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +100 -24
  105. package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +5 -5
  106. package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +3 -2
  107. package/node_modules/@maka/runtime-host/dist/server/goal-coordinator.js +40 -1
  108. package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +96 -17
  109. package/node_modules/@maka/runtime-host/dist/server/host-residency-registry.js +13 -7
  110. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-admission-registry.js +3 -1
  111. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-recovery.js +124 -62
  112. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +76 -6
  113. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +325 -73
  114. package/node_modules/@maka/runtime-host/dist/server/scheduled-task-coordinator.js +37 -2
  115. package/node_modules/@maka/runtime-host/dist/server/serial-outbound-writer.js +45 -3
  116. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +50 -7
  117. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +87 -25
  118. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +8 -55
  119. package/node_modules/@maka/runtime-host/dist/server/session-sidecar-purge.js +1 -16
  120. package/node_modules/@maka/runtime-host/dist/server/session-transcript-pager.js +0 -1
  121. package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +460 -70
  122. package/node_modules/@maka/runtime-host/dist/server/shared-session-transcript.js +1 -1
  123. package/node_modules/@maka/runtime-host/dist/server/storage-maintenance.js +109 -0
  124. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +0 -1
  125. package/node_modules/@maka/storage/dist/artifact-store.js +21 -10
  126. package/node_modules/@maka/storage/dist/artifact-stores.js +1 -1
  127. package/node_modules/@maka/storage/dist/claude-code-session-adapter.js +0 -4
  128. package/node_modules/@maka/storage/dist/codex-session-adapter.js +0 -2
  129. package/node_modules/@maka/storage/dist/context-offload-snapshot.js +325 -0
  130. package/node_modules/@maka/storage/dist/execution-stores.js +9 -7
  131. package/node_modules/@maka/storage/dist/file-session-repository.js +1012 -0
  132. package/node_modules/@maka/storage/dist/opencode-session-adapter.js +0 -4
  133. package/node_modules/@maka/storage/dist/operational-state-backup.js +9 -5
  134. package/node_modules/@maka/storage/dist/runtime-event-persistence.js +1 -0
  135. package/node_modules/@maka/storage/dist/runtime-transcript-query.js +308 -0
  136. package/node_modules/@maka/storage/dist/session-bundle-policy.js +24 -4
  137. package/node_modules/@maka/storage/dist/session-message-projection.js +15 -0
  138. package/node_modules/@maka/storage/dist/session-repository.js +767 -0
  139. package/node_modules/@maka/storage/dist/session-store.js +25 -99
  140. package/node_modules/@maka/storage/dist/sqlite-artifact-metadata.js +10 -3
  141. package/node_modules/@maka/storage/dist/sqlite-context-offload-store.js +24 -8
  142. package/node_modules/@maka/storage/dist/sqlite-core-execution-schema.js +7 -1
  143. package/node_modules/@maka/storage/dist/sqlite-runtime-schema.js +44 -1
  144. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +129 -25
  145. package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +109 -892
  146. package/node_modules/@maka/storage/dist/tool-result-archive-evidence.js +111 -0
  147. package/node_modules/@maka/storage/package.json +2 -0
  148. package/package.json +1 -1
@@ -27,7 +27,7 @@ import { buildSessionRecapMessages } from '@maka/runtime/session-recap';
27
27
  import { buildSessionTitlePrompt, cleanGeneratedSessionTitle, SESSION_TITLE_GENERATION_TIMEOUT_MS, } from './session-title.js';
28
28
  import { createProxiedFetchTransport, } from '@maka/runtime/network/scoped-fetch-transport';
29
29
  import { generateToolFreeModelCall, generateProviderPrefixModelCall, ProviderPrefixModelCallUnavailableError, } from '@maka/runtime/tool-free-model-call';
30
- import { modelUsesAnthropicMessages } from '@maka/runtime/model-runtime';
30
+ import { resolveModelRuntime } from '@maka/runtime/model-runtime';
31
31
  import { memoryExtractionMaxOutputTokens, } from '@maka/runtime/memory-extraction';
32
32
  import { createHostOAuthModelFetch, OAuthExecutionCredentialError, } from './oauth-execution-authority.js';
33
33
  import { toRuntimePolicyProxy } from './runtime-policy-proxy.js';
@@ -267,7 +267,8 @@ async function runHostAuxiliaryModelCall(authority, input) {
267
267
  let result;
268
268
  try {
269
269
  result = await readDuringBackendCreation(() => {
270
- const providerOptions = buildProviderOptions(target.connection, target.model, input.header.thinkingLevel);
270
+ const runtime = resolveModelRuntime(target.connection, target.model);
271
+ const providerOptions = buildProviderOptions(target.connection, target.model, input.header.thinkingLevel, runtime);
271
272
  const model = getAIModel({
272
273
  sessionId: input.transportContextId,
273
274
  connection: target.connection,
@@ -275,14 +276,13 @@ async function runHostAuxiliaryModelCall(authority, input) {
275
276
  modelId: target.model,
276
277
  fetch: modelFetch,
277
278
  requestHeaders: target.requestHeaders,
279
+ resolvedRuntime: runtime,
278
280
  });
279
281
  return request.tools !== undefined
280
282
  ? generateProviderPrefixModelCall({
281
283
  model,
282
284
  ...request,
283
- toolChoicePolicy: modelUsesAnthropicMessages(target.connection, target.model)
284
- ? 'omit'
285
- : 'none',
285
+ toolChoicePolicy: runtime.wire === 'anthropic-messages' ? 'omit' : 'none',
286
286
  abortSignal: input.abortSignal,
287
287
  providerOptions: request.providerOptions ?? providerOptions,
288
288
  })
@@ -215,8 +215,9 @@ async function buildHostAiSdkBackend(input, target) {
215
215
  permissionMode: input.context.header.permissionMode,
216
216
  }),
217
217
  },
218
- appendMessage: input.context.appendMessage ??
219
- ((message) => input.context.store.appendMessage(input.context.sessionId, message)),
218
+ ...(input.context.recordSystemNote
219
+ ? { recordSystemNote: input.context.recordSystemNote }
220
+ : {}),
220
221
  readExecutionBoundary: () => input.context.store.readExecutionBoundary(input.context.sessionId),
221
222
  ...(input.context.store.createSandboxBoundaryRequest
222
223
  ? {
@@ -85,7 +85,7 @@ export class HostGoalCoordinator {
85
85
  goalManager: this.manager,
86
86
  evaluator: options.evaluator,
87
87
  getRecentContext: async (sessionId) => {
88
- const messages = await this.#stores.sessionStore.readMessagesSnapshot(sessionId);
88
+ const messages = await options.readSessionMessages(sessionId);
89
89
  tokenCache.set(sessionId, tokenCount(messages));
90
90
  return recentContext(messages);
91
91
  },
@@ -229,6 +229,45 @@ export class HostGoalCoordinator {
229
229
  this.continuation.unarchiveSession(sessionId);
230
230
  }
231
231
  }
232
+ holdForHandoff() {
233
+ if (this.#draining)
234
+ return undefined;
235
+ const hold = this.continuation.holdForHandoff();
236
+ if (!hold)
237
+ return undefined;
238
+ const settled = async () => {
239
+ await hold.settled();
240
+ await this.#flushGoalState();
241
+ };
242
+ return {
243
+ settled,
244
+ release: hold.release,
245
+ residencies: async (executions) => {
246
+ await settled();
247
+ if (this.#draining)
248
+ return undefined;
249
+ for (const [sessionId] of this.#residencies) {
250
+ const authority = this.#authorityBySession.get(sessionId);
251
+ if (!authority)
252
+ return undefined;
253
+ const current = authority.record.currentExecution;
254
+ const paused = executions.find((execution) => execution.sessionId === sessionId);
255
+ // An observed external turn is not a durable Goal execution. Its
256
+ // in-memory completion registration cannot be silently discarded.
257
+ if (paused &&
258
+ (!current ||
259
+ current.execution.turnId !== paused.turnId ||
260
+ current.execution.runId !== paused.runId))
261
+ return undefined;
262
+ if (current && !paused)
263
+ return undefined;
264
+ if (current && !this.matchesActive(sessionId, current.checkpoint, current.controlLease))
265
+ return undefined;
266
+ }
267
+ return [...this.#residencies.values()];
268
+ },
269
+ };
270
+ }
232
271
  beginDrain() {
233
272
  if (this.#draining)
234
273
  return;
@@ -70,6 +70,7 @@ export class RuntimeHostKernel {
70
70
  #hasAcceptedConnection = false;
71
71
  #activeOperations = 0;
72
72
  #activeCommandOperations = 0;
73
+ #handoff;
73
74
  #retainedUntilProcessExit = false;
74
75
  #composition;
75
76
  #compositionDrainBegun = false;
@@ -231,6 +232,8 @@ export class RuntimeHostKernel {
231
232
  }
232
233
  this.#state = 'ready';
233
234
  await this.#publishRegistration();
235
+ if (!this.#shutdownRequested)
236
+ this.#composition?.startMaintenance?.();
234
237
  this.#scheduleIdleIfNeeded();
235
238
  }
236
239
  #accept(connection) {
@@ -306,7 +309,7 @@ export class RuntimeHostKernel {
306
309
  }
307
310
  async #admitHandshake(hello, transport, authority) {
308
311
  const admittedState = await this.#readAdmissionState();
309
- if (!admittedState) {
312
+ if (!admittedState || this.#handoff) {
310
313
  return {
311
314
  kind: 'draining',
312
315
  hostEpoch: this.hostEpoch,
@@ -337,7 +340,13 @@ export class RuntimeHostKernel {
337
340
  hello.generation !== undefined &&
338
341
  hello.generation !== this.#options.generation;
339
342
  if (generationMismatch && hello.takeover?.expectedHostEpoch === this.hostEpoch) {
340
- if (authority.principalKind === 'local_owner' && this.#isTrueIdle(transport)) {
343
+ const residencyCount = hello.activitySnapshotVersion === 2
344
+ ? this.#residencies.drainCount
345
+ : this.#residencies.activeCount;
346
+ if (authority.principalKind === 'local_owner' &&
347
+ residencyCount === 0 &&
348
+ this.#hasNoObservedWork(transport)) {
349
+ this.#shutdownReason = 'retirement';
341
350
  this.#requestDrain();
342
351
  return {
343
352
  kind: 'draining',
@@ -364,8 +373,9 @@ export class RuntimeHostKernel {
364
373
  replacement: this.#lifecycle.kind === 'ephemeral' && this.#isSettledForReplacementAdvice()
365
374
  ? 'wait_for_idle_exit'
366
375
  : 'blocked_by_residency',
367
- ...(generationMismatch && authority.principalKind === 'local_owner'
368
- ? { activity: this.#activitySnapshot() }
376
+ ...(authority.principalKind === 'local_owner' &&
377
+ (generationMismatch || hello.activitySnapshotVersion === 2)
378
+ ? { activity: this.#activitySnapshot(hello.activitySnapshotVersion) }
369
379
  : {}),
370
380
  };
371
381
  }
@@ -376,6 +386,9 @@ export class RuntimeHostKernel {
376
386
  this.#cancelIdle();
377
387
  return {
378
388
  kind: 'accepted',
389
+ ...(hello.activitySnapshotVersion === 2 && this.#composition?.prepareHandoff
390
+ ? { cooperativeHandoff: true }
391
+ : {}),
379
392
  rootId: this.#options.owner.capability.rootId,
380
393
  hostEpoch: this.hostEpoch,
381
394
  connectionId: randomUUID(),
@@ -401,6 +414,10 @@ export class RuntimeHostKernel {
401
414
  async #beginOperation(frame) {
402
415
  if (!(await this.#readAdmissionState()))
403
416
  return 'host_draining';
417
+ if (this.#handoff &&
418
+ HOST_OPERATION_SPECS[frame.operation].mode === 'command' &&
419
+ (this.#handoff.commandsClosed || frame.operation !== 'turn.stop'))
420
+ return 'host_draining';
404
421
  if (HOST_OPERATION_SPECS[frame.operation].availability !== 'bootstrap' &&
405
422
  this.#state !== 'ready') {
406
423
  return 'host_not_ready';
@@ -475,14 +492,9 @@ export class RuntimeHostKernel {
475
492
  this.#settleLifecycleAfterWork();
476
493
  }
477
494
  #acquireResidency(label) {
478
- const residency = this.#residencies.acquire(label);
495
+ const residency = this.#residencies.acquire(label, 'drain', () => this.#settleLifecycleAfterWork());
479
496
  this.#cancelIdle();
480
- return {
481
- release: () => {
482
- residency.release();
483
- this.#settleLifecycleAfterWork();
484
- },
485
- };
497
+ return residency;
486
498
  }
487
499
  #retainUntilProcessExit() {
488
500
  if (this.#retainedUntilProcessExit)
@@ -523,7 +535,7 @@ export class RuntimeHostKernel {
523
535
  ok: true,
524
536
  result: await this.#resourceCollector.snapshot(this.hostEpoch),
525
537
  }),
526
- 'host.upgrade.prepare': async (input) => {
538
+ 'host.upgrade.prepare': async (input, context) => {
527
539
  if (input.expectedHostEpoch !== this.hostEpoch) {
528
540
  return {
529
541
  ok: false,
@@ -534,7 +546,10 @@ export class RuntimeHostKernel {
534
546
  };
535
547
  }
536
548
  if (!input.allowInterruptActiveTasks && this.#hasUpgradeBlockingActivity(1)) {
537
- return { ok: true, result: { kind: 'active_tasks' } };
549
+ if (!input.allowCooperativeHandoff ||
550
+ !(await this.#prepareCooperativeHandoff(context.inputClosedSignal))) {
551
+ return { ok: true, result: { kind: 'active_tasks' } };
552
+ }
538
553
  }
539
554
  this.#shutdownReason = 'retirement';
540
555
  this.#requestDrain();
@@ -600,12 +615,18 @@ export class RuntimeHostKernel {
600
615
  : {}),
601
616
  };
602
617
  }
603
- #activitySnapshot() {
618
+ #activitySnapshot(version) {
604
619
  return {
605
620
  connections: this.#acceptedTransports.size,
606
621
  activeOperations: this.#activeOperations,
607
622
  processUptimeSeconds: Math.max(0, Math.floor(process.uptime())),
608
623
  residencies: this.#residencies.snapshot(),
624
+ ...(version === 2
625
+ ? {
626
+ drainResidencies: this.#residencies.drainCount,
627
+ ...(this.#composition?.prepareHandoff ? { cooperativeHandoff: true } : {}),
628
+ }
629
+ : {}),
609
630
  };
610
631
  }
611
632
  #hasUpgradeBlockingActivity(selfCommands) {
@@ -621,6 +642,62 @@ export class RuntimeHostKernel {
621
642
  return true;
622
643
  return this.#residencies.drainCount > 0;
623
644
  }
645
+ async #prepareCooperativeHandoff(inputClosedSignal) {
646
+ if (!inputClosedSignal ||
647
+ inputClosedSignal.aborted ||
648
+ !this.#composition?.prepareHandoff ||
649
+ this.#handoff ||
650
+ this.#acceptedTransports.size > 1 ||
651
+ this.#activeCommandOperations > 1)
652
+ return false;
653
+ const handoff = { abort: new AbortController(), commandsClosed: false, committing: false };
654
+ this.#handoff = handoff;
655
+ const cancelOnDisconnect = () => {
656
+ if (!handoff.committing)
657
+ handoff.abort.abort();
658
+ };
659
+ inputClosedSignal.addEventListener('abort', cancelOnDisconnect, { once: true });
660
+ const timer = setTimeout(() => handoff.abort.abort(), 10_000);
661
+ let prepared;
662
+ try {
663
+ prepared = await this.#composition.prepareHandoff(this.hostEpoch, handoff.abort.signal);
664
+ if (!prepared || handoff.abort.signal.aborted || this.#activeCommandOperations !== 1)
665
+ return false;
666
+ handoff.commandsClosed = true;
667
+ if (!(await prepared.seal()))
668
+ return false;
669
+ const residencies = await prepared.residencies();
670
+ if (!residencies ||
671
+ handoff.abort.signal.aborted ||
672
+ !(await this.#hasLiveOwnerOrDrain()) ||
673
+ handoff.abort.signal.aborted ||
674
+ this.#handoff !== handoff ||
675
+ this.#acceptedTransports.size !== 1 ||
676
+ this.#activeCommandOperations !== 1 ||
677
+ this.#residencies.hasDrainResidenciesExcept(residencies))
678
+ return false;
679
+ // No await between the final exact-handle proof and closing all command
680
+ // admission. After this cut cancellation must not restart the old runs.
681
+ handoff.committing = true;
682
+ clearTimeout(timer);
683
+ await prepared.detach();
684
+ return true;
685
+ }
686
+ finally {
687
+ clearTimeout(timer);
688
+ inputClosedSignal.removeEventListener('abort', cancelOnDisconnect);
689
+ if (handoff.committing) {
690
+ this.#shutdownReason = 'retirement';
691
+ this.#requestDrain();
692
+ }
693
+ else {
694
+ handoff.abort.abort();
695
+ prepared?.cancel();
696
+ }
697
+ if (this.#handoff === handoff)
698
+ this.#handoff = undefined;
699
+ }
700
+ }
624
701
  #beginCompositionDrain() {
625
702
  if (!this.#composition || this.#compositionDrainBegun)
626
703
  return;
@@ -659,7 +736,10 @@ export class RuntimeHostKernel {
659
736
  void this.#commitShutdown().catch(() => undefined);
660
737
  }, this.#lifecycle.idleGraceMs);
661
738
  }
662
- #isTrueIdle(exceptHandshaking) {
739
+ #isTrueIdle() {
740
+ return this.#residencies.activeCount === 0 && this.#hasNoObservedWork();
741
+ }
742
+ #hasNoObservedWork(exceptHandshaking) {
663
743
  // A transport mid-handshake keeps the Host busy, except the one whose
664
744
  // admission is being decided right now: counting it would make every
665
745
  // true-idle takeover observe itself as activity.
@@ -669,8 +749,7 @@ export class RuntimeHostKernel {
669
749
  return (this.#state === 'ready' &&
670
750
  this.#acceptedTransports.size === 0 &&
671
751
  handshaking === 0 &&
672
- this.#activeOperations === 0 &&
673
- this.#residencies.activeCount === 0);
752
+ this.#activeOperations === 0);
674
753
  }
675
754
  // The replacement advice in a rejection is what a stale Client acts on.
676
755
  // In-flight handshakes resolve within milliseconds and must not flip that
@@ -21,34 +21,41 @@ export class HostResidencyRegistry {
21
21
  #counts = new Map();
22
22
  #drainWaiters = new Set();
23
23
  #activeCount = 0;
24
- #drainCount = 0;
24
+ #drainHandles = new Set();
25
25
  /** Residencies of either kind keep the process alive against idle exit. */
26
26
  get activeCount() {
27
27
  return this.#activeCount;
28
28
  }
29
29
  /** Only drain-kind residencies block maintenance probes and graceful close. */
30
30
  get drainCount() {
31
- return this.#drainCount;
31
+ return this.#drainHandles.size;
32
32
  }
33
- acquire(label, kind = 'drain') {
33
+ hasDrainResidenciesExcept(allowed) {
34
+ const proven = new Set(allowed);
35
+ return [...this.#drainHandles].some((handle) => !proven.has(handle));
36
+ }
37
+ acquire(label, kind = 'drain', onRelease) {
34
38
  requireResidencyLabel(label);
35
39
  this.#activeCount += 1;
36
- if (kind === 'drain')
37
- this.#drainCount += 1;
38
40
  const counts = this.#counts.get(label) ?? { total: 0, drain: 0 };
39
41
  counts.total += 1;
40
42
  if (kind === 'drain')
41
43
  counts.drain += 1;
42
44
  this.#counts.set(label, counts);
43
45
  let active = true;
44
- return {
46
+ const handle = {
45
47
  release: () => {
46
48
  if (!active)
47
49
  return;
48
50
  active = false;
51
+ this.#drainHandles.delete(handle);
49
52
  this.#release(label, kind);
53
+ onRelease?.();
50
54
  },
51
55
  };
56
+ if (kind === 'drain')
57
+ this.#drainHandles.add(handle);
58
+ return handle;
52
59
  }
53
60
  snapshot() {
54
61
  return [...this.#counts]
@@ -70,7 +77,6 @@ export class HostResidencyRegistry {
70
77
  counts.total -= 1;
71
78
  if (kind === 'drain') {
72
79
  counts.drain -= 1;
73
- this.#drainCount -= 1;
74
80
  }
75
81
  this.#activeCount -= 1;
76
82
  if (counts.total === 0)
@@ -131,7 +131,9 @@ export class HostedExecutionAdmissionRegistry {
131
131
  }
132
132
  }
133
133
  waitForSettledAdmissions() {
134
- return Promise.all([...this.#bySession.values()].map((value) => value.admissionSettled.promise)).then(() => undefined);
134
+ return Promise.all([...this.#bySession.values()]
135
+ .filter((value) => value.kind === 'pending')
136
+ .map((value) => value.admissionSettled.promise)).then(() => undefined);
135
137
  }
136
138
  }
137
139
  export function hostedExecutionDeferred() {