agent-transport-system 0.7.0 → 0.7.2

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.
package/dist/ats.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { $ as formatLocalComponentsSummaryLabel, $n as SPACE_MEMBER_REMOVE_NOTICE_PURPOSE, $t as removeSpaceMembersResponseSchema, A as claimExecutionDiagnosticsQuerySchema, An as submitRuntimeRegistrationResponseSchema, Ar as normalizeSpacePasswordText, At as normalizeBuiltinControllerAgentId, B as currentDeviceTargetResponseSchema, Bn as AGENT_REPLY_PREVIEW_PURPOSE, Br as sanitizeSignalTextPreview, Bt as patchStartSessionBodySchema, C as atsRequestContextSchema, Cn as startSessionSpaceChoiceBodySchema, Cr as daemonHubSubmitTaskResultRequestSchema, Ct as leaveSpaceResponseSchema, D as canonicalizeBuiltinControllerRef, Dn as submitRuntimeCapabilityReportsBodySchema, Dr as getSpaceMessageAddressingRelationSupportForTargetKind, Dt as listSpaceThreadsResponseSchema, E as buildControllerRoutingKeyForKind, En as structuredGuidePayloadFromInputSchema, Er as formatCanonicalMentionLiteral, Et as listSpaceThreadSignalsResponseSchema, F as createSpaceDiagnosticReportResponseSchema, Fn as writeSetupTokenLocalRuntimeObservedMetadataBodySchema, Fr as resolveSingleSpaceMentionLabels, Ft as notifyAgentProfileRouteCatalogChangedResponseSchema, G as dispatchBriefSchema, Gn as DISPATCH_ACTIVITY_DISPATCHING_PURPOSE, Gt as postSpaceThreadSignalBodySchema, H as daemonRouteObservationResponseSchema, Hn as CONVERSATION_CONTINUITY_WARNING_PURPOSE, Ht as postNormalMessageResponseSchema, I as createSpaceResponseSchema, In as writeSetupTokenLocalRuntimeObservedMetadataResponseSchema, Ir as resolveSpaceMentionLabels, It as observabilityWakeTraceSelectorSchema, J as entryBriefSchema, Jn as LEGACY_RUNTIME_DISPATCH_POLICY, Jt as prepareSessionStreamServerFrameSchema, K as ensureAgentProfilePrimaryBindingBodySchema, Kn as DISPATCH_ACTIVITY_FAILED_PURPOSE, Kt as postSpaceThreadSignalResponseSchema, L as createSpaceThreadBodySchema, Ln as AGENT_REPLYING_END_PURPOSE, Lt as patchProfileSpaceHistoryStatusResponseSchema, M as continuitySchema, Mn as upsertSpaceDeletionTombstoneResponseSchema, Mr as profileWorkspaceModeSchema, Mt as normalizeListSignalsReadQuerySemantics, N as createSpaceBodySchema, Nn as writeCurrentDeviceObservedMetadataBodySchema, Nr as resolveBuiltinUpstreamConversationRefKind, Nt as normalizeSpaceCursorPatch, O as canonicalizeControllerRefForKind, On as submitRuntimeCapabilityReportsResponseSchema, Or as normalizeMessageEnvelope, Ot as localRuntimesQuerySchema, P as createSpaceDiagnosticReportBodySchema, Pn as writeCurrentDeviceObservedMetadataResponseSchema, Pr as resolveMessageEnvelopeTargetField, Pt as notifyAgentProfileRouteCatalogChangedBodySchema, Q as formatLocalComponentsSummaryDescription, Qn as SPACE_MEMBER_JOIN_NOTICE_PURPOSE, Qt as querySpaceDeletionTombstonesResponseSchema, R as createSpaceThreadResponseSchema, Rn as AGENT_REPLYING_PURPOSE, Rt as patchSpaceContractBodySchema, S as atsProfileIdSchema, Sn as startSessionResponseSchema, Sr as daemonHubRouteCatalogChangedFramePayloadSchema, St as isExplicitBuiltinControllerRef, T as atsdControlPlaneResponseSchema, Tn as startSessionWithTokenResponseSchema, Tr as daemonStreamFrameSchema, Tt as listSpaceThreadEventsResponseSchema, U as daemonRuntimeLeaseSchema, Un as CURRENT_DAEMON_EXECUTION_CONTRACT_EPOCH, Ut as postSpaceMembersBodySchema, V as currentLocalRuntimeReplyReadinessResponseSchema, Vn as ATSD_TASK_RESULT_SCHEMA_VERSION, Vt as postNormalMessageBodySchema, W as deleteSpaceResponseSchema, Wn as DAEMON_HUB_SCHEMA_VERSION, Wt as postSpaceMembersResponseSchema, X as forgetComputerResponseSchema, Xn as MAX_SIGNAL_REPLY_TO_PREVIEW_LENGTH, Xt as projectSpaceDispatchTraceFinalVisibleOutcome, Y as finalClaimRouteParamsSchema, Yn as MAX_PROFILE_WORKING_DIRECTORY_LENGTH, Yt as projectObservabilityWakeCorrelation, Z as forgetCurrentComputerResponseSchema, Zn as MESSAGE_MENTION_TYPE_VALUES, Zt as providerDispatchRuntimeContextSchema, _ as ATSD_CONTROL_PLANE_SCHEMA_VERSION, _n as spaceMetaSchema, _r as daemonHubDispatchRuntimeEvidenceRequestSchema, _t as getSpaceUpdatesResponseSchema, a as runWithHeldLock, an as serverErrorFrameSchema, ar as atsdTaskResultEnvelopeWriteSchema, at as getAgentExecutionReadinessBatchResponseSchema, b as agentExecutionReadinessRouteParamsSchema, bn as startProfileReadinessSummarySchema, br as daemonHubRegisterSessionRequestSchema, bt as incomingServerMessageSchema, c as LEGACY_ATS_RUNTIME_SESSION_ENV_KEY, cn as signalEnvelopeSchema, cr as buildUpstreamConversationRef, ct as getPrepareReadinessQuerySchema, d as resolveRuntimeSession, dn as spaceConversationBindingImportResponseSchema, dr as createDaemonRouteObservationSummary, dt as getSpaceConversationRemoteStatusResponseSchema, en as reserveFinalClaimBodySchema, er as SPACE_MENTION_REJECT_NOTICE_PURPOSE, et as formatLocalSetupActionDescription, f as resolveRuntimeSessionId, fn as spaceConversationBindingResponseSchema, fr as daemonHubDeliverDispatchRequestSchema, ft as getSpaceConversationStatusResponseSchema, g as resolveMappedPublicAgentFailureReason, gn as spaceMembersSnapshotSchema, gr as daemonHubDispatchPreviewRequestSchema, gt as getSpaceThreadResponseSchema, h as resolveBuiltinAgentControllerBrand, hn as spaceDispatchTraceResponseSchema, hr as daemonHubDispatchPreviewEndRequestSchema, ht as getSpaceStatusResponseSchema, i as releaseLock, in as resolveStartHandoffResponseSchema, ir as atsSpaceEgressActionSchema, it as getAgentExecutionReadinessBatchBodySchema, j as claimExecutionDiagnosticsResponseSchema, jn as upsertProfileSpaceHistoryResponseSchema, jr as parseOptionalClientMessageId, jt as normalizeBuiltinControllerProviderId, k as catchupResponseSchema, kn as submitRuntimeRegistrationBodySchema, kr as normalizeOptionalWorkingDirectory, kt as localRuntimesResponseSchema, l as listRuntimeSessionStates, ln as spaceConversationBindingConflictResponseSchema, lr as collectCanonicalMentionTextFragments, lt as getPrepareReadinessResponseSchema, m as CODEX_UPGRADE_REQUIRED_REASON, mn as spaceCreatorSchema, mr as daemonHubDispatchLifecycleRequestSchema, mt as getSpaceDispatchResultResponseSchema, n as isAtsLockError, nn as resolveSpaceDispatchTraceRootCause, nr as SPACE_UPDATES_MAX_LIMIT, nt as gatewayErrorCodeSchema, o as tryCleanupStaleLock, on as setCurrentDeviceTargetBodySchema, or as atsdTaskResultOpenClawGatewayVisibilityStatusSchema, ot as getAgentExecutionReadinessResponseSchema, p as writeRuntimeSessionState, pn as spaceConversationBindingUpsertResponseSchema, pr as daemonHubDeliveryExecutionIdentitySchema, pt as getSpaceDispatchLookupResponseSchema, q as ensureAgentProfilePrimaryBindingResponseSchema, qn as DISPATCH_ACTIVITY_RETRYING_PURPOSE, qt as prepareSessionResponseSchema, r as readLockMeta, rn as resolveStartHandoffBodySchema, rr as atsRuntimeProfileIdSchema, rt as gatewayErrorEnvelopeSchema, s as ATS_RUNTIME_SESSION_ENV_KEY, sn as setLocalRuntimeDisplayNameBodySchema, sr as atsdTaskResultPayloadSchema, st as getAgentProfilePrimaryBindingResponseSchema, t as acquireLock, tn as resolveBuiltinProviderConversationCapability, tr as SPACE_PASSWORD_MIN_LENGTH, tt as formatLocalSetupActionLabel, u as readRuntimeSessionState, un as spaceConversationBindingDeleteResponseSchema, ur as conversationExecutionStateSchema, ut as getSpaceContractResponseSchema, v as LOCAL_COMPONENTS_SCHEMA_VERSION, vn as spaceViewerMembershipResponseSchema, vr as daemonHubHeartbeatRequestSchema, vt as getSpaceWakeProgressResponseSchema, w as atsdControlPlaneRequestSchema, wn as startSessionSpaceChoiceResponseSchema, wr as daemonServiceContractSchema, wt as listProfileSpaceHistoryResponseSchema, x as agentProfileBindingRouteParamsSchema, xn as startSessionProgressSchema, xr as daemonHubRegisterSessionResponseSchema, xt as installedLocalComponentsSnapshotSchema, y as SPACE_DISPATCH_TRACE_PROMPT_PREVIEW_MAX_CHARS, yn as startDeviceProjectionSchema, yr as daemonHubHeartbeatResponseSchema, yt as getSpaceWakeTraceWaterfallResponseSchema, z as createStartSessionBodySchema, zn as AGENT_REPLY_PREVIEW_END_PURPOSE, zr as runtimeCoordinatorExecutionTokenEnvelopeSchema, zt as patchSpaceContractResponseSchema } from "./lock-BVLNLUDp.js";
3
+ import { $ as formatLocalSetupActionDescription, $n as SPACE_PASSWORD_MIN_LENGTH, $t as resolveBuiltinProviderConversationCapability, A as claimExecutionDiagnosticsQuerySchema, An as upsertSpaceDeletionTombstoneResponseSchema, Ar as profileWorkspaceModeSchema, At as normalizeBuiltinControllerProviderId, B as currentDeviceTargetResponseSchema, Bn as CONVERSATION_CONTINUITY_WARNING_PURPOSE, Bt as postNormalMessageBodySchema, C as atsRequestContextSchema, Cn as startSessionWithTokenResponseSchema, Cr as daemonStreamFrameSchema, Ct as listProfileSpaceHistoryResponseSchema, D as canonicalizeBuiltinControllerRef, Dn as submitRuntimeRegistrationBodySchema, Dr as normalizeOptionalWorkingDirectory, Dt as localRuntimesQuerySchema, E as buildControllerRoutingKeyForKind, En as submitRuntimeCapabilityReportsResponseSchema, Er as normalizeMessageEnvelope, Et as listSpaceThreadsResponseSchema, F as createSpaceDiagnosticReportResponseSchema, Fn as AGENT_REPLYING_END_PURPOSE, Ft as observabilityWakeTraceSelectorSchema, G as dispatchBriefSchema, Gn as DISPATCH_ACTIVITY_RETRYING_PURPOSE, Gt as postSpaceThreadSignalResponseSchema, H as daemonRouteObservationResponseSchema, Hn as DAEMON_HUB_SCHEMA_VERSION, Ht as postSpaceMembersBodySchema, I as createSpaceResponseSchema, In as AGENT_REPLYING_PURPOSE, It as patchProfileSpaceHistoryStatusResponseSchema, J as entryBriefSchema, Jn as MAX_SIGNAL_REPLY_TO_PREVIEW_LENGTH, Jt as projectObservabilityWakeCorrelation, K as ensureAgentProfilePrimaryBindingBodySchema, Kn as LEGACY_RUNTIME_DISPATCH_POLICY, Kt as prepareSessionResponseSchema, L as createSpaceThreadBodySchema, Ln as AGENT_REPLY_PREVIEW_END_PURPOSE, Lr as runtimeCoordinatorExecutionTokenEnvelopeSchema, Lt as patchSpaceContractBodySchema, M as continuitySchema, Mn as writeCurrentDeviceObservedMetadataResponseSchema, Mr as resolveMessageEnvelopeTargetField, Mt as normalizeSpaceCursorPatch, N as createSpaceBodySchema, Nn as writeSetupTokenLocalRuntimeObservedMetadataBodySchema, Nr as resolveSingleSpaceMentionLabels, Nt as notifyAgentProfileRouteCatalogChangedBodySchema, O as canonicalizeControllerRefForKind, On as submitRuntimeRegistrationResponseSchema, Or as normalizeSpacePasswordText, Ot as localRuntimesResponseSchema, P as createSpaceDiagnosticReportBodySchema, Pn as writeSetupTokenLocalRuntimeObservedMetadataResponseSchema, Pr as resolveSpaceMentionLabels, Pt as notifyAgentProfileRouteCatalogChangedResponseSchema, Q as formatLocalComponentsSummaryLabel, Qn as SPACE_MENTION_REJECT_NOTICE_PURPOSE, Qt as removeSpaceMembersResponseSchema, R as createSpaceThreadResponseSchema, Rn as AGENT_REPLY_PREVIEW_PURPOSE, Rr as sanitizeSignalTextPreview, Rt as patchSpaceContractResponseSchema, S as atsProfileIdSchema, Sn as startSessionSpaceChoiceResponseSchema, Sr as daemonServiceContractSchema, St as leaveSpaceResponseSchema, T as atsdControlPlaneResponseSchema, Tn as submitRuntimeCapabilityReportsBodySchema, Tr as getSpaceMessageAddressingRelationSupportForTargetKind, Tt as listSpaceThreadSignalsResponseSchema, U as daemonRuntimeLeaseSchema, Un as DISPATCH_ACTIVITY_DISPATCHING_PURPOSE, Ut as postSpaceMembersResponseSchema, V as currentLocalRuntimeReplyReadinessResponseSchema, Vn as CURRENT_DAEMON_EXECUTION_CONTRACT_EPOCH, Vt as postNormalMessageResponseSchema, W as deleteSpaceResponseSchema, Wn as DISPATCH_ACTIVITY_FAILED_PURPOSE, Wt as postSpaceThreadSignalBodySchema, X as forgetCurrentComputerResponseSchema, Xn as SPACE_MEMBER_JOIN_NOTICE_PURPOSE, Xt as providerDispatchRuntimeContextSchema, Y as forgetComputerResponseSchema, Yn as MESSAGE_MENTION_TYPE_VALUES, Yt as projectSpaceDispatchTraceFinalVisibleOutcome, Z as formatLocalComponentsSummaryDescription, Zn as SPACE_MEMBER_REMOVE_NOTICE_PURPOSE, Zt as querySpaceDeletionTombstonesResponseSchema, _ as ATSD_CONTROL_PLANE_SCHEMA_VERSION, _n as startDeviceProjectionSchema, _r as daemonHubHeartbeatResponseSchema, _t as getSpaceWakeProgressResponseSchema, a as runWithHeldLock, an as setLocalRuntimeDisplayNameBodySchema, ar as atsdTaskResultPayloadSchema, at as getAgentExecutionReadinessResponseSchema, b as agentExecutionReadinessRouteParamsSchema, bn as startSessionResponseSchema, br as daemonHubRouteCatalogChangedFramePayloadSchema, bt as installedLocalComponentsSnapshotSchema, c as LEGACY_ATS_RUNTIME_SESSION_ENV_KEY, cn as spaceConversationBindingDeleteResponseSchema, cr as conversationExecutionStateSchema, ct as getPrepareReadinessResponseSchema, d as resolveRuntimeSession, dn as spaceConversationBindingUpsertResponseSchema, dr as daemonHubDeliveryExecutionIdentitySchema, dt as getSpaceConversationStatusResponseSchema, en as resolveSpaceDispatchTraceRootCause, er as SPACE_UPDATES_MAX_LIMIT, et as formatLocalSetupActionLabel, f as resolveRuntimeSessionId, fn as spaceCreatorSchema, fr as daemonHubDispatchLifecycleRequestSchema, ft as getSpaceDispatchLookupResponseSchema, g as resolveMappedPublicAgentFailureReason, gn as spaceViewerMembershipResponseSchema, gr as daemonHubHeartbeatRequestSchema, gt as getSpaceUpdatesResponseSchema, h as resolveBuiltinAgentControllerBrand, hn as spaceMetaSchema, hr as daemonHubDispatchRuntimeEvidenceRequestSchema, ht as getSpaceThreadResponseSchema, i as releaseLock, in as setCurrentDeviceTargetBodySchema, ir as atsdTaskResultOpenClawGatewayVisibilityStatusSchema, it as getAgentExecutionReadinessBatchResponseSchema, j as claimExecutionDiagnosticsResponseSchema, jn as writeCurrentDeviceObservedMetadataBodySchema, jr as resolveBuiltinUpstreamConversationRefKind, jt as normalizeListSignalsReadQuerySemantics, k as catchupResponseSchema, kn as upsertProfileSpaceHistoryResponseSchema, kr as parseOptionalClientMessageId, kt as normalizeBuiltinControllerAgentId, l as listRuntimeSessionStates, ln as spaceConversationBindingImportResponseSchema, lr as createDaemonRouteObservationSummary, lt as getSpaceContractResponseSchema, m as CODEX_UPGRADE_REQUIRED_REASON, mn as spaceMembersSnapshotSchema, mr as daemonHubDispatchPreviewRequestSchema, mt as getSpaceStatusResponseSchema, n as isAtsLockError, nn as resolveStartHandoffResponseSchema, nr as atsSpaceEgressActionSchema, nt as gatewayErrorEnvelopeSchema, o as tryCleanupStaleLock, on as signalEnvelopeSchema, or as buildUpstreamConversationRef, ot as getAgentProfilePrimaryBindingResponseSchema, p as writeRuntimeSessionState, pn as spaceDispatchTraceResponseSchema, pr as daemonHubDispatchPreviewEndRequestSchema, pt as getSpaceDispatchResultResponseSchema, q as ensureAgentProfilePrimaryBindingResponseSchema, qn as MAX_PROFILE_WORKING_DIRECTORY_LENGTH, qt as prepareSessionStreamServerFrameSchema, r as readLockMeta, rn as serverErrorFrameSchema, rr as atsdTaskResultEnvelopeWriteSchema, rt as getAgentExecutionReadinessBatchBodySchema, s as ATS_RUNTIME_SESSION_ENV_KEY, sn as spaceConversationBindingConflictResponseSchema, sr as collectCanonicalMentionTextFragments, st as getPrepareReadinessQuerySchema, t as acquireLock, tn as resolveStartHandoffBodySchema, tr as atsRuntimeProfileIdSchema, tt as gatewayErrorCodeSchema, u as readRuntimeSessionState, un as spaceConversationBindingResponseSchema, ur as daemonHubDeliverDispatchRequestSchema, ut as getSpaceConversationRemoteStatusResponseSchema, v as LOCAL_COMPONENTS_SCHEMA_VERSION, vn as startProfileReadinessSummarySchema, vr as daemonHubRegisterSessionRequestSchema, vt as getSpaceWakeTraceWaterfallResponseSchema, w as atsdControlPlaneRequestSchema, wn as structuredGuidePayloadFromInputSchema, wr as formatCanonicalMentionLiteral, wt as listSpaceThreadEventsResponseSchema, x as agentProfileBindingRouteParamsSchema, xn as startSessionSpaceChoiceBodySchema, xr as daemonHubSubmitTaskResultRequestSchema, xt as isExplicitBuiltinControllerRef, y as SPACE_DISPATCH_TRACE_PROMPT_PREVIEW_MAX_CHARS, yn as startSessionProgressSchema, yr as daemonHubRegisterSessionResponseSchema, yt as incomingServerMessageSchema, z as createStartSessionBodySchema, zn as ATSD_TASK_RESULT_SCHEMA_VERSION, zt as patchStartSessionBodySchema } from "./lock-BG0gWBdN.js";
4
4
  import { A as runtimeDir, C as normalizeAtsProfileId, D as resolveAtsEnvPreset, E as resolveAtsCliEntryNameFromArgv, F as systemDir, N as skillsDir, O as resolveAtsRootDir, P as spacesDir, S as normalizeAccountKey, T as profileViewPath, a as accountProfileWorkspacePath, c as atsRootDir, d as deviceOpenClawProfileBootstrapPath, f as deviceOpenClawProfileDir, i as accountProfileViewPath, j as runtimeLogsDir, k as resolveDefaultAtsHomeDirname, n as accountProfileLocalMetaPath, o as accountsDir, p as deviceOpenClawProfileWorkspaceDir, r as accountProfileSpaceCacheDir, s as atsBackupsDir, t as ATS_HOME_ENV_KEY, w as profileDir, y as legacyAccountProfileSpacesDir } from "./paths-DFiopT5Y.js";
5
- import { A as toSpaceCursorUrl, B as toSpaceSignalsUrl, C as resolveDefaultGatewayBaseUrl, D as toDaemonRouteObservationUrl, E as toClaimExecutionDiagnosticsUrl, F as toSpaceMembersUrl, H as toSpaceWsUrl, I as toSpaceMetaUrl, L as toSpacePasswordUrl, M as toSpaceDispatchLookupUrl, N as toSpaceDispatchTraceUrl, O as toSpaceContractUrl, P as toSpaceLeaveUrl, R as toSpaceRemoveMembersUrl, S as resolveBaseUrlOrNull, T as normalizeBaseUrl, V as toSpaceUpdatesUrl, _ as updateConfiguredStartV1OnboardingState, a as getConfiguredDeviceRuntimeState, b as normalizeGatewayBaseUrlOrNull, c as getConfiguredStartV1OnboardingState, d as resolveRuntimeSkillsCustomTargetId, f as setConfiguredBaseUrl, g as updateConfiguredSkillsConfig, h as updateConfiguredOnboardingConfig, i as getConfiguredDaemonDispatchLimits, j as toSpaceDeleteUrl, k as toSpaceCreateUrl, l as getConfiguredViewCustomization, m as updateConfiguredDeviceRuntimeState, n as alignRuntimeConfigStorage, o as getConfiguredOnboardingDisclaimerAcceptedAt, p as setConfiguredSkillsConfig, r as createDefaultRuntimeAgentControllerSettings, s as getConfiguredSkillsConfig, t as DEFAULT_RUNTIME_AGENT_TRANSPORT_MODE, u as getRuntimeConfigReadHealth, w as resolveExplicitGatewayUrlOrThrow, x as resolveBaseUrl, y as normalizeGatewayBaseUrl, z as toSpaceResultUrl } from "./runtime-config-DMaYdwtU.js";
5
+ import { A as toSpaceCursorUrl, B as toSpaceSignalsUrl, C as resolveDefaultGatewayBaseUrl, D as toDaemonRouteObservationUrl, E as toClaimExecutionDiagnosticsUrl, F as toSpaceMembersUrl, H as toSpaceWsUrl, I as toSpaceMetaUrl, L as toSpacePasswordUrl, M as toSpaceDispatchLookupUrl, N as toSpaceDispatchTraceUrl, O as toSpaceContractUrl, P as toSpaceLeaveUrl, R as toSpaceRemoveMembersUrl, S as resolveBaseUrlOrNull, T as normalizeBaseUrl, V as toSpaceUpdatesUrl, _ as updateConfiguredStartV1OnboardingState, a as getConfiguredDeviceRuntimeState, b as normalizeGatewayBaseUrlOrNull, c as getConfiguredStartV1OnboardingState, d as resolveRuntimeSkillsCustomTargetId, f as setConfiguredBaseUrl, g as updateConfiguredSkillsConfig, h as updateConfiguredOnboardingConfig, i as getConfiguredDaemonDispatchLimits, j as toSpaceDeleteUrl, k as toSpaceCreateUrl, l as getConfiguredViewCustomization, m as updateConfiguredDeviceRuntimeState, n as alignRuntimeConfigStorage, o as getConfiguredOnboardingDisclaimerAcceptedAt, p as setConfiguredSkillsConfig, r as createDefaultRuntimeAgentControllerSettings, s as getConfiguredSkillsConfig, t as DEFAULT_RUNTIME_AGENT_TRANSPORT_MODE, u as getRuntimeConfigReadHealth, w as resolveExplicitGatewayUrlOrThrow, x as resolveBaseUrl, y as normalizeGatewayBaseUrl, z as toSpaceResultUrl } from "./runtime-config-D3F15r0W.js";
6
6
  import { createRequire } from "node:module";
7
7
  import { Command, Option } from "commander";
8
8
  import { accessSync, appendFileSync, chmodSync, constants, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync } from "node:fs";
@@ -27,7 +27,7 @@ import wrapAnsi from "wrap-ansi";
27
27
  import { Box, Container, Editor, Key, ProcessTerminal, TUI, Text, getEditorKeybindings, matchesKey } from "@mariozechner/pi-tui";
28
28
 
29
29
  //#region package.json
30
- var version = "0.7.0";
30
+ var version = "0.7.2";
31
31
  var package_default = {
32
32
  $schema: "https://www.schemastore.org/package.json",
33
33
  name: "agent-transport-system",
@@ -1547,6 +1547,7 @@ function isMissingFileError(error) {
1547
1547
  //#region src/runtime/cli-entry-command.ts
1548
1548
  const ATS_CLI_COMMAND = "ats";
1549
1549
  const ATS_CLI_NPX_COMMAND$1 = "npx -y agent-transport-system@latest";
1550
+ const ATS_SETUP_FOLLOW_UP_CLI_COMMAND_ENV = "ATS_SETUP_FOLLOW_UP_CLI_COMMAND";
1550
1551
  const ATS_USER_FACING_CLI_COMMAND_ENV$2 = "ATS_USER_FACING_CLI_COMMAND";
1551
1552
  const ATS_TOP_LEVEL_COMMANDS = [
1552
1553
  "adapter",
@@ -1607,6 +1608,11 @@ function resolveUserFacingCliEntryCommand(input = {}) {
1607
1608
  if (explicitCommand.length > 0) return explicitCommand;
1608
1609
  return isNpxCliInvocation(input) ? ATS_CLI_NPX_COMMAND$1 : ATS_CLI_COMMAND;
1609
1610
  }
1611
+ function resolveSetupFollowUpCliEntryCommand(input = {}) {
1612
+ const setupCommand = normalizeText$10((input.env ?? process$1.env)[ATS_SETUP_FOLLOW_UP_CLI_COMMAND_ENV]);
1613
+ if (setupCommand.length > 0) return setupCommand;
1614
+ return resolveUserFacingCliEntryCommand(input);
1615
+ }
1610
1616
  function formatAtsCliCommand(command, input = {}) {
1611
1617
  if (!ATS_COMMAND_PREFIX_RE$1.test(command)) return command;
1612
1618
  return command.replace(ATS_COMMAND_PREFIX_RE$1, resolveUserFacingCliEntryCommand(input));
@@ -3789,7 +3795,7 @@ async function requestLatestPackageVersion(packageName) {
3789
3795
  if (!version) throw new Error("missing version");
3790
3796
  return version;
3791
3797
  } catch (error) {
3792
- throw new Error(`version check failed: invalid registry response: ${toErrorMessage$38(error)}`);
3798
+ throw new Error(`version check failed: invalid registry response: ${toErrorMessage$40(error)}`);
3793
3799
  }
3794
3800
  }
3795
3801
  function compareSemver(a, b) {
@@ -3854,7 +3860,7 @@ function toNonEmptyString(value) {
3854
3860
  const normalized = value.trim();
3855
3861
  return normalized.length > 0 ? normalized : null;
3856
3862
  }
3857
- function toErrorMessage$38(error) {
3863
+ function toErrorMessage$40(error) {
3858
3864
  if (error instanceof Error) return error.message;
3859
3865
  return String(error);
3860
3866
  }
@@ -4330,7 +4336,7 @@ async function setDaemonServiceRuntimeState(state, pathInput = {}) {
4330
4336
  await writeDaemonServiceRuntimeState(state, pathInput);
4331
4337
  }
4332
4338
  async function clearDaemonServiceRuntimeState(pathInput = {}) {
4333
- const { clearDaemonRuntimeLease } = await import("./daemon-runtime-lease-CRNcsm85.js");
4339
+ const { clearDaemonRuntimeLease } = await import("./daemon-runtime-lease-DYVTk_Z6.js");
4334
4340
  await Promise.all([rm(daemonServiceRuntimeStatePath(pathInput), { force: true }), clearDaemonRuntimeLease(pathInput)]);
4335
4341
  }
4336
4342
  async function withDaemonServiceRunLock(callback, meta = {
@@ -5046,7 +5052,7 @@ async function storeAccessToken(input) {
5046
5052
  key
5047
5053
  };
5048
5054
  }
5049
- throw new Error(`failed to store access token in macOS Keychain: ${toErrorMessage$37(error)}`);
5055
+ throw new Error(`failed to store access token in macOS Keychain: ${toErrorMessage$39(error)}`);
5050
5056
  }
5051
5057
  if (process.platform === "win32") try {
5052
5058
  await setWindowsDpapiToken({
@@ -5068,7 +5074,7 @@ async function storeAccessToken(input) {
5068
5074
  key
5069
5075
  };
5070
5076
  }
5071
- throw new Error(`failed to store access token via Windows DPAPI: ${toErrorMessage$37(error)}`);
5077
+ throw new Error(`failed to store access token via Windows DPAPI: ${toErrorMessage$39(error)}`);
5072
5078
  }
5073
5079
  if (allowInsecureFallback()) {
5074
5080
  await setInsecureFileToken({
@@ -5320,7 +5326,7 @@ function normalizeToken(value) {
5320
5326
  const normalized = value.trim();
5321
5327
  return normalized.length > 0 ? normalized : null;
5322
5328
  }
5323
- function toErrorMessage$37(error) {
5329
+ function toErrorMessage$39(error) {
5324
5330
  if (error instanceof Error) return error.message;
5325
5331
  return String(error);
5326
5332
  }
@@ -8428,7 +8434,7 @@ function normalizeOptionalText$46(value) {
8428
8434
  function nowIsoString() {
8429
8435
  return (/* @__PURE__ */ new Date()).toISOString();
8430
8436
  }
8431
- function toErrorMessage$36(error) {
8437
+ function toErrorMessage$38(error) {
8432
8438
  if (error instanceof Error) return error.message;
8433
8439
  return String(error);
8434
8440
  }
@@ -11326,7 +11332,7 @@ const backupAndCleanRuntimeState = async (input) => {
11326
11332
  appliedAt: input.nowIso,
11327
11333
  backupPaths,
11328
11334
  cleanedPaths,
11329
- errorMessage: toErrorMessage$36(error),
11335
+ errorMessage: toErrorMessage$38(error),
11330
11336
  fromEpoch: input.fromEpoch,
11331
11337
  reason: input.reason,
11332
11338
  status: "failed",
@@ -12173,7 +12179,7 @@ function createSpaceRequestTimeoutError(input) {
12173
12179
  return error;
12174
12180
  }
12175
12181
  function createSpaceRequestNetworkError(input) {
12176
- const error = new Error(`${input.operation} request could not reach ${describeRequestTarget(input.url)} (${toErrorMessage$35(input.cause)})`, { cause: input.cause });
12182
+ const error = new Error(`${input.operation} request could not reach ${describeRequestTarget(input.url)} (${toErrorMessage$37(input.cause)})`, { cause: input.cause });
12177
12183
  error.code = "network.request_failed";
12178
12184
  return error;
12179
12185
  }
@@ -12211,7 +12217,7 @@ function describeRequestTarget(url) {
12211
12217
  return url;
12212
12218
  }
12213
12219
  }
12214
- function toErrorMessage$35(error) {
12220
+ function toErrorMessage$37(error) {
12215
12221
  if (error instanceof Error) {
12216
12222
  const message = error.message.trim();
12217
12223
  return message.length > 0 ? message : "request failed";
@@ -12221,7 +12227,7 @@ function toErrorMessage$35(error) {
12221
12227
  }
12222
12228
  function shouldWrapNetworkRequestError(error) {
12223
12229
  if (error instanceof TypeError) return true;
12224
- const message = toErrorMessage$35(error).toLowerCase();
12230
+ const message = toErrorMessage$37(error).toLowerCase();
12225
12231
  return message.includes("fetch failed") || message.includes("failed to fetch") || message.includes("network request failed");
12226
12232
  }
12227
12233
 
@@ -12284,7 +12290,7 @@ function normalizeProfileIdList(value) {
12284
12290
  if (!Array.isArray(value)) return [];
12285
12291
  return value.map((item) => normalize$1(item)).filter((item) => item.length > 0);
12286
12292
  }
12287
- function toErrorMessage$34(err) {
12293
+ function toErrorMessage$36(err) {
12288
12294
  if (err instanceof Error) return err.message;
12289
12295
  return String(err);
12290
12296
  }
@@ -13668,7 +13674,7 @@ async function verifyLaunchContractFiles(input) {
13668
13674
  };
13669
13675
  } catch (error) {
13670
13676
  return {
13671
- errorMessage: toErrorMessage$33(error),
13677
+ errorMessage: toErrorMessage$35(error),
13672
13678
  ok: false
13673
13679
  };
13674
13680
  }
@@ -13695,7 +13701,7 @@ async function verifyCliLaunchContract(input) {
13695
13701
  return fileCheck;
13696
13702
  } catch (error) {
13697
13703
  return {
13698
- errorMessage: `${input.displayName} can't start on this device: ${toErrorMessage$33(error)}`,
13704
+ errorMessage: `${input.displayName} can't start on this device: ${toErrorMessage$35(error)}`,
13699
13705
  ok: false
13700
13706
  };
13701
13707
  }
@@ -13756,7 +13762,7 @@ async function inspectInstalledNodeScriptLaunchCandidate(input) {
13756
13762
  };
13757
13763
  } catch (error) {
13758
13764
  return {
13759
- errorMessage: `${input.displayName} is installed, but ATS could not inspect its launch files: ${toErrorMessage$33(error)}`,
13765
+ errorMessage: `${input.displayName} is installed, but ATS could not inspect its launch files: ${toErrorMessage$35(error)}`,
13760
13766
  ok: false
13761
13767
  };
13762
13768
  }
@@ -13953,7 +13959,7 @@ function shortenPathForDisplay(path) {
13953
13959
  function resolveNodeVersionFromPath(path) {
13954
13960
  return normalizeOptionalText$40(path.match(NODE_VERSION_PATH_RE)?.[1]);
13955
13961
  }
13956
- function toErrorMessage$33(error) {
13962
+ function toErrorMessage$35(error) {
13957
13963
  return error instanceof Error ? error.message : String(error);
13958
13964
  }
13959
13965
 
@@ -14962,7 +14968,7 @@ async function invokeOpenClawWithSingleContextHeal(input) {
14962
14968
  createRebuildFailedError: (error) => new OpenClawRuntimeError({
14963
14969
  code: "context.rebuild_failed",
14964
14970
  errorType: "adapter",
14965
- message: `context.rebuild_failed: ${toErrorMessage$32(error)}`
14971
+ message: `context.rebuild_failed: ${toErrorMessage$34(error)}`
14966
14972
  }),
14967
14973
  invokeOnce: (sessionId) => invokeOpenClawOnce({
14968
14974
  openClawAgentId: input.openClawAgentId,
@@ -15013,11 +15019,11 @@ async function invokeOpenClawOnce(input) {
15013
15019
  throw new OpenClawRuntimeError({
15014
15020
  code: "upstream_unreachable",
15015
15021
  errorType: "adapter",
15016
- message: `upstream_unreachable: ${toErrorMessage$32(error)}`
15022
+ message: `upstream_unreachable: ${toErrorMessage$34(error)}`
15017
15023
  });
15018
15024
  }
15019
15025
  }
15020
- function toErrorMessage$32(error) {
15026
+ function toErrorMessage$34(error) {
15021
15027
  if (error instanceof Error) return error.message;
15022
15028
  return String(error);
15023
15029
  }
@@ -15310,7 +15316,7 @@ function toOpenClawGatewayTransportError(error) {
15310
15316
  });
15311
15317
  const stderr = normalizeOptionalText$32(error?.stderr);
15312
15318
  const stdout = normalizeOptionalText$32(error?.stdout);
15313
- return classifyGatewayFailure(stderr ?? stdout ?? toErrorMessage$31(error));
15319
+ return classifyGatewayFailure(stderr ?? stdout ?? toErrorMessage$33(error));
15314
15320
  }
15315
15321
  function classifyGatewayFailure(message) {
15316
15322
  return new OpenClawGatewayTransportError(classifyOpenClawFailureMessage({ message }));
@@ -15319,7 +15325,7 @@ function normalizeOptionalText$32(value) {
15319
15325
  const normalized = String(value ?? "").trim();
15320
15326
  return normalized.length > 0 ? normalized : null;
15321
15327
  }
15322
- function toErrorMessage$31(error) {
15328
+ function toErrorMessage$33(error) {
15323
15329
  return error instanceof Error ? error.message : String(error);
15324
15330
  }
15325
15331
 
@@ -15591,7 +15597,7 @@ async function runOpenClawJsonCommand(input) {
15591
15597
  try {
15592
15598
  return JSON.parse(stdout);
15593
15599
  } catch (error) {
15594
- throw new Error(`openclaw JSON output could not be parsed: ${toErrorMessage$30(error)}`);
15600
+ throw new Error(`openclaw JSON output could not be parsed: ${toErrorMessage$32(error)}`);
15595
15601
  }
15596
15602
  }
15597
15603
  async function runOpenClawCommand(input) {
@@ -15626,7 +15632,7 @@ function normalizeOptionalText$30(value) {
15626
15632
  const normalized = String(value ?? "").trim();
15627
15633
  return normalized.length > 0 ? normalized : null;
15628
15634
  }
15629
- function toErrorMessage$30(error) {
15635
+ function toErrorMessage$32(error) {
15630
15636
  return error instanceof Error ? error.message : String(error);
15631
15637
  }
15632
15638
  function isExecFileTimeoutError(error) {
@@ -15640,7 +15646,7 @@ function resolveOpenClawCliErrorMessage(error, timeoutMs) {
15640
15646
  const cliMessage = normalizeOptionalText$30(error.stderr) ?? stdout;
15641
15647
  if (timeoutMs !== void 0 && isExecFileTimeoutError(error)) return cliMessage ? `openclaw command timed out after ${String(timeoutMs)}ms: ${cliMessage}` : `openclaw command timed out after ${String(timeoutMs)}ms`;
15642
15648
  if (cliMessage) return cliMessage;
15643
- return `openclaw command failed: ${toErrorMessage$30(error)}`;
15649
+ return `openclaw command failed: ${toErrorMessage$32(error)}`;
15644
15650
  }
15645
15651
  function parseOpenClawAgentSummary(value) {
15646
15652
  if (!value || typeof value !== "object") return null;
@@ -16021,7 +16027,7 @@ async function ensureOpenClawGatewayAgentVisible(input, deps = DEFAULT_OPENCLAW_
16021
16027
  gatewayRestartAttempted: true,
16022
16028
  gatewayVisibility: "missing_before_restart"
16023
16029
  },
16024
- message: `OpenClaw gateway restart failed while making agent '${agentId}' visible: ${toErrorMessage$29(error)}`
16030
+ message: `OpenClaw gateway restart failed while making agent '${agentId}' visible: ${toErrorMessage$31(error)}`
16025
16031
  });
16026
16032
  }
16027
16033
  let lastVisibilityError = null;
@@ -16050,7 +16056,7 @@ async function ensureOpenClawGatewayAgentVisible(input, deps = DEFAULT_OPENCLAW_
16050
16056
  gatewayRestartAttempted: true,
16051
16057
  gatewayVisibility: "missing_after_restart"
16052
16058
  },
16053
- message: lastVisibilityError === null ? `OpenClaw gateway is running but agent '${agentId}' is still not visible after a gateway restart` : `OpenClaw gateway still cannot confirm agent '${agentId}' after a gateway restart: ${toErrorMessage$29(lastVisibilityError)}`
16059
+ message: lastVisibilityError === null ? `OpenClaw gateway is running but agent '${agentId}' is still not visible after a gateway restart` : `OpenClaw gateway still cannot confirm agent '${agentId}' after a gateway restart: ${toErrorMessage$31(lastVisibilityError)}`
16054
16060
  });
16055
16061
  }
16056
16062
  async function maybeCopyOpenClawAuth(input) {
@@ -16091,7 +16097,7 @@ async function ensureParentDirectory(path) {
16091
16097
  async function pathExists$2(path) {
16092
16098
  return await access(path, constants.F_OK).then(() => true).catch(() => false);
16093
16099
  }
16094
- function toErrorMessage$29(error) {
16100
+ function toErrorMessage$31(error) {
16095
16101
  return error instanceof Error ? error.message : String(error);
16096
16102
  }
16097
16103
  function normalizeBootstrapReadError(error) {
@@ -16210,7 +16216,7 @@ function assertOpenClawWorkspaceMatch(input) {
16210
16216
  });
16211
16217
  }
16212
16218
  function isOpenClawAgentAlreadyExistsError(error) {
16213
- const normalizedMessage = toErrorMessage$29(error).toLowerCase();
16219
+ const normalizedMessage = toErrorMessage$31(error).toLowerCase();
16214
16220
  return normalizedMessage.includes("agent") && normalizedMessage.includes("already exists");
16215
16221
  }
16216
16222
  function resolveProviderRuntimeWorkingDirectory(value) {
@@ -16248,7 +16254,7 @@ async function prepareOpenClawRuntime(input, deps = DEFAULT_OPENCLAW_RUNTIME_PRE
16248
16254
  }).catch((error) => {
16249
16255
  throw new DaemonServiceRunError({
16250
16256
  code: "controller.bootstrap.failed",
16251
- message: `controller.bootstrap.failed: ${toErrorMessage$28(error)}`,
16257
+ message: `controller.bootstrap.failed: ${toErrorMessage$30(error)}`,
16252
16258
  providerErrorCode: extractErrorCode$1(error)
16253
16259
  });
16254
16260
  });
@@ -16258,7 +16264,7 @@ async function prepareOpenClawRuntime(input, deps = DEFAULT_OPENCLAW_RUNTIME_PRE
16258
16264
  }).catch((error) => {
16259
16265
  throw new DaemonServiceRunError({
16260
16266
  code: "controller.gateway.unhealthy",
16261
- message: `controller.gateway.unhealthy: ${toErrorMessage$28(error)}`,
16267
+ message: `controller.gateway.unhealthy: ${toErrorMessage$30(error)}`,
16262
16268
  providerErrorCode: extractErrorCode$1(error)
16263
16269
  });
16264
16270
  });
@@ -16270,7 +16276,7 @@ async function prepareOpenClawRuntime(input, deps = DEFAULT_OPENCLAW_RUNTIME_PRE
16270
16276
  const gatewayFailure = buildOpenClawGatewayVisibilityFailure(error);
16271
16277
  throw new DaemonServiceRunError({
16272
16278
  code: "controller.gateway.unhealthy",
16273
- message: `controller.gateway.unhealthy: ${toErrorMessage$28(error)}`,
16279
+ message: `controller.gateway.unhealthy: ${toErrorMessage$30(error)}`,
16274
16280
  providerErrorCode: extractErrorCode$1(error),
16275
16281
  ...gatewayFailure
16276
16282
  });
@@ -16309,7 +16315,7 @@ function resolveOpenClawGatewayVisibilityDiagnostics(error) {
16309
16315
  gatewayVisibility: parsedGatewayVisibility.data
16310
16316
  };
16311
16317
  }
16312
- function toErrorMessage$28(error) {
16318
+ function toErrorMessage$30(error) {
16313
16319
  return error instanceof Error ? error.message : String(error);
16314
16320
  }
16315
16321
 
@@ -16359,7 +16365,7 @@ function createOpenClawLocalDiagnosticsFailure(error) {
16359
16365
  return {
16360
16366
  errorCode: extractErrorCode(error),
16361
16367
  kind: "failed",
16362
- message: toErrorMessage$27(error)
16368
+ message: toErrorMessage$29(error)
16363
16369
  };
16364
16370
  }
16365
16371
  function isOpenClawLocalDiagnosticsFailure(diagnostics) {
@@ -16443,7 +16449,7 @@ async function resolveInspectModeDiagnostics(input) {
16443
16449
  openClawBin: input.openClawBin
16444
16450
  }).then(() => "healthy").catch((error) => ({
16445
16451
  errorCode: extractErrorCode(error),
16446
- message: toErrorMessage$27(error)
16452
+ message: toErrorMessage$29(error)
16447
16453
  }));
16448
16454
  if (gatewayHealth !== "healthy") return {
16449
16455
  ...inspected,
@@ -16523,7 +16529,7 @@ async function resolveInspectGatewayVisibility(input) {
16523
16529
  return {
16524
16530
  errorCode: extractErrorCode(error),
16525
16531
  gatewayVisibility: "not_checked",
16526
- message: toErrorMessage$27(error)
16532
+ message: toErrorMessage$29(error)
16527
16533
  };
16528
16534
  }
16529
16535
  }
@@ -16532,7 +16538,7 @@ function resolveDiagnosticsFailureDetail(input) {
16532
16538
  const inspectedMessage = typeof input.inspected.message === "string" && input.inspected.message.trim().length > 0 ? input.inspected.message.trim() : null;
16533
16539
  return {
16534
16540
  errorCode: inspectedErrorCode ?? extractErrorCode(input.error),
16535
- message: inspectedMessage ?? toErrorMessage$27(input.error)
16541
+ message: inspectedMessage ?? toErrorMessage$29(input.error)
16536
16542
  };
16537
16543
  }
16538
16544
  function resolveDiagnosticsTargetAgent(input) {
@@ -16593,7 +16599,7 @@ function buildBootstrapDiagnosticStatus(bootstrapStatus, errorCode, message) {
16593
16599
  }
16594
16600
  function resolveExplicitBootstrapDiagnostic(error) {
16595
16601
  const explicitErrorCode = extractErrorCode(error);
16596
- const explicitMessage = error ? toErrorMessage$27(error) : null;
16602
+ const explicitMessage = error ? toErrorMessage$29(error) : null;
16597
16603
  switch (explicitErrorCode) {
16598
16604
  case "openclaw.bootstrap.binding_conflict": return buildBootstrapDiagnosticStatus("binding_conflict", explicitErrorCode, explicitMessage);
16599
16605
  case "openclaw.bootstrap.workspace_mismatch": return buildBootstrapDiagnosticStatus("workspace_mismatch", explicitErrorCode, explicitMessage);
@@ -16613,7 +16619,7 @@ function resolveExistingBootstrapStatus(input) {
16613
16619
  }
16614
16620
  function resolveInvalidBootstrapStatus(input) {
16615
16621
  if (input.workspaceAgents.length > 1) return buildBootstrapDiagnosticStatus("workspace_ambiguous", "openclaw.bootstrap.workspace_ambiguous", null);
16616
- return buildBootstrapDiagnosticStatus("invalid", input.bootstrapRead.error?.code ?? extractErrorCode(input.error), input.bootstrapRead.error?.message ?? (input.error ? toErrorMessage$27(input.error) : null));
16622
+ return buildBootstrapDiagnosticStatus("invalid", input.bootstrapRead.error?.code ?? extractErrorCode(input.error), input.bootstrapRead.error?.message ?? (input.error ? toErrorMessage$29(input.error) : null));
16617
16623
  }
16618
16624
  function resolveMissingBootstrapStatus(workspaceAgents, input = {}) {
16619
16625
  if (workspaceAgents.length > 1) return buildBootstrapDiagnosticStatus("workspace_ambiguous", "openclaw.bootstrap.workspace_ambiguous", null);
@@ -16657,7 +16663,7 @@ function extractProviderErrorCode(error) {
16657
16663
  const normalized = String(error.providerErrorCode ?? "").trim();
16658
16664
  return normalized.length > 0 ? normalized : null;
16659
16665
  }
16660
- function toErrorMessage$27(error) {
16666
+ function toErrorMessage$29(error) {
16661
16667
  return error instanceof Error ? error.message : String(error);
16662
16668
  }
16663
16669
 
@@ -16884,12 +16890,6 @@ function resolveClaimFact(claimDiagnostics) {
16884
16890
  reasonCodes,
16885
16891
  source: "claim_diagnostics"
16886
16892
  };
16887
- if (isLegacyFinalClaimDiagnostic(reasonCodes)) return {
16888
- executionBlocked: false,
16889
- grantsClaimSuccess: false,
16890
- reasonCodes,
16891
- source: "claim_diagnostics"
16892
- };
16893
16893
  return {
16894
16894
  executionBlocked: true,
16895
16895
  grantsClaimSuccess: false,
@@ -16897,9 +16897,6 @@ function resolveClaimFact(claimDiagnostics) {
16897
16897
  source: "claim_diagnostics"
16898
16898
  };
16899
16899
  }
16900
- function isLegacyFinalClaimDiagnostic(reasonCodes) {
16901
- return reasonCodes.some((reasonCode) => reasonCode.startsWith("final_claim."));
16902
- }
16903
16900
  function resolveRouteFact(route) {
16904
16901
  if (!route) return {
16905
16902
  deviceId: null,
@@ -17111,7 +17108,6 @@ function formatReasonCodeFamily(reasonCode) {
17111
17108
  if (reasonCode.startsWith("agent_profile.")) return "ATS could not confirm this agent profile.";
17112
17109
  if (reasonCode.startsWith("service.") || reasonCode.startsWith("background_helper.") || reasonCode.startsWith("daemon.runtime_contract.")) return "ATS Service is not connected on this computer.";
17113
17110
  if (reasonCode.startsWith("claim_eligibility.") || reasonCode.startsWith("dispatch.claim_eligibility.")) return "Wake cannot use this local connection for this agent yet.";
17114
- if (reasonCode.startsWith("final_claim.")) return "An older Wake reservation check was recorded for diagnostics only.";
17115
17111
  if (reasonCode.startsWith("runtime.capability_report_") || reasonCode.startsWith("runtime.capability_report.")) return "This computer has not reported current local agent support yet.";
17116
17112
  if (reasonCode.startsWith("runtime.")) return "This computer needs a fresh check for this agent.";
17117
17113
  if (reasonCode.startsWith("agent_profile_binding.")) return "This agent's local connection needs setup.";
@@ -17217,10 +17213,6 @@ const REASON_TEXT = {
17217
17213
  "dispatch.claim_eligibility.binding.enabled_primary": "This agent's local connection is not available for Wake.",
17218
17214
  "dispatch.claim_eligibility.binding.missing": "This agent is not connected to a local agent yet.",
17219
17215
  "dispatch.claim_eligibility.binding.owner_mismatch": DIFFERENT_ACCOUNT_REASON,
17220
- "final_claim.claimant_identity_missing": "An older Wake reservation check was recorded for diagnostics only.",
17221
- "final_claim.legacy_diagnostic_only": "An older Wake reservation check was recorded for diagnostics only.",
17222
- "final_claim.lease_reserved": "An older Wake reservation check was recorded for diagnostics only.",
17223
- "final_claim.rejected": "An older Wake reservation check was recorded for diagnostics only.",
17224
17216
  "prepare_readiness.read_failed": "ATS could not check this computer for local agent support.",
17225
17217
  "background_helper.update_required": SERVICE_UPDATE_REQUIRED_REASON,
17226
17218
  "runtime.capability_ref_invalid": "ATS could not identify this local agent capability.",
@@ -18824,7 +18816,6 @@ const createCurrentDeviceApi = (client) => {
18824
18816
  }
18825
18817
  };
18826
18818
  };
18827
- const reserveFinalClaimInputSchema = finalClaimRouteParamsSchema.merge(reserveFinalClaimBodySchema).extend({ requestContext: atsRequestContextSchema.optional() });
18828
18819
  function buildPrepareReadinessRoute(deviceId) {
18829
18820
  return `/v1/devices/${encodeURIComponent(deviceId)}/prepare-readiness`;
18830
18821
  }
@@ -19683,7 +19674,7 @@ async function resolveDaemonRuntimeContractCompatibility(input) {
19683
19674
  observedEpoch: null,
19684
19675
  updatedAt: null,
19685
19676
  reasonCode: "daemon.runtime_contract.unavailable",
19686
- errorMessage: toErrorMessage$36(error)
19677
+ errorMessage: toErrorMessage$38(error)
19687
19678
  };
19688
19679
  }
19689
19680
  if (!meta) return {
@@ -21024,7 +21015,7 @@ async function invokeClaudeWithSingleContextHeal(input) {
21024
21015
  return new ClaudeRuntimeError({
21025
21016
  code: "context.rebuild_failed",
21026
21017
  errorType: "adapter",
21027
- message: `context.rebuild_failed: ${toErrorMessage$26(error)}`,
21018
+ message: `context.rebuild_failed: ${toErrorMessage$28(error)}`,
21028
21019
  ...providerAccessEvidence ? { providerAccessEvidence } : {}
21029
21020
  });
21030
21021
  },
@@ -21084,7 +21075,7 @@ async function invokeClaudeOnce(input) {
21084
21075
  throw new ClaudeRuntimeError({
21085
21076
  code: "upstream_unreachable",
21086
21077
  errorType: "adapter",
21087
- message: `upstream_unreachable: ${toErrorMessage$26(error)}`
21078
+ message: `upstream_unreachable: ${toErrorMessage$28(error)}`
21088
21079
  });
21089
21080
  }
21090
21081
  }
@@ -21094,7 +21085,7 @@ function getClaudeProviderAccessEvidence(error) {
21094
21085
  if (!evidence || typeof evidence !== "object") return null;
21095
21086
  return evidence;
21096
21087
  }
21097
- function toErrorMessage$26(error) {
21088
+ function toErrorMessage$28(error) {
21098
21089
  if (error instanceof Error) return error.message;
21099
21090
  return String(error);
21100
21091
  }
@@ -21711,7 +21702,7 @@ async function invokeCodexWithSingleContextHeal(input) {
21711
21702
  createRebuildFailedError: (error) => new CodexRuntimeError({
21712
21703
  code: "context.rebuild_failed",
21713
21704
  errorType: "adapter",
21714
- message: `context.rebuild_failed: ${toErrorMessage$25(error)}`
21705
+ message: `context.rebuild_failed: ${toErrorMessage$27(error)}`
21715
21706
  }),
21716
21707
  invokeOnce: (threadId) => invokeCodexOnce({
21717
21708
  launchContract: input.launchContract,
@@ -21765,11 +21756,11 @@ async function invokeCodexOnce(input) {
21765
21756
  throw new CodexRuntimeError({
21766
21757
  code: "upstream_unreachable",
21767
21758
  errorType: "adapter",
21768
- message: `upstream_unreachable: ${toErrorMessage$25(error)}`
21759
+ message: `upstream_unreachable: ${toErrorMessage$27(error)}`
21769
21760
  });
21770
21761
  }
21771
21762
  }
21772
- function toErrorMessage$25(error) {
21763
+ function toErrorMessage$27(error) {
21773
21764
  if (error instanceof Error) return error.message;
21774
21765
  return String(error);
21775
21766
  }
@@ -22713,7 +22704,7 @@ async function syncDeviceRuntimeStateProjection(input) {
22713
22704
  const projectedControllers = await loadProjectedControllers();
22714
22705
  const registeredCustomTargetIds = await loadRegisteredCustomTargetIds();
22715
22706
  const targetStates = await listAgentTargetStates().catch((error) => {
22716
- throw new Error(`failed to load ATS agent target states: ${toErrorMessage$24(error)}`);
22707
+ throw new Error(`failed to load ATS agent target states: ${toErrorMessage$26(error)}`);
22717
22708
  });
22718
22709
  const targetStateById = new Map(targetStates.map((state) => [state.agentId, state]));
22719
22710
  const projectedControllerIds = [...projectedControllers.keys()].sort();
@@ -22787,12 +22778,12 @@ async function hasValidAuthSession() {
22787
22778
  }
22788
22779
  async function loadProjectedControllers() {
22789
22780
  return await collectProjectedControllers(await listAtsProfiles().catch((error) => {
22790
- throw new Error(`failed to list ATS profiles: ${toErrorMessage$24(error)}`);
22781
+ throw new Error(`failed to list ATS profiles: ${toErrorMessage$26(error)}`);
22791
22782
  }));
22792
22783
  }
22793
22784
  async function loadRegisteredCustomTargetIds() {
22794
22785
  const customTargets = await listAgentCustomTargets().catch((error) => {
22795
- throw new Error(`failed to list ATS custom targets: ${toErrorMessage$24(error)}`);
22786
+ throw new Error(`failed to list ATS custom targets: ${toErrorMessage$26(error)}`);
22796
22787
  });
22797
22788
  return new Set(customTargets.map((target) => target.id));
22798
22789
  }
@@ -23069,7 +23060,7 @@ function emitProjectionEvidence(result) {
23069
23060
  function normalizeText$1(value) {
23070
23061
  return String(value ?? "").trim();
23071
23062
  }
23072
- function toErrorMessage$24(error) {
23063
+ function toErrorMessage$26(error) {
23073
23064
  if (error instanceof Error) return error.message;
23074
23065
  return String(error);
23075
23066
  }
@@ -23496,7 +23487,7 @@ async function readPrimaryBindingForRouteCatalog(input) {
23496
23487
  } catch (error) {
23497
23488
  throw new DaemonServiceRunError({
23498
23489
  code: "daemon.run.primary_binding_lookup_failed",
23499
- message: `Core primary binding lookup failed for profile ${input.profile.atsProfileId}: ${toErrorMessage$36(error)}`
23490
+ message: `Core primary binding lookup failed for profile ${input.profile.atsProfileId}: ${toErrorMessage$38(error)}`
23500
23491
  });
23501
23492
  }
23502
23493
  }
@@ -23504,7 +23495,7 @@ async function repairLocalReplyStateOrThrow(input) {
23504
23495
  try {
23505
23496
  await syncDeviceRuntimeStateProjection({ mode: "repair" });
23506
23497
  } catch (error) {
23507
- const errorMessage = toErrorMessage$36(error);
23498
+ const errorMessage = toErrorMessage$38(error);
23508
23499
  emitRunLine({
23509
23500
  presenter: input.presenter,
23510
23501
  code: "daemon.run.projection_sync_failed",
@@ -23518,7 +23509,7 @@ async function repairLocalReplyStateOrThrow(input) {
23518
23509
  try {
23519
23510
  await syncProfileWorkspaceState({ mode: "repair" });
23520
23511
  } catch (error) {
23521
- const errorMessage = toErrorMessage$36(error);
23512
+ const errorMessage = toErrorMessage$38(error);
23522
23513
  emitRunLine({
23523
23514
  presenter: input.presenter,
23524
23515
  code: "daemon.run.profile_workspace_sync_failed",
@@ -23560,12 +23551,12 @@ async function syncDaemonRouteCatalogState(input) {
23560
23551
  return {
23561
23552
  status: "failed",
23562
23553
  reason: "load_failed",
23563
- errorMessage: toErrorMessage$36(error)
23554
+ errorMessage: toErrorMessage$38(error)
23564
23555
  };
23565
23556
  }
23566
23557
  const nextFingerprint = buildRouteCatalogFingerprint(nextCatalog);
23567
23558
  if (nextFingerprint === input.catalogState.fingerprint) {
23568
- if (input.forceRegister && nextCatalog.profileIds.length > 0) {
23559
+ if ((input.forceRegister || nextCatalog.profileIds.some((profileId) => !input.leasesByProfileId.has(profileId))) && nextCatalog.profileIds.length > 0) {
23569
23560
  let registerResponse;
23570
23561
  try {
23571
23562
  registerResponse = await input.registerCatalog(nextCatalog.profileIds);
@@ -23573,7 +23564,7 @@ async function syncDaemonRouteCatalogState(input) {
23573
23564
  return {
23574
23565
  status: "failed",
23575
23566
  reason: "register_failed",
23576
- errorMessage: toErrorMessage$36(error)
23567
+ errorMessage: toErrorMessage$38(error)
23577
23568
  };
23578
23569
  }
23579
23570
  applyAcceptedLeases({
@@ -23604,7 +23595,7 @@ async function syncDaemonRouteCatalogState(input) {
23604
23595
  return {
23605
23596
  status: "failed",
23606
23597
  reason: "register_failed",
23607
- errorMessage: toErrorMessage$36(error)
23598
+ errorMessage: toErrorMessage$38(error)
23608
23599
  };
23609
23600
  }
23610
23601
  const diff = buildRouteCatalogDiff({
@@ -23747,7 +23738,7 @@ async function resolveDaemonLocalServiceDemand(input) {
23747
23738
  decision: "indeterminate",
23748
23739
  hasWakeableLocalRoute: false,
23749
23740
  repairableReplyCandidateCount: 0,
23750
- reason: `failed to load local daemon routes: ${toErrorMessage$36(error)}`,
23741
+ reason: `failed to load local daemon routes: ${toErrorMessage$38(error)}`,
23751
23742
  wakeableLocalRouteCount: 0,
23752
23743
  projection
23753
23744
  };
@@ -23872,7 +23863,7 @@ async function maybeAutoStopIdleBackgroundDaemonService(input) {
23872
23863
  } catch (error) {
23873
23864
  input.presenter.line({
23874
23865
  code: `${input.codePrefix}.auto_stop_failed`,
23875
- text: `ATS could not auto-stop the background service. ${toErrorMessage$36(error)}`
23866
+ text: `ATS could not auto-stop the background service. ${toErrorMessage$38(error)}`
23876
23867
  });
23877
23868
  return {
23878
23869
  autoStopped: false,
@@ -23966,9 +23957,9 @@ async function resolveGatewayChainReadiness(input = {}) {
23966
23957
  applicable: true,
23967
23958
  baseUrl: fallbackBaseUrl,
23968
23959
  checkedAt,
23969
- details: toErrorMessage$34(error),
23960
+ details: toErrorMessage$36(error),
23970
23961
  errorCode: null,
23971
- errorMessage: toErrorMessage$34(error),
23962
+ errorMessage: toErrorMessage$36(error),
23972
23963
  failureKind: "gateway_unreachable",
23973
23964
  ready: false,
23974
23965
  status: null,
@@ -24885,7 +24876,7 @@ function buildLookupFailedRouteObservationDetail(input) {
24885
24876
  observedAt: input.observedAt,
24886
24877
  reasonCode: "lookup_failed"
24887
24878
  });
24888
- const rawError = toErrorMessage$23(input.error).trim();
24879
+ const rawError = toErrorMessage$25(input.error).trim();
24889
24880
  if (rawError.length === 0 || rawError === detail) return detail;
24890
24881
  return `${detail} Raw lookup error: ${rawError}`;
24891
24882
  }
@@ -24913,7 +24904,7 @@ function enrichRuntimeStateWithManager(input) {
24913
24904
  serviceController: input.runtimeState.serviceController === "unknown" && input.serviceManager?.controller !== void 0 ? input.serviceManager.controller : input.runtimeState.serviceController
24914
24905
  };
24915
24906
  }
24916
- function toErrorMessage$23(error) {
24907
+ function toErrorMessage$25(error) {
24917
24908
  if (error instanceof Error) return error.message;
24918
24909
  return String(error);
24919
24910
  }
@@ -25694,7 +25685,7 @@ function dedupeAnomalyCodes(anomalyCodes) {
25694
25685
 
25695
25686
  //#endregion
25696
25687
  //#region src/system/daemon-status-snapshot.ts
25697
- const DAEMON_STATUS_GATEWAY_CHAIN_TIMEOUT_MS = 5e3;
25688
+ const DAEMON_STATUS_GATEWAY_CHAIN_TIMEOUT_MS = DEFAULT_GATEWAY_CHAIN_TIMEOUT_MS;
25698
25689
  async function resolveDaemonStatusSnapshot(input = {}) {
25699
25690
  const runtime = input.runtime ?? await resolveRuntimeContext({
25700
25691
  profile: input.profile,
@@ -25802,7 +25793,7 @@ async function captureDaemonServiceEvidence(input = {}) {
25802
25793
  errorMessage: null
25803
25794
  })).catch((error) => ({
25804
25795
  snapshot: null,
25805
- errorMessage: toErrorMessage$22(error)
25796
+ errorMessage: toErrorMessage$24(error)
25806
25797
  })),
25807
25798
  captureOwnedProcessesArtifact(phaseRootPath),
25808
25799
  captureSystemServiceDiagnosticsArtifact(phaseRootPath)
@@ -25916,7 +25907,7 @@ async function captureDirectoryArtifact(input) {
25916
25907
  };
25917
25908
  } catch (error) {
25918
25909
  return {
25919
- errorMessage: toErrorMessage$22(error),
25910
+ errorMessage: toErrorMessage$24(error),
25920
25911
  relativePath: null,
25921
25912
  sourcePath: input.sourcePath,
25922
25913
  status: "error"
@@ -25942,7 +25933,7 @@ async function captureFileArtifact(input) {
25942
25933
  };
25943
25934
  } catch (error) {
25944
25935
  return {
25945
- errorMessage: toErrorMessage$22(error),
25936
+ errorMessage: toErrorMessage$24(error),
25946
25937
  relativePath: null,
25947
25938
  sourcePath: input.sourcePath,
25948
25939
  status: "error"
@@ -25964,7 +25955,7 @@ async function captureOwnedProcessesArtifact(evidencePath) {
25964
25955
  } };
25965
25956
  } catch (error) {
25966
25957
  return { artifact: {
25967
- errorMessage: toErrorMessage$22(error),
25958
+ errorMessage: toErrorMessage$24(error),
25968
25959
  relativePath: null,
25969
25960
  sourcePath: null,
25970
25961
  status: "error"
@@ -26071,7 +26062,7 @@ async function runCommand$1(command, args, input = {}) {
26071
26062
  child.once("close", handleClose);
26072
26063
  });
26073
26064
  }
26074
- function toErrorMessage$22(error) {
26065
+ function toErrorMessage$24(error) {
26075
26066
  if (error instanceof Error) return error.message;
26076
26067
  return String(error);
26077
26068
  }
@@ -26243,7 +26234,7 @@ async function runDaemonServiceLifecycle(input) {
26243
26234
  failureStage: state.failureStage,
26244
26235
  evidencePath: state.evidencePath,
26245
26236
  recoveryStatus: "failed_before_safe_state",
26246
- errorMessage: toErrorMessage$21(error)
26237
+ errorMessage: toErrorMessage$23(error)
26247
26238
  };
26248
26239
  }
26249
26240
  }
@@ -26383,7 +26374,7 @@ async function executeDaemonServiceLifecycle(input) {
26383
26374
  }
26384
26375
  }
26385
26376
  async function recoverLifecycleFailure(input) {
26386
- const originalErrorMessage = toErrorMessage$21(input.error);
26377
+ const originalErrorMessage = toErrorMessage$23(input.error);
26387
26378
  const originalFailureStage = resolveLifecycleFailureStage(input.error, input.state.failureStage);
26388
26379
  const originalReasonCodes = resolveLifecycleFailureReasonCodes(input.error);
26389
26380
  if (input.restorePoint.trusted) {
@@ -26901,7 +26892,7 @@ function resolveLifecycleFailureReasonCodes(error) {
26901
26892
  if (error instanceof DaemonServiceLifecycleStageError) return error.reasonCodes;
26902
26893
  return [];
26903
26894
  }
26904
- function toErrorMessage$21(error) {
26895
+ function toErrorMessage$23(error) {
26905
26896
  if (error instanceof Error) return error.message;
26906
26897
  return String(error);
26907
26898
  }
@@ -26918,7 +26909,7 @@ async function stopDaemonProcess$1(pid, signal) {
26918
26909
  process$1.kill(pid, signal);
26919
26910
  } catch (error) {
26920
26911
  if (error instanceof Error && error.code === "ESRCH") return true;
26921
- throw new Error(`Failed to send ${signal} to pid ${String(pid)}: ${toErrorMessage$21(error)}`);
26912
+ throw new Error(`Failed to send ${signal} to pid ${String(pid)}: ${toErrorMessage$23(error)}`);
26922
26913
  }
26923
26914
  if (signal === "SIGKILL") return true;
26924
26915
  return await waitForProcessToExit$1(pid, PROCESS_STOP_WAIT_MS);
@@ -26928,7 +26919,7 @@ async function stopDaemonProcessWithTimeout(pid, signal, timeoutMs) {
26928
26919
  process$1.kill(pid, signal);
26929
26920
  } catch (error) {
26930
26921
  if (error instanceof Error && error.code === "ESRCH") return true;
26931
- throw new Error(`Failed to send ${signal} to pid ${String(pid)}: ${toErrorMessage$21(error)}`);
26922
+ throw new Error(`Failed to send ${signal} to pid ${String(pid)}: ${toErrorMessage$23(error)}`);
26932
26923
  }
26933
26924
  return await waitForProcessToExit$1(pid, timeoutMs);
26934
26925
  }
@@ -26945,7 +26936,7 @@ async function sleep$7(ms) {
26945
26936
  }
26946
26937
  function isLaunchdBootstrapIoError(serviceManager, error) {
26947
26938
  if (serviceManager.controller !== "launchd") return false;
26948
- const message = toErrorMessage$21(error).toLowerCase();
26939
+ const message = toErrorMessage$23(error).toLowerCase();
26949
26940
  return message.includes("bootstrap failed") && message.includes("input/output error");
26950
26941
  }
26951
26942
  async function writeLifecycleEvidenceEvent(input) {
@@ -27383,7 +27374,7 @@ async function resolveUpgradeStatus(input) {
27383
27374
  status: "check_failed",
27384
27375
  currentVersion: input.currentVersion,
27385
27376
  checkedAt: input.checkedAt,
27386
- error: toErrorMessage$20(error)
27377
+ error: toErrorMessage$22(error)
27387
27378
  };
27388
27379
  }
27389
27380
  }
@@ -27754,7 +27745,7 @@ function emitUpgradeCompleted(input) {
27754
27745
  text: "ATS CLI upgrade completed."
27755
27746
  });
27756
27747
  }
27757
- function toErrorMessage$20(error) {
27748
+ function toErrorMessage$22(error) {
27758
27749
  if (error instanceof Error) return error.message;
27759
27750
  return String(error);
27760
27751
  }
@@ -31815,7 +31806,7 @@ async function submitPrepareRuntimeCapabilityReports(input) {
31815
31806
  });
31816
31807
  } catch (error) {
31817
31808
  console.warn("[ats.runtime_reporting.write_failed]", {
31818
- error: toErrorMessage$19(error),
31809
+ error: toErrorMessage$21(error),
31819
31810
  event: "cli.runtime_reporting.write_failed",
31820
31811
  profileIds: input.reports.map((report) => report.diagnosticProfileId).filter((profileId) => Boolean(profileId)),
31821
31812
  reportCount: input.reports.length
@@ -31921,7 +31912,7 @@ function failedSubmission(input) {
31921
31912
  status: "failed"
31922
31913
  };
31923
31914
  }
31924
- function toErrorMessage$19(error) {
31915
+ function toErrorMessage$21(error) {
31925
31916
  if (error instanceof Error) {
31926
31917
  const message = error.message.trim();
31927
31918
  return message.length > 0 ? message : "unknown error";
@@ -32048,7 +32039,7 @@ async function ensureAgentProfileRuntimeBinding(input) {
32048
32039
  };
32049
32040
  } catch (error) {
32050
32041
  console.warn("[ats.agent_profile_binding.ensure_failed]", {
32051
- error: toErrorMessage$18(error),
32042
+ error: toErrorMessage$20(error),
32052
32043
  event: "cli.agent_profile_binding.ensure_failed",
32053
32044
  profileId: input.profile.atsProfileId
32054
32045
  });
@@ -32169,7 +32160,7 @@ function uniqueReasonCodes(reasonCodes) {
32169
32160
  async function sleep$6(durationMs) {
32170
32161
  await new Promise((resolve) => setTimeout(resolve, durationMs));
32171
32162
  }
32172
- function toErrorMessage$18(error) {
32163
+ function toErrorMessage$20(error) {
32173
32164
  if (error instanceof Error) {
32174
32165
  const message = error.message.trim();
32175
32166
  return message.length > 0 ? message : "unknown error";
@@ -33783,7 +33774,7 @@ async function runAuthLogin(input) {
33783
33774
  ott: input.ott,
33784
33775
  allowBackToCaller: input.allowBackToCaller === true
33785
33776
  }).catch((error) => {
33786
- if (runtime.resolvedView === "agent") throw createAuthLoginGuideError(toErrorMessage$17(error));
33777
+ if (runtime.resolvedView === "agent") throw createAuthLoginGuideError(toErrorMessage$19(error));
33787
33778
  throw error;
33788
33779
  });
33789
33780
  if (resolved.status !== "submitted") return handleAuthLoginExit({
@@ -33852,7 +33843,7 @@ async function runAuthLogin(input) {
33852
33843
  }
33853
33844
  });
33854
33845
  }
33855
- throw createAuthLoginGuideError(toErrorMessage$17(error));
33846
+ throw createAuthLoginGuideError(toErrorMessage$19(error));
33856
33847
  }
33857
33848
  throw error;
33858
33849
  }
@@ -34189,7 +34180,7 @@ function resolveClientIdForLogin(value, resolvedView) {
34189
34180
  try {
34190
34181
  return resolveClientId(value);
34191
34182
  } catch (error) {
34192
- if (resolvedView === "agent") throw createAuthLoginGuideError(toErrorMessage$17(error));
34183
+ if (resolvedView === "agent") throw createAuthLoginGuideError(toErrorMessage$19(error));
34193
34184
  throw error;
34194
34185
  }
34195
34186
  }
@@ -34612,7 +34603,7 @@ function normalizeOptionalString$14(value) {
34612
34603
  const normalized = String(value ?? "").trim();
34613
34604
  return normalized.length > 0 ? normalized : null;
34614
34605
  }
34615
- function toErrorMessage$17(error) {
34606
+ function toErrorMessage$19(error) {
34616
34607
  if (error instanceof Error) return error.message;
34617
34608
  return String(error);
34618
34609
  }
@@ -35541,6 +35532,7 @@ const historySizeByPath = /* @__PURE__ */ new Map();
35541
35532
  const HISTORY_ROTATION_MAX_BYTES = 4 * 1024 * 1024;
35542
35533
  const HISTORY_ROTATION_MAX_ARCHIVES = 3;
35543
35534
  const DEDUPE_RETENTION_MS = 2880 * 60 * 1e3;
35535
+ const INFLIGHT_RETENTION_MS = DEDUPE_RETENTION_MS;
35544
35536
  const AGENT_CONTEXT_RETENTION_MS = 720 * 60 * 60 * 1e3;
35545
35537
  const AGENT_CONTEXT_MAX_ENTRIES = 2e3;
35546
35538
  const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
@@ -35780,9 +35772,10 @@ const compactLedgerState = (input) => {
35780
35772
  state: input.state
35781
35773
  });
35782
35774
  const dedupeCutoffMs = referenceNowMs - DEDUPE_RETENTION_MS;
35775
+ const inflightCutoffMs = referenceNowMs - INFLIGHT_RETENTION_MS;
35783
35776
  const agentContextCutoffMs = referenceNowMs - AGENT_CONTEXT_RETENTION_MS;
35784
35777
  const nextDedupeFirstSeenByKey = Object.fromEntries(Object.entries(input.state.dedupeFirstSeenByKey).filter(([, firstSeenAtMs]) => firstSeenAtMs >= dedupeCutoffMs));
35785
- const nextInflightByTaskId = Object.fromEntries(Object.entries(input.state.inflightByTaskId).map(([taskId, taskState]) => [taskId, { ...taskState }]));
35778
+ const nextInflightByTaskId = Object.fromEntries(Object.entries(input.state.inflightByTaskId).filter(([, taskState]) => taskState.firstSeenAtMs >= inflightCutoffMs).map(([taskId, taskState]) => [taskId, { ...taskState }]));
35786
35779
  const inflightTaskIdSet = new Set(Object.keys(nextInflightByTaskId));
35787
35780
  const nextReplayedTaskIds = Object.fromEntries(Object.entries(input.state.replayedTaskIds).filter(([taskId, replayed]) => replayed === true && inflightTaskIdSet.has(taskId)));
35788
35781
  const filteredAgentContexts = Object.entries(input.state.agentContextByLookupKey).filter(([, context]) => context.updatedAtMs >= agentContextCutoffMs).sort((left, right) => {
@@ -37984,13 +37977,13 @@ async function bindImportedUpstreamConversationLocally(input) {
37984
37977
  agentContextLookupKey: seeded.agentContextLookupKey
37985
37978
  };
37986
37979
  } catch (error) {
37987
- if (!snapshot) throw new Error(`local imported upstream conversation bind failed on this device: ${toErrorMessage$16(error)}`);
37980
+ if (!snapshot) throw new Error(`local imported upstream conversation bind failed on this device: ${toErrorMessage$18(error)}`);
37988
37981
  try {
37989
37982
  await restoreImportedConversationExecution({ snapshot });
37990
37983
  } catch (restoreError) {
37991
- throw new LocalImportedUpstreamConversationBindError("daemon.control.local_imported_upstream_conversation_recovery_failed", `local imported upstream conversation bind failed and local recovery also failed on this device: original bind error: ${toErrorMessage$16(error)}; local recovery failed: ${toErrorMessage$16(restoreError)}`, { cause: restoreError });
37984
+ throw new LocalImportedUpstreamConversationBindError("daemon.control.local_imported_upstream_conversation_recovery_failed", `local imported upstream conversation bind failed and local recovery also failed on this device: original bind error: ${toErrorMessage$18(error)}; local recovery failed: ${toErrorMessage$18(restoreError)}`, { cause: restoreError });
37992
37985
  }
37993
- throw new LocalImportedUpstreamConversationBindError("daemon.control.local_imported_upstream_conversation_bind_failed", `local imported upstream conversation bind failed on this device: ${toErrorMessage$16(error)}`, { cause: error });
37986
+ throw new LocalImportedUpstreamConversationBindError("daemon.control.local_imported_upstream_conversation_bind_failed", `local imported upstream conversation bind failed on this device: ${toErrorMessage$18(error)}`, { cause: error });
37994
37987
  }
37995
37988
  }
37996
37989
  async function clearImportedUpstreamConversationLocalStateLocally(input) {
@@ -38003,10 +37996,10 @@ async function clearImportedUpstreamConversationLocalStateLocally(input) {
38003
37996
  transportMode: input.transportMode
38004
37997
  });
38005
37998
  } catch (error) {
38006
- throw new LocalImportedUpstreamConversationBindError("daemon.control.local_imported_upstream_conversation_local_state_clear_failed", "local imported upstream conversation local state clear failed on this device: " + toErrorMessage$16(error), { cause: error });
37999
+ throw new LocalImportedUpstreamConversationBindError("daemon.control.local_imported_upstream_conversation_local_state_clear_failed", "local imported upstream conversation local state clear failed on this device: " + toErrorMessage$18(error), { cause: error });
38007
38000
  }
38008
38001
  }
38009
- function toErrorMessage$16(error) {
38002
+ function toErrorMessage$18(error) {
38010
38003
  if (error instanceof Error && error.message.trim().length > 0) return error.message;
38011
38004
  return String(error);
38012
38005
  }
@@ -38370,315 +38363,6 @@ function resolveDaemonCapabilities(input) {
38370
38363
  return { runtimeAdapters };
38371
38364
  }
38372
38365
 
38373
- //#endregion
38374
- //#region src/daemon/dispatch/dispatch-backpressure-queue.ts
38375
- function createDispatchBackpressureQueue(input) {
38376
- const pendingTasks = [];
38377
- const activeCountByControllerKey = /* @__PURE__ */ new Map();
38378
- const activeCountByProfileId = /* @__PURE__ */ new Map();
38379
- const ownedAttemptKeys = /* @__PURE__ */ new Set();
38380
- const ownedTaskIds = /* @__PURE__ */ new Map();
38381
- const drainWaiters = [];
38382
- let activeGlobal = 0;
38383
- const resolveActiveForProfile = (profileId) => {
38384
- return activeCountByProfileId.get(profileId) ?? 0;
38385
- };
38386
- const resolveActiveForController = (controllerKey) => {
38387
- return activeCountByControllerKey.get(controllerKey) ?? 0;
38388
- };
38389
- const buildSnapshot = (profileId, controllerKey) => {
38390
- return {
38391
- activeForController: resolveActiveForController(controllerKey),
38392
- activeForProfile: resolveActiveForProfile(profileId),
38393
- activeGlobal,
38394
- limits: input.limits,
38395
- queueDepth: pendingTasks.length
38396
- };
38397
- };
38398
- const resolveWaitReason = (inputWait) => {
38399
- if (activeGlobal >= input.limits.globalConcurrency) return "global_concurrency";
38400
- if (resolveActiveForProfile(inputWait.profileId) >= input.limits.perProfileConcurrency) return "profile_concurrency";
38401
- return "none";
38402
- };
38403
- const buildLocalQueueDiagnostics = (inputDiagnostics) => {
38404
- const waitReason = inputDiagnostics.waitReason ?? resolveWaitReason({ profileId: inputDiagnostics.profileId });
38405
- const status = inputDiagnostics.status ?? (waitReason === "none" ? "starting_runtime" : "queued");
38406
- return {
38407
- ...buildSnapshot(inputDiagnostics.profileId, inputDiagnostics.controllerKey),
38408
- controllerConcurrencyPolicy: "diagnostic_only",
38409
- queuePosition: status === "queued" ? inputDiagnostics.queuePosition : null,
38410
- status,
38411
- waitReason
38412
- };
38413
- };
38414
- const buildTaskOwnerSnapshot = (owner) => {
38415
- return {
38416
- attemptId: owner.attemptId,
38417
- dispatchId: owner.dispatchId,
38418
- executionTokenRunId: owner.executionTokenRunId,
38419
- runtimeCoordinatorExecutionId: owner.runtimeCoordinatorExecutionId,
38420
- taskId: owner.taskId
38421
- };
38422
- };
38423
- const clearQueuedLifecycle = (pendingTask) => {
38424
- pendingTask.stopQueuedLifecycle?.();
38425
- pendingTask.stopQueuedLifecycle = null;
38426
- };
38427
- const releaseTaskOwnership = (task) => {
38428
- ownedAttemptKeys.delete(buildAttemptKey(task.dispatchId, task.attemptId));
38429
- const activeOwner = ownedTaskIds.get(task.taskId);
38430
- if (activeOwner && activeOwner.attemptId === task.attemptId && activeOwner.dispatchId === task.dispatchId) ownedTaskIds.delete(task.taskId);
38431
- };
38432
- const notifyDrainWaitersIfIdle = () => {
38433
- if (pendingTasks.length > 0 || activeGlobal > 0) return;
38434
- while (drainWaiters.length > 0) drainWaiters.shift()?.();
38435
- };
38436
- const pump = () => {
38437
- while (activeGlobal < input.limits.globalConcurrency) {
38438
- const nextTaskIndex = pendingTasks.findIndex((candidate) => {
38439
- return resolveActiveForProfile(candidate.task.profileId) < input.limits.perProfileConcurrency;
38440
- });
38441
- if (nextTaskIndex < 0) break;
38442
- const selectedPendingTask = pendingTasks.splice(nextTaskIndex, 1)[0];
38443
- if (!selectedPendingTask) continue;
38444
- clearQueuedLifecycle(selectedPendingTask);
38445
- const selectedTask = selectedPendingTask.task;
38446
- activeGlobal += 1;
38447
- activeCountByProfileId.set(selectedTask.profileId, resolveActiveForProfile(selectedTask.profileId) + 1);
38448
- activeCountByControllerKey.set(selectedTask.controllerKey, resolveActiveForController(selectedTask.controllerKey) + 1);
38449
- const startedEvent = {
38450
- adapterId: selectedTask.adapterId,
38451
- attemptId: selectedTask.attemptId,
38452
- controllerKey: selectedTask.controllerKey,
38453
- dispatchId: selectedTask.dispatchId,
38454
- localQueue: buildLocalQueueDiagnostics({
38455
- controllerKey: selectedTask.controllerKey,
38456
- profileId: selectedTask.profileId,
38457
- queuePosition: null,
38458
- status: "starting_runtime",
38459
- waitReason: "none"
38460
- }),
38461
- profileId: selectedTask.profileId,
38462
- spaceId: selectedTask.spaceId,
38463
- taskId: selectedTask.taskId,
38464
- targetLabel: selectedTask.targetLabel,
38465
- transportMode: selectedTask.transportMode,
38466
- ...buildSnapshot(selectedTask.profileId, selectedTask.controllerKey)
38467
- };
38468
- input.onTaskStarted?.(startedEvent);
38469
- const startedAtMs = Date.now();
38470
- Promise.resolve().then(async () => {
38471
- const completionResult = resolveTaskCompletionResult(await selectedTask.run());
38472
- input.onTaskCompleted?.({
38473
- adapterId: selectedTask.adapterId,
38474
- attemptId: selectedTask.attemptId,
38475
- ...buildSnapshot(selectedTask.profileId, selectedTask.controllerKey),
38476
- controllerKey: selectedTask.controllerKey,
38477
- dispatchId: selectedTask.dispatchId,
38478
- durationMs: Math.max(0, Date.now() - startedAtMs),
38479
- errorCode: completionResult.errorCode,
38480
- errorMessage: completionResult.errorMessage,
38481
- localQueue: buildLocalQueueDiagnostics({
38482
- controllerKey: selectedTask.controllerKey,
38483
- profileId: selectedTask.profileId,
38484
- queuePosition: null,
38485
- status: "starting_runtime",
38486
- waitReason: "none"
38487
- }),
38488
- profileId: selectedTask.profileId,
38489
- result: completionResult.result,
38490
- spaceId: selectedTask.spaceId,
38491
- taskId: selectedTask.taskId,
38492
- targetLabel: selectedTask.targetLabel,
38493
- transportMode: selectedTask.transportMode
38494
- });
38495
- }).catch((error) => {
38496
- input.onTaskCompleted?.({
38497
- adapterId: selectedTask.adapterId,
38498
- attemptId: selectedTask.attemptId,
38499
- ...buildSnapshot(selectedTask.profileId, selectedTask.controllerKey),
38500
- controllerKey: selectedTask.controllerKey,
38501
- dispatchId: selectedTask.dispatchId,
38502
- durationMs: Math.max(0, Date.now() - startedAtMs),
38503
- errorCode: null,
38504
- errorMessage: toErrorMessage$15(error),
38505
- localQueue: buildLocalQueueDiagnostics({
38506
- controllerKey: selectedTask.controllerKey,
38507
- profileId: selectedTask.profileId,
38508
- queuePosition: null,
38509
- status: "starting_runtime",
38510
- waitReason: "none"
38511
- }),
38512
- profileId: selectedTask.profileId,
38513
- result: "failed",
38514
- spaceId: selectedTask.spaceId,
38515
- taskId: selectedTask.taskId,
38516
- targetLabel: selectedTask.targetLabel,
38517
- transportMode: selectedTask.transportMode
38518
- });
38519
- }).finally(() => {
38520
- releaseTaskOwnership(selectedTask);
38521
- activeGlobal = Math.max(0, activeGlobal - 1);
38522
- const remainingActiveForProfile = Math.max(0, resolveActiveForProfile(selectedTask.profileId) - 1);
38523
- if (remainingActiveForProfile === 0) activeCountByProfileId.delete(selectedTask.profileId);
38524
- else activeCountByProfileId.set(selectedTask.profileId, remainingActiveForProfile);
38525
- const remainingActiveForController = Math.max(0, resolveActiveForController(selectedTask.controllerKey) - 1);
38526
- if (remainingActiveForController === 0) activeCountByControllerKey.delete(selectedTask.controllerKey);
38527
- else activeCountByControllerKey.set(selectedTask.controllerKey, remainingActiveForController);
38528
- notifyDrainWaitersIfIdle();
38529
- pump();
38530
- });
38531
- }
38532
- };
38533
- return {
38534
- enqueue(task) {
38535
- const attemptKey = buildAttemptKey(task.dispatchId, task.attemptId);
38536
- if (ownedAttemptKeys.has(attemptKey)) return {
38537
- accepted: true,
38538
- deduped: true,
38539
- snapshot: buildSnapshot(task.profileId, task.controllerKey)
38540
- };
38541
- const activeOwner = ownedTaskIds.get(task.taskId);
38542
- if (activeOwner) return {
38543
- accepted: false,
38544
- activeOwner: buildTaskOwnerSnapshot(activeOwner),
38545
- reason: "task.owner_conflict",
38546
- snapshot: buildSnapshot(task.profileId, task.controllerKey)
38547
- };
38548
- if (pendingTasks.length >= input.limits.queueMax) return {
38549
- accepted: false,
38550
- reason: "queue.full",
38551
- snapshot: buildSnapshot(task.profileId, task.controllerKey)
38552
- };
38553
- ownedAttemptKeys.add(attemptKey);
38554
- ownedTaskIds.set(task.taskId, {
38555
- attemptId: task.attemptId,
38556
- dispatchId: task.dispatchId,
38557
- executionTokenRunId: task.executionTokenRunId ?? null,
38558
- runtimeCoordinatorExecutionId: task.runtimeCoordinatorExecutionId ?? null,
38559
- taskId: task.taskId
38560
- });
38561
- const pendingTask = {
38562
- stopQueuedLifecycle: null,
38563
- task
38564
- };
38565
- pendingTasks.push(pendingTask);
38566
- const snapshot = buildSnapshot(task.profileId, task.controllerKey);
38567
- if (task.onQueued) try {
38568
- const queuePosition = pendingTasks.indexOf(pendingTask) + 1;
38569
- const stopQueuedLifecycle = task.onQueued({
38570
- adapterId: task.adapterId,
38571
- attemptId: task.attemptId,
38572
- controllerKey: task.controllerKey,
38573
- dispatchId: task.dispatchId,
38574
- localQueue: buildLocalQueueDiagnostics({
38575
- controllerKey: task.controllerKey,
38576
- profileId: task.profileId,
38577
- queuePosition
38578
- }),
38579
- profileId: task.profileId,
38580
- spaceId: task.spaceId,
38581
- taskId: task.taskId,
38582
- targetLabel: task.targetLabel,
38583
- transportMode: task.transportMode,
38584
- ...snapshot
38585
- });
38586
- pendingTask.stopQueuedLifecycle = typeof stopQueuedLifecycle === "function" ? stopQueuedLifecycle : null;
38587
- } catch (error) {
38588
- pendingTasks.pop();
38589
- releaseTaskOwnership(task);
38590
- throw error;
38591
- }
38592
- pump();
38593
- return {
38594
- accepted: true,
38595
- deduped: false,
38596
- snapshot
38597
- };
38598
- },
38599
- dropPendingTasks(inputDrop) {
38600
- const reason = toPendingDropReason(inputDrop?.reason);
38601
- const shouldDrop = inputDrop?.shouldDrop ?? (() => true);
38602
- let droppedCount = 0;
38603
- for (let index = pendingTasks.length - 1; index >= 0; index -= 1) {
38604
- const pendingTask = pendingTasks[index];
38605
- if (!(pendingTask && shouldDrop(pendingTask.task))) continue;
38606
- pendingTasks.splice(index, 1);
38607
- clearQueuedLifecycle(pendingTask);
38608
- releaseTaskOwnership(pendingTask.task);
38609
- droppedCount += 1;
38610
- input.onTaskDropped?.({
38611
- adapterId: pendingTask.task.adapterId,
38612
- attemptId: pendingTask.task.attemptId,
38613
- controllerKey: pendingTask.task.controllerKey,
38614
- dispatchId: pendingTask.task.dispatchId,
38615
- localQueue: buildLocalQueueDiagnostics({
38616
- controllerKey: pendingTask.task.controllerKey,
38617
- profileId: pendingTask.task.profileId,
38618
- queuePosition: null,
38619
- status: "queued"
38620
- }),
38621
- profileId: pendingTask.task.profileId,
38622
- reason,
38623
- spaceId: pendingTask.task.spaceId,
38624
- taskId: pendingTask.task.taskId,
38625
- targetLabel: pendingTask.task.targetLabel,
38626
- transportMode: pendingTask.task.transportMode,
38627
- ...buildSnapshot(pendingTask.task.profileId, pendingTask.task.controllerKey)
38628
- });
38629
- }
38630
- notifyDrainWaitersIfIdle();
38631
- return { droppedCount };
38632
- },
38633
- drain() {
38634
- if (pendingTasks.length === 0 && activeGlobal === 0) return Promise.resolve();
38635
- return new Promise((resolve) => {
38636
- drainWaiters.push(resolve);
38637
- });
38638
- },
38639
- getDrainState() {
38640
- return {
38641
- activeGlobal,
38642
- pendingCount: pendingTasks.length
38643
- };
38644
- },
38645
- getSnapshot(profileId, controllerKey) {
38646
- return buildSnapshot(profileId, controllerKey);
38647
- }
38648
- };
38649
- }
38650
- function buildAttemptKey(dispatchId, attemptId) {
38651
- return `${dispatchId}::${attemptId}`;
38652
- }
38653
- function toErrorMessage$15(error) {
38654
- if (error instanceof Error && error.message.trim().length > 0) return error.message;
38655
- if (typeof error === "string" && error.trim().length > 0) return error;
38656
- return "unknown error";
38657
- }
38658
- function resolveTaskCompletionResult(result) {
38659
- if (!result || typeof result !== "object") return {
38660
- errorCode: null,
38661
- errorMessage: null,
38662
- result: "success"
38663
- };
38664
- const normalizedResult = result.result === "failed" || result.result === "partial_success" || result.result === "success" ? result.result : "success";
38665
- return {
38666
- errorCode: toOptionalText(result.errorCode),
38667
- errorMessage: toOptionalText(result.errorMessage),
38668
- result: normalizedResult
38669
- };
38670
- }
38671
- function toOptionalText(value) {
38672
- if (typeof value !== "string") return null;
38673
- const normalized = value.trim();
38674
- return normalized.length > 0 ? normalized : null;
38675
- }
38676
- function toPendingDropReason(value) {
38677
- if (typeof value !== "string") return "queue.drop";
38678
- const normalized = value.trim();
38679
- return normalized.length > 0 ? normalized : "queue.drop";
38680
- }
38681
-
38682
38366
  //#endregion
38683
38367
  //#region src/daemon/dispatch/send-dispatch-result.ts
38684
38368
  function sendDispatchResultEnvelopeFrame(input) {
@@ -39054,7 +38738,7 @@ function flushDispatchResultOutbox(input) {
39054
38738
  return {
39055
38739
  ...record,
39056
38740
  attemptCount: record.attemptCount + 1,
39057
- lastFailureReason: toErrorMessage$36(error),
38741
+ lastFailureReason: toErrorMessage$38(error),
39058
38742
  nextAttemptAtMs: nowMs + resolveOutboxBackoffMs(record.attemptCount + 1),
39059
38743
  updatedAtMs: nowMs
39060
38744
  };
@@ -39105,6 +38789,301 @@ const isDispatchResultOutboxRecord = (value) => {
39105
38789
  return candidate.schema === OUTBOX_RECORD_SCHEMA && typeof candidate.attemptId === "string" && typeof candidate.dispatchId === "string" && typeof candidate.daemonSessionId === "string" && typeof candidate.executionIdentityEcho === "object" && candidate.executionIdentityEcho !== null && typeof candidate.leaseEpoch === "number" && typeof candidate.connectionGeneration === "number" && typeof candidate.taskId === "string" && typeof candidate.taskResult === "object" && candidate.taskResult !== null && typeof candidate.createdAtMs === "number" && typeof candidate.updatedAtMs === "number" && typeof candidate.nextAttemptAtMs === "number" && typeof candidate.attemptCount === "number";
39106
38790
  };
39107
38791
 
38792
+ //#endregion
38793
+ //#region src/daemon/dispatch/local-execution-slots.ts
38794
+ const LOCAL_AGENT_PROFILE_CONCURRENCY_LIMIT = 1;
38795
+ function createLocalExecutionSlots(input) {
38796
+ const pendingTasks = [];
38797
+ const activeCountByProfileId = /* @__PURE__ */ new Map();
38798
+ const ownedAttemptKeys = /* @__PURE__ */ new Set();
38799
+ const ownedTaskIds = /* @__PURE__ */ new Map();
38800
+ const drainWaiters = [];
38801
+ let activeGlobal = 0;
38802
+ const resolveActiveForProfile = (profileId) => {
38803
+ return activeCountByProfileId.get(profileId) ?? 0;
38804
+ };
38805
+ const buildSnapshot = (profileId) => {
38806
+ return {
38807
+ activeForProfile: resolveActiveForProfile(profileId),
38808
+ activeGlobal,
38809
+ limits: input.limits,
38810
+ queueDepth: pendingTasks.length
38811
+ };
38812
+ };
38813
+ const resolveWaitReason = (inputWait) => {
38814
+ if (activeGlobal >= input.limits.globalConcurrency) return "global_concurrency";
38815
+ if (resolveActiveForProfile(inputWait.profileId) >= LOCAL_AGENT_PROFILE_CONCURRENCY_LIMIT) return "profile_concurrency";
38816
+ return "none";
38817
+ };
38818
+ const buildLocalQueueDiagnostics = (inputDiagnostics) => {
38819
+ const waitReason = inputDiagnostics.waitReason ?? resolveWaitReason({ profileId: inputDiagnostics.profileId });
38820
+ const status = inputDiagnostics.status ?? (waitReason === "none" ? "starting_runtime" : "queued");
38821
+ return {
38822
+ ...buildSnapshot(inputDiagnostics.profileId),
38823
+ queuePosition: status === "queued" ? inputDiagnostics.queuePosition : null,
38824
+ status,
38825
+ waitReason
38826
+ };
38827
+ };
38828
+ const buildTaskOwnerSnapshot = (owner) => {
38829
+ return {
38830
+ attemptId: owner.attemptId,
38831
+ dispatchId: owner.dispatchId,
38832
+ executionTokenRunId: owner.executionTokenRunId,
38833
+ runtimeCoordinatorExecutionId: owner.runtimeCoordinatorExecutionId,
38834
+ taskId: owner.taskId
38835
+ };
38836
+ };
38837
+ const clearQueuedLifecycle = (pendingTask) => {
38838
+ pendingTask.stopQueuedLifecycle?.();
38839
+ pendingTask.stopQueuedLifecycle = null;
38840
+ };
38841
+ const releaseTaskOwnership = (task) => {
38842
+ ownedAttemptKeys.delete(buildAttemptKey(task.dispatchId, task.attemptId));
38843
+ const activeOwner = ownedTaskIds.get(task.taskId);
38844
+ if (activeOwner && activeOwner.attemptId === task.attemptId && activeOwner.dispatchId === task.dispatchId) ownedTaskIds.delete(task.taskId);
38845
+ };
38846
+ const notifyDrainWaitersIfIdle = () => {
38847
+ if (pendingTasks.length > 0 || activeGlobal > 0) return;
38848
+ while (drainWaiters.length > 0) drainWaiters.shift()?.();
38849
+ };
38850
+ const pump = () => {
38851
+ while (activeGlobal < input.limits.globalConcurrency) {
38852
+ const nextTaskIndex = pendingTasks.findIndex((candidate) => {
38853
+ return resolveActiveForProfile(candidate.task.profileId) < LOCAL_AGENT_PROFILE_CONCURRENCY_LIMIT;
38854
+ });
38855
+ if (nextTaskIndex < 0) break;
38856
+ const selectedPendingTask = pendingTasks.splice(nextTaskIndex, 1)[0];
38857
+ if (!selectedPendingTask) continue;
38858
+ clearQueuedLifecycle(selectedPendingTask);
38859
+ const selectedTask = selectedPendingTask.task;
38860
+ activeGlobal += 1;
38861
+ activeCountByProfileId.set(selectedTask.profileId, resolveActiveForProfile(selectedTask.profileId) + 1);
38862
+ const startedEvent = {
38863
+ adapterId: selectedTask.adapterId,
38864
+ attemptId: selectedTask.attemptId,
38865
+ controllerKey: selectedTask.controllerKey,
38866
+ dispatchId: selectedTask.dispatchId,
38867
+ localQueue: buildLocalQueueDiagnostics({
38868
+ profileId: selectedTask.profileId,
38869
+ queuePosition: null,
38870
+ status: "starting_runtime",
38871
+ waitReason: "none"
38872
+ }),
38873
+ profileId: selectedTask.profileId,
38874
+ spaceId: selectedTask.spaceId,
38875
+ taskId: selectedTask.taskId,
38876
+ targetLabel: selectedTask.targetLabel,
38877
+ transportMode: selectedTask.transportMode,
38878
+ ...buildSnapshot(selectedTask.profileId)
38879
+ };
38880
+ input.onTaskStarted?.(startedEvent);
38881
+ const startedAtMs = Date.now();
38882
+ Promise.resolve().then(async () => {
38883
+ const completionResult = resolveTaskCompletionResult(await selectedTask.run());
38884
+ input.onTaskCompleted?.({
38885
+ adapterId: selectedTask.adapterId,
38886
+ attemptId: selectedTask.attemptId,
38887
+ ...buildSnapshot(selectedTask.profileId),
38888
+ controllerKey: selectedTask.controllerKey,
38889
+ dispatchId: selectedTask.dispatchId,
38890
+ durationMs: Math.max(0, Date.now() - startedAtMs),
38891
+ errorCode: completionResult.errorCode,
38892
+ errorMessage: completionResult.errorMessage,
38893
+ localQueue: buildLocalQueueDiagnostics({
38894
+ profileId: selectedTask.profileId,
38895
+ queuePosition: null,
38896
+ status: "starting_runtime",
38897
+ waitReason: "none"
38898
+ }),
38899
+ profileId: selectedTask.profileId,
38900
+ result: completionResult.result,
38901
+ spaceId: selectedTask.spaceId,
38902
+ taskId: selectedTask.taskId,
38903
+ targetLabel: selectedTask.targetLabel,
38904
+ transportMode: selectedTask.transportMode
38905
+ });
38906
+ }).catch((error) => {
38907
+ input.onTaskCompleted?.({
38908
+ adapterId: selectedTask.adapterId,
38909
+ attemptId: selectedTask.attemptId,
38910
+ ...buildSnapshot(selectedTask.profileId),
38911
+ controllerKey: selectedTask.controllerKey,
38912
+ dispatchId: selectedTask.dispatchId,
38913
+ durationMs: Math.max(0, Date.now() - startedAtMs),
38914
+ errorCode: null,
38915
+ errorMessage: toErrorMessage$17(error),
38916
+ localQueue: buildLocalQueueDiagnostics({
38917
+ profileId: selectedTask.profileId,
38918
+ queuePosition: null,
38919
+ status: "starting_runtime",
38920
+ waitReason: "none"
38921
+ }),
38922
+ profileId: selectedTask.profileId,
38923
+ result: "failed",
38924
+ spaceId: selectedTask.spaceId,
38925
+ taskId: selectedTask.taskId,
38926
+ targetLabel: selectedTask.targetLabel,
38927
+ transportMode: selectedTask.transportMode
38928
+ });
38929
+ }).finally(() => {
38930
+ releaseTaskOwnership(selectedTask);
38931
+ activeGlobal = Math.max(0, activeGlobal - 1);
38932
+ const remainingActiveForProfile = Math.max(0, resolveActiveForProfile(selectedTask.profileId) - 1);
38933
+ if (remainingActiveForProfile === 0) activeCountByProfileId.delete(selectedTask.profileId);
38934
+ else activeCountByProfileId.set(selectedTask.profileId, remainingActiveForProfile);
38935
+ notifyDrainWaitersIfIdle();
38936
+ pump();
38937
+ });
38938
+ }
38939
+ };
38940
+ return {
38941
+ request(task) {
38942
+ const attemptKey = buildAttemptKey(task.dispatchId, task.attemptId);
38943
+ if (ownedAttemptKeys.has(attemptKey)) return {
38944
+ accepted: true,
38945
+ deduped: true,
38946
+ snapshot: buildSnapshot(task.profileId)
38947
+ };
38948
+ const activeOwner = ownedTaskIds.get(task.taskId);
38949
+ if (activeOwner) return {
38950
+ accepted: false,
38951
+ activeOwner: buildTaskOwnerSnapshot(activeOwner),
38952
+ reason: "task.owner_conflict",
38953
+ snapshot: buildSnapshot(task.profileId)
38954
+ };
38955
+ if (pendingTasks.length >= input.limits.queueMax) return {
38956
+ accepted: false,
38957
+ reason: "queue.full",
38958
+ snapshot: buildSnapshot(task.profileId)
38959
+ };
38960
+ ownedAttemptKeys.add(attemptKey);
38961
+ ownedTaskIds.set(task.taskId, {
38962
+ attemptId: task.attemptId,
38963
+ dispatchId: task.dispatchId,
38964
+ executionTokenRunId: task.executionTokenRunId ?? null,
38965
+ runtimeCoordinatorExecutionId: task.runtimeCoordinatorExecutionId ?? null,
38966
+ taskId: task.taskId
38967
+ });
38968
+ const pendingTask = {
38969
+ stopQueuedLifecycle: null,
38970
+ task
38971
+ };
38972
+ pendingTasks.push(pendingTask);
38973
+ const snapshot = buildSnapshot(task.profileId);
38974
+ if (task.onQueued) try {
38975
+ const queuePosition = pendingTasks.indexOf(pendingTask) + 1;
38976
+ const stopQueuedLifecycle = task.onQueued({
38977
+ adapterId: task.adapterId,
38978
+ attemptId: task.attemptId,
38979
+ controllerKey: task.controllerKey,
38980
+ dispatchId: task.dispatchId,
38981
+ localQueue: buildLocalQueueDiagnostics({
38982
+ profileId: task.profileId,
38983
+ queuePosition
38984
+ }),
38985
+ profileId: task.profileId,
38986
+ spaceId: task.spaceId,
38987
+ taskId: task.taskId,
38988
+ targetLabel: task.targetLabel,
38989
+ transportMode: task.transportMode,
38990
+ ...snapshot
38991
+ });
38992
+ pendingTask.stopQueuedLifecycle = typeof stopQueuedLifecycle === "function" ? stopQueuedLifecycle : null;
38993
+ } catch (error) {
38994
+ pendingTasks.pop();
38995
+ releaseTaskOwnership(task);
38996
+ throw error;
38997
+ }
38998
+ pump();
38999
+ return {
39000
+ accepted: true,
39001
+ deduped: false,
39002
+ snapshot
39003
+ };
39004
+ },
39005
+ dropPendingTasks(inputDrop) {
39006
+ const reason = toPendingDropReason(inputDrop?.reason);
39007
+ const shouldDrop = inputDrop?.shouldDrop ?? (() => true);
39008
+ let droppedCount = 0;
39009
+ for (let index = pendingTasks.length - 1; index >= 0; index -= 1) {
39010
+ const pendingTask = pendingTasks[index];
39011
+ if (!(pendingTask && shouldDrop(pendingTask.task))) continue;
39012
+ pendingTasks.splice(index, 1);
39013
+ clearQueuedLifecycle(pendingTask);
39014
+ releaseTaskOwnership(pendingTask.task);
39015
+ droppedCount += 1;
39016
+ input.onTaskDropped?.({
39017
+ adapterId: pendingTask.task.adapterId,
39018
+ attemptId: pendingTask.task.attemptId,
39019
+ controllerKey: pendingTask.task.controllerKey,
39020
+ dispatchId: pendingTask.task.dispatchId,
39021
+ localQueue: buildLocalQueueDiagnostics({
39022
+ profileId: pendingTask.task.profileId,
39023
+ queuePosition: null,
39024
+ status: "queued"
39025
+ }),
39026
+ profileId: pendingTask.task.profileId,
39027
+ reason,
39028
+ spaceId: pendingTask.task.spaceId,
39029
+ taskId: pendingTask.task.taskId,
39030
+ targetLabel: pendingTask.task.targetLabel,
39031
+ transportMode: pendingTask.task.transportMode,
39032
+ ...buildSnapshot(pendingTask.task.profileId)
39033
+ });
39034
+ }
39035
+ notifyDrainWaitersIfIdle();
39036
+ return { droppedCount };
39037
+ },
39038
+ drain() {
39039
+ if (pendingTasks.length === 0 && activeGlobal === 0) return Promise.resolve();
39040
+ return new Promise((resolve) => {
39041
+ drainWaiters.push(resolve);
39042
+ });
39043
+ },
39044
+ getDrainState() {
39045
+ return {
39046
+ activeGlobal,
39047
+ pendingCount: pendingTasks.length
39048
+ };
39049
+ },
39050
+ getSnapshot(profileId) {
39051
+ return buildSnapshot(profileId);
39052
+ }
39053
+ };
39054
+ }
39055
+ function buildAttemptKey(dispatchId, attemptId) {
39056
+ return `${dispatchId}::${attemptId}`;
39057
+ }
39058
+ function toErrorMessage$17(error) {
39059
+ if (error instanceof Error && error.message.trim().length > 0) return error.message;
39060
+ if (typeof error === "string" && error.trim().length > 0) return error;
39061
+ return "unknown error";
39062
+ }
39063
+ function resolveTaskCompletionResult(result) {
39064
+ if (!result || typeof result !== "object") return {
39065
+ errorCode: null,
39066
+ errorMessage: null,
39067
+ result: "success"
39068
+ };
39069
+ const normalizedResult = result.result === "failed" || result.result === "partial_success" || result.result === "success" ? result.result : "success";
39070
+ return {
39071
+ errorCode: toOptionalText(result.errorCode),
39072
+ errorMessage: toOptionalText(result.errorMessage),
39073
+ result: normalizedResult
39074
+ };
39075
+ }
39076
+ function toOptionalText(value) {
39077
+ if (typeof value !== "string") return null;
39078
+ const normalized = value.trim();
39079
+ return normalized.length > 0 ? normalized : null;
39080
+ }
39081
+ function toPendingDropReason(value) {
39082
+ if (typeof value !== "string") return "queue.drop";
39083
+ const normalized = value.trim();
39084
+ return normalized.length > 0 ? normalized : "queue.drop";
39085
+ }
39086
+
39108
39087
  //#endregion
39109
39088
  //#region src/local-runtime/inventory.ts
39110
39089
  async function collectLocalRuntimeInventory(input = {}) {
@@ -40093,7 +40072,7 @@ function enqueueDispatchDeliverFrame(input) {
40093
40072
  phase: "received",
40094
40073
  presenter: input.presenter
40095
40074
  });
40096
- const enqueueResult = input.dispatchBackpressureQueue.enqueue({
40075
+ const enqueueResult = input.localExecutionSlots.request({
40097
40076
  adapterId: queueLogMeta.adapterId,
40098
40077
  attemptId: correlation.attemptId,
40099
40078
  controllerKey: queueLogMeta.controllerKey,
@@ -40157,7 +40136,7 @@ function enqueueDispatchDeliverFrame(input) {
40157
40136
  });
40158
40137
  if (!enqueueResult.accepted) {
40159
40138
  const queueRejectErrorCode = enqueueResult.reason === "task.owner_conflict" ? "runtime.task.local_owner_conflict" : "queue.full";
40160
- const queueRejectMessage = enqueueResult.reason === "task.owner_conflict" ? `${queueRejectErrorCode}: local task owner conflict for task ${correlation.taskId}; activeOwner=${enqueueResult.activeOwner.dispatchId}/${enqueueResult.activeOwner.attemptId}` : `queue.full: dispatch queue is full (queueMax=${String(enqueueResult.snapshot.limits.queueMax)}, pending=${String(enqueueResult.snapshot.queueDepth)})`;
40139
+ const queueRejectMessage = enqueueResult.reason === "task.owner_conflict" ? `${queueRejectErrorCode}: local task owner conflict for task ${correlation.taskId}; activeOwner=${enqueueResult.activeOwner.dispatchId}/${enqueueResult.activeOwner.attemptId}` : `queue.full: local execution slot queue is full (queueMax=${String(enqueueResult.snapshot.limits.queueMax)}, pending=${String(enqueueResult.snapshot.queueDepth)})`;
40161
40140
  const queueRejectPayload = buildFailedTaskResultPayload({
40162
40141
  attemptId: correlation.attemptId,
40163
40142
  controllerRef: correlation.controllerRef,
@@ -40211,11 +40190,10 @@ function enqueueDispatchDeliverFrame(input) {
40211
40190
  });
40212
40191
  emitRunLine({
40213
40192
  presenter: input.presenter,
40214
- code: "daemon.run.dispatch_queue_rejected",
40215
- text: `dispatch queue rejected task ${correlation.taskId} for ${queueLogMeta.targetLabel}: ${enqueueResult.reason}`,
40193
+ code: "daemon.run.local_execution_slot_rejected",
40194
+ text: `local execution slot rejected task ${correlation.taskId} for ${queueLogMeta.targetLabel}: ${enqueueResult.reason}`,
40216
40195
  payload: {
40217
40196
  adapterId: queueLogMeta.adapterId,
40218
- activeForController: enqueueResult.snapshot.activeForController,
40219
40197
  activeForProfile: enqueueResult.snapshot.activeForProfile,
40220
40198
  activeGlobal: enqueueResult.snapshot.activeGlobal,
40221
40199
  controllerKey: queueLogMeta.controllerKey,
@@ -40223,9 +40201,6 @@ function enqueueDispatchDeliverFrame(input) {
40223
40201
  durationMs: null,
40224
40202
  errorCode: queueRejectErrorCode,
40225
40203
  globalConcurrency: enqueueResult.snapshot.limits.globalConcurrency,
40226
- perControllerConcurrency: enqueueResult.snapshot.limits.perControllerConcurrency,
40227
- controllerConcurrencyPolicy: "diagnostic_only",
40228
- perProfileConcurrency: enqueueResult.snapshot.limits.perProfileConcurrency,
40229
40204
  profileId: deliverRequest.profileId,
40230
40205
  queueDepth: enqueueResult.snapshot.queueDepth,
40231
40206
  queueMax: enqueueResult.snapshot.limits.queueMax,
@@ -40254,8 +40229,8 @@ function enqueueDispatchDeliverFrame(input) {
40254
40229
  if (enqueueResult.deduped) {
40255
40230
  emitRunLine({
40256
40231
  presenter: input.presenter,
40257
- code: "daemon.run.dispatch_queue_deduped",
40258
- text: `dispatch queue deduped attempt ${correlation.attemptId} for task ${correlation.taskId}`,
40232
+ code: "daemon.run.local_execution_slot_deduped",
40233
+ text: `local execution slot deduped attempt ${correlation.attemptId} for task ${correlation.taskId}`,
40259
40234
  payload: {
40260
40235
  adapterId: queueLogMeta.adapterId,
40261
40236
  attemptId: correlation.attemptId,
@@ -40270,11 +40245,10 @@ function enqueueDispatchDeliverFrame(input) {
40270
40245
  }
40271
40246
  emitRunLine({
40272
40247
  presenter: input.presenter,
40273
- code: "daemon.run.dispatch_queue_enqueued",
40274
- text: `dispatch queue enqueued task ${correlation.taskId} for ${queueLogMeta.targetLabel}`,
40248
+ code: "daemon.run.local_execution_slot_accepted",
40249
+ text: `local execution slot accepted task ${correlation.taskId} for ${queueLogMeta.targetLabel}`,
40275
40250
  payload: {
40276
40251
  adapterId: queueLogMeta.adapterId,
40277
- activeForController: enqueueResult.snapshot.activeForController,
40278
40252
  activeForProfile: enqueueResult.snapshot.activeForProfile,
40279
40253
  activeGlobal: enqueueResult.snapshot.activeGlobal,
40280
40254
  connectionGeneration: deliverRequest.connectionGeneration,
@@ -40284,9 +40258,6 @@ function enqueueDispatchDeliverFrame(input) {
40284
40258
  durationMs: null,
40285
40259
  errorCode: null,
40286
40260
  globalConcurrency: enqueueResult.snapshot.limits.globalConcurrency,
40287
- perControllerConcurrency: enqueueResult.snapshot.limits.perControllerConcurrency,
40288
- controllerConcurrencyPolicy: "diagnostic_only",
40289
- perProfileConcurrency: enqueueResult.snapshot.limits.perProfileConcurrency,
40290
40261
  profileId: deliverRequest.profileId,
40291
40262
  queueDepth: enqueueResult.snapshot.queueDepth,
40292
40263
  queueMax: enqueueResult.snapshot.limits.queueMax,
@@ -40367,7 +40338,7 @@ function reportInvalidDeliverRequest(input) {
40367
40338
  leaseEpoch: identity.leaseEpoch,
40368
40339
  metadata: {
40369
40340
  ...buildResultDispatchJournalMetadata(resultPayload),
40370
- errorMessage: toErrorMessage$36(error),
40341
+ errorMessage: toErrorMessage$38(error),
40371
40342
  parseIssues: issues
40372
40343
  },
40373
40344
  profileId: identity.targetProfileId,
@@ -40378,10 +40349,10 @@ function reportInvalidDeliverRequest(input) {
40378
40349
  emitRunLine({
40379
40350
  presenter: input.presenter,
40380
40351
  code: "daemon.run.invalid_deliver_result_send_failed",
40381
- text: `failed to send invalid deliver result for dispatch ${identity.dispatchId}: ${toErrorMessage$36(error)}`,
40352
+ text: `failed to send invalid deliver result for dispatch ${identity.dispatchId}: ${toErrorMessage$38(error)}`,
40382
40353
  payload: {
40383
40354
  dispatchId: identity.dispatchId,
40384
- errorMessage: toErrorMessage$36(error),
40355
+ errorMessage: toErrorMessage$38(error),
40385
40356
  result: "failed",
40386
40357
  taskId: identity.taskId
40387
40358
  }
@@ -40440,7 +40411,7 @@ async function handleDispatchDeliverFrame(input) {
40440
40411
  const { currentSocketRef } = input;
40441
40412
  emitDispatchLocalPhaseJournalEvent({
40442
40413
  deliverRequest: input.deliverRequest,
40443
- metadata: { source: "dispatch_queue_task" },
40414
+ metadata: { source: "local_execution_slot_task" },
40444
40415
  parsedTask: null,
40445
40416
  phase: "task_started",
40446
40417
  result: "started"
@@ -41575,7 +41546,7 @@ function normalizeResolvedPostMessageAction(input) {
41575
41546
  resolvedSpaceAction: normalizedPostMessageAction.action
41576
41547
  };
41577
41548
  } catch (error) {
41578
- const failureReason = toErrorMessage$36(error);
41549
+ const failureReason = toErrorMessage$38(error);
41579
41550
  emitRunLine({
41580
41551
  presenter: input.presenter,
41581
41552
  code: "daemon.run.post_message_validation_rejected",
@@ -41641,7 +41612,7 @@ function normalizeResolvedThreadAction(input) {
41641
41612
  })
41642
41613
  };
41643
41614
  } catch (error) {
41644
- const failureReason = toErrorMessage$36(error);
41615
+ const failureReason = toErrorMessage$38(error);
41645
41616
  emitRunLine({
41646
41617
  presenter: input.presenter,
41647
41618
  code: "daemon.run.thread_action_validation_rejected",
@@ -41750,7 +41721,7 @@ async function maybeRepairStructuredSpaceAction(input) {
41750
41721
  dispatchId: input.parsedTask.dispatchId,
41751
41722
  ...resolveStructuredActionFailureDiagnostics({
41752
41723
  carrierKind: "none",
41753
- parseError: toErrorMessage$36(error),
41724
+ parseError: toErrorMessage$38(error),
41754
41725
  publicFailureReason: input.failureReason,
41755
41726
  repairMode: "controller_roundtrip",
41756
41727
  runtimeResult: input.runtimeResult
@@ -41766,7 +41737,7 @@ async function maybeRepairStructuredSpaceAction(input) {
41766
41737
  return {
41767
41738
  finalFailureDiagnostics: resolveStructuredActionFailureDiagnostics({
41768
41739
  carrierKind: "none",
41769
- parseError: toErrorMessage$36(error),
41740
+ parseError: toErrorMessage$38(error),
41770
41741
  publicFailureReason: input.failureReason,
41771
41742
  repairMode: "controller_roundtrip",
41772
41743
  runtimeResult: input.runtimeResult
@@ -42495,7 +42466,7 @@ function toTaskExecutionError(error) {
42495
42466
  return {
42496
42467
  errorCode: "dispatch.execution_failed",
42497
42468
  errorType: "internal",
42498
- message: toErrorMessage$36(error)
42469
+ message: toErrorMessage$38(error)
42499
42470
  };
42500
42471
  }
42501
42472
  function normalizeOptionalContextId(contextId) {
@@ -42890,7 +42861,7 @@ function sendResultAndSummarize(input) {
42890
42861
  leaseEpoch: input.leaseEpoch,
42891
42862
  metadata: {
42892
42863
  ...buildResultDispatchJournalMetadata(input.payload),
42893
- errorMessage: toErrorMessage$36(error)
42864
+ errorMessage: toErrorMessage$38(error)
42894
42865
  },
42895
42866
  result: input.payload.status,
42896
42867
  taskId: input.taskId,
@@ -42899,7 +42870,7 @@ function sendResultAndSummarize(input) {
42899
42870
  emitRunLine({
42900
42871
  presenter: input.presenter,
42901
42872
  code: "daemon.run.result_send_failed",
42902
- text: `daemon result send failed for dispatch ${input.dispatchId}: ${toErrorMessage$36(error)}`,
42873
+ text: `daemon result send failed for dispatch ${input.dispatchId}: ${toErrorMessage$38(error)}`,
42903
42874
  payload: {
42904
42875
  attemptId: input.attemptId,
42905
42876
  connectionGeneration: input.connectionGeneration,
@@ -42932,7 +42903,7 @@ function emitDispatchPreviewFrame(input) {
42932
42903
  emitRunLine({
42933
42904
  presenter: input.presenter,
42934
42905
  code: "daemon.run.preview_send_failed",
42935
- text: `daemon preview send failed for dispatch ${input.dispatchId}: ${toErrorMessage$36(error)}`,
42906
+ text: `daemon preview send failed for dispatch ${input.dispatchId}: ${toErrorMessage$38(error)}`,
42936
42907
  payload: {
42937
42908
  attemptId: input.attemptId,
42938
42909
  dispatchId: input.dispatchId,
@@ -42958,7 +42929,7 @@ function emitDispatchPreviewEndFrame(input) {
42958
42929
  emitRunLine({
42959
42930
  presenter: input.presenter,
42960
42931
  code: "daemon.run.preview_end_send_failed",
42961
- text: `daemon preview end send failed for dispatch ${input.dispatchId}: ${toErrorMessage$36(error)}`,
42932
+ text: `daemon preview end send failed for dispatch ${input.dispatchId}: ${toErrorMessage$38(error)}`,
42962
42933
  payload: {
42963
42934
  attemptId: input.attemptId,
42964
42935
  dispatchId: input.dispatchId,
@@ -43001,7 +42972,7 @@ function emitDispatchRuntimeEvidenceTransition(input) {
43001
42972
  emitRunLine({
43002
42973
  presenter: input.presenter,
43003
42974
  code: "daemon.run.runtime_evidence_send_failed",
43004
- text: `daemon runtime evidence ${input.phase} send failed for dispatch ${identity.dispatchId}: ${toErrorMessage$36(error)}`,
42975
+ text: `daemon runtime evidence ${input.phase} send failed for dispatch ${identity.dispatchId}: ${toErrorMessage$38(error)}`,
43005
42976
  payload: {
43006
42977
  attemptId: identity.attemptId,
43007
42978
  dispatchId: identity.dispatchId,
@@ -43068,13 +43039,9 @@ function resolveRuntimeEvidenceResultReasonCode(payload) {
43068
43039
  }
43069
43040
  function toDaemonHubDispatchLocalQueueDiagnostics(input) {
43070
43041
  return {
43071
- activeForController: input.activeForController,
43072
43042
  activeForProfile: input.activeForProfile,
43073
43043
  activeGlobal: input.activeGlobal,
43074
- controllerConcurrencyPolicy: input.controllerConcurrencyPolicy,
43075
43044
  globalConcurrency: input.limits.globalConcurrency,
43076
- perControllerConcurrency: input.limits.perControllerConcurrency,
43077
- perProfileConcurrency: input.limits.perProfileConcurrency,
43078
43045
  queueDepth: input.queueDepth,
43079
43046
  queueMax: input.limits.queueMax,
43080
43047
  queuePosition: input.queuePosition,
@@ -43104,7 +43071,7 @@ function emitDispatchLifecycleTransition(input) {
43104
43071
  dispatchId: input.dispatchId,
43105
43072
  leaseEpoch: input.leaseEpoch,
43106
43073
  metadata: {
43107
- errorMessage: toErrorMessage$36(error),
43074
+ errorMessage: toErrorMessage$38(error),
43108
43075
  localQueue: input.localQueue ?? null,
43109
43076
  phase: input.phase
43110
43077
  },
@@ -43115,7 +43082,7 @@ function emitDispatchLifecycleTransition(input) {
43115
43082
  emitRunLine({
43116
43083
  presenter: input.presenter,
43117
43084
  code: "daemon.run.lifecycle_send_failed",
43118
- text: `daemon lifecycle ${input.phase} send failed for dispatch ${input.dispatchId}: ${toErrorMessage$36(error)}`,
43085
+ text: `daemon lifecycle ${input.phase} send failed for dispatch ${input.dispatchId}: ${toErrorMessage$38(error)}`,
43119
43086
  payload: {
43120
43087
  attemptId: input.attemptId,
43121
43088
  dispatchId: input.dispatchId,
@@ -43350,7 +43317,7 @@ function handleDaemonSocketFrame(input) {
43350
43317
  contextStore: input.contextStore,
43351
43318
  currentSocketRef: input.currentSocketRef,
43352
43319
  daemonSessionId: input.daemonSessionId,
43353
- dispatchBackpressureQueue: input.dispatchBackpressureQueue,
43320
+ localExecutionSlots: input.localExecutionSlots,
43354
43321
  inflightDispatchMetaByTaskId: input.inflightDispatchMetaByTaskId,
43355
43322
  inflightTaskControlRegistry: input.inflightTaskControlRegistry,
43356
43323
  ledgerPaths: input.ledgerPaths,
@@ -43482,24 +43449,20 @@ async function runDaemonSocketSession(input) {
43482
43449
  let forceCatalogSyncReason = null;
43483
43450
  let pendingLocalExecutionEvidenceRefreshReason = null;
43484
43451
  const pendingRouteCatalogSyncRequests = [];
43485
- const dispatchBackpressureQueue = createDispatchBackpressureQueue({
43452
+ const localExecutionSlots = createLocalExecutionSlots({
43486
43453
  limits: input.dispatchLimits,
43487
43454
  onTaskDropped: (event) => {
43488
43455
  emitRunLine({
43489
43456
  presenter: input.presenter,
43490
- code: "daemon.run.dispatch_queue_dropped",
43491
- text: `dispatch queue dropped pending task ${event.taskId} for ${event.targetLabel}: ${event.reason}`,
43457
+ code: "daemon.run.local_execution_slot_dropped",
43458
+ text: `local execution slot dropped pending task ${event.taskId} for ${event.targetLabel}: ${event.reason}`,
43492
43459
  payload: {
43493
43460
  adapterId: event.adapterId,
43494
- activeForController: event.activeForController,
43495
43461
  activeForProfile: event.activeForProfile,
43496
43462
  activeGlobal: event.activeGlobal,
43497
43463
  controllerKey: event.controllerKey,
43498
43464
  dispatchId: event.dispatchId,
43499
43465
  globalConcurrency: event.limits.globalConcurrency,
43500
- perControllerConcurrency: event.limits.perControllerConcurrency,
43501
- controllerConcurrencyPolicy: "diagnostic_only",
43502
- perProfileConcurrency: event.limits.perProfileConcurrency,
43503
43466
  profileId: event.profileId,
43504
43467
  queueDepth: event.queueDepth,
43505
43468
  localQueueStatus: event.localQueue.status,
@@ -43518,11 +43481,10 @@ async function runDaemonSocketSession(input) {
43518
43481
  onTaskStarted: (event) => {
43519
43482
  emitRunLine({
43520
43483
  presenter: input.presenter,
43521
- code: "daemon.run.dispatch_queue_started",
43522
- text: `dispatch queue started task ${event.taskId} for ${event.targetLabel}`,
43484
+ code: "daemon.run.local_execution_slot_reserved",
43485
+ text: `local execution slot reserved task ${event.taskId} for ${event.targetLabel}`,
43523
43486
  payload: {
43524
43487
  adapterId: event.adapterId,
43525
- activeForController: event.activeForController,
43526
43488
  activeForProfile: event.activeForProfile,
43527
43489
  activeGlobal: event.activeGlobal,
43528
43490
  controllerKey: event.controllerKey,
@@ -43530,9 +43492,6 @@ async function runDaemonSocketSession(input) {
43530
43492
  durationMs: null,
43531
43493
  errorCode: null,
43532
43494
  globalConcurrency: event.limits.globalConcurrency,
43533
- perControllerConcurrency: event.limits.perControllerConcurrency,
43534
- controllerConcurrencyPolicy: "diagnostic_only",
43535
- perProfileConcurrency: event.limits.perProfileConcurrency,
43536
43495
  profileId: event.profileId,
43537
43496
  queueDepth: event.queueDepth,
43538
43497
  localQueueStatus: event.localQueue.status,
@@ -43549,16 +43508,15 @@ async function runDaemonSocketSession(input) {
43549
43508
  });
43550
43509
  },
43551
43510
  onTaskCompleted: (event) => {
43552
- let completionText = `dispatch queue failed task ${event.taskId} for ${event.targetLabel}`;
43553
- if (event.result === "success") completionText = `dispatch queue completed task ${event.taskId} for ${event.targetLabel}`;
43554
- else if (event.result === "partial_success") completionText = `dispatch queue partially completed task ${event.taskId} for ${event.targetLabel}`;
43511
+ let completionText = `local execution slot failed task ${event.taskId} for ${event.targetLabel}`;
43512
+ if (event.result === "success") completionText = `local execution slot completed task ${event.taskId} for ${event.targetLabel}`;
43513
+ else if (event.result === "partial_success") completionText = `local execution slot partially completed task ${event.taskId} for ${event.targetLabel}`;
43555
43514
  emitRunLine({
43556
43515
  presenter: input.presenter,
43557
- code: "daemon.run.dispatch_queue_completed",
43516
+ code: "daemon.run.local_execution_slot_completed",
43558
43517
  text: completionText,
43559
43518
  payload: {
43560
43519
  adapterId: event.adapterId,
43561
- activeForController: event.activeForController,
43562
43520
  activeForProfile: event.activeForProfile,
43563
43521
  activeGlobal: event.activeGlobal,
43564
43522
  controllerKey: event.controllerKey,
@@ -43567,9 +43525,6 @@ async function runDaemonSocketSession(input) {
43567
43525
  errorCode: event.errorCode,
43568
43526
  ...event.errorMessage ? { errorMessage: event.errorMessage } : {},
43569
43527
  globalConcurrency: event.limits.globalConcurrency,
43570
- perControllerConcurrency: event.limits.perControllerConcurrency,
43571
- controllerConcurrencyPolicy: "diagnostic_only",
43572
- perProfileConcurrency: event.limits.perProfileConcurrency,
43573
43528
  profileId: event.profileId,
43574
43529
  queueDepth: event.queueDepth,
43575
43530
  localQueueStatus: event.localQueue.status,
@@ -43756,7 +43711,7 @@ async function runDaemonSocketSession(input) {
43756
43711
  emitRunLine({
43757
43712
  presenter: input.presenter,
43758
43713
  code: "daemon.run.heartbeat_failed",
43759
- text: `heartbeat failed (${String(consecutiveHeartbeatFailures)}/${String(HEARTBEAT_CONSECUTIVE_FAILURES_BEFORE_CLOSE)}): ${toErrorMessage$36(error)}`
43714
+ text: `heartbeat failed (${String(consecutiveHeartbeatFailures)}/${String(HEARTBEAT_CONSECUTIVE_FAILURES_BEFORE_CLOSE)}): ${toErrorMessage$38(error)}`
43760
43715
  });
43761
43716
  if (shouldCloseSocket) {
43762
43717
  input.socket.close(1011, "heartbeat_failed");
@@ -43789,7 +43744,7 @@ async function runDaemonSocketSession(input) {
43789
43744
  emitRunLine({
43790
43745
  presenter: input.presenter,
43791
43746
  code: "daemon.run.heartbeat_failed",
43792
- text: `heartbeat failed: ${toErrorMessage$36(error)}`
43747
+ text: `heartbeat failed: ${toErrorMessage$38(error)}`
43793
43748
  });
43794
43749
  });
43795
43750
  }, normalizedDelayMs);
@@ -43831,7 +43786,7 @@ async function runDaemonSocketSession(input) {
43831
43786
  emitRunLine({
43832
43787
  presenter: input.presenter,
43833
43788
  code: "daemon.run.catalog_sync_signal_read_failed",
43834
- text: `catalog sync signal read failed: ${toErrorMessage$36(error)}`
43789
+ text: `catalog sync signal read failed: ${toErrorMessage$38(error)}`
43835
43790
  });
43836
43791
  }).finally(() => {
43837
43792
  scheduleCatalogSyncSignalPoll();
@@ -44057,7 +44012,7 @@ async function runDaemonSocketSession(input) {
44057
44012
  emitRunLine({
44058
44013
  presenter: input.presenter,
44059
44014
  code: "daemon.run.runtime_capability_report_sync_failed",
44060
- text: `runtime capability report sync failed: ${toErrorMessage$36(error)}`
44015
+ text: `runtime capability report sync failed: ${toErrorMessage$38(error)}`
44061
44016
  });
44062
44017
  }
44063
44018
  };
@@ -44065,7 +44020,7 @@ async function runDaemonSocketSession(input) {
44065
44020
  emitRunLine({
44066
44021
  presenter: input.presenter,
44067
44022
  code: "daemon.run.socket_error",
44068
- text: `daemon stream socket error: ${toErrorMessage$36(error)}`
44023
+ text: `daemon stream socket error: ${toErrorMessage$38(error)}`
44069
44024
  });
44070
44025
  });
44071
44026
  input.socket.onMessage((raw) => {
@@ -44110,7 +44065,7 @@ async function runDaemonSocketSession(input) {
44110
44065
  contextStore: input.contextStore,
44111
44066
  currentSocketRef,
44112
44067
  daemonSessionId: input.daemonSessionId,
44113
- dispatchBackpressureQueue,
44068
+ localExecutionSlots,
44114
44069
  inflightDispatchMetaByTaskId: input.inflightDispatchMetaByTaskId,
44115
44070
  inflightTaskControlRegistry: input.inflightTaskControlRegistry,
44116
44071
  ledgerPaths: input.ledgerPaths,
@@ -44182,10 +44137,10 @@ async function runDaemonSocketSession(input) {
44182
44137
  input.attachRouteCatalogSyncInvoker?.(null);
44183
44138
  clearHeartbeatTimer();
44184
44139
  clearCatalogSyncSignalTimer();
44185
- if (closeCode === 1e3 && closeReason === "shutdown") await dispatchBackpressureQueue.drain();
44140
+ if (closeCode === 1e3 && closeReason === "shutdown") await localExecutionSlots.drain();
44186
44141
  else {
44187
- const droppedPending = dispatchBackpressureQueue.dropPendingTasks({ reason: "daemon.session.unexpected_close" });
44188
- const drainState = dispatchBackpressureQueue.getDrainState();
44142
+ const droppedPending = localExecutionSlots.dropPendingTasks({ reason: "daemon.session.unexpected_close" });
44143
+ const drainState = localExecutionSlots.getDrainState();
44189
44144
  emitRunLine({
44190
44145
  presenter: input.presenter,
44191
44146
  code: "daemon.run.socket_drain_skipped",
@@ -44720,7 +44675,7 @@ const runDaemonServiceLoop = async (input) => {
44720
44675
  action: reconcileDecision.action,
44721
44676
  backoffMs,
44722
44677
  driftClass: reconcileDecision.driftClass,
44723
- error: toErrorMessage$36(error),
44678
+ error: toErrorMessage$38(error),
44724
44679
  foregroundActive: reconcileDecision.foregroundActive,
44725
44680
  lifecycleLocked: reconcileDecision.lifecycleLocked,
44726
44681
  owner: reconcileDecision.owner,
@@ -44731,7 +44686,7 @@ const runDaemonServiceLoop = async (input) => {
44731
44686
  action: reconcileDecision.action,
44732
44687
  backoffMs,
44733
44688
  driftClass: reconcileDecision.driftClass,
44734
- error: toErrorMessage$36(error),
44689
+ error: toErrorMessage$38(error),
44735
44690
  foregroundActive: reconcileDecision.foregroundActive,
44736
44691
  lifecycleLocked: reconcileDecision.lifecycleLocked,
44737
44692
  owner: reconcileDecision.owner,
@@ -44741,11 +44696,11 @@ const runDaemonServiceLoop = async (input) => {
44741
44696
  emitRunLine({
44742
44697
  presenter: input.presenter,
44743
44698
  code: "daemon.run.reconnect",
44744
- text: `daemon stream reconnect scheduled in ${String(backoffMs)}ms (${toErrorMessage$36(error)})`,
44699
+ text: `daemon stream reconnect scheduled in ${String(backoffMs)}ms (${toErrorMessage$38(error)})`,
44745
44700
  payload: {
44746
44701
  attempt: reconnectAttempt,
44747
44702
  backoffMs,
44748
- error: toErrorMessage$36(error)
44703
+ error: toErrorMessage$38(error)
44749
44704
  }
44750
44705
  });
44751
44706
  await sleep$10(backoffMs);
@@ -45218,16 +45173,16 @@ function isLaunchdBootstrapIosError$1(message) {
45218
45173
  }
45219
45174
  function shouldAttemptLaunchdAutoRepair(input) {
45220
45175
  if (input.controller !== "launchd") return false;
45221
- return isLaunchdBootstrapIosError$1(sanitizeSystemServiceErrorMessage$1(toErrorMessage$14(input.error)));
45176
+ return isLaunchdBootstrapIosError$1(sanitizeSystemServiceErrorMessage$1(toErrorMessage$16(input.error)));
45222
45177
  }
45223
45178
  function buildLaunchdAutoRepairFailureError(input) {
45224
45179
  return new Error([
45225
45180
  "launchd auto-repair retry failed.",
45226
- `initial error: ${toErrorMessage$14(input.initialError)}`,
45227
- `retry error: ${toErrorMessage$14(input.retryError)}`
45181
+ `initial error: ${toErrorMessage$16(input.initialError)}`,
45182
+ `retry error: ${toErrorMessage$16(input.retryError)}`
45228
45183
  ].join(" "));
45229
45184
  }
45230
- function toErrorMessage$14(error) {
45185
+ function toErrorMessage$16(error) {
45231
45186
  if (error instanceof Error) return error.message;
45232
45187
  return String(error);
45233
45188
  }
@@ -45590,7 +45545,7 @@ var DaemonReinstallUnexpectedStartError = class extends Error {
45590
45545
  diagnosticDetail;
45591
45546
  outcome;
45592
45547
  constructor(input) {
45593
- super(toErrorMessage$13(input.cause));
45548
+ super(toErrorMessage$15(input.cause));
45594
45549
  this.name = "DaemonReinstallUnexpectedStartError";
45595
45550
  this.cause = input.cause;
45596
45551
  this.diagnosticDetail = input.diagnosticDetail;
@@ -45608,7 +45563,7 @@ var DaemonReinstallFailureError = class extends Error {
45608
45563
  evidencePath;
45609
45564
  failureStage;
45610
45565
  constructor(input) {
45611
- super(toErrorMessage$13(input.cause));
45566
+ super(toErrorMessage$15(input.cause));
45612
45567
  this.name = "DaemonReinstallFailureError";
45613
45568
  this.backupDataPath = input.backupDataPath;
45614
45569
  this.cause = input.cause;
@@ -46306,7 +46261,7 @@ async function runDaemonReinstall(input, options = {}) {
46306
46261
  if (error instanceof DaemonReinstallFailureError) throw new Error(buildDaemonReinstallFailureMessage({
46307
46262
  action: displayAction,
46308
46263
  backupDataPath: error.backupDataPath,
46309
- errorMessage: toErrorMessage$13(error.cause),
46264
+ errorMessage: toErrorMessage$15(error.cause),
46310
46265
  failureStage: error.failureStage,
46311
46266
  evidencePath: error.evidencePath ?? await captureDaemonServiceEvidenceBestEffort({
46312
46267
  runtime,
@@ -46533,7 +46488,7 @@ async function applyDaemonReinstallTargetDesiredState(input) {
46533
46488
  }
46534
46489
  function buildDaemonReinstallUnexpectedStartSummary(error, action = "repair") {
46535
46490
  const actionLabel = formatDaemonServiceMaintenanceActionLabel(action);
46536
- const detail = sanitizeSystemServiceErrorMessage(toErrorMessage$13(error));
46491
+ const detail = sanitizeSystemServiceErrorMessage(toErrorMessage$15(error));
46537
46492
  if (!detail) return `ATS hit a local start error right after service ${actionLabel}.`;
46538
46493
  return `ATS hit a local start error right after service ${actionLabel}: ${detail}`;
46539
46494
  }
@@ -46749,7 +46704,7 @@ async function stopDaemonForStrictTeardown(input) {
46749
46704
  await input.context.serviceManager.stop().catch((error) => {
46750
46705
  throw createStrictTeardownError({
46751
46706
  reason: input.reason,
46752
- message: `failed to stop system service (${input.context.serviceManager?.controller}): ${toErrorMessage$13(error)}`,
46707
+ message: `failed to stop system service (${input.context.serviceManager?.controller}): ${toErrorMessage$15(error)}`,
46753
46708
  hint: "run `ats service stop --force` and retry",
46754
46709
  stage: "stop-wait"
46755
46710
  });
@@ -46794,7 +46749,7 @@ async function uninstallSystemServiceForStrictTeardown(input) {
46794
46749
  for (const manager of managers) await manager.uninstall().catch((error) => {
46795
46750
  throw createStrictTeardownError({
46796
46751
  reason: input.reason,
46797
- message: `failed to uninstall system service (${manager.controller}): ${toErrorMessage$13(error)}`,
46752
+ message: `failed to uninstall system service (${manager.controller}): ${toErrorMessage$15(error)}`,
46798
46753
  hint: "fix OS service permissions and retry",
46799
46754
  stage: "uninstall-verify"
46800
46755
  });
@@ -46811,7 +46766,7 @@ async function verifySystemServiceRemovedAfterStrictTeardown(input) {
46811
46766
  const finalManagerStatus = await manager.status().catch((error) => {
46812
46767
  throw createStrictTeardownError({
46813
46768
  reason: input.reason,
46814
- message: `failed to verify system service status (${manager.controller}): ${toErrorMessage$13(error)}`,
46769
+ message: `failed to verify system service status (${manager.controller}): ${toErrorMessage$15(error)}`,
46815
46770
  hint: "run `ats service status` and confirm service manager state",
46816
46771
  stage: "uninstall-verify"
46817
46772
  });
@@ -46828,7 +46783,7 @@ async function verifySystemServiceRemovedAfterStrictTeardown(input) {
46828
46783
  const finalManagerStatus = await manager.status().catch((error) => {
46829
46784
  throw createStrictTeardownError({
46830
46785
  reason: input.reason,
46831
- message: `failed to verify system service status (${manager.controller}): ${toErrorMessage$13(error)}`,
46786
+ message: `failed to verify system service status (${manager.controller}): ${toErrorMessage$15(error)}`,
46832
46787
  hint: "run `ats service status` and confirm service manager state",
46833
46788
  stage: "uninstall-verify"
46834
46789
  });
@@ -47660,7 +47615,7 @@ function isLocalControllerSignInRequiredReason(reason) {
47660
47615
  return reason === "sign in required";
47661
47616
  }
47662
47617
  function buildSystemServiceStartupFailureReport(input) {
47663
- const message = sanitizeSystemServiceErrorMessage(toErrorMessage$13(input.error));
47618
+ const message = sanitizeSystemServiceErrorMessage(toErrorMessage$15(input.error));
47664
47619
  const localLogPath = getDaemonSystemServiceLogPath();
47665
47620
  if (isLaunchdBootstrapIosError(message)) {
47666
47621
  const card = buildDaemonStartNeedsAttentionCard({
@@ -48002,7 +47957,7 @@ async function runDirectDaemonServiceLoop(input) {
48002
47957
  };
48003
47958
  } catch (error) {
48004
47959
  return await handleDaemonRunStartFailure({
48005
- fallbackRawLine: toErrorMessage$13(error),
47960
+ fallbackRawLine: toErrorMessage$15(error),
48006
47961
  gatewayUrl: input.gatewayUrl,
48007
47962
  presenter: input.presenter,
48008
47963
  runtime: input.runtime,
@@ -48304,11 +48259,11 @@ async function stopRegisteredDaemonServiceManager(input) {
48304
48259
  run: async () => await input.ownerSnapshot.serviceManager?.stop()
48305
48260
  });
48306
48261
  } catch (error) {
48307
- if (input.mode !== "best_effort") throw new Error(`Failed to stop system service (${input.ownerSnapshot.runtimeStatus.serviceController}): ${toErrorMessage$13(error)}`);
48262
+ if (input.mode !== "best_effort") throw new Error(`Failed to stop system service (${input.ownerSnapshot.runtimeStatus.serviceController}): ${toErrorMessage$15(error)}`);
48308
48263
  return buildDaemonStopWarningResult({
48309
48264
  reason: "stop_failed",
48310
48265
  runtimeStatus: input.ownerSnapshot.runtimeStatus,
48311
- errorMessage: toErrorMessage$13(error)
48266
+ errorMessage: toErrorMessage$15(error)
48312
48267
  });
48313
48268
  }
48314
48269
  if (!await waitForDaemonSystemServiceToStop({
@@ -48339,7 +48294,7 @@ async function stopRegisteredDaemonServiceManager(input) {
48339
48294
  return buildDaemonStopWarningResult({
48340
48295
  reason: "stop_failed",
48341
48296
  runtimeStatus: input.ownerSnapshot.runtimeStatus,
48342
- errorMessage: toErrorMessage$13(error)
48297
+ errorMessage: toErrorMessage$15(error)
48343
48298
  });
48344
48299
  }
48345
48300
  const finalOwnerSnapshot = residualCleanupResult.shouldRefresh ? await readCurrentDaemonOwnerSnapshot() : residualCleanupResult.ownerSnapshot;
@@ -48412,7 +48367,7 @@ async function stopCurrentLaneDaemonProcess(input) {
48412
48367
  pid: daemonPid,
48413
48368
  reason: "stop_failed",
48414
48369
  runtimeStatus: input.runtimeStatus,
48415
- errorMessage: toErrorMessage$13(error)
48370
+ errorMessage: toErrorMessage$15(error)
48416
48371
  };
48417
48372
  }
48418
48373
  }
@@ -48496,7 +48451,7 @@ async function stopTrackedDaemonProcess(input) {
48496
48451
  type: "process_stop.action",
48497
48452
  result: "failed",
48498
48453
  metadata: {
48499
- errorMessage: toErrorMessage$13(error),
48454
+ errorMessage: toErrorMessage$15(error),
48500
48455
  pid: input.pid,
48501
48456
  reason: input.reason,
48502
48457
  signal: input.signal
@@ -49520,13 +49475,13 @@ async function runDaemonServiceDetached(input) {
49520
49475
  if (typeof child.pid === "number" && child.pid > 0) await cleanupDetachedRuntimeStateIfOwnedByPid(child.pid).catch(() => {});
49521
49476
  return await handleDaemonRunStartFailure({
49522
49477
  cursor: startFailureLogCursor,
49523
- fallbackRawLine: selectRelevantDaemonStartFailureLogLine(startupOutput.summary()) ?? toErrorMessage$13(error),
49478
+ fallbackRawLine: selectRelevantDaemonStartFailureLogLine(startupOutput.summary()) ?? toErrorMessage$15(error),
49524
49479
  gatewayUrl: input.gatewayUrl,
49525
49480
  presenter: input.presenter,
49526
49481
  runtime: input.runtime,
49527
49482
  genericErrorPayload: {
49528
49483
  codePrefix: "daemon.run.start_failed",
49529
- error: /* @__PURE__ */ new Error(`Failed to start ATS Service process: ${toErrorMessage$13(error)}`)
49484
+ error: /* @__PURE__ */ new Error(`Failed to start ATS Service process: ${toErrorMessage$15(error)}`)
49530
49485
  }
49531
49486
  });
49532
49487
  } finally {
@@ -49996,7 +49951,7 @@ function describeDaemonRuntimeStatus(status) {
49996
49951
  if (status.status === "not_running") return "Service is not running.";
49997
49952
  return "Service runtime status is unknown.";
49998
49953
  }
49999
- function toErrorMessage$13(error) {
49954
+ function toErrorMessage$15(error) {
50000
49955
  if (error instanceof Error) return error.message;
50001
49956
  return String(error);
50002
49957
  }
@@ -50026,7 +49981,7 @@ async function stopDaemonProcess(pid, signal) {
50026
49981
  process.kill(pid, signal);
50027
49982
  } catch (error) {
50028
49983
  if (isNodeErrorCode(error, "ESRCH")) return true;
50029
- throw new Error(`Failed to send ${signal} to pid ${String(pid)}: ${toErrorMessage$13(error)}`);
49984
+ throw new Error(`Failed to send ${signal} to pid ${String(pid)}: ${toErrorMessage$15(error)}`);
50030
49985
  }
50031
49986
  if (signal === "SIGKILL") return true;
50032
49987
  return await waitForProcessToExit(pid);
@@ -50335,7 +50290,7 @@ async function runDaemonServiceParticipationRefresh(input) {
50335
50290
  summary: "ATS Service was repaired, but it is not running yet. Local Wake work will keep waiting until ATS Service starts. Run `ats service start`."
50336
50291
  });
50337
50292
  return {
50338
- errorMessage: toErrorMessage$36(error),
50293
+ errorMessage: toErrorMessage$38(error),
50339
50294
  status: "needs_attention"
50340
50295
  };
50341
50296
  }
@@ -50642,7 +50597,7 @@ async function runDaemonServiceAutoHeal(input) {
50642
50597
  cooldownUntil: null
50643
50598
  };
50644
50599
  } catch (error) {
50645
- const errorMessage = toErrorMessage$12(error);
50600
+ const errorMessage = toErrorMessage$14(error);
50646
50601
  await recordDaemonServiceRepairFailure({
50647
50602
  actions: safeActions,
50648
50603
  errorMessage
@@ -50749,7 +50704,7 @@ function isPidAlive$1(pid) {
50749
50704
  async function sleep$4(ms) {
50750
50705
  await new Promise((resolve) => setTimeout(resolve, ms));
50751
50706
  }
50752
- function toErrorMessage$12(error) {
50707
+ function toErrorMessage$14(error) {
50753
50708
  if (error instanceof Error && error.message.trim().length > 0) return error.message;
50754
50709
  return String(error);
50755
50710
  }
@@ -57965,7 +57920,7 @@ async function runDoctorProfileCheck(input) {
57965
57920
  }
57966
57921
  atsProfile = {
57967
57922
  ok: false,
57968
- message: `ats-profile failed: ${toErrorMessage$11(error)}`
57923
+ message: `ats-profile failed: ${toErrorMessage$13(error)}`
57969
57924
  };
57970
57925
  }
57971
57926
  emitCheckResult(input.presenter, atsProfile, {
@@ -58352,7 +58307,7 @@ async function runCheck(label, fn) {
58352
58307
  } catch (err) {
58353
58308
  return {
58354
58309
  ok: false,
58355
- message: `${label} failed: ${toErrorMessage$11(err)}`
58310
+ message: `${label} failed: ${toErrorMessage$13(err)}`
58356
58311
  };
58357
58312
  }
58358
58313
  }
@@ -58477,7 +58432,7 @@ async function maybePromptRepairAfterLogin(presenter) {
58477
58432
  function normalizeDoctorHumanText(text) {
58478
58433
  return text.replace(DOCTOR_TEXT_PREFIX_RE, "");
58479
58434
  }
58480
- function toErrorMessage$11(err) {
58435
+ function toErrorMessage$13(err) {
58481
58436
  if (err instanceof Error) return err.message;
58482
58437
  return String(err);
58483
58438
  }
@@ -58872,10 +58827,10 @@ async function resolveAgentProfileRuntimeState(profile, _input = {}) {
58872
58827
  });
58873
58828
  const agentReplyReadiness = currentReplyReadiness.agentReplyReadiness;
58874
58829
  const workspace = buildProfileWorkspacePresentation(currentReplyReadiness.profileWorkspaceRuntimeResolution);
58875
- const readiness = agentReplyReadiness ? mapAgentReplyReadinessToLegacyAutoReply(agentReplyReadiness) : {
58876
- ready: false,
58877
- reason: "reply readiness is not available"
58878
- };
58830
+ const replyState = resolveRouteAwareReplyState({
58831
+ agentReplyReadiness,
58832
+ daemonRouteObservation: currentReplyReadiness.daemonRouteObservation
58833
+ });
58879
58834
  const localAgentId = agentReplyReadiness?.localAgentId ?? null;
58880
58835
  const localAgentDisplayName = localAgentId ? resolveHumanControllerDisplayName({
58881
58836
  controllerKind: "builtin",
@@ -58886,18 +58841,47 @@ async function resolveAgentProfileRuntimeState(profile, _input = {}) {
58886
58841
  daemonRouteObservation: currentReplyReadiness.daemonRouteObservation,
58887
58842
  openClawLocalDiagnostics: resolveOpenClawLocalDiagnosticsValue(currentReplyReadiness.openClawLocalDiagnostics),
58888
58843
  transportMode: agentReplyReadiness?.transportMode ?? RAW_NOT_CONFIGURED,
58889
- autoReplyReady: readiness.ready,
58890
- autoReplyReason: readiness.reason,
58891
- replyReadiness: agentReplyReadiness?.replyReadiness ?? "unknown",
58892
- replyReadinessLabel: agentReplyReadiness ? formatAgentReplyReadinessLabel(agentReplyReadiness) : "unknown (reply readiness is not available)",
58893
- replyReadinessReasonCodes: agentReplyReadiness?.reasonCodes ?? [],
58894
- replyReadinessReasonText: agentReplyReadiness?.reasonText ?? "reply readiness is not available",
58844
+ ...replyState,
58895
58845
  localAgentId,
58896
58846
  localAgentDisplayName,
58897
58847
  localAgentEnabled,
58898
58848
  workspace
58899
58849
  };
58900
58850
  }
58851
+ function resolveRouteAwareReplyState(input) {
58852
+ if (!input.agentReplyReadiness) return {
58853
+ autoReplyReady: false,
58854
+ autoReplyReason: "reply readiness is not available",
58855
+ replyReadiness: "unknown",
58856
+ replyReadinessLabel: "unknown (reply readiness is not available)",
58857
+ replyReadinessReasonCodes: [],
58858
+ replyReadinessReasonText: "reply readiness is not available"
58859
+ };
58860
+ if (input.agentReplyReadiness.replyReadiness === "ready" && input.daemonRouteObservation.status !== "online") {
58861
+ const reasonText = describeRouteObservationReplyBlocker(input.daemonRouteObservation);
58862
+ return {
58863
+ autoReplyReady: false,
58864
+ autoReplyReason: reasonText,
58865
+ replyReadiness: "blocked",
58866
+ replyReadinessLabel: `blocked (${reasonText})`,
58867
+ replyReadinessReasonCodes: [input.daemonRouteObservation.reasonCode],
58868
+ replyReadinessReasonText: reasonText
58869
+ };
58870
+ }
58871
+ const readiness = mapAgentReplyReadinessToLegacyAutoReply(input.agentReplyReadiness);
58872
+ return {
58873
+ autoReplyReady: readiness.ready,
58874
+ autoReplyReason: readiness.reason,
58875
+ replyReadiness: input.agentReplyReadiness.replyReadiness,
58876
+ replyReadinessLabel: formatAgentReplyReadinessLabel(input.agentReplyReadiness),
58877
+ replyReadinessReasonCodes: [...input.agentReplyReadiness.reasonCodes],
58878
+ replyReadinessReasonText: input.agentReplyReadiness.reasonText
58879
+ };
58880
+ }
58881
+ function describeRouteObservationReplyBlocker(observation) {
58882
+ if (observation.status === "offline") return "server cannot reach this device";
58883
+ return "server route is not confirmed";
58884
+ }
58901
58885
  function buildAgentProfileRuntimeRows(runtimeState) {
58902
58886
  if (!runtimeState) return [];
58903
58887
  return [
@@ -60722,7 +60706,7 @@ async function runRepairLocalState(input) {
60722
60706
  command: "repair.local_state"
60723
60707
  });
60724
60708
  const report = await runLocalStateAlignment({ mode: "repair" });
60725
- const daemonService = await runDaemonStartupPreflight({
60709
+ const daemonService = input.includeDaemonService === false ? null : await runDaemonStartupPreflight({
60726
60710
  expectedVersion: resolveCurrentDaemonExpectedVersion(),
60727
60711
  view: runtime.resolvedView
60728
60712
  });
@@ -60765,6 +60749,7 @@ function describeLocalStateRepairOutcome(report) {
60765
60749
  return localStateChanged ? "Automatic local ATS data upgrade and cleanup completed." : "Local ATS data is up to date.";
60766
60750
  }
60767
60751
  function describeDaemonStartupPreflightOutcome(daemonService) {
60752
+ if (daemonService === null) return "";
60768
60753
  const status = daemonService.status;
60769
60754
  switch (status) {
60770
60755
  case "already_aligned": return "ATS Service for this lane is already aligned.";
@@ -60780,7 +60765,7 @@ function describeDaemonStartupPreflightOutcome(daemonService) {
60780
60765
  }
60781
60766
  }
60782
60767
  function joinRepairSummaryClauses(clauses) {
60783
- return clauses.join("\n");
60768
+ return clauses.filter((clause) => clause.length > 0).join("\n");
60784
60769
  }
60785
60770
  function hasAlignmentChanges(report) {
60786
60771
  return report.storageVersionUpdated || report.runtimeConfig.migratedLegacyConfig || report.runtimeConfig.removedLegacyConfig || report.selectedAtsProfile.migratedSessionSelections > 0 || report.selectedAtsProfile.removedLegacyDirectory || report.selectedAtsProfile.removedLegacySelectionFile || report.spaceCache.migratedAccountSpaceFiles > 0 || report.spaceCache.removedLegacyAccountSpaceDirs > 0 || report.spaceCache.migratedLegacyProfileFiles > 0 || report.spaceCache.removedLegacyProfilesDir || report.spaceCache.migratedLegacyViews > 0 || report.spaceCache.backedUpCorruptFiles > 0 || report.cleanup.removedTemporaryFiles > 0;
@@ -61161,7 +61146,7 @@ async function resolvePrepareReadinessApiEvidence(input) {
61161
61146
  } catch (error) {
61162
61147
  console.warn("[ats.prepare_readiness.api_read_failed]", {
61163
61148
  event: "cli.prepare_readiness.api_read_failed",
61164
- error: toErrorMessage$10(error),
61149
+ error: toErrorMessage$12(error),
61165
61150
  profileId: input.profile.atsProfileId
61166
61151
  });
61167
61152
  return unavailableEvidence({
@@ -61202,7 +61187,7 @@ function unavailableEvidence(input) {
61202
61187
  status: "unavailable"
61203
61188
  };
61204
61189
  }
61205
- function toErrorMessage$10(error) {
61190
+ function toErrorMessage$12(error) {
61206
61191
  if (error instanceof Error) {
61207
61192
  const message = error.message.trim();
61208
61193
  return message.length > 0 ? message : "unknown error";
@@ -62172,10 +62157,6 @@ function buildHumanTraceRows(input) {
62172
62157
  value: `${input.trace.dispatch.status} · attempts ${input.trace.dispatch.attemptCount}`
62173
62158
  });
62174
62159
  appendPublicationDiagnosticRows(rows, input.trace);
62175
- rows.push({
62176
- label: "Legacy Claim Diagnostic Evidence",
62177
- value: formatClaimExecutionDiagnosticsLabel(input.claimExecutionDiagnostics)
62178
- });
62179
62160
  if (input.agentExecutionStatus) {
62180
62161
  rows.push({
62181
62162
  label: "Current Local Execution Diagnostics",
@@ -62207,7 +62188,6 @@ function buildHumanTraceRows(input) {
62207
62188
  rows.push(...buildProfileWorkspaceRows(input.currentProfileWorkspace));
62208
62189
  }
62209
62190
  appendRuntimeCoordinatorRows(rows, input.trace);
62210
- appendClaimLeaseRows(rows, input.trace);
62211
62191
  appendDispatchResultRows(rows, input.trace);
62212
62192
  appendResultInboxRows(rows, input.trace);
62213
62193
  appendDaemonDispatchJournalRows(rows, input.daemonDispatchJournal);
@@ -62317,14 +62297,6 @@ async function resolveServiceTraceActorProfile(input) {
62317
62297
  function formatServiceTraceActorLabel(profile) {
62318
62298
  return `${profile.profileName} (${profile.atsProfileId}) · ${profile.profileKind}`;
62319
62299
  }
62320
- function formatClaimExecutionDiagnosticsLabel(diagnostics) {
62321
- if (diagnostics.status === "unavailable") return "unavailable";
62322
- const leaseLabel = diagnostics.claimLease ? `legacyClaimLease=${diagnostics.claimLease.claimLeaseId}` : "legacyClaimLease=missing";
62323
- const runtimeLabel = diagnostics.claimLease?.runtimeId ? `runtime=${diagnostics.claimLease.runtimeId}` : "runtime=missing";
62324
- const capabilityLabel = diagnostics.claimLease?.capabilityRef ? `capability=${diagnostics.claimLease.capabilityRef}` : "capability=missing";
62325
- const resultLabel = diagnostics.result ? `result=${diagnostics.result.publicOutcome}` : "result=missing";
62326
- return `${diagnostics.status} · diagnostic_only · ${leaseLabel} · ${runtimeLabel} · ${capabilityLabel} · ${resultLabel}`;
62327
- }
62328
62300
  function formatCorrelationChain(correlation) {
62329
62301
  return [
62330
62302
  correlation.spaceId ? `space=${correlation.spaceId}` : null,
@@ -62334,7 +62306,7 @@ function formatCorrelationChain(correlation) {
62334
62306
  correlation.dispatchId ? `dispatch=${correlation.dispatchId}` : null,
62335
62307
  correlation.runtimeCoordinatorExecutionId ? `runtimeCoordinatorExecution=${correlation.runtimeCoordinatorExecutionId}` : null,
62336
62308
  correlation.latestAttemptId ? `attempt=${correlation.latestAttemptId}` : null,
62337
- correlation.claimLeaseId ? `legacyClaimLease=${correlation.claimLeaseId}` : null,
62309
+ correlation.claimLeaseId ? `claimLease=${correlation.claimLeaseId}` : null,
62338
62310
  correlation.bindingId ? `binding=${correlation.bindingId}` : null,
62339
62311
  correlation.runtimeId ? `runtime=${correlation.runtimeId}` : null,
62340
62312
  correlation.capabilityRef ? `capability=${correlation.capabilityRef}` : null,
@@ -62351,7 +62323,7 @@ function formatWakeTraceSelector(selector) {
62351
62323
  case "client_message": return `client_message · space=${selector.spaceId} · client=${selector.clientMessageId} · target=${selector.targetProfileId}`;
62352
62324
  case "source_signal": return `source_signal · space=${selector.spaceId} · source=${selector.sourceSignalId} · target=${selector.targetProfileId}`;
62353
62325
  case "dispatch": return `dispatch · space=${selector.spaceId} · dispatch=${selector.dispatchId}`;
62354
- case "claim_lease": return `legacy_claim_lease · diagnostic_only · claimLease=${selector.claimLeaseId}`;
62326
+ case "claim_lease": return `claim_lease · diagnostic · claimLease=${selector.claimLeaseId}`;
62355
62327
  default: return "unknown";
62356
62328
  }
62357
62329
  }
@@ -62405,11 +62377,6 @@ function appendRuntimeCoordinatorRows(rows, trace) {
62405
62377
  label: "Ignored Runtime Events",
62406
62378
  value: ignoredEventSummary
62407
62379
  });
62408
- const legacyFinalClaimSummary = formatRuntimeCoordinatorLegacyFinalClaimSummary(trace.runtimeCoordinatorEvents);
62409
- if (legacyFinalClaimSummary) rows.push({
62410
- label: "Legacy Final Claim",
62411
- value: legacyFinalClaimSummary
62412
- });
62413
62380
  }
62414
62381
  function formatRuntimeCoordinatorHeadLifecycleLabel(headLifecycle) {
62415
62382
  if (headLifecycle.readStatus === "authority_unavailable") return `authority_unavailable · ${headLifecycle.reasonCode}`;
@@ -62443,7 +62410,6 @@ const RUNTIME_COORDINATOR_IGNORED_EVENT_TYPES = new Set([
62443
62410
  "execution_token_superseded",
62444
62411
  "execution_token_terminal_late",
62445
62412
  "execution_token_validation_failed",
62446
- "final_claim_rejected_legacy",
62447
62413
  "owner_conflict_current_token",
62448
62414
  "owner_conflict_missing_token",
62449
62415
  "owner_conflict_stale_token",
@@ -62489,11 +62455,6 @@ function formatRuntimeCoordinatorIgnoredEvent(event) {
62489
62455
  tokenFingerprint ? `fingerprint=${tokenFingerprint}` : null
62490
62456
  ].filter((part) => part !== null).join(" ");
62491
62457
  }
62492
- function formatRuntimeCoordinatorLegacyFinalClaimSummary(events) {
62493
- const latestFinalClaimEvent = events.filter((event) => event.eventType === "final_claim_rejected_legacy").at(-1);
62494
- if (!latestFinalClaimEvent) return null;
62495
- return `rejected · diagnostic_only · ${latestFinalClaimEvent.reasonCode ?? "no_reason"}`;
62496
- }
62497
62458
  function inferTokenStatusFromRuntimeCoordinatorEvent(eventType) {
62498
62459
  switch (eventType) {
62499
62460
  case "execution_token_issued": return "active";
@@ -62516,17 +62477,6 @@ function readRuntimeCoordinatorPayloadString(payload, fieldName) {
62516
62477
  const value = payload?.[fieldName];
62517
62478
  return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
62518
62479
  }
62519
- function appendClaimLeaseRows(rows, trace) {
62520
- if (!trace?.claimLease) return;
62521
- rows.push({
62522
- label: "Legacy Claim Lease Evidence",
62523
- value: `${trace.claimLease.claimLeaseId} · ${trace.claimLease.leaseState} · diagnostic_only`
62524
- });
62525
- rows.push({
62526
- label: "Legacy Claim Binding Evidence",
62527
- value: `${trace.claimLease.bindingId} · ${trace.claimLease.runtimeId} · ${trace.claimLease.capabilityRef}`
62528
- });
62529
- }
62530
62480
  function appendDispatchResultRows(rows, trace) {
62531
62481
  if (!trace?.result) return;
62532
62482
  rows.push({
@@ -63510,7 +63460,7 @@ async function assertCurrentLocalRuntimeCanReceiveWake(input) {
63510
63460
  } catch (error) {
63511
63461
  throw new Error(formatCurrentLocalRuntimeReplyReadinessFailure({
63512
63462
  commandLabel: input.commandLabel,
63513
- detail: toErrorMessage$9(error),
63463
+ detail: toErrorMessage$11(error),
63514
63464
  supportCode: "current_reply_readiness.read_failed"
63515
63465
  }));
63516
63466
  }
@@ -63539,9 +63489,9 @@ function resolveCurrentReplyReadinessSupportCode(response) {
63539
63489
  return response.service.reasonCodes[0] ?? response.runtime.reasonCodes[0] ?? `current_reply_readiness.${response.primaryBlocker}`;
63540
63490
  }
63541
63491
  function formatCurrentLocalRuntimeReplyReadinessFailure(input) {
63542
- return `ATS Service started, but ATS Web could not confirm this computer can receive local Wake work yet. Keep ATS Service running, then copy a fresh setup command from ATS Web and run ${input.commandLabel ?? "setup"} again. Support code: ${input.supportCode}.${input.detail ? ` Detail: ${input.detail}` : ""}`;
63492
+ return `ATS Service started, but ATS could not confirm this computer can receive local Wake work yet. Keep ATS Service running, then run ${input.commandLabel ?? "setup"} again from this terminal. Support code: ${input.supportCode}.${input.detail ? ` Detail: ${input.detail}` : ""}`;
63543
63493
  }
63544
- function toErrorMessage$9(error) {
63494
+ function toErrorMessage$11(error) {
63545
63495
  if (error instanceof Error) {
63546
63496
  const message = error.message.trim();
63547
63497
  return message.length > 0 ? message : "unknown error";
@@ -64296,7 +64246,7 @@ async function syncLocalSetupCurrentDeviceTargetFromServiceContract(input) {
64296
64246
  const serviceContract = await readDaemonServiceContract();
64297
64247
  const deviceId = serviceContract?.deviceId ?? null;
64298
64248
  const runtimeLane = serviceContract?.lane ?? null;
64299
- if (!(serviceContract && deviceId && runtimeLane)) throw new Error("ATS could not reconnect this computer because ATS Service has not finished starting. Keep ATS Service running, then copy a fresh setup command from ATS Web and run setup again.");
64249
+ if (!(serviceContract && deviceId && runtimeLane)) throw new Error(`ATS could not reconnect this computer because ATS Service has not finished starting. Keep ATS Service running, then run \`${formatAtsCliCommand("ats setup --view agent")}\` again. You can also run \`${formatAtsCliCommand("ats service status --view agent")}\` to inspect the local service.`);
64300
64250
  const currentDeviceApi = createCurrentDeviceApi(createCliApiClientFoundation(input.gatewayUrl));
64301
64251
  const currentTarget = await currentDeviceApi.setCurrentTarget({
64302
64252
  activationSource: "local_setup",
@@ -64785,7 +64735,13 @@ async function connectSelectedLocalAgentsToAts(input) {
64785
64735
  readiness,
64786
64736
  localAgentIds: input.localAgentIds
64787
64737
  }));
64788
- if (input.syncRouteCatalog) await waitForConfirmedRouteCatalogSync$1({ reason: "prepare_selected_agents_connected" });
64738
+ if (input.syncRouteCatalog) await waitForConfirmedRouteCatalogSync$1({
64739
+ confirmWakeAvailability: async () => await assertCurrentLocalRuntimeCanReceiveWake({
64740
+ gatewayUrl: input.gatewayUrl,
64741
+ runtimeIdentity
64742
+ }),
64743
+ reason: "prepare_selected_agents_connected"
64744
+ });
64789
64745
  return {
64790
64746
  ...runtimeIdentity,
64791
64747
  localReadinessSnapshot: buildPrepareLocalReadinessSnapshot(readiness)
@@ -64822,7 +64778,7 @@ async function readTerminalRuntimeIdentityFromServiceContract() {
64822
64778
  const serviceContract = await readDaemonServiceContract();
64823
64779
  const deviceId = serviceContract?.deviceId;
64824
64780
  const runtimeLane = serviceContract?.lane;
64825
- if (!(deviceId && runtimeLane)) throw new Error("ATS could not verify selected agents because ATS Service did not provide this computer's device identity yet. Keep ATS Service running, then copy a fresh setup command from ATS Web and run setup again.");
64781
+ if (!(deviceId && runtimeLane)) throw new Error(`ATS could not verify selected agents because ATS Service did not provide this computer's device identity yet. Keep ATS Service running, then run \`${formatAtsCliCommand("ats setup --view agent")}\` again. You can also run \`${formatAtsCliCommand("ats service status --view agent")}\` to inspect the local service.`);
64826
64782
  return {
64827
64783
  deviceId,
64828
64784
  runtimeLane
@@ -64835,6 +64791,12 @@ async function waitForConfirmedRouteCatalogSync$1(input) {
64835
64791
  if (latestDelivery.delivery === "control_plane") return latestDelivery;
64836
64792
  if (attempt < ROUTE_CATALOG_SYNC_MAX_ATTEMPTS$1) await sleep$2(ROUTE_CATALOG_SYNC_RETRY_DELAY_MS$1);
64837
64793
  }
64794
+ if (latestDelivery?.delivery === "signal" && input.confirmWakeAvailability) try {
64795
+ await input.confirmWakeAvailability();
64796
+ return latestDelivery;
64797
+ } catch (error) {
64798
+ throw new Error(formatRouteCatalogSyncFailure$1(latestDelivery, error));
64799
+ }
64838
64800
  throw new Error(formatRouteCatalogSyncFailure$1(latestDelivery));
64839
64801
  }
64840
64802
  async function assertSelectedRuntimeReadinessIsReadableByAts(input) {
@@ -64849,10 +64811,12 @@ async function assertSelectedRuntimeReadinessIsReadableByAts(input) {
64849
64811
  const missingCapabilityRef = capabilityRefs.find((capabilityRef) => !runnableCapabilityRefs.has(capabilityRef));
64850
64812
  if (response.status === "ready" && response.runtimeId && !missingCapabilityRef) return;
64851
64813
  const reasonCode = response.summary.reasonCodes[0] ?? response.reason ?? (missingCapabilityRef ? "prepare_readiness.capability_not_ready" : "prepare_readiness.not_ready");
64852
- throw new Error(`ATS could not verify that selected agents are connected to ATS yet. Keep ATS Service running, then copy a fresh setup command from ATS Web and run setup again. Support code: ${reasonCode}.`);
64814
+ throw new Error(`ATS could not verify that selected agents are available for Wake yet. Keep ATS Service running, then run \`${formatAtsCliCommand("ats setup --view agent")}\` again. You can also run \`${formatAtsCliCommand("ats service status --view agent")}\` to inspect the local service. Support code: ${reasonCode}.`);
64853
64815
  }
64854
- function formatRouteCatalogSyncFailure$1(latestDelivery) {
64855
- return `ATS Service started, but ATS could not confirm that selected agents are available for Wake yet. Keep ATS Service running, then copy a fresh setup command from ATS Web and run setup again. Support code: ${latestDelivery?.delivery === "signal" ? `route_catalog_sync.${latestDelivery.fallbackReason}` : "route_catalog_sync.unavailable"}.`;
64816
+ function formatRouteCatalogSyncFailure$1(latestDelivery, error) {
64817
+ const supportCode = latestDelivery?.delivery === "signal" ? `route_catalog_sync.${latestDelivery.fallbackReason}` : "route_catalog_sync.unavailable";
64818
+ const detail = error ? ` Detail: ${toErrorMessage$10(error)}` : "";
64819
+ return `ATS Service started, but ATS could not confirm that selected agents are available for Wake yet. Keep ATS Service running, then run \`${formatAtsCliCommand("ats setup --view agent")}\` again. You can also run \`${formatAtsCliCommand("ats service status --view agent")}\` to inspect the local service. Support code: ${supportCode}.${detail}`;
64856
64820
  }
64857
64821
  function buildPrepareLocalReadinessSnapshot(readiness) {
64858
64822
  return {
@@ -65100,6 +65064,14 @@ function toStatusCodeSlug(title) {
65100
65064
  const slug = title.toLowerCase().replaceAll(/[^a-z0-9]+/g, "_").replaceAll(/^_+|_+$/g, "");
65101
65065
  return slug.length > 0 ? slug : "status";
65102
65066
  }
65067
+ function toErrorMessage$10(error) {
65068
+ if (error instanceof Error) {
65069
+ const message = error.message.trim();
65070
+ return message.length > 0 ? message : "unknown error";
65071
+ }
65072
+ const message = String(error ?? "").trim();
65073
+ return message.length > 0 ? message : "unknown error";
65074
+ }
65103
65075
  var PrepareSessionTerminalReplacedError = class extends Error {
65104
65076
  constructor(message) {
65105
65077
  super(message);
@@ -68126,7 +68098,14 @@ async function runSetup(input) {
68126
68098
  localAgentIds: selectedLocalAgentIds
68127
68099
  });
68128
68100
  assertSelectedLocalRuntimeReportsAccepted(runtimeReports);
68129
- const routeCatalogSync = selectedLocalAgentIds.length > 0 ? await waitForConfirmedRouteCatalogSync({ reason: "setup_to_wake_path_connected" }) : null;
68101
+ const routeCatalogSync = selectedLocalAgentIds.length > 0 ? await waitForConfirmedRouteCatalogSync({
68102
+ confirmWakeAvailability: async () => await assertSetupCompletionCanReceiveWake({
68103
+ gatewayUrl,
68104
+ runtimeIdentity,
68105
+ selectedLocalAgentIds
68106
+ }),
68107
+ reason: "setup_to_wake_path_connected"
68108
+ }) : null;
68130
68109
  await assertSetupCompletionCanReceiveWake({
68131
68110
  gatewayUrl,
68132
68111
  runtimeIdentity,
@@ -68188,10 +68167,18 @@ async function waitForConfirmedRouteCatalogSync(input) {
68188
68167
  if (latestDelivery.delivery === "control_plane") return latestDelivery;
68189
68168
  if (attempt < ROUTE_CATALOG_SYNC_MAX_ATTEMPTS) await sleep(ROUTE_CATALOG_SYNC_RETRY_DELAY_MS);
68190
68169
  }
68170
+ if (latestDelivery?.delivery === "signal" && input.confirmWakeAvailability) try {
68171
+ await input.confirmWakeAvailability();
68172
+ return latestDelivery;
68173
+ } catch (error) {
68174
+ throw new Error(formatRouteCatalogSyncFailure(latestDelivery, error));
68175
+ }
68191
68176
  throw new Error(formatRouteCatalogSyncFailure(latestDelivery));
68192
68177
  }
68193
- function formatRouteCatalogSyncFailure(latestDelivery) {
68194
- return `ATS Service started, but ATS could not confirm that selected agents are available for Wake yet. Keep ATS Service running, then copy a fresh setup command from ATS Web and run setup again. Support code: ${latestDelivery?.delivery === "signal" ? `route_catalog_sync.${latestDelivery.fallbackReason}` : "route_catalog_sync.unavailable"}.`;
68178
+ function formatRouteCatalogSyncFailure(latestDelivery, error) {
68179
+ const supportCode = latestDelivery?.delivery === "signal" ? `route_catalog_sync.${latestDelivery.fallbackReason}` : "route_catalog_sync.unavailable";
68180
+ const detail = error ? ` Detail: ${toErrorMessage$9(error)}` : "";
68181
+ return `ATS Service started, but ATS could not confirm that selected agents are available for Wake yet. Keep ATS Service running, then run \`${formatAtsCliCommand("ats setup --view agent")}\` again. You can also run \`${formatAtsCliCommand("ats service status --view agent")}\` to inspect the local service. Support code: ${supportCode}.${detail}`;
68195
68182
  }
68196
68183
  function emitSetupStatus(runtime, title, lines) {
68197
68184
  if (runtime.resolvedView !== "human") return;
@@ -68221,7 +68208,14 @@ async function emitSetupCompleteForDelegatedPath(input) {
68221
68208
  }
68222
68209
  async function resolveDelegatedSetupCompletionFacts(input) {
68223
68210
  if (input.setupResult.completionFacts) {
68224
- const routeCatalogSync = input.setupResult.completionFacts.runtimeReports.length > 0 ? await waitForConfirmedRouteCatalogSync({ reason: "setup_profile_connection_path_connected" }) : null;
68211
+ const routeCatalogSync = input.setupResult.completionFacts.runtimeReports.length > 0 ? await waitForConfirmedRouteCatalogSync({
68212
+ confirmWakeAvailability: async () => await assertSetupCompletionCanReceiveWake({
68213
+ gatewayUrl: input.gatewayUrl,
68214
+ runtimeIdentity: input.setupResult.completionFacts.runtimeIdentity,
68215
+ selectedLocalAgentIds: input.setupResult.completionFacts.selectedLocalAgentIds
68216
+ }),
68217
+ reason: "setup_profile_connection_path_connected"
68218
+ }) : null;
68225
68219
  await assertSetupCompletionCanReceiveWake({
68226
68220
  gatewayUrl: input.gatewayUrl,
68227
68221
  runtimeIdentity: input.setupResult.completionFacts.runtimeIdentity,
@@ -68273,7 +68267,14 @@ async function resolveDelegatedSetupCompletionFacts(input) {
68273
68267
  localAgentIds: selectedLocalAgentIds
68274
68268
  });
68275
68269
  assertSelectedLocalRuntimeReportsAccepted(runtimeReports);
68276
- const routeCatalogSync = await waitForConfirmedRouteCatalogSync({ reason: "setup_delegated_path_connected" });
68270
+ const routeCatalogSync = await waitForConfirmedRouteCatalogSync({
68271
+ confirmWakeAvailability: async () => await assertSetupCompletionCanReceiveWake({
68272
+ gatewayUrl: input.gatewayUrl,
68273
+ runtimeIdentity,
68274
+ selectedLocalAgentIds
68275
+ }),
68276
+ reason: "setup_delegated_path_connected"
68277
+ });
68277
68278
  await assertSetupCompletionCanReceiveWake({
68278
68279
  gatewayUrl: input.gatewayUrl,
68279
68280
  runtimeIdentity,
@@ -68288,7 +68289,7 @@ async function resolveDelegatedSetupCompletionFacts(input) {
68288
68289
  }
68289
68290
  async function assertSetupCompletionCanReceiveWake(input) {
68290
68291
  if (input.selectedLocalAgentIds.length === 0) return;
68291
- if (!input.runtimeIdentity) throw new Error("ATS Service started, but ATS Web could not confirm this computer can receive local Wake work yet. Keep ATS Service running, then copy a fresh setup command from ATS Web and run setup again. Support code: current_reply_readiness.current_target_missing.");
68292
+ if (!input.runtimeIdentity) throw new Error(`ATS Service started, but ATS could not confirm this computer can receive local Wake work yet. Keep ATS Service running, then run \`${formatAtsCliCommand("ats setup --view agent")}\` again. Support code: current_reply_readiness.current_target_missing.`);
68292
68293
  await assertCurrentLocalRuntimeCanReceiveWake({
68293
68294
  gatewayUrl: input.gatewayUrl,
68294
68295
  runtimeIdentity: input.runtimeIdentity
@@ -68305,7 +68306,7 @@ function hasExplicitLocalAgentSelection(input) {
68305
68306
  return Boolean(normalizeOptionalString$5(input.localAgents) ?? (input.localAgent && input.localAgent.length > 0 ? "local-agent" : null));
68306
68307
  }
68307
68308
  function emitSetupComplete(input) {
68308
- const cliCommandPrefix = resolveUserFacingCliEntryCommand();
68309
+ const cliCommandPrefix = resolveSetupFollowUpCliEntryCommand();
68309
68310
  const nextCommands = [`${cliCommandPrefix} whoami --view agent`, `${cliCommandPrefix} service status --view agent`];
68310
68311
  const payload = {
68311
68312
  lane: resolveAtsEnvPreset(),
@@ -68441,6 +68442,14 @@ function normalizeOptionalString$5(value) {
68441
68442
  const normalized = String(value ?? "").trim();
68442
68443
  return normalized.length > 0 ? normalized : null;
68443
68444
  }
68445
+ function toErrorMessage$9(error) {
68446
+ if (error instanceof Error) {
68447
+ const message = error.message.trim();
68448
+ return message.length > 0 ? message : "unknown error";
68449
+ }
68450
+ const message = String(error ?? "").trim();
68451
+ return message.length > 0 ? message : "unknown error";
68452
+ }
68444
68453
  function sleep(ms) {
68445
68454
  return new Promise((resolve) => {
68446
68455
  setTimeout(resolve, ms);
@@ -97272,13 +97281,16 @@ program.command("repair").description("Repair your local ATS data.").action(asyn
97272
97281
  await runRepairLocalState({ view });
97273
97282
  }
97274
97283
  });
97275
- }).command("local-state").description("Run automatic local ATS data upgrade and cleanup.").action(async () => {
97284
+ }).command("local-state").description("Run automatic local ATS data upgrade and cleanup.").option("--data-only", "Repair local ATS data without checking ATS Service.").action(async (opts) => {
97276
97285
  const view = getGlobalViewOption();
97277
97286
  await runCommandWithEntryChecks({
97278
97287
  routeTokens: ["repair", "local-state"],
97279
97288
  view,
97280
97289
  run: async () => {
97281
- await runRepairLocalState({ view });
97290
+ await runRepairLocalState({
97291
+ includeDaemonService: !opts.dataOnly,
97292
+ view
97293
+ });
97282
97294
  }
97283
97295
  });
97284
97296
  });