agent-transport-system 0.7.95 → 0.7.97

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,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { C as updateConfiguredSkillsConfig, S as updateConfiguredOnboardingConfig, _ as getRuntimeConfigReadHealth, a as resolveBaseUrl, b as setConfiguredSkillsConfig, c as resolveExplicitGatewayUrlOrThrow, d as createDefaultRuntimeAgentControllerSettings, f as getConfiguredDaemonDispatchLimits, g as getConfiguredViewCustomization, h as getConfiguredSkillsConfig, i as normalizeGatewayBaseUrlOrNull, l as DEFAULT_RUNTIME_AGENT_TRANSPORT_MODE, m as getConfiguredOnboardingDisclaimerAcceptedAt, o as resolveBaseUrlOrNull, p as getConfiguredDeviceRuntimeState, r as normalizeGatewayBaseUrl, s as resolveDefaultGatewayBaseUrl, u as alignRuntimeConfigStorage, v as resolveRuntimeSkillsCustomTargetId, w as updateConfiguredStartV1OnboardingState, x as updateConfiguredDeviceRuntimeState, y as setConfiguredBaseUrl } from "./base-url-BLRaPMVx.js";
4
- import { $ as getSpaceThreadResponseSchema, $n as daemonStreamFrameSchema, $t as spaceMembersSnapshotSchema, A as dispatchBriefSchema, An as MAX_VISITED_PROFILE_IDS, Ar as runtimeTransportDispatchRuntimeEvidenceRequestSchema, At as prepareSessionResponseSchema, B as getAgentExecutionReadinessBatchResponseSchema, Bn as atsdControlPlaneRequestSchema, Br as runtimeTransportSubmitTaskResultRequestSchema, Bt as setCurrentLocalAgentEnabledResponseSchema, C as createSpaceThreadResponseSchema, Cn as DISPATCH_ACTIVITY_FAILED_PURPOSE, Ct as patchSpaceContractResponseSchema, D as daemonRouteObservationResponseSchema, Dn as MAX_PROFILE_ID_LENGTH, Dr as runtimeTransportDispatchLifecycleRequestSchema, Dt as postSpaceMembersResponseSchema, E as daemonRouteCatalogCacheSchema, En as LOCAL_COMPONENTS_SCHEMA_VERSION, Er as runtimeTransportDeliveryExecutionIdentitySchema, Et as postSpaceMembersBodySchema, F as forgetCurrentComputerResponseSchema, Fn as SPACE_MENTION_REJECT_NOTICE_PURPOSE, Fr as runtimeTransportLocalAgentControlRefreshCatalogFramePayloadSchema, Ft as refreshCurrentLocalAgentCatalogResponseSchema, G as getModelCatalogResponseSchema, Gn as buildAgentControllerConversationRef, Gt as signalEnvelopeSchema, H as getAgentProfilePrimaryBindingResponseSchema, Hn as atsdTaskResultEnvelopeWriteSchema, Ht as setSpaceAccessModeBodySchema, I as gatewayErrorCodeSchema, In as SPACE_PASSWORD_MIN_LENGTH, Ir as runtimeTransportLocalAgentControlSetEnabledFramePayloadSchema, It as removeSpaceMembersResponseSchema, J as getSpaceContractResponseSchema, Jn as canonicalizeBuiltinAgentControllerRef, Jt as spaceCreatorSchema, K as getPrepareReadinessQuerySchema, Kn as buildAgentControllerRoutingKey, Kt as spaceAccessModeStateSchema, L as gatewayErrorEnvelopeSchema, Ln as SPACE_UPDATES_MAX_LIMIT, Lr as runtimeTransportRegisterSessionRequestSchema, Lt as resolveSpaceDispatchTraceRootCause, M as ensureAgentProfilePrimaryBindingResponseSchema, Mn as RUNTIME_TRANSPORT_SCHEMA_VERSION, Mr as runtimeTransportHeartbeatResponseSchema, Mt as prepareSetupBootstrapWriteSchema, N as entryBriefSchema, Nn as SPACE_MEMBER_JOIN_NOTICE_PURPOSE, Nr as runtimeTransportLocalAgentControlCancelFramePayloadSchema, Nt as projectObservabilityWakeCorrelation, O as daemonRuntimeLeaseSchema, On as MAX_PROFILE_WORKING_DIRECTORY_LENGTH, Or as runtimeTransportDispatchPreviewEndRequestSchema, Ot as postSpaceThreadSignalBodySchema, P as forgetComputerResponseSchema, Pn as SPACE_MEMBER_REMOVE_NOTICE_PURPOSE, Pr as runtimeTransportLocalAgentControlInterruptFramePayloadSchema, Pt as projectSpaceDispatchTraceFinalVisibleOutcome, Q as getSpaceStatusResponseSchema, Qn as daemonServiceLaneSchema, Qt as spaceMemberDirectorySchema, R as getActiveSpaceWakeProgressResponseSchema, Rn as atsRuntimeProfileIdSchema, Rr as runtimeTransportRegisterSessionResponseSchema, Rt as serverErrorFrameSchema, S as createSpaceThreadBodySchema, Sn as DISPATCH_ACTIVITY_DISPATCHING_PURPOSE, St as patchSpaceContractBodySchema, T as currentLocalRuntimeReplyReadinessResponseSchema, Tn as LEGACY_RUNTIME_DISPATCH_POLICY, Tr as runtimeTransportDeliverDispatchRequestSchema, Tt as postNormalMessageResponseSchema, U as getLocalRuntimeExpectedRoutesQuerySchema, Un as atsdTaskResultOpenClawGatewayVisibilityStatusSchema, Ut as setupPlanAgentViewEventSchema, V as getAgentExecutionReadinessResponseSchema, Vn as atsdControlPlaneResponseSchema, Vr as sanitizeSignalTextPreview, Vt as setLocalRuntimeDisplayNameBodySchema, W as getLocalRuntimeExpectedRoutesResponseSchema, Wn as atsdTaskResultPayloadSchema, Wt as setupPlanAgentViewPayloadSchema, X as getSpaceDispatchResultResponseSchema, Xn as conversationExecutionStateSchema, Xt as spaceIdentityDirectorySchema, Y as getSpaceDispatchLookupResponseSchema, Yn as collectCanonicalMentionTextFragments, Yt as spaceDispatchTraceResponseSchema, Z as getSpaceMessageDetailsResponseSchema, Zn as daemonServiceContractSchema, Zt as spaceMemberDirectoryEntrySchema, _ as continuitySchema, _n as AGENT_REPLY_PREVIEW_PURPOSE, _r as providerDispatchRuntimeContextSchema, _t as notifyAgentProfileRouteCatalogChangedBodySchema, a as DAEMON_ROUTE_CATALOG_CACHE_SCHEMA_VERSION, an as submitRuntimeProviderConversationProofsBodySchema, ar as getSpaceMessageAddressingRelationSupportForTargetKind, at as listProfileSpaceHistoryResponseSchema, b as createSpaceDiagnosticReportResponseSchema, bn as CONVERSATION_CONTINUITY_WARNING_PURPOSE, br as resolveSingleSpaceMentionLabels, bt as observabilityWakeTraceSelectorSchema, c as SETUP_PLAN_AGENT_VIEW_SCHEMA_VERSION, cn as submitRuntimeRegistrationResponseSchema, cr as normalizeKnownBuiltinAgentControllerId, ct as listSpaceThreadsResponseSchema, d as agentControllerPermissionModeSchema, dn as upsertProfileSpaceHistoryResponseSchema, dr as normalizeSpacePasswordText, dt as localRuntimeEnrollmentResponseSchema, en as spaceMetaSchema, er as formatCanonicalMentionLiteral, et as getSpaceUpdatesResponseSchema, f as agentExecutionReadinessRouteParamsSchema, fn as writeCurrentDeviceObservedMetadataBodySchema, fr as parseAgentControllerRef$1, ft as localRuntimesQuerySchema, g as cliJsonOutputEnvelopeSchema, gn as AGENT_REPLY_PREVIEW_END_PURPOSE, gr as profileWorkspaceModeSchema, gt as normalizeSpaceCursorPatch, h as catchupResponseSchema, hn as AGENT_REPLYING_PURPOSE, hr as postSpaceWakeStopResponseSchema, ht as normalizeListSignalsReadQuerySemantics, i as DAEMON_ROUTE_CATALOG_CACHE_SCHEMA_NAME, in as submitRuntimeAgentControllerReportsResponseSchema, ir as formatLocalSetupActionLabel, it as leaveSpaceResponseSchema, j as ensureAgentProfilePrimaryBindingBodySchema, jn as MESSAGE_MENTION_TYPE_VALUES, jr as runtimeTransportHeartbeatRequestSchema, jt as prepareSessionStreamServerFrameSchema, k as deleteSpaceResponseSchema, kn as MAX_SIGNAL_REPLY_TO_PREVIEW_LENGTH, kr as runtimeTransportDispatchPreviewRequestSchema, kt as postSpaceThreadSignalResponseSchema, l as SPACE_DISPATCH_TRACE_PROMPT_PREVIEW_MAX_CHARS, ln as updateAgentProfilePrimaryBindingAgentControllerPermissionModeBodySchema, lr as normalizeMessageEnvelope, lt as localAgentCatalogSchema, m as atsRequestContextSchema, mn as AGENT_REPLYING_END_PURPOSE, mr as postSpaceWakeStopBodySchema, mt as modelCatalogSchema, n as resolveBuiltinAgentControllerBrand, nn as structuredGuidePayloadFromInputSchema, nr as formatLocalComponentsSummaryLabel, nt as getSpaceWakeTraceWaterfallResponseSchema, o as PREPARE_SESSION_STREAM_PROTOCOL_VERSION, on as submitRuntimeProviderConversationProofsResponseSchema, or as installedLocalComponentsSnapshotSchema, ot as listSpaceThreadEventsResponseSchema, p as agentProfileBindingRouteParamsSchema, pn as writeCurrentDeviceObservedMetadataResponseSchema, pr as parseOptionalClientMessageId, pt as localRuntimesResponseSchema, q as getPrepareReadinessResponseSchema, qn as canonicalizeAgentControllerRef, qt as spaceBootstrapResponseSchema, r as resolveMappedPublicAgentFailureReason, rn as submitRuntimeAgentControllerReportsBodySchema, rr as formatLocalSetupActionDescription, rt as incomingServerMessageSchema, s as SETUP_PLAN_AGENT_VIEW_CODE, sn as submitRuntimeRegistrationBodySchema, sr as normalizeBuiltinAgentControllerId, st as listSpaceThreadSignalsResponseSchema, t as CODEX_UPGRADE_REQUIRED_REASON, tn as spaceViewerMembershipResponseSchema, tr as formatLocalComponentsSummaryDescription, tt as getSpaceWakeProgressResponseSchema, u as accountSpaceIndexResponseSchema, un as updateAgentProfilePrimaryBindingModelSelectionBodySchema, ur as normalizeOptionalWorkingDirectory, ut as localRuntimeEnrollmentBodySchema, v as createSpaceBodySchema, vn as ATSD_CONTROL_PLANE_SCHEMA_VERSION, vr as resolveBuiltinAgentControllerConversationKind, vt as notifyAgentProfileRouteCatalogChangedResponseSchema, w as currentDeviceTargetResponseSchema, wn as DISPATCH_ACTIVITY_RETRYING_PURPOSE, wr as runtimeCoordinatorExecutionTokenEnvelopeSchema, wt as postNormalMessageBodySchema, x as createSpaceResponseSchema, xn as CURRENT_DAEMON_EXECUTION_CONTRACT_EPOCH, xr as resolveSpaceMentionLabels, xt as patchProfileSpaceHistoryStatusResponseSchema, y as createSpaceDiagnosticReportBodySchema, yn as ATSD_TASK_RESULT_SCHEMA_VERSION, yr as resolveMessageEnvelopeTargetField, yt as notifyAgentProfilesRouteCatalogChangedBodySchema, z as getAgentExecutionReadinessBatchBodySchema, zn as atsSpaceEgressActionSchema, zr as runtimeTransportRouteCatalogChangedFramePayloadSchema, zt as setCurrentLocalAgentEnabledBodySchema } from "./dist-CeaupHgY.js";
3
+ import { C as updateConfiguredSkillsConfig, S as updateConfiguredOnboardingConfig, _ as getRuntimeConfigReadHealth, a as resolveBaseUrl, b as setConfiguredSkillsConfig, c as resolveExplicitGatewayUrlOrThrow, d as createDefaultRuntimeAgentControllerSettings, f as getConfiguredDaemonDispatchLimits, g as getConfiguredViewCustomization, h as getConfiguredSkillsConfig, i as normalizeGatewayBaseUrlOrNull, l as DEFAULT_RUNTIME_AGENT_TRANSPORT_MODE, m as getConfiguredOnboardingDisclaimerAcceptedAt, o as resolveBaseUrlOrNull, p as getConfiguredDeviceRuntimeState, r as normalizeGatewayBaseUrl, s as resolveDefaultGatewayBaseUrl, u as alignRuntimeConfigStorage, v as resolveRuntimeSkillsCustomTargetId, w as updateConfiguredStartV1OnboardingState, x as updateConfiguredDeviceRuntimeState, y as setConfiguredBaseUrl } from "./base-url-SXaImoj4.js";
4
+ import { $ as getSpaceStatusResponseSchema, $n as daemonServiceLaneSchema, $t as spaceMemberDirectorySchema, A as deleteSpaceResponseSchema, An as MAX_SIGNAL_REPLY_TO_PREVIEW_LENGTH, Ar as runtimeTransportDispatchPreviewRequestSchema, At as postSpaceThreadSignalResponseSchema, B as getAgentExecutionReadinessBatchBodySchema, Bn as atsSpaceEgressActionSchema, Br as runtimeTransportRouteCatalogChangedFramePayloadSchema, Bt as setCurrentLocalAgentEnabledBodySchema, C as createSpaceThreadBodySchema, Cn as DISPATCH_ACTIVITY_DISPATCHING_PURPOSE, Ct as patchSpaceContractBodySchema, D as daemonRouteCatalogCacheSchema, Dn as LOCAL_COMPONENTS_SCHEMA_VERSION, Dr as runtimeTransportDeliveryExecutionIdentitySchema, Dt as postSpaceMembersBodySchema, E as currentLocalRuntimeReplyReadinessResponseSchema, En as LEGACY_RUNTIME_DISPATCH_POLICY, Er as runtimeTransportDeliverDispatchRequestSchema, Et as postNormalMessageResponseSchema, F as forgetComputerResponseSchema, Fn as SPACE_MEMBER_REMOVE_NOTICE_PURPOSE, Fr as runtimeTransportLocalAgentControlInterruptFramePayloadSchema, Ft as projectSpaceDispatchTraceFinalVisibleOutcome, G as getLocalRuntimeExpectedRoutesResponseSchema, Gn as atsdTaskResultPayloadSchema, Gt as setupPlanAgentViewPayloadSchema, H as getAgentExecutionReadinessResponseSchema, Hn as atsdControlPlaneResponseSchema, Hr as sanitizeSignalTextPreview, Ht as setLocalRuntimeDisplayNameBodySchema, I as forgetCurrentComputerResponseSchema, In as SPACE_MENTION_REJECT_NOTICE_PURPOSE, Ir as runtimeTransportLocalAgentControlRefreshCatalogFramePayloadSchema, It as refreshCurrentLocalAgentCatalogResponseSchema, J as getPrepareReadinessResponseSchema, Jn as canonicalizeAgentControllerRef, Jt as spaceBootstrapResponseSchema, K as getModelCatalogResponseSchema, Kn as buildAgentControllerConversationRef, Kt as signalEnvelopeSchema, L as gatewayErrorCodeSchema, Ln as SPACE_PASSWORD_MIN_LENGTH, Lr as runtimeTransportLocalAgentControlSetEnabledFramePayloadSchema, Lt as removeSpaceMembersResponseSchema, M as ensureAgentProfilePrimaryBindingBodySchema, Mn as MESSAGE_MENTION_TYPE_VALUES, Mr as runtimeTransportHeartbeatRequestSchema, Mt as prepareSessionStreamServerFrameSchema, N as ensureAgentProfilePrimaryBindingResponseSchema, Nn as RUNTIME_TRANSPORT_SCHEMA_VERSION, Nr as runtimeTransportHeartbeatResponseSchema, Nt as prepareSetupBootstrapWriteSchema, O as daemonRouteObservationResponseSchema, On as MAX_PROFILE_ID_LENGTH, Or as runtimeTransportDispatchLifecycleRequestSchema, Ot as postSpaceMembersResponseSchema, P as entryBriefSchema, Pn as SPACE_MEMBER_JOIN_NOTICE_PURPOSE, Pr as runtimeTransportLocalAgentControlCancelFramePayloadSchema, Pt as projectObservabilityWakeCorrelation, Q as getSpaceMessageDetailsResponseSchema, Qn as daemonServiceContractSchema, Qt as spaceMemberDirectoryEntrySchema, R as gatewayErrorEnvelopeSchema, Rn as SPACE_UPDATES_MAX_LIMIT, Rr as runtimeTransportRegisterSessionRequestSchema, Rt as resolveSpaceDispatchTraceRootCause, S as createSpaceResponseSchema, Sn as CURRENT_DAEMON_EXECUTION_CONTRACT_EPOCH, Sr as resolveSpaceMentionLabels, St as patchProfileSpaceHistoryStatusResponseSchema, T as currentDeviceTargetResponseSchema, Tn as DISPATCH_ACTIVITY_RETRYING_PURPOSE, Tr as runtimeCoordinatorExecutionTokenEnvelopeSchema, Tt as postNormalMessageBodySchema, U as getAgentProfilePrimaryBindingResponseSchema, Un as atsdTaskResultEnvelopeWriteSchema, Ut as setSpaceAccessModeBodySchema, V as getAgentExecutionReadinessBatchResponseSchema, Vn as atsdControlPlaneRequestSchema, Vr as runtimeTransportSubmitTaskResultRequestSchema, Vt as setCurrentLocalAgentEnabledResponseSchema, W as getLocalRuntimeExpectedRoutesQuerySchema, Wn as atsdTaskResultOpenClawGatewayVisibilityStatusSchema, Wt as setupPlanAgentViewEventSchema, X as getSpaceDispatchLookupResponseSchema, Xn as collectCanonicalMentionTextFragments, Xt as spaceDispatchTraceResponseSchema, Y as getSpaceContractResponseSchema, Yn as canonicalizeBuiltinAgentControllerRef, Yt as spaceCreatorSchema, Z as getSpaceDispatchResultResponseSchema, Zn as conversationExecutionStateSchema, Zt as spaceIdentityDirectorySchema, _ as cliJsonOutputEnvelopeSchema, _n as AGENT_REPLY_PREVIEW_END_PURPOSE, _r as profileWorkspaceModeSchema, _t as normalizeSpaceCursorPatch, a as DAEMON_ROUTE_CATALOG_CACHE_SCHEMA_VERSION, an as submitRuntimeAgentControllerReportsResponseSchema, ar as formatLocalSetupActionLabel, at as leaveSpaceResponseSchema, b as createSpaceDiagnosticReportBodySchema, bn as ATSD_TASK_RESULT_SCHEMA_VERSION, br as resolveMessageEnvelopeTargetField, bt as notifyAgentProfilesRouteCatalogChangedBodySchema, c as SETUP_PLAN_AGENT_VIEW_CODE, cn as submitRuntimeRegistrationBodySchema, cr as normalizeBuiltinAgentControllerId, ct as listSpaceThreadSignalsResponseSchema, d as accountSpaceIndexResponseSchema, dn as updateAgentProfilePrimaryBindingModelSelectionBodySchema, dr as normalizeOptionalWorkingDirectory, dt as localRuntimeEnrollmentBodySchema, en as spaceMembersSnapshotSchema, er as daemonStreamFrameSchema, et as getSpaceThreadResponseSchema, f as agentControllerPermissionModeSchema, fn as upsertProfileSpaceHistoryResponseSchema, fr as normalizeSpacePasswordText, ft as localRuntimeEnrollmentResponseSchema, g as catchupResponseSchema, gn as AGENT_REPLYING_PURPOSE, gr as postSpaceWakeStopResponseSchema, gt as normalizeListSignalsReadQuerySemantics, h as atsRequestContextSchema, hn as AGENT_REPLYING_END_PURPOSE, hr as postSpaceWakeStopBodySchema, ht as modelCatalogSchema, i as DAEMON_ROUTE_CATALOG_CACHE_SCHEMA_NAME, in as submitRuntimeAgentControllerReportsBodySchema, ir as formatLocalSetupActionDescription, it as incomingServerMessageSchema, j as dispatchBriefSchema, jn as MAX_VISITED_PROFILE_IDS, jr as runtimeTransportDispatchRuntimeEvidenceRequestSchema, jt as prepareSessionResponseSchema, k as daemonRuntimeLeaseSchema, kn as MAX_PROFILE_WORKING_DIRECTORY_LENGTH, kr as runtimeTransportDispatchPreviewEndRequestSchema, kt as postSpaceThreadSignalBodySchema, l as SETUP_PLAN_AGENT_VIEW_SCHEMA_VERSION, ln as submitRuntimeRegistrationResponseSchema, lr as normalizeKnownBuiltinAgentControllerId, lt as listSpaceThreadsResponseSchema, m as agentProfileBindingRouteParamsSchema, mn as writeCurrentDeviceObservedMetadataResponseSchema, mr as parseOptionalClientMessageId, mt as localRuntimesResponseSchema, n as resolveBuiltinAgentControllerBrand, nn as spaceViewerMembershipResponseSchema, nr as formatLocalComponentsSummaryDescription, nt as getSpaceWakeProgressResponseSchema, o as PREPARE_SESSION_STREAM_PROTOCOL_VERSION, on as submitRuntimeProviderConversationProofsBodySchema, or as getSpaceMessageAddressingRelationSupportForTargetKind, ot as listProfileSpaceHistoryResponseSchema, p as agentExecutionReadinessRouteParamsSchema, pn as writeCurrentDeviceObservedMetadataBodySchema, pr as parseAgentControllerRef$1, pt as localRuntimesQuerySchema, q as getPrepareReadinessQuerySchema, qn as buildAgentControllerRoutingKey, qt as spaceAccessModeStateSchema, r as resolveMappedPublicAgentFailureReason, rn as structuredGuidePayloadFromInputSchema, rr as formatLocalComponentsSummaryLabel, rt as getSpaceWakeTraceWaterfallResponseSchema, s as PREPARE_STEP_DIAGNOSTICS_MAX_CHARS, sn as submitRuntimeProviderConversationProofsResponseSchema, sr as installedLocalComponentsSnapshotSchema, st as listSpaceThreadEventsResponseSchema, t as CODEX_UPGRADE_REQUIRED_REASON, tn as spaceMetaSchema, tr as formatCanonicalMentionLiteral, tt as getSpaceUpdatesResponseSchema, u as SPACE_DISPATCH_TRACE_PROMPT_PREVIEW_MAX_CHARS, un as updateAgentProfilePrimaryBindingAgentControllerPermissionModeBodySchema, ur as normalizeMessageEnvelope, ut as localAgentCatalogSchema, v as continuitySchema, vn as AGENT_REPLY_PREVIEW_PURPOSE, vr as providerDispatchRuntimeContextSchema, vt as notifyAgentProfileRouteCatalogChangedBodySchema, w as createSpaceThreadResponseSchema, wn as DISPATCH_ACTIVITY_FAILED_PURPOSE, wt as patchSpaceContractResponseSchema, x as createSpaceDiagnosticReportResponseSchema, xn as CONVERSATION_CONTINUITY_WARNING_PURPOSE, xr as resolveSingleSpaceMentionLabels, xt as observabilityWakeTraceSelectorSchema, y as createSpaceBodySchema, yn as ATSD_CONTROL_PLANE_SCHEMA_VERSION, yr as resolveBuiltinAgentControllerConversationKind, yt as notifyAgentProfileRouteCatalogChangedResponseSchema, z as getActiveSpaceWakeProgressResponseSchema, zn as atsRuntimeProfileIdSchema, zr as runtimeTransportRegisterSessionResponseSchema, zt as serverErrorFrameSchema } from "./dist-CyQTYZTj.js";
5
5
  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-DP4LBid2.js";
6
6
  import { a as runWithHeldLock, c as LEGACY_ATS_CLI_CONTEXT_ENV_KEY, d as resolveCliContext, f as resolveCliContextId, i as releaseLock, l as listCliContextStates, n as isAtsLockError, o as tryCleanupStaleLock, p as writeCliContextState, r as readLockMeta, s as ATS_CLI_CONTEXT_ENV_KEY, t as acquireLock, u as readCliContextState } from "./lock-CBIWEyt0.js";
7
7
  import { _ as toSpaceWsUrl, a as toSpaceCursorUrl, c as toSpaceDispatchTraceUrl, d as toSpaceMetaUrl, f as toSpacePasswordUrl, g as toSpaceUpdatesUrl, h as toSpaceSignalsUrl, i as toSpaceCreateUrl, l as toSpaceLeaveUrl, m as toSpaceResultUrl, n as toDaemonRouteObservationUrl, o as toSpaceDeleteUrl, p as toSpaceRemoveMembersUrl, r as toSpaceContractUrl, s as toSpaceDispatchLookupUrl, t as normalizeBaseUrl, u as toSpaceMembersUrl } from "./urls-B8ZoQgpS.js";
@@ -12,7 +12,7 @@ import { cancel, confirm, intro, isCancel, multiselect, note, outro, password, s
12
12
  import crypto$1, { createHash, randomBytes, randomUUID } from "node:crypto";
13
13
  import { access, appendFile, chmod, copyFile, cp, lstat, mkdir, mkdtemp, open, readFile, readdir, readlink, realpath, rename, rm, stat, symlink, writeFile } from "node:fs/promises";
14
14
  import path, { basename, delimiter, dirname, extname, isAbsolute, join, normalize, relative, resolve } from "node:path";
15
- import { homedir, hostname, release, tmpdir, userInfo } from "node:os";
15
+ import os, { homedir, hostname, release, tmpdir, userInfo } from "node:os";
16
16
  import pc from "picocolors";
17
17
  import { promisify, stripVTControlCharacters } from "node:util";
18
18
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
@@ -29,14 +29,15 @@ import { createOpencodeClient } from "@opencode-ai/sdk/v2";
29
29
  import wrapAnsi from "wrap-ansi";
30
30
  import { Box, Container, Editor, Key, ProcessTerminal, TUI, Text, getEditorKeybindings, matchesKey } from "@mariozechner/pi-tui";
31
31
  import { ReadStream, WriteStream } from "node:tty";
32
+ import { performance } from "node:perf_hooks";
32
33
 
33
34
  //#region package.json
34
- var version = "0.7.95";
35
+ var version = "0.7.97";
35
36
  var package_default = {
36
37
  $schema: "https://www.schemastore.org/package.json",
37
38
  name: "agent-transport-system",
38
39
  version,
39
- atsReleaseDate: "2026-07-02",
40
+ atsReleaseDate: "2026-07-03",
40
41
  description: "Agent Transport System CLI - https://ats.sh",
41
42
  license: "MIT",
42
43
  type: "module",
@@ -105,7 +106,7 @@ var package_default = {
105
106
  "unplugin-lightningcss": "^0.4.0",
106
107
  "vitest": "~3.2.0"
107
108
  },
108
- ats: { "minRequiredCliVersion": "0.7.91" }
109
+ ats: { "minRequiredCliVersion": "0.7.94" }
109
110
  };
110
111
 
111
112
  //#endregion
@@ -3985,7 +3986,7 @@ function resolveAtsAccountContext(input) {
3985
3986
  };
3986
3987
  }
3987
3988
  async function resolveCurrentAtsAccountContext() {
3988
- const { getAuthSessionMetadata } = await import("./auth-session-D53RZPAF.js");
3989
+ const { getAuthSessionMetadata } = await import("./auth-session-DBnyC4LY.js");
3989
3990
  return resolveAtsAccountContext({ session: await getAuthSessionMetadata().catch(() => null) });
3990
3991
  }
3991
3992
  function resolveHostKey(baseUrl) {
@@ -4436,7 +4437,7 @@ async function setDaemonServiceRuntimeState(state, pathInput = {}) {
4436
4437
  await writeDaemonServiceRuntimeState(state, pathInput);
4437
4438
  }
4438
4439
  async function clearDaemonServiceRuntimeState(pathInput = {}) {
4439
- const { clearDaemonRuntimeLease } = await import("./daemon-runtime-lease-fLtqNcO6.js");
4440
+ const { clearDaemonRuntimeLease } = await import("./daemon-runtime-lease-DzRz8pH5.js");
4440
4441
  await Promise.all([rm(daemonServiceRuntimeStatePath(pathInput), { force: true }), clearDaemonRuntimeLease(pathInput)]);
4441
4442
  }
4442
4443
  async function withDaemonServiceRunLock(callback, meta = {
@@ -7721,14 +7722,52 @@ async function buildAtsProfileIdentityRequestHeadersWithAuth(input) {
7721
7722
  ...input.spacePassword === void 0 ? {} : { spacePassword: input.spacePassword }
7722
7723
  });
7723
7724
  }
7725
+ function resolveAuthTokenAttachment(input) {
7726
+ const compatibility = resolveAuthRequestCompatibility({
7727
+ session: input.session,
7728
+ requestUrl: input.requestUrl
7729
+ });
7730
+ const token = normalizeAccessToken(input.session);
7731
+ if (!token) return {
7732
+ status: "dropped",
7733
+ reason: "empty_token",
7734
+ requestHost: compatibility.requestHost,
7735
+ authHost: compatibility.authHost,
7736
+ expectedGatewayHost: compatibility.expectedGatewayHost
7737
+ };
7738
+ if (!compatibility.compatible) return {
7739
+ status: "dropped",
7740
+ reason: compatibility.reason,
7741
+ requestHost: compatibility.requestHost,
7742
+ authHost: compatibility.authHost,
7743
+ expectedGatewayHost: compatibility.expectedGatewayHost
7744
+ };
7745
+ return {
7746
+ status: "attachable",
7747
+ token,
7748
+ tokenType: normalizeTokenType(input.session.tokenType)
7749
+ };
7750
+ }
7724
7751
  async function attachAuthHeader(headers, input) {
7725
7752
  const session = await resolveAuthSessionForHeaders(input);
7726
7753
  if (session === null) return;
7727
- const token = normalizeAccessToken(session);
7728
- if (!token) return;
7729
- if (!canAttachAuthTokenToRequest(session, input.requestUrl)) return;
7730
- const tokenType = normalizeTokenType(session.tokenType);
7731
- if (token.length > 0) headers[AUTHORIZATION_HEADER] = `${tokenType} ${token}`;
7754
+ const attachment = resolveAuthTokenAttachment({
7755
+ session,
7756
+ requestUrl: input.requestUrl
7757
+ });
7758
+ if (attachment.status === "dropped") {
7759
+ warnDroppedAuthToken(attachment);
7760
+ return;
7761
+ }
7762
+ headers[AUTHORIZATION_HEADER] = `${attachment.tokenType} ${attachment.token}`;
7763
+ }
7764
+ function warnDroppedAuthToken(attachment) {
7765
+ console.warn("[ats.auth.request_token_dropped]", {
7766
+ authHost: attachment.authHost,
7767
+ expectedGatewayHost: attachment.expectedGatewayHost,
7768
+ reason: attachment.reason,
7769
+ requestHost: attachment.requestHost
7770
+ });
7732
7771
  }
7733
7772
  async function resolveAuthSessionForHeaders(input) {
7734
7773
  if (input.authSession !== void 0) return input.authSession;
@@ -26915,6 +26954,12 @@ async function runDaemonServiceManagerAction(input) {
26915
26954
  });
26916
26955
  return result;
26917
26956
  } catch (error) {
26957
+ let errorMetadata = null;
26958
+ try {
26959
+ errorMetadata = input.resolveErrorMetadata?.(error) ?? null;
26960
+ } catch {
26961
+ errorMetadata = null;
26962
+ }
26918
26963
  await emitDaemonLifecycleEvent({
26919
26964
  type: "service_manager.action",
26920
26965
  result: "failed",
@@ -26923,6 +26968,7 @@ async function runDaemonServiceManagerAction(input) {
26923
26968
  controller: input.controller,
26924
26969
  durationMs: Date.now() - startedAtMs,
26925
26970
  errorMessage: toJournalErrorMessage$1(error),
26971
+ ...errorMetadata ?? {},
26926
26972
  ...input.metadata ?? {}
26927
26973
  },
26928
26974
  pathInput: input.pathInput,
@@ -26972,6 +27018,31 @@ async function readLatestDaemonLifecycleEvent(input) {
26972
27018
  }
26973
27019
  return null;
26974
27020
  }
27021
+ async function readRecentDaemonLifecycleEvents(input) {
27022
+ if (input.maxEntries <= 0) return [];
27023
+ const journalPath = daemonLifecycleJournalPath(input.pathInput);
27024
+ let content;
27025
+ try {
27026
+ content = await readFile(journalPath, "utf8");
27027
+ } catch (error) {
27028
+ if (error.code === "ENOENT") return [];
27029
+ throw error;
27030
+ }
27031
+ const lines = content.split("\n").map((line) => line.trim()).filter((line) => line.length > 0);
27032
+ const recent = [];
27033
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
27034
+ const line = lines[index];
27035
+ if (!line) continue;
27036
+ try {
27037
+ const parsed = JSON.parse(line);
27038
+ if (isDaemonLifecycleEvent(parsed)) {
27039
+ recent.push(parsed);
27040
+ if (recent.length >= input.maxEntries) break;
27041
+ }
27042
+ } catch {}
27043
+ }
27044
+ return recent.reverse();
27045
+ }
26975
27046
  function formatDaemonLifecycleOriginSummary(event) {
26976
27047
  const intent = formatDaemonLifecycleIntent(event.intent);
26977
27048
  return `${event.result} ${intent} from ${event.command} at ${event.timestamp} (pid ${event.pid})`;
@@ -26981,9 +27052,43 @@ function formatDaemonLifecycleIntent(intent) {
26981
27052
  return intent.replaceAll("_", " ");
26982
27053
  }
26983
27054
 
27055
+ //#endregion
27056
+ //#region src/local-service/inventory/agent-controller-interface-keeper.ts
27057
+ const LAST_GOOD_REUSE_TTL_MS = 15 * 6e4;
27058
+ const TRANSIENT_FAILURE_REPORT_THRESHOLD = 3;
27059
+ const keeperEntries = /* @__PURE__ */ new Map();
27060
+ function buildAgentControllerInterfaceKeeperKey(input) {
27061
+ return `${input.agentId}\u0000${input.commandPath ?? ""}`;
27062
+ }
27063
+ function readReusableAgentControllerInterfaceSnapshot(input) {
27064
+ const entry = keeperEntries.get(input.keeperKey);
27065
+ if (!entry?.lastGoodSnapshot) return null;
27066
+ if (input.nowMs - entry.lastSuccessAtMs >= LAST_GOOD_REUSE_TTL_MS) return null;
27067
+ return entry.lastGoodSnapshot;
27068
+ }
27069
+ function recordAgentControllerInterfaceProbeSuccess(input) {
27070
+ keeperEntries.set(input.keeperKey, {
27071
+ failStreak: 0,
27072
+ lastGoodSnapshot: input.snapshot,
27073
+ lastSuccessAtMs: input.nowMs
27074
+ });
27075
+ }
27076
+ function recordAgentControllerInterfaceProbeFailure(input) {
27077
+ const entry = keeperEntries.get(input.keeperKey) ?? {
27078
+ failStreak: 0,
27079
+ lastGoodSnapshot: null,
27080
+ lastSuccessAtMs: 0
27081
+ };
27082
+ entry.failStreak += 1;
27083
+ keeperEntries.set(input.keeperKey, entry);
27084
+ if (entry.lastGoodSnapshot && entry.failStreak < TRANSIENT_FAILURE_REPORT_THRESHOLD) return { heldSnapshot: entry.lastGoodSnapshot };
27085
+ return { heldSnapshot: null };
27086
+ }
27087
+
26984
27088
  //#endregion
26985
27089
  //#region src/local-service/inventory/opencode-readiness-probe.ts
26986
27090
  const DEFAULT_PROBE_TIMEOUT_MS = 8e3;
27091
+ const SDK_READ_TIMEOUT_MS = 4e3;
26987
27092
  const PROBE_OUTPUT_LIMIT$1 = 32e3;
26988
27093
  const OPENCODE_MODEL_ID_RE = /^[A-Za-z0-9_.-]+\/[^\s/]+$/u;
26989
27094
  const OPENCODE_PROBE_HOSTNAME = "127.0.0.1";
@@ -27002,13 +27107,15 @@ async function probeOpenCodeReadiness(input) {
27002
27107
  directory: process.cwd(),
27003
27108
  throwOnError: true
27004
27109
  });
27005
- const [providerListResult] = await Promise.all([client.provider.list(), client.app.agents()]);
27110
+ const [providerListResult] = await rejectAfterTimeout(Promise.all([client.provider.list(), client.app.agents()]), SDK_READ_TIMEOUT_MS, `Timed out while reading OpenCode provider status after ${SDK_READ_TIMEOUT_MS}ms.`);
27006
27111
  return resolveOpenCodeReadinessFromProviderList(providerListResult.data);
27007
27112
  } catch (error) {
27113
+ const auth = resolveOpenCodeAuthSnapshotFromProbeError(error);
27008
27114
  return {
27009
- auth: resolveOpenCodeAuthSnapshotFromProbeError(error),
27115
+ auth,
27010
27116
  message: `OpenCode is installed, but ATS could not confirm a connected OpenCode provider: ${toErrorMessage$29(error)}`,
27011
27117
  models: [],
27118
+ probeCompleted: auth.status === "unauthenticated",
27012
27119
  status: "error"
27013
27120
  };
27014
27121
  } finally {
@@ -27108,6 +27215,20 @@ function killOpenCodeProbeProcess(child, signal) {
27108
27215
  child.kill(signal);
27109
27216
  } catch {}
27110
27217
  }
27218
+ function rejectAfterTimeout(promise, timeoutMs, timeoutMessage) {
27219
+ return new Promise((resolve, reject) => {
27220
+ const timer = setTimeout(() => {
27221
+ reject(new Error(timeoutMessage));
27222
+ }, timeoutMs);
27223
+ promise.then((value) => {
27224
+ clearTimeout(timer);
27225
+ resolve(value);
27226
+ }, (error) => {
27227
+ clearTimeout(timer);
27228
+ reject(error);
27229
+ });
27230
+ });
27231
+ }
27111
27232
  function findAvailableLocalPort() {
27112
27233
  return new Promise((resolve, reject) => {
27113
27234
  const server = createServer();
@@ -27144,6 +27265,7 @@ function resolveOpenCodeReadinessFromProviderList(providerList) {
27144
27265
  auth: { status: "unknown" },
27145
27266
  message: "OpenCode is installed, but its provider list was empty.",
27146
27267
  models: [],
27268
+ probeCompleted: true,
27147
27269
  status: "error"
27148
27270
  };
27149
27271
  const connectedProviders = new Set(providerList.connected.map((providerId) => normalizeOptionalText$30(providerId)).filter((providerId) => Boolean(providerId)));
@@ -27151,6 +27273,7 @@ function resolveOpenCodeReadinessFromProviderList(providerList) {
27151
27273
  auth: { status: "unknown" },
27152
27274
  message: "OpenCode is installed, but no connected provider was reported. Open OpenCode and sign in to a provider before ATS can launch it.",
27153
27275
  models: [],
27276
+ probeCompleted: true,
27154
27277
  status: "error"
27155
27278
  };
27156
27279
  const models = parseOpenCodeProviderModels({
@@ -27165,6 +27288,7 @@ function resolveOpenCodeReadinessFromProviderList(providerList) {
27165
27288
  },
27166
27289
  message: "OpenCode is installed and has a connected provider, but it did not report any models ATS can use.",
27167
27290
  models: [],
27291
+ probeCompleted: true,
27168
27292
  status: "error"
27169
27293
  };
27170
27294
  return {
@@ -27175,6 +27299,7 @@ function resolveOpenCodeReadinessFromProviderList(providerList) {
27175
27299
  },
27176
27300
  message: null,
27177
27301
  models,
27302
+ probeCompleted: true,
27178
27303
  status: "ready"
27179
27304
  };
27180
27305
  }
@@ -27248,6 +27373,7 @@ function toErrorMessage$29(error) {
27248
27373
  //#endregion
27249
27374
  //#region src/local-service/inventory/agent-controller-interface.ts
27250
27375
  const PROBE_TIMEOUT_MS = 8e3;
27376
+ const CODEX_AUX_INVENTORY_GRACE_MS = 2500;
27251
27377
  const LATEST_VERSION_TIMEOUT_MS = 4e3;
27252
27378
  const LATEST_VERSION_CACHE_TTL_MS = 3600 * 1e3;
27253
27379
  const PROBE_OUTPUT_LIMIT = 32e3;
@@ -27284,11 +27410,34 @@ async function resolveAgentControllerInterfaceSnapshot(input) {
27284
27410
  };
27285
27411
  if (input.state.launchStatus !== "ready" || !input.state.launchContract) return baseSnapshot;
27286
27412
  const snapshotResolver = CONTROLLER_INTERFACE_SNAPSHOT_RESOLVERS[input.state.agentId];
27287
- if (snapshotResolver) return await snapshotResolver({
27413
+ if (!snapshotResolver) return baseSnapshot;
27414
+ const probePolicy = input.probePolicy ?? "fresh";
27415
+ const keeperKey = buildAgentControllerInterfaceKeeperKey({
27416
+ agentId: input.state.agentId,
27417
+ commandPath: resolveLaunchContractCommandPath(input.state.launchContract)
27418
+ });
27419
+ if (probePolicy === "background") {
27420
+ const reusableSnapshot = readReusableAgentControllerInterfaceSnapshot({
27421
+ keeperKey,
27422
+ nowMs: Date.now()
27423
+ });
27424
+ if (reusableSnapshot) return reusableSnapshot;
27425
+ }
27426
+ const outcome = await snapshotResolver({
27288
27427
  baseSnapshot,
27289
27428
  launchContract: input.state.launchContract
27290
27429
  });
27291
- return baseSnapshot;
27430
+ if (outcome.probeCompleted) {
27431
+ recordAgentControllerInterfaceProbeSuccess({
27432
+ keeperKey,
27433
+ nowMs: Date.now(),
27434
+ snapshot: outcome.snapshot
27435
+ });
27436
+ return outcome.snapshot;
27437
+ }
27438
+ const { heldSnapshot } = recordAgentControllerInterfaceProbeFailure({ keeperKey });
27439
+ if (probePolicy === "background" && heldSnapshot) return heldSnapshot;
27440
+ return outcome.snapshot;
27292
27441
  }
27293
27442
  function resolveLaunchSnapshot(state) {
27294
27443
  return {
@@ -27422,12 +27571,35 @@ async function resolveCodexInterfaceSnapshot(input) {
27422
27571
  if (appServerProbe.ok) {
27423
27572
  const version = appServerProbe.version ?? input.baseSnapshot.version;
27424
27573
  return {
27574
+ probeCompleted: true,
27575
+ snapshot: {
27576
+ ...input.baseSnapshot,
27577
+ auth: appServerProbe.auth,
27578
+ message: appServerProbe.message,
27579
+ models: appServerProbe.models,
27580
+ skills: appServerProbe.skills,
27581
+ status: appServerProbe.status,
27582
+ version,
27583
+ versionAdvisory: await resolveControllerVersionAdvisory({
27584
+ checkedAt: input.baseSnapshot.checkedAt,
27585
+ controllerId: input.baseSnapshot.controllerId,
27586
+ currentVersion: version,
27587
+ launchContract: input.launchContract
27588
+ })
27589
+ }
27590
+ };
27591
+ }
27592
+ const versionProbe = await runLaunchContractCommand({
27593
+ args: ["--version"],
27594
+ launchContract: input.launchContract
27595
+ });
27596
+ const version = versionProbe.ok ? parseCliVersion(versionProbe.stdout) : null;
27597
+ return {
27598
+ probeCompleted: false,
27599
+ snapshot: {
27425
27600
  ...input.baseSnapshot,
27426
- auth: appServerProbe.auth,
27427
27601
  message: appServerProbe.message,
27428
- models: appServerProbe.models,
27429
- skills: appServerProbe.skills,
27430
- status: appServerProbe.status,
27602
+ status: input.baseSnapshot.status === "ready" && appServerProbe.auth.status === "unknown" ? "warning" : input.baseSnapshot.status,
27431
27603
  version,
27432
27604
  versionAdvisory: await resolveControllerVersionAdvisory({
27433
27605
  checkedAt: input.baseSnapshot.checkedAt,
@@ -27435,24 +27607,7 @@ async function resolveCodexInterfaceSnapshot(input) {
27435
27607
  currentVersion: version,
27436
27608
  launchContract: input.launchContract
27437
27609
  })
27438
- };
27439
- }
27440
- const versionProbe = await runLaunchContractCommand({
27441
- args: ["--version"],
27442
- launchContract: input.launchContract
27443
- });
27444
- const version = versionProbe.ok ? parseCliVersion(versionProbe.stdout) : null;
27445
- return {
27446
- ...input.baseSnapshot,
27447
- message: appServerProbe.message,
27448
- status: input.baseSnapshot.status === "ready" && appServerProbe.auth.status === "unknown" ? "warning" : input.baseSnapshot.status,
27449
- version,
27450
- versionAdvisory: await resolveControllerVersionAdvisory({
27451
- checkedAt: input.baseSnapshot.checkedAt,
27452
- controllerId: input.baseSnapshot.controllerId,
27453
- currentVersion: version,
27454
- launchContract: input.launchContract
27455
- })
27610
+ }
27456
27611
  };
27457
27612
  }
27458
27613
  async function resolveClaudeCodeInterfaceSnapshot(input) {
@@ -27467,17 +27622,20 @@ async function resolveClaudeCodeInterfaceSnapshot(input) {
27467
27622
  const auth = resolveClaudeAuthSnapshot(authProbe);
27468
27623
  const version = versionProbe.ok ? parseCliVersion(versionProbe.stdout) : null;
27469
27624
  return {
27470
- ...input.baseSnapshot,
27471
- auth,
27472
- message: auth.status === "unauthenticated" ? "Claude Code is installed, but this computer is not signed in to Claude Code." : input.baseSnapshot.message,
27473
- status: auth.status === "unauthenticated" ? "error" : input.baseSnapshot.status,
27474
- version,
27475
- versionAdvisory: await resolveControllerVersionAdvisory({
27476
- checkedAt: input.baseSnapshot.checkedAt,
27477
- controllerId: input.baseSnapshot.controllerId,
27478
- currentVersion: version,
27479
- launchContract: input.launchContract
27480
- })
27625
+ probeCompleted: authProbe.ok,
27626
+ snapshot: {
27627
+ ...input.baseSnapshot,
27628
+ auth,
27629
+ message: auth.status === "unauthenticated" ? "Claude Code is installed, but this computer is not signed in to Claude Code." : input.baseSnapshot.message,
27630
+ status: auth.status === "unauthenticated" ? "error" : input.baseSnapshot.status,
27631
+ version,
27632
+ versionAdvisory: await resolveControllerVersionAdvisory({
27633
+ checkedAt: input.baseSnapshot.checkedAt,
27634
+ controllerId: input.baseSnapshot.controllerId,
27635
+ currentVersion: version,
27636
+ launchContract: input.launchContract
27637
+ })
27638
+ }
27481
27639
  };
27482
27640
  }
27483
27641
  async function resolveOpenCodeInterfaceSnapshot(input) {
@@ -27490,12 +27648,15 @@ async function resolveOpenCodeInterfaceSnapshot(input) {
27490
27648
  })]);
27491
27649
  const version = versionProbe.ok ? parseCliVersion(versionProbe.stdout) : null;
27492
27650
  return {
27493
- ...input.baseSnapshot,
27494
- auth: readinessProbe.auth,
27495
- message: readinessProbe.message ?? input.baseSnapshot.message,
27496
- models: readinessProbe.models,
27497
- status: readinessProbe.status,
27498
- version
27651
+ probeCompleted: readinessProbe.probeCompleted,
27652
+ snapshot: {
27653
+ ...input.baseSnapshot,
27654
+ auth: readinessProbe.auth,
27655
+ message: readinessProbe.message ?? input.baseSnapshot.message,
27656
+ models: readinessProbe.models,
27657
+ status: readinessProbe.status,
27658
+ version
27659
+ }
27499
27660
  };
27500
27661
  }
27501
27662
  function runLaunchContractCommand(input) {
@@ -27682,6 +27843,9 @@ function probeCodexAppServer(launchContract) {
27682
27843
  });
27683
27844
  });
27684
27845
  runCodexAppServerProbeRequests({
27846
+ clearProbeTimeout: () => {
27847
+ clearTimeout(timeout);
27848
+ },
27685
27849
  finish,
27686
27850
  notify,
27687
27851
  request
@@ -27703,11 +27867,11 @@ async function runCodexAppServerProbeRequests(input) {
27703
27867
  }
27704
27868
  });
27705
27869
  input.notify("initialized", {});
27706
- const [account, skills, models] = await Promise.all([
27707
- input.request("account/read", {}),
27708
- input.request("skills/list", { cwds: [process.cwd()] }).catch(() => null),
27709
- requestAllCodexModels(input.request).catch(() => [])
27710
- ]);
27870
+ const skillsPromise = input.request("skills/list", { cwds: [process.cwd()] }).catch(() => null);
27871
+ const modelsPromise = requestAllCodexModels(input.request).catch(() => []);
27872
+ const account = await input.request("account/read", {});
27873
+ input.clearProbeTimeout();
27874
+ const [skills, models] = await resolveWithinGrace(Promise.all([skillsPromise, modelsPromise]), CODEX_AUX_INVENTORY_GRACE_MS, [null, []]);
27711
27875
  const auth = resolveCodexAuthSnapshot(account);
27712
27876
  input.finish({
27713
27877
  auth,
@@ -27719,6 +27883,20 @@ async function runCodexAppServerProbeRequests(input) {
27719
27883
  version: parseCodexUserAgentVersion(initialized)
27720
27884
  });
27721
27885
  }
27886
+ function resolveWithinGrace(promise, graceMs, fallback) {
27887
+ return new Promise((resolve) => {
27888
+ const timer = setTimeout(() => {
27889
+ resolve(fallback);
27890
+ }, graceMs);
27891
+ promise.then((value) => {
27892
+ clearTimeout(timer);
27893
+ resolve(value);
27894
+ }, () => {
27895
+ clearTimeout(timer);
27896
+ resolve(fallback);
27897
+ });
27898
+ });
27899
+ }
27722
27900
  function consumeJsonRpcMessagesFromChunk(input) {
27723
27901
  let lineBuffer = `${input.lineBuffer}${String(input.chunk)}`;
27724
27902
  while (true) {
@@ -27899,9 +28077,20 @@ const CONTROLLER_AUTH_UNAUTHENTICATED_REASON_CODES = ["provider_account.access_r
27899
28077
  const CONTROLLER_INTERFACE_ERROR_REASON_CODES = ["controller.interface.error"];
27900
28078
  async function collectLocalAgentControllerInventory(input = {}) {
27901
28079
  const builtinStates = (await listAgentTargetStates()).filter((state) => state.targetKind === "builtin");
28080
+ if (input.probePolicy === "background") {
28081
+ const capabilities = [];
28082
+ for (const state of builtinStates) capabilities.push(await resolveLocalAgentControllerInventoryItem({
28083
+ includeControllerInterface: input.includeControllerInterface === true,
28084
+ localAdapterContainer: input.localAdapterContainer,
28085
+ probePolicy: input.probePolicy,
28086
+ state
28087
+ }));
28088
+ return { capabilities };
28089
+ }
27902
28090
  return { capabilities: await Promise.all(builtinStates.map((state) => resolveLocalAgentControllerInventoryItem({
27903
28091
  includeControllerInterface: input.includeControllerInterface === true,
27904
28092
  localAdapterContainer: input.localAdapterContainer,
28093
+ probePolicy: input.probePolicy,
27905
28094
  state
27906
28095
  }))) };
27907
28096
  }
@@ -27912,6 +28101,7 @@ async function resolveLocalAgentControllerInventoryItem(input) {
27912
28101
  ...item,
27913
28102
  agentControllerInterface: await resolveAgentControllerInterfaceSnapshot({
27914
28103
  agentControllerRef: item.agentControllerRef,
28104
+ probePolicy: input.probePolicy,
27915
28105
  state: input.state
27916
28106
  })
27917
28107
  };
@@ -30200,7 +30390,8 @@ function toErrorMessage$25(error) {
30200
30390
  async function syncLocalServiceRuntimeAgentControllerReports(input) {
30201
30391
  const reports = (await collectLocalAgentControllerInventory({
30202
30392
  includeControllerInterface: true,
30203
- localAdapterContainer: input.localAdapterContainer
30393
+ localAdapterContainer: input.localAdapterContainer,
30394
+ probePolicy: input.probePolicy
30204
30395
  })).capabilities.filter((capability) => capability.registered).map((capability) => {
30205
30396
  if (!capability.agentControllerRef) return null;
30206
30397
  const reportDecision = resolveLocalAgentControllerReportDecision(capability, { requireEnabled: true });
@@ -30745,9 +30936,9 @@ function createModelCatalogReadSession(input) {
30745
30936
  async function readModelCatalogOnce(baseUrl) {
30746
30937
  try {
30747
30938
  const [apiClient, baseUrlModule, clientFoundationModule] = await Promise.all([
30748
- import("./dist-Cgdr3L3K.js"),
30749
- import("./base-url-BLRaPMVx.js").then((n) => n.n),
30750
- import("./api-client-foundation-hzrybspj.js")
30939
+ import("./dist-zUuzNkK0.js"),
30940
+ import("./base-url-SXaImoj4.js").then((n) => n.n),
30941
+ import("./api-client-foundation-DFdzzDaR.js")
30751
30942
  ]);
30752
30943
  if (typeof apiClient.createConfigApi !== "function") throw new Error("config api client is unavailable");
30753
30944
  const resolvedBaseUrl = baseUrl ?? await baseUrlModule.resolveBaseUrl();
@@ -37256,6 +37447,14 @@ const LAUNCHD_SERVICE_NOT_FOUND_PATTERNS = [
37256
37447
  /service could not be found/i,
37257
37448
  /could not find domain/i
37258
37449
  ];
37450
+ const LAUNCHD_PRINT_RUNS_PATTERN = /^\s*runs\s*=\s*(\d+)\s*$/m;
37451
+ const LAUNCHD_PRINT_STATE_PATTERN = /^\s*state\s*=\s*(.+?)\s*$/m;
37452
+ const LAUNCHD_PRINT_LAST_EXIT_CODE_PATTERN = /^\s*last exit code\s*=\s*(.+?)\s*$/m;
37453
+ const LAUNCHD_PRINT_PENDED_NONDEMAND_SPAWN_PATTERN = /^\s*pended nondemand spawn\s*=\s*(.+?)\s*$/m;
37454
+ const LAUNCHD_PRINT_PROPERTIES_PATTERN = /^\s*properties\s*=\s*(.+?)\s*$/m;
37455
+ const LAUNCHD_PROPERTIES_KEEPALIVE_PATTERN = /\bkeepalive\b/i;
37456
+ const LAUNCHD_PROPERTIES_RUNATLOAD_PATTERN = /\brunatload\b/i;
37457
+ const INTEGER_TEXT_PATTERN = /^-?\d+$/;
37259
37458
  const SYSTEM_SERVICE_WAIT_MS = 15e3;
37260
37459
  const SYSTEM_SERVICE_POLL_MS = 200;
37261
37460
  const QUOTED_XML_REPLACEMENT = "&quot;";
@@ -37470,6 +37669,41 @@ function parseLaunchdEnabled(output) {
37470
37669
  const value = parseRegexGroup(output, LAUNCHD_ENABLED_PATTERN);
37471
37670
  return value !== null && value.toLowerCase() === "true";
37472
37671
  }
37672
+ function parseLaunchdServiceJobDiagnostics(printOutput) {
37673
+ const runsText = parseRegexGroup(printOutput, LAUNCHD_PRINT_RUNS_PATTERN);
37674
+ const lastExitCodeText = parseRegexGroup(printOutput, LAUNCHD_PRINT_LAST_EXIT_CODE_PATTERN);
37675
+ const propertiesText = parseRegexGroup(printOutput, LAUNCHD_PRINT_PROPERTIES_PATTERN);
37676
+ return {
37677
+ controller: LAUNCHD_CONTROLLER,
37678
+ loaded: true,
37679
+ runs: runsText === null ? null : Number.parseInt(runsText, 10),
37680
+ state: parseRegexGroup(printOutput, LAUNCHD_PRINT_STATE_PATTERN),
37681
+ lastExitCodeText,
37682
+ lastExitCode: lastExitCodeText !== null && INTEGER_TEXT_PATTERN.test(lastExitCodeText) ? Number.parseInt(lastExitCodeText, 10) : null,
37683
+ pendedNondemandSpawn: parseRegexGroup(printOutput, LAUNCHD_PRINT_PENDED_NONDEMAND_SPAWN_PATTERN),
37684
+ keepaliveRunAtLoad: propertiesText !== null && LAUNCHD_PROPERTIES_KEEPALIVE_PATTERN.test(propertiesText) && LAUNCHD_PROPERTIES_RUNATLOAD_PATTERN.test(propertiesText)
37685
+ };
37686
+ }
37687
+ function isDaemonServiceJobNeverSpawned(diagnostics) {
37688
+ return diagnostics.loaded && diagnostics.runs === 0 && diagnostics.keepaliveRunAtLoad;
37689
+ }
37690
+ function readDaemonServiceJobCrashExitCode(diagnostics) {
37691
+ if (!diagnostics.loaded) return null;
37692
+ if (diagnostics.runs === null || diagnostics.runs <= 0) return null;
37693
+ if (diagnostics.lastExitCode === null || diagnostics.lastExitCode === 0) return null;
37694
+ return diagnostics.lastExitCode;
37695
+ }
37696
+ function formatDaemonServiceJobDiagnosticsEvidence(diagnostics) {
37697
+ if (!diagnostics.loaded) return `${diagnostics.controller} job: not loaded`;
37698
+ const parts = [
37699
+ `state=${diagnostics.state ?? "unknown"}`,
37700
+ `runs=${diagnostics.runs ?? "unknown"}`,
37701
+ `last exit code=${diagnostics.lastExitCodeText ?? "unknown"}`,
37702
+ ...diagnostics.pendedNondemandSpawn ? [`pended nondemand spawn=${diagnostics.pendedNondemandSpawn}`] : [],
37703
+ ...diagnostics.keepaliveRunAtLoad ? ["properties=keepalive|runatload"] : []
37704
+ ];
37705
+ return `${diagnostics.controller} job: ${parts.join(", ")}`;
37706
+ }
37473
37707
  function parseLaunchdEnabledFromDisabledServices(output, label) {
37474
37708
  const lines = output.split("\n");
37475
37709
  for (const line of lines) {
@@ -37624,6 +37858,7 @@ function buildSystemdManager(pathInput = {}) {
37624
37858
  commandSummary: installed ? await readSystemServiceCommandSummary(unitPath, "ExecStart=") : null
37625
37859
  };
37626
37860
  },
37861
+ readJobDiagnostics: async () => null,
37627
37862
  waitUntilAbsent: async () => {
37628
37863
  await waitForCondition({
37629
37864
  until: async () => {
@@ -37783,6 +38018,25 @@ function buildLaunchdManager(pathInput = {}) {
37783
38018
  commandSummary: installed ? await readLaunchdProgramArguments(plistPath) : null
37784
38019
  };
37785
38020
  },
38021
+ readJobDiagnostics: async () => {
38022
+ const printResult = await runCommand$3({
38023
+ command: "launchctl",
38024
+ args: ["print", launchdServiceKey],
38025
+ throwOnError: false
38026
+ });
38027
+ if (printResult.exitCode === 0) return parseLaunchdServiceJobDiagnostics(`${printResult.stdout}\n${printResult.stderr}`);
38028
+ if (isLaunchdServiceMissing(printResult)) return {
38029
+ controller: LAUNCHD_CONTROLLER,
38030
+ loaded: false,
38031
+ runs: null,
38032
+ state: null,
38033
+ lastExitCodeText: null,
38034
+ lastExitCode: null,
38035
+ pendedNondemandSpawn: null,
38036
+ keepaliveRunAtLoad: false
38037
+ };
38038
+ return null;
38039
+ },
37786
38040
  waitUntilAbsent: async () => {
37787
38041
  await waitForCondition({
37788
38042
  until: async () => {
@@ -38006,6 +38260,7 @@ function buildWindowsManager(pathInput = {}) {
38006
38260
  commandSummary: await readWindowsRunnerCommandSummary(scriptPath) ?? parseRegexGroup(qc.stdout, WINDOWS_BINARY_PATH_PATTERN) ?? null
38007
38261
  };
38008
38262
  },
38263
+ readJobDiagnostics: async () => null,
38009
38264
  waitUntilAbsent: async () => {
38010
38265
  await waitForCondition({
38011
38266
  until: async () => {
@@ -40647,12 +40902,17 @@ const OUTBOX_SCHEMA = "ats-daemon-dispatch-result-outbox-v1";
40647
40902
  const OUTBOX_RECORD_SCHEMA = "ats-daemon-dispatch-result-outbox-record-v1";
40648
40903
  const RESULT_OUTBOX_FILE_NAME = "dispatch-result-outbox.json";
40649
40904
  const RESULT_OUTBOX_TEMP_FILE_NAME = "dispatch-result-outbox.tmp";
40650
- const BACKOFF_MS = [
40905
+ const SEND_FAILURE_BACKOFF_MS = [
40651
40906
  1e3,
40652
40907
  5e3,
40653
40908
  15e3,
40654
40909
  3e4
40655
40910
  ];
40911
+ const ACK_PENDING_BACKOFF_MS = [
40912
+ 15e3,
40913
+ 3e4,
40914
+ 6e4
40915
+ ];
40656
40916
  function enqueueDispatchResultOutboxRecord(input) {
40657
40917
  const nowMs = Date.now();
40658
40918
  const record = {
@@ -40703,7 +40963,7 @@ function acknowledgeDispatchResultOutboxRecord(input) {
40703
40963
  ...record,
40704
40964
  blockedReasonCode: null,
40705
40965
  lastFailureReason: input.reasonCode ?? "daemon.dispatch.result_retry_later",
40706
- nextAttemptAtMs: record.nextAttemptAtMs > acknowledgedAtMs ? record.nextAttemptAtMs : acknowledgedAtMs + resolveOutboxBackoffMs(attemptCount),
40966
+ nextAttemptAtMs: record.nextAttemptAtMs > acknowledgedAtMs ? record.nextAttemptAtMs : acknowledgedAtMs + resolveAckPendingBackoffMs(attemptCount),
40707
40967
  updatedAtMs: acknowledgedAtMs
40708
40968
  }];
40709
40969
  }
@@ -40780,7 +41040,7 @@ function flushDispatchResultOutbox(input) {
40780
41040
  connectionGeneration: activeConnectionGeneration,
40781
41041
  lastFailureReason: null,
40782
41042
  lastSendAtMs: nowMs,
40783
- nextAttemptAtMs: nowMs + resolveOutboxBackoffMs(record.attemptCount + 1),
41043
+ nextAttemptAtMs: nowMs + resolveAckPendingBackoffMs(record.attemptCount + 1),
40784
41044
  updatedAtMs: nowMs
40785
41045
  };
40786
41046
  } catch (error) {
@@ -40789,7 +41049,7 @@ function flushDispatchResultOutbox(input) {
40789
41049
  ...record,
40790
41050
  attemptCount: record.attemptCount + 1,
40791
41051
  lastFailureReason: toErrorMessage$30(error),
40792
- nextAttemptAtMs: nowMs + resolveOutboxBackoffMs(record.attemptCount + 1),
41052
+ nextAttemptAtMs: nowMs + resolveSendFailureBackoffMs(record.attemptCount + 1),
40793
41053
  updatedAtMs: nowMs
40794
41054
  };
40795
41055
  }
@@ -40800,8 +41060,12 @@ const sanitizeTaskResultPayload = (payload) => {
40800
41060
  const { bootstrapTemplateFacts: _bootstrapTemplateFacts, promptTrace: _promptTrace, ...safePayload } = payload;
40801
41061
  return safePayload;
40802
41062
  };
40803
- const resolveOutboxBackoffMs = (attemptCount) => {
40804
- const backoffMs = BACKOFF_MS[Math.min(BACKOFF_MS.length - 1, Math.max(0, attemptCount - 1))];
41063
+ const resolveAckPendingBackoffMs = (attemptCount) => {
41064
+ const backoffMs = ACK_PENDING_BACKOFF_MS[Math.min(ACK_PENDING_BACKOFF_MS.length - 1, Math.max(0, attemptCount - 1))];
41065
+ return typeof backoffMs === "number" ? backoffMs : 6e4;
41066
+ };
41067
+ const resolveSendFailureBackoffMs = (attemptCount) => {
41068
+ const backoffMs = SEND_FAILURE_BACKOFF_MS[Math.min(SEND_FAILURE_BACKOFF_MS.length - 1, Math.max(0, attemptCount - 1))];
40805
41069
  return typeof backoffMs === "number" ? backoffMs : 3e4;
40806
41070
  };
40807
41071
  const upsertOutboxRecord = (ledgerPaths, record) => {
@@ -46584,6 +46848,7 @@ async function runDaemonSocketSession(input) {
46584
46848
  let nextCatalogSyncAtMs = 0;
46585
46849
  let nextProviderConversationProofSyncAtMs = 0;
46586
46850
  let nextRuntimeAgentControllerReportSyncAtMs = 0;
46851
+ let forceFreshAgentControllerProbes = false;
46587
46852
  let providerConversationProofSyncInFlight = false;
46588
46853
  let runtimeAgentControllerReportSyncInFlight = false;
46589
46854
  let latestCatalogSyncStatus = null;
@@ -46769,6 +47034,7 @@ async function runDaemonSocketSession(input) {
46769
47034
  nextCatalogSyncAtMs = 0;
46770
47035
  nextProviderConversationProofSyncAtMs = 0;
46771
47036
  nextRuntimeAgentControllerReportSyncAtMs = 0;
47037
+ forceFreshAgentControllerProbes = true;
46772
47038
  if (heartbeatInFlight || routeCatalogSyncInFlight) pendingLocalExecutionEvidenceRefreshReason = inputRequest.reason;
46773
47039
  scheduleHeartbeat({
46774
47040
  delayMs: 0,
@@ -46801,6 +47067,7 @@ async function runDaemonSocketSession(input) {
46801
47067
  nextCatalogSyncAtMs = 0;
46802
47068
  nextProviderConversationProofSyncAtMs = 0;
46803
47069
  nextRuntimeAgentControllerReportSyncAtMs = 0;
47070
+ forceFreshAgentControllerProbes = true;
46804
47071
  scheduleHeartbeat({
46805
47072
  delayMs: 0,
46806
47073
  reason: "pending_local_execution_evidence_refresh"
@@ -47244,8 +47511,13 @@ async function runDaemonSocketSession(input) {
47244
47511
  const syncRuntimeAgentControllerReportsIfDue = async () => {
47245
47512
  if (runtimeAgentControllerReportSyncInFlight || Date.now() < nextRuntimeAgentControllerReportSyncAtMs) return;
47246
47513
  runtimeAgentControllerReportSyncInFlight = true;
47514
+ const probeFresh = forceFreshAgentControllerProbes;
47515
+ forceFreshAgentControllerProbes = false;
47247
47516
  try {
47248
- const result = await syncLocalServiceRuntimeAgentControllerReports({ localAdapterContainer: input.localAdapterContainer });
47517
+ const result = await syncLocalServiceRuntimeAgentControllerReports({
47518
+ localAdapterContainer: input.localAdapterContainer,
47519
+ probePolicy: probeFresh ? "fresh" : "background"
47520
+ });
47249
47521
  const retryInMs = result.failedCount > 0 ? RUNTIME_AGENT_CONTROLLER_REPORT_SYNC_RETRY_INTERVAL_MS : RUNTIME_AGENT_CONTROLLER_REPORT_SYNC_INTERVAL_MS;
47250
47522
  nextRuntimeAgentControllerReportSyncAtMs = Date.now() + retryInMs;
47251
47523
  let reportSyncLineText;
@@ -47373,7 +47645,10 @@ async function runDaemonSocketSession(input) {
47373
47645
  const result = await setAgentRegistrationEnabled(controlInput);
47374
47646
  let reportSyncStatus = "failed";
47375
47647
  try {
47376
- reportSyncStatus = (await syncLocalServiceRuntimeAgentControllerReports({ localAdapterContainer: input.localAdapterContainer })).status;
47648
+ reportSyncStatus = (await syncLocalServiceRuntimeAgentControllerReports({
47649
+ localAdapterContainer: input.localAdapterContainer,
47650
+ probePolicy: "fresh"
47651
+ })).status;
47377
47652
  } catch (error) {
47378
47653
  emitRunLine({
47379
47654
  presenter: input.presenter,
@@ -47749,9 +48024,11 @@ function resolveLocalAgentEnabledErrorCode$1(error) {
47749
48024
  //#region src/local-service/carrier/service-runner.ts
47750
48025
  var DaemonStreamAuthenticationRequiredError = class extends Error {
47751
48026
  authState;
48027
+ credentialFailure;
47752
48028
  constructor(input) {
47753
- super(`authentication required before connecting daemon stream (session=${input.authState})`);
48029
+ super(input.credentialFailure ? `authentication required before connecting daemon stream (session=${input.authState}, credentials=${input.credentialFailure.reason}, requestHost=${input.credentialFailure.requestHost ?? "unknown"}, authHost=${input.credentialFailure.authHost ?? "unknown"}, expectedGatewayHost=${input.credentialFailure.expectedGatewayHost ?? "unknown"})` : `authentication required before connecting daemon stream (session=${input.authState})`);
47754
48030
  this.authState = input.authState;
48031
+ this.credentialFailure = input.credentialFailure ?? null;
47755
48032
  this.name = "DaemonStreamAuthenticationRequiredError";
47756
48033
  }
47757
48034
  };
@@ -47791,6 +48068,15 @@ async function resolveDaemonStreamAuthContext(input) {
47791
48068
  authState: resolveAuthenticationRequiredAuthState(authState),
47792
48069
  status: "authentication_required"
47793
48070
  };
48071
+ const attachment = resolveAuthTokenAttachment({
48072
+ session: authState.session,
48073
+ requestUrl: input.requestUrl
48074
+ });
48075
+ if (attachment.status === "dropped") return {
48076
+ authState: "invalid",
48077
+ credentialFailure: attachment,
48078
+ status: "authentication_required"
48079
+ };
47794
48080
  return {
47795
48081
  authState: "valid",
47796
48082
  headers: await buildDaemonStreamRequestHeaders({
@@ -48028,13 +48314,11 @@ const runDaemonServiceLoop = async (input) => {
48028
48314
  requestUrl: wsUrl,
48029
48315
  selectedAtsProfile
48030
48316
  });
48031
- if (authContext.status === "authentication_required") {
48032
- noteAuthenticationRequiredState({
48033
- authState: authContext.authState,
48034
- connectionState
48035
- });
48036
- throw new DaemonStreamAuthenticationRequiredError({ authState: authContext.authState });
48037
- }
48317
+ if (authContext.status === "authentication_required") throwDaemonStreamAuthenticationRequired({
48318
+ authState: authContext.authState,
48319
+ connectionState,
48320
+ credentialFailure: authContext.credentialFailure ?? null
48321
+ });
48038
48322
  const ws = await connectWebSocket(wsUrl, {
48039
48323
  headers: authContext.headers,
48040
48324
  openTimeoutMs: DAEMON_STREAM_CONNECT_TIMEOUT_MS
@@ -48298,7 +48582,10 @@ async function handleLocalControlPlaneSetLocalAgentEnabled(input) {
48298
48582
  });
48299
48583
  let reportSyncStatus = "failed";
48300
48584
  try {
48301
- reportSyncStatus = (await syncLocalServiceRuntimeAgentControllerReports({ localAdapterContainer: input.localAdapterContainer })).status;
48585
+ reportSyncStatus = (await syncLocalServiceRuntimeAgentControllerReports({
48586
+ localAdapterContainer: input.localAdapterContainer,
48587
+ probePolicy: "fresh"
48588
+ })).status;
48302
48589
  } catch (error) {
48303
48590
  emitRunLine({
48304
48591
  presenter: input.presenter,
@@ -48472,10 +48759,28 @@ function noteReconnectFailureState(input) {
48472
48759
  reason: input.failureReason
48473
48760
  });
48474
48761
  }
48762
+ function throwDaemonStreamAuthenticationRequired(input) {
48763
+ if (input.credentialFailure) console.warn("[ats.daemon.stream_credentials_not_attachable]", {
48764
+ authHost: input.credentialFailure.authHost,
48765
+ expectedGatewayHost: input.credentialFailure.expectedGatewayHost,
48766
+ reason: input.credentialFailure.reason,
48767
+ requestHost: input.credentialFailure.requestHost
48768
+ });
48769
+ noteAuthenticationRequiredState({
48770
+ authState: input.authState,
48771
+ connectionState: input.connectionState,
48772
+ credentialFailure: input.credentialFailure
48773
+ });
48774
+ throw new DaemonStreamAuthenticationRequiredError({
48775
+ authState: input.authState,
48776
+ ...input.credentialFailure ? { credentialFailure: input.credentialFailure } : {}
48777
+ });
48778
+ }
48475
48779
  function noteAuthenticationRequiredState(input) {
48780
+ const detail = input.credentialFailure ? `stored credentials are not attachable to the daemon stream (${input.credentialFailure.reason}: requestHost=${input.credentialFailure.requestHost ?? "unknown"}, authHost=${input.credentialFailure.authHost ?? "unknown"}, expectedGatewayHost=${input.credentialFailure.expectedGatewayHost ?? "unknown"})` : `connecting without credentials, session=${input.authState}`;
48476
48781
  input.connectionState.set("authentication_required", {
48477
48782
  authState: input.authState,
48478
- detail: `connecting without credentials, session=${input.authState}`,
48783
+ detail,
48479
48784
  reason: "auth_rejected"
48480
48785
  });
48481
48786
  }
@@ -53072,6 +53377,12 @@ function sliceDaemonStartFailureLogBuffer(input) {
53072
53377
  if (input.rawBuffer.length < input.cursor.size) return input.rawBuffer;
53073
53378
  return input.rawBuffer.subarray(input.cursor.size);
53074
53379
  }
53380
+ async function readDaemonStartFailureLogTailLines(input) {
53381
+ if (input.maxLines <= 0) return [];
53382
+ const rawBuffer = await readFile(getDaemonSystemServiceLogPath()).catch(() => null);
53383
+ if (!rawBuffer || rawBuffer.length === 0) return [];
53384
+ return rawBuffer.toString("utf8").split(LOG_LINE_SPLIT_PATTERN).map((line) => normalizeLogLine(line)).filter((line) => line.length > 0).filter((line) => !LOG_STACK_TRACE_PATTERN.test(line)).filter((line) => !isLogNoise(line)).slice(-input.maxLines);
53385
+ }
53075
53386
  function selectRelevantDaemonStartFailureLogLine(rawLog) {
53076
53387
  const lines = rawLog.split(LOG_LINE_SPLIT_PATTERN).map((line) => normalizeLogLine(line)).filter((line) => line.length > 0).filter((line) => !LOG_STACK_TRACE_PATTERN.test(line));
53077
53388
  for (let index = lines.length - 1; index >= 0; index -= 1) {
@@ -55455,17 +55766,49 @@ var SystemServiceStartupTimeoutError = class extends Error {
55455
55766
  inventory;
55456
55767
  managerStatus;
55457
55768
  runtimeStatus;
55769
+ jobDiagnostics;
55458
55770
  constructor(input) {
55459
55771
  super(buildSystemServiceStartupTimeoutMessage(input));
55460
55772
  this.name = "SystemServiceStartupTimeoutError";
55461
55773
  this.inventory = input.inventory;
55462
55774
  this.managerStatus = input.managerStatus;
55463
55775
  this.runtimeStatus = input.runtimeStatus;
55776
+ this.jobDiagnostics = input.jobDiagnostics ?? null;
55464
55777
  }
55465
55778
  };
55466
55779
  function buildSystemServiceStartupFailureReport(input) {
55467
55780
  const message = sanitizeSystemServiceErrorMessage(toErrorMessage$43(input.error));
55468
55781
  const localLogPath = getDaemonSystemServiceLogPath();
55782
+ const jobDiagnostics = isSystemServiceStartupTimeoutError(input.error) ? input.error.jobDiagnostics ?? null : null;
55783
+ if (jobDiagnostics && isDaemonServiceJobNeverSpawned(jobDiagnostics)) {
55784
+ const summary = "macOS is blocking the ATS Service background item, so ATS Service never launched.";
55785
+ const card = buildDaemonStartNeedsAttentionCard({
55786
+ summary,
55787
+ nextStep: formatInlineAtsCliCommands("Open System Settings > General > Login Items & Extensions, enable the ATS background item, then run `ats service start` again. Power users can audit Background Task Management with `sfltool dumpbtm`."),
55788
+ autoRepairAttempted: input.autoRepairAttempted,
55789
+ detail: input.detail ?? formatDaemonServiceJobDiagnosticsEvidence(jobDiagnostics)
55790
+ });
55791
+ return {
55792
+ title: card.title,
55793
+ summary,
55794
+ rows: card.rows
55795
+ };
55796
+ }
55797
+ const crashExitCode = jobDiagnostics ? readDaemonServiceJobCrashExitCode(jobDiagnostics) : null;
55798
+ if (jobDiagnostics && crashExitCode !== null) {
55799
+ const summary = `ATS Service launched but keeps exiting (launchd reports ${jobDiagnostics.runs} runs, last exit code ${crashExitCode}).`;
55800
+ const card = buildDaemonStartNeedsAttentionCard({
55801
+ summary,
55802
+ nextStep: formatInlineAtsCliCommands(`Run \`ats service start --mode foreground\` to see the live error. The latest local service log is at \`${localLogPath}\`. If it still fails, run \`ats service repair\`.`),
55803
+ autoRepairAttempted: input.autoRepairAttempted,
55804
+ detail: input.detail ?? formatDaemonServiceJobDiagnosticsEvidence(jobDiagnostics)
55805
+ });
55806
+ return {
55807
+ title: card.title,
55808
+ summary,
55809
+ rows: card.rows
55810
+ };
55811
+ }
55469
55812
  if (isLaunchdBootstrapIosError(message)) {
55470
55813
  const card = buildDaemonStartNeedsAttentionCard({
55471
55814
  summary: "ATS could not finish starting ATS Service on this Mac.",
@@ -55515,6 +55858,7 @@ function buildSystemServiceStartupFailureDiagnostics(input) {
55515
55858
  anomalies: timeoutError?.inventory?.anomalies ?? [],
55516
55859
  autoRepairAttempted: input.autoRepairAttempted === true,
55517
55860
  controller: input.controller ?? null,
55861
+ jobDiagnostics: timeoutError?.jobDiagnostics ?? null,
55518
55862
  launchdLabel: (input.controller ?? null) === "launchd" ? getDaemonServiceLaunchdLabel() : null,
55519
55863
  lifecycleJournalPath: daemonLifecycleJournalPath(),
55520
55864
  managerStatus: timeoutError?.managerStatus ?? null,
@@ -55525,7 +55869,9 @@ function buildSystemServiceStartupFailureDiagnostics(input) {
55525
55869
  };
55526
55870
  }
55527
55871
  function buildSystemServiceStartupTimeoutMessage(input) {
55528
- return `ATS Service failed to reach a running local service state in time. runtime=${input.runtimeStatus?.status ?? "unknown"}, reason=${input.runtimeStatus?.reason || "unknown"}, managerRunning=${String(input.managerStatus?.running ?? false)}, anomalies=${input.inventory?.anomalies.map((anomaly) => anomaly.code).join(",") || "unknown"}`;
55872
+ const base = `ATS Service failed to reach a running local service state in time. runtime=${input.runtimeStatus?.status ?? "unknown"}, reason=${input.runtimeStatus?.reason || "unknown"}, managerRunning=${String(input.managerStatus?.running ?? false)}, anomalies=${input.inventory?.anomalies.map((anomaly) => anomaly.code).join(",") || "unknown"}`;
55873
+ if (!input.jobDiagnostics) return base;
55874
+ return `${base}; ${formatDaemonServiceJobDiagnosticsEvidence(input.jobDiagnostics)}`;
55529
55875
  }
55530
55876
  function isSystemServiceStartupTimeoutError(error) {
55531
55877
  return error instanceof SystemServiceStartupTimeoutError || typeof error === "object" && error !== null && "code" in error && error.code === "ats.service.startup_timeout";
@@ -55579,7 +55925,8 @@ async function waitForSystemServiceStartup(input) {
55579
55925
  throw new SystemServiceStartupTimeoutError({
55580
55926
  inventory: finalInventory,
55581
55927
  managerStatus: await input.manager.status().catch(() => null),
55582
- runtimeStatus: finalRuntimeStatus
55928
+ runtimeStatus: finalRuntimeStatus,
55929
+ jobDiagnostics: await input.manager.readJobDiagnostics?.().catch(() => null) ?? null
55583
55930
  });
55584
55931
  }
55585
55932
 
@@ -58574,6 +58921,7 @@ async function runSystemServiceManager(input) {
58574
58921
  command: "ats service run",
58575
58922
  controller: input.systemManager.controller,
58576
58923
  intent: "run_background",
58924
+ resolveErrorMetadata: (error) => isSystemServiceStartupTimeoutError(error) && error.jobDiagnostics ? { jobDiagnostics: error.jobDiagnostics } : null,
58577
58925
  run: async () => await waitForSystemServiceStartup({
58578
58926
  expectedVersion: input.daemonVersion,
58579
58927
  manager: input.systemManager,
@@ -82581,6 +82929,16 @@ function toErrorMessage$7(error) {
82581
82929
  //#endregion
82582
82930
  //#region src/space/web-url.ts
82583
82931
  function buildSpaceWebUrl(baseUrl, spaceId, options) {
82932
+ const url = new URL(resolveGatewayWebOrigin(baseUrl));
82933
+ const surface = options?.surface ?? "public";
82934
+ url.pathname = surface === "app" ? `/app/spaces/${encodeURIComponent(spaceId)}` : `/spaces/${encodeURIComponent(spaceId)}`;
82935
+ url.search = "";
82936
+ const profileId = normalizeOptionalText$5(options?.profileId);
82937
+ if (surface === "app" && profileId) url.searchParams.set("profileId", profileId);
82938
+ url.hash = "";
82939
+ return url.toString();
82940
+ }
82941
+ function resolveGatewayWebOrigin(baseUrl) {
82584
82942
  const url = new URL(baseUrl);
82585
82943
  if (isLoopbackHostname$2(url.hostname) && url.port === "8080") url.port = "3000";
82586
82944
  if (url.hostname === "gateway.ats.sh") {
@@ -82588,13 +82946,10 @@ function buildSpaceWebUrl(baseUrl, spaceId, options) {
82588
82946
  url.port = "";
82589
82947
  url.protocol = "https:";
82590
82948
  }
82591
- const surface = options?.surface ?? "public";
82592
- url.pathname = surface === "app" ? `/app/spaces/${encodeURIComponent(spaceId)}` : `/spaces/${encodeURIComponent(spaceId)}`;
82949
+ url.pathname = "";
82593
82950
  url.search = "";
82594
- const profileId = normalizeOptionalText$5(options?.profileId);
82595
- if (surface === "app" && profileId) url.searchParams.set("profileId", profileId);
82596
82951
  url.hash = "";
82597
- return url.toString();
82952
+ return url.origin;
82598
82953
  }
82599
82954
  function isLoopbackHostname$2(hostname) {
82600
82955
  return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1";
@@ -97785,6 +98140,69 @@ function requireValidSetupBootstrapWrite(input) {
97785
98140
  return parsed.data;
97786
98141
  }
97787
98142
 
98143
+ //#endregion
98144
+ //#region src/guides/local-agents-guide-url.ts
98145
+ const LOCAL_AGENTS_GUIDE_PATH = "/guides/local-agents";
98146
+ const LOCAL_AGENTS_GUIDE_AGENT_NAMES = "Codex, Claude Code, or OpenCode";
98147
+ function buildLocalAgentsGuideUrl(baseUrl) {
98148
+ const url = new URL(resolveGatewayWebOrigin(baseUrl));
98149
+ url.pathname = LOCAL_AGENTS_GUIDE_PATH;
98150
+ url.search = "";
98151
+ url.hash = "";
98152
+ return url.toString();
98153
+ }
98154
+ function buildNoLocalAgentsNoticeLines(input) {
98155
+ return [
98156
+ `ATS did not find ${LOCAL_AGENTS_GUIDE_AGENT_NAMES} on this computer.`,
98157
+ "Install and sign in to one of them if you want this computer to run local agents from ATS.",
98158
+ `Guide: ${input.guideUrl}`
98159
+ ];
98160
+ }
98161
+ function appendLocalAgentsGuideUrl(input) {
98162
+ return `${input.message} Install guide: ${input.guideUrl}`;
98163
+ }
98164
+ async function confirmContinueWithoutLocalAgents(input) {
98165
+ return await runInteractivePrompt({
98166
+ initialState: { guideUrl: input.guideUrl },
98167
+ fallbackResult: "continue",
98168
+ renderLines: renderLocalAgentsGuidePromptLines,
98169
+ handleKeypress: handleLocalAgentsGuidePromptKeypress
98170
+ }, input.streams);
98171
+ }
98172
+ function renderLocalAgentsGuidePromptLines(state, status) {
98173
+ if (status === "submitted") return ["Continuing setup without local agents."];
98174
+ if (status === "cancelled") return ["Setup cancelled."];
98175
+ return [...buildNoLocalAgentsNoticeLines({ guideUrl: state.guideUrl }), "Continue setting up the ATS service without any local agents? [Y/n]"];
98176
+ }
98177
+ function handleLocalAgentsGuidePromptKeypress(input) {
98178
+ if (input.key.name === "return" || input.key.name === "enter") return {
98179
+ type: "result",
98180
+ status: "submitted",
98181
+ result: "continue",
98182
+ state: input.state
98183
+ };
98184
+ const value = String(input.str ?? "").trim().toLowerCase();
98185
+ if (value === "y") return {
98186
+ type: "result",
98187
+ status: "submitted",
98188
+ result: "continue",
98189
+ state: input.state
98190
+ };
98191
+ if (value === "n" || input.key.name === "escape") return {
98192
+ type: "result",
98193
+ status: "cancelled",
98194
+ result: "cancelled",
98195
+ state: input.state
98196
+ };
98197
+ if (input.key.ctrl && input.key.name === "c") return {
98198
+ type: "result",
98199
+ status: "cancelled",
98200
+ result: "cancelled",
98201
+ state: input.state
98202
+ };
98203
+ return { type: "ignore" };
98204
+ }
98205
+
97788
98206
  //#endregion
97789
98207
  //#region src/local-service/reporting/selected-agent-controller-reporting.ts
97790
98208
  function resolveSelectedAgentControllerReadiness(input) {
@@ -97895,6 +98313,64 @@ function normalizeId(value) {
97895
98313
  return value.trim();
97896
98314
  }
97897
98315
 
98316
+ //#endregion
98317
+ //#region src/ui/controlling-terminal.ts
98318
+ const CONTROLLING_TERMINAL_PATH = "/dev/tty";
98319
+ function hasUsableProcessTerminal() {
98320
+ return process$1.stdin.isTTY === true && process$1.stdout.isTTY === true && typeof process$1.stdin.setRawMode === "function";
98321
+ }
98322
+ function closeFdSafely(fd) {
98323
+ if (fd === null) return;
98324
+ try {
98325
+ closeSync(fd);
98326
+ } catch {}
98327
+ }
98328
+ function resolveControllingTerminalSession() {
98329
+ if (hasUsableProcessTerminal()) return {
98330
+ streams: {
98331
+ input: process$1.stdin,
98332
+ output: process$1.stdout
98333
+ },
98334
+ close: () => void 0
98335
+ };
98336
+ if (process$1.platform === "win32") return null;
98337
+ let readFd = null;
98338
+ let writeFd = null;
98339
+ let input = null;
98340
+ let output = null;
98341
+ try {
98342
+ readFd = openSync(CONTROLLING_TERMINAL_PATH, "r");
98343
+ input = new ReadStream(readFd);
98344
+ readFd = null;
98345
+ writeFd = openSync(CONTROLLING_TERMINAL_PATH, "w");
98346
+ output = new WriteStream(writeFd);
98347
+ writeFd = null;
98348
+ if (input.isTTY !== true || output.isTTY !== true || typeof input.setRawMode !== "function") {
98349
+ input.destroy();
98350
+ output.destroy();
98351
+ return null;
98352
+ }
98353
+ const ttyInput = input;
98354
+ const ttyOutput = output;
98355
+ return {
98356
+ streams: {
98357
+ input: ttyInput,
98358
+ output: ttyOutput
98359
+ },
98360
+ close: () => {
98361
+ ttyInput.destroy();
98362
+ ttyOutput.destroy();
98363
+ }
98364
+ };
98365
+ } catch {
98366
+ if (input) input.destroy();
98367
+ else closeFdSafely(readFd);
98368
+ if (output) output.destroy();
98369
+ else closeFdSafely(writeFd);
98370
+ return null;
98371
+ }
98372
+ }
98373
+
97898
98374
  //#endregion
97899
98375
  //#region src/ui/setup-progress.ts
97900
98376
  function createSetupProgressReporter(input) {
@@ -98526,62 +99002,129 @@ async function writeConnectedComputerEnrollmentToServiceContract(input) {
98526
99002
  }
98527
99003
 
98528
99004
  //#endregion
98529
- //#region src/ui/controlling-terminal.ts
98530
- const CONTROLLING_TERMINAL_PATH = "/dev/tty";
98531
- function hasUsableProcessTerminal() {
98532
- return process$1.stdin.isTTY === true && process$1.stdout.isTTY === true && typeof process$1.stdin.setRawMode === "function";
99005
+ //#region src/commands/prepare-step-diagnostics.ts
99006
+ const PREPARE_STEP_DIAGNOSTICS_PAYLOAD_MAX_CHARS = Math.min(16e3, PREPARE_STEP_DIAGNOSTICS_MAX_CHARS);
99007
+ const ATS_NO_DIAGNOSTICS_ENV = "ATS_NO_DIAGNOSTICS";
99008
+ const LIFECYCLE_JOURNAL_TAIL_MAX_ENTRIES = 10;
99009
+ const SERVICE_LOG_TAIL_MAX_LINES = 30;
99010
+ const SERVICE_LOG_LINE_MAX_CHARS = 320;
99011
+ const JOURNAL_ENTRY_MAX_CHARS = 700;
99012
+ const SOURCE_TIMEOUT_MS = 2e3;
99013
+ function isPrepareStepDiagnosticsOptedOut(env = process$1.env) {
99014
+ return String(env[ATS_NO_DIAGNOSTICS_ENV] ?? "").trim() === "1";
98533
99015
  }
98534
- function closeFdSafely(fd) {
98535
- if (fd === null) return;
99016
+ async function collectPrepareStepDiagnostics(input) {
98536
99017
  try {
98537
- closeSync(fd);
98538
- } catch {}
99018
+ if (isPrepareStepDiagnosticsOptedOut(input.env)) return null;
99019
+ const sources = input.sources ?? {};
99020
+ const collectionErrors = [];
99021
+ const [lifecycleJournalTail, serviceLogTail, inventoryAnomalies, serviceJob] = await Promise.all([
99022
+ collectDiagnosticsSource({
99023
+ collectionErrors,
99024
+ sourceName: "lifecycle_journal",
99025
+ read: sources.readLifecycleJournalTail ?? (() => readRecentDaemonLifecycleEvents({ maxEntries: LIFECYCLE_JOURNAL_TAIL_MAX_ENTRIES }))
99026
+ }),
99027
+ collectDiagnosticsSource({
99028
+ collectionErrors,
99029
+ sourceName: "service_log",
99030
+ read: sources.readServiceLogTail ?? (() => readDaemonStartFailureLogTailLines({ maxLines: SERVICE_LOG_TAIL_MAX_LINES }))
99031
+ }),
99032
+ collectDiagnosticsSource({
99033
+ collectionErrors,
99034
+ sourceName: "inventory_anomalies",
99035
+ read: sources.readInventoryAnomalyCodes ?? readInventoryAnomalyCodes
99036
+ }),
99037
+ collectDiagnosticsSource({
99038
+ collectionErrors,
99039
+ sourceName: "service_job",
99040
+ read: sources.readServiceJobDiagnostics ?? readServiceJobDiagnostics
99041
+ })
99042
+ ]);
99043
+ const cliVersion = getCliVersionInfo().version;
99044
+ return serializeBoundedPrepareStepDiagnostics({
99045
+ bundleVersion: 1,
99046
+ collectedAt: (/* @__PURE__ */ new Date()).toISOString(),
99047
+ supportCode: input.supportCode,
99048
+ stepId: input.stepId,
99049
+ cliVersion,
99050
+ os: {
99051
+ platform: process$1.platform,
99052
+ release: os.release()
99053
+ },
99054
+ inventoryAnomalies,
99055
+ serviceJob,
99056
+ lifecycleJournalTail: lifecycleJournalTail === null ? null : lifecycleJournalTail.map(boundLifecycleJournalEntry),
99057
+ serviceLogTail: serviceLogTail === null ? null : serviceLogTail.map(boundServiceLogLine),
99058
+ collectionErrors,
99059
+ truncated: false
99060
+ });
99061
+ } catch {
99062
+ return null;
99063
+ }
98539
99064
  }
98540
- function resolveControllingTerminalSession() {
98541
- if (hasUsableProcessTerminal()) return {
98542
- streams: {
98543
- input: process$1.stdin,
98544
- output: process$1.stdout
98545
- },
98546
- close: () => void 0
99065
+ function serializeBoundedPrepareStepDiagnostics(bundle) {
99066
+ let candidate = bundle;
99067
+ let serialized = JSON.stringify(candidate);
99068
+ if (serialized.length <= PREPARE_STEP_DIAGNOSTICS_PAYLOAD_MAX_CHARS) return serialized;
99069
+ candidate = {
99070
+ ...candidate,
99071
+ truncated: true
98547
99072
  };
98548
- if (process$1.platform === "win32") return null;
98549
- let readFd = null;
98550
- let writeFd = null;
98551
- let input = null;
98552
- let output = null;
98553
- try {
98554
- readFd = openSync(CONTROLLING_TERMINAL_PATH, "r");
98555
- input = new ReadStream(readFd);
98556
- readFd = null;
98557
- writeFd = openSync(CONTROLLING_TERMINAL_PATH, "w");
98558
- output = new WriteStream(writeFd);
98559
- writeFd = null;
98560
- if (input.isTTY !== true || output.isTTY !== true || typeof input.setRawMode !== "function") {
98561
- input.destroy();
98562
- output.destroy();
98563
- return null;
98564
- }
98565
- const ttyInput = input;
98566
- const ttyOutput = output;
98567
- return {
98568
- streams: {
98569
- input: ttyInput,
98570
- output: ttyOutput
98571
- },
98572
- close: () => {
98573
- ttyInput.destroy();
98574
- ttyOutput.destroy();
98575
- }
99073
+ serialized = JSON.stringify(candidate);
99074
+ while (serialized.length > PREPARE_STEP_DIAGNOSTICS_PAYLOAD_MAX_CHARS) {
99075
+ const serviceLogTail = candidate.serviceLogTail;
99076
+ const lifecycleJournalTail = candidate.lifecycleJournalTail;
99077
+ if (serviceLogTail && serviceLogTail.length > 0) candidate = {
99078
+ ...candidate,
99079
+ serviceLogTail: serviceLogTail.slice(1)
98576
99080
  };
99081
+ else if (lifecycleJournalTail && lifecycleJournalTail.length > 0) candidate = {
99082
+ ...candidate,
99083
+ lifecycleJournalTail: lifecycleJournalTail.slice(1)
99084
+ };
99085
+ else {
99086
+ candidate = {
99087
+ ...candidate,
99088
+ lifecycleJournalTail: null,
99089
+ serviceLogTail: null
99090
+ };
99091
+ serialized = JSON.stringify(candidate);
99092
+ break;
99093
+ }
99094
+ serialized = JSON.stringify(candidate);
99095
+ }
99096
+ return serialized;
99097
+ }
99098
+ async function collectDiagnosticsSource(input) {
99099
+ let timer = null;
99100
+ try {
99101
+ return await Promise.race([input.read(), new Promise((_, reject) => {
99102
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error("diagnostics source timed out")), SOURCE_TIMEOUT_MS);
99103
+ })]);
98577
99104
  } catch {
98578
- if (input) input.destroy();
98579
- else closeFdSafely(readFd);
98580
- if (output) output.destroy();
98581
- else closeFdSafely(writeFd);
99105
+ input.collectionErrors.push(input.sourceName);
98582
99106
  return null;
99107
+ } finally {
99108
+ if (timer !== null) clearTimeout(timer);
98583
99109
  }
98584
99110
  }
99111
+ async function readInventoryAnomalyCodes() {
99112
+ return (await inspectDaemonServiceInventory({ expectedVersion: resolveCurrentDaemonExpectedVersion() })).anomalies.map((anomaly) => anomaly.code);
99113
+ }
99114
+ async function readServiceJobDiagnostics() {
99115
+ return await (await resolveDaemonServiceManager())?.readJobDiagnostics?.() ?? null;
99116
+ }
99117
+ function boundLifecycleJournalEntry(entry) {
99118
+ if (JSON.stringify(entry).length <= JOURNAL_ENTRY_MAX_CHARS) return entry;
99119
+ return {
99120
+ ...entry,
99121
+ metadata: { truncated: true }
99122
+ };
99123
+ }
99124
+ function boundServiceLogLine(line) {
99125
+ if (line.length <= SERVICE_LOG_LINE_MAX_CHARS) return line;
99126
+ return `${line.slice(0, SERVICE_LOG_LINE_MAX_CHARS - 1).trimEnd()}…`;
99127
+ }
98585
99128
 
98586
99129
  //#endregion
98587
99130
  //#region src/commands/prepare-session-executor.ts
@@ -98720,12 +99263,15 @@ async function runPrepareSessionExecutorOnce(input) {
98720
99263
  }
98721
99264
  async function resolveAgentSelection(input) {
98722
99265
  if (input.input.localAgentSelection) {
99266
+ const guideUrl = buildLocalAgentsGuideUrl(input.input.gatewayUrl);
98723
99267
  const localAgentIds = resolveTerminalSelectedLocalAgentIds({
99268
+ guideUrl,
98724
99269
  selection: input.input.localAgentSelection,
98725
99270
  snapshot: input.snapshot
98726
99271
  });
98727
99272
  if (hasAgentSelectionBeenSaved(input.snapshot) && haveSameLocalAgentIds(input.snapshot.selectedLocalAgentIds, localAgentIds)) return input.snapshot;
98728
99273
  return await writeTerminalAgentSelection({
99274
+ ...localAgentIds.length === 0 && input.input.localAgentSelection.mode !== "none" ? { emptySelectionGuideUrl: guideUrl } : {},
98729
99275
  input: input.input,
98730
99276
  localAgentIds,
98731
99277
  stream: input.stream,
@@ -98748,10 +99294,7 @@ const PROMPT_LOCAL_AGENT_SELECTION_MESSAGE = "Choose the local agents to connect
98748
99294
  async function resolveTerminalInteractiveLocalAgentSelection(input) {
98749
99295
  const selectableEntries = resolveSelectableLocalAgentCatalogEntries(input.snapshot);
98750
99296
  if (selectableEntries.length === 0) {
98751
- emitPrepareProgressLine(input.input, {
98752
- state: "success",
98753
- text: "No supported local agents found. Setup will continue without local agents."
98754
- });
99297
+ await confirmZeroLocalAgentPrepareSessionIfNeeded({ input: input.input });
98755
99298
  return [];
98756
99299
  }
98757
99300
  const allSelectableIds = selectableEntries.map((entry) => entry.agentId);
@@ -98783,6 +99326,35 @@ async function resolveTerminalInteractiveLocalAgentSelection(input) {
98783
99326
  terminal.close();
98784
99327
  }
98785
99328
  }
99329
+ async function confirmZeroLocalAgentPrepareSessionIfNeeded(input) {
99330
+ const guideUrl = buildLocalAgentsGuideUrl(input.input.gatewayUrl);
99331
+ const terminal = input.input.runtime.resolvedView === "human" ? resolveControllingTerminalSession() : null;
99332
+ if (!terminal) {
99333
+ emitPrepareNoLocalAgentsNotice({
99334
+ guideUrl,
99335
+ input: input.input
99336
+ });
99337
+ return;
99338
+ }
99339
+ try {
99340
+ if (await confirmContinueWithoutLocalAgents({
99341
+ guideUrl,
99342
+ streams: terminal.streams
99343
+ }) === "continue") return;
99344
+ emitHumanStatus(input.input, "Setup cancelled", ["Install an agent CLI, then re-run the setup command from ATS Web.", `Guide: ${guideUrl}`]);
99345
+ throw new Error("ATS setup was cancelled before choosing local agents.");
99346
+ } finally {
99347
+ terminal.close();
99348
+ }
99349
+ }
99350
+ function emitPrepareNoLocalAgentsNotice(input) {
99351
+ const [summary, ...details] = buildNoLocalAgentsNoticeLines({ guideUrl: input.guideUrl });
99352
+ emitPrepareProgressLine(input.input, {
99353
+ state: "success",
99354
+ text: summary ? `${summary} Setup will continue without local agents.` : "Setup will continue without local agents."
99355
+ });
99356
+ for (const detail of details) emitPrepareProgressDetail(input.input, detail);
99357
+ }
98786
99358
  function resolveSelectableLocalAgentCatalogEntries(snapshot) {
98787
99359
  return (snapshot.localAgentCatalog?.entries ?? []).filter((entry) => entry.selectable);
98788
99360
  }
@@ -98796,10 +99368,17 @@ function resolveTerminalSelectedLocalAgentIds(input) {
98796
99368
  const missingIds = selectedIds.filter((agentId) => !selectableById.has(agentId));
98797
99369
  if (missingIds.length > 0) {
98798
99370
  const selectableIds = [...selectableById.keys()];
98799
- throw new Error([`ATS cannot select local agent ${missingIds.join(", ")} for setup.`, selectableIds.length > 0 ? `Selectable local agents: ${selectableIds.join(", ")}.` : "No selectable local agents were found on this computer."].join(" "));
99371
+ throw new Error([`ATS cannot select local agent ${missingIds.join(", ")} for setup.`, selectableIds.length > 0 ? `Selectable local agents: ${selectableIds.join(", ")}.` : formatNoSelectableLocalAgentsFound(input.guideUrl)].join(" "));
98800
99372
  }
98801
99373
  return selectedIds;
98802
99374
  }
99375
+ function formatNoSelectableLocalAgentsFound(guideUrl) {
99376
+ const message = "No selectable local agents were found on this computer.";
99377
+ return guideUrl ? appendLocalAgentsGuideUrl({
99378
+ guideUrl,
99379
+ message
99380
+ }) : message;
99381
+ }
98803
99382
  function assertCompletedPrepareSessionMatchesTerminalSelection(input) {
98804
99383
  const localAgentIds = resolveTerminalSelectedLocalAgentIds(input);
98805
99384
  if (haveSameLocalAgentIds(input.snapshot.selectedLocalAgentIds, localAgentIds)) return;
@@ -98819,13 +99398,20 @@ async function writeTerminalAgentSelection(input) {
98819
99398
  });
98820
99399
  emitPrepareProgressLine(input.input, {
98821
99400
  state: "success",
98822
- text: input.localAgentIds.length === 0 ? "Selected: no local agents" : `Selected: ${formatSelectedLocalAgentNames({
99401
+ text: input.localAgentIds.length === 0 ? formatSelectedNoLocalAgents(input.emptySelectionGuideUrl) : `Selected: ${formatSelectedLocalAgentNames({
98823
99402
  localAgentIds: input.localAgentIds,
98824
99403
  snapshot: selectedSnapshot
98825
99404
  })}`
98826
99405
  });
98827
99406
  return selectedSnapshot;
98828
99407
  }
99408
+ function formatSelectedNoLocalAgents(guideUrl) {
99409
+ const message = "Selected: no local agents";
99410
+ return guideUrl ? appendLocalAgentsGuideUrl({
99411
+ guideUrl,
99412
+ message
99413
+ }) : message;
99414
+ }
98829
99415
  async function reportLocalAgentCatalogForSelection(input) {
98830
99416
  const connectionEpoch = requireConnectionEpoch(input.snapshot);
98831
99417
  emitHumanSection(input.input, "Local agents");
@@ -98988,19 +99574,33 @@ async function runTerminalStep(input) {
98988
99574
  stepId: input.stepId,
98989
99575
  rawMessage
98990
99576
  });
99577
+ const reasonCode = resolveTerminalStepFailureReasonCode({
99578
+ rawMessage,
99579
+ stepId: input.stepId
99580
+ });
99581
+ const diagnostics = await (input.collectDiagnostics ?? collectPrepareStepDiagnostics)({
99582
+ stepId: input.stepId,
99583
+ supportCode: reasonCode
99584
+ });
98991
99585
  input.stream.writeTerminalStep({
98992
99586
  connectionEpoch: input.connectionEpoch,
98993
99587
  expectedRevision: startedSnapshot.sessionRevision,
98994
99588
  stepId: input.stepId,
98995
99589
  status: "failed",
98996
- reasonCode: resolveTerminalStepFailureReasonCode({
98997
- rawMessage,
98998
- stepId: input.stepId
98999
- }),
99000
- message
99590
+ reasonCode,
99591
+ message,
99592
+ ...diagnostics === null ? {} : { diagnostics }
99593
+ });
99594
+ if (diagnostics !== null) await waitForTerminalStepWriteToSettle({
99595
+ revisionFloor: startedSnapshot.sessionRevision,
99596
+ stream: input.stream
99001
99597
  });
99002
99598
  progress.fail(message);
99003
- emitHumanStatus(input.input, "Setup blocked", [message, "After fixing this step, copy a fresh setup command from ATS Web and run setup again."]);
99599
+ emitHumanStatus(input.input, "Setup blocked", [
99600
+ message,
99601
+ "After fixing this step, copy a fresh setup command from ATS Web and run setup again.",
99602
+ ...diagnostics === null ? [] : [`A diagnostic summary was shared with ATS to help fix this (support code: ${reasonCode}).`]
99603
+ ]);
99004
99604
  const userFacingError = new Error(message);
99005
99605
  userFacingError.cause = error;
99006
99606
  throw userFacingError;
@@ -99490,6 +100090,20 @@ function buildPrepareSessionClientHelloFrame(input) {
99490
100090
  function isLegacyPrepareSessionClientHelloRejection(input) {
99491
100091
  return input.code === "schema.invalid" && input.message === "Invalid prepare session frame.";
99492
100092
  }
100093
+ function isPrepareSessionFrameSchemaRejection(input) {
100094
+ return input.code === "prepare.session.protocol_mismatch" || input.code === "schema.invalid";
100095
+ }
100096
+ const TERMINAL_STEP_FAILURE_SETTLE_TIMEOUT_MS = 2e3;
100097
+ async function waitForTerminalStepWriteToSettle(input) {
100098
+ let timer = null;
100099
+ try {
100100
+ await Promise.race([input.stream.waitForSnapshot((snapshot) => snapshot.sessionRevision > input.revisionFloor), new Promise((resolve) => {
100101
+ timer = setTimeout(resolve, TERMINAL_STEP_FAILURE_SETTLE_TIMEOUT_MS);
100102
+ })]);
100103
+ } catch {} finally {
100104
+ if (timer !== null) clearTimeout(timer);
100105
+ }
100106
+ }
99493
100107
  async function waitForSnapshotWithProgress(input) {
99494
100108
  let progress = input.progress ?? null;
99495
100109
  let progressStartedByWait = false;
@@ -99523,6 +100137,7 @@ async function connectPrepareSessionStream(input) {
99523
100137
  };
99524
100138
  let closedError = null;
99525
100139
  let stateWriteSent = false;
100140
+ let pendingStepWriteFallbackFrame = null;
99526
100141
  const assertStreamOpen = () => {
99527
100142
  if (closedError) throw closedError;
99528
100143
  };
@@ -99535,6 +100150,18 @@ async function connectPrepareSessionStream(input) {
99535
100150
  throw closedError;
99536
100151
  }
99537
100152
  };
100153
+ const handleServerErrorFrame = (payload) => {
100154
+ if (!stateWriteSent && isLegacyPrepareSessionClientHelloRejection(payload)) return;
100155
+ if (pendingStepWriteFallbackFrame !== null && isPrepareSessionFrameSchemaRejection(payload)) {
100156
+ const fallbackFrame = pendingStepWriteFallbackFrame;
100157
+ pendingStepWriteFallbackFrame = null;
100158
+ try {
100159
+ sendFrame(fallbackFrame);
100160
+ } catch {}
100161
+ return;
100162
+ }
100163
+ rejectWaiters(errorFromPrepareSessionServerError(payload));
100164
+ };
99538
100165
  ws.onMessage((raw) => {
99539
100166
  const frame = parseServerFrame(raw);
99540
100167
  if (!frame) return;
@@ -99544,11 +100171,11 @@ async function connectPrepareSessionStream(input) {
99544
100171
  return;
99545
100172
  }
99546
100173
  if (frame.type === "server.error") {
99547
- if (!stateWriteSent && isLegacyPrepareSessionClientHelloRejection(frame.payload)) return;
99548
- rejectWaiters(errorFromPrepareSessionServerError(frame.payload));
100174
+ handleServerErrorFrame(frame.payload);
99549
100175
  return;
99550
100176
  }
99551
100177
  if (frame.type !== "snapshot" && frame.type !== "snapshot_changed") return;
100178
+ pendingStepWriteFallbackFrame = null;
99552
100179
  const snapshot = frame.payload.snapshot;
99553
100180
  latestSnapshot = snapshot;
99554
100181
  for (const waiter of [...waiters]) {
@@ -99584,20 +100211,36 @@ async function connectPrepareSessionStream(input) {
99584
100211
  writeTerminalStep: (step) => {
99585
100212
  if (!latestSnapshot) throw new Error("Setup session snapshot is not available yet.");
99586
100213
  stateWriteSent = true;
100214
+ const basePayload = {
100215
+ prepareSessionId: latestSnapshot.prepareSessionId,
100216
+ connectionEpoch: step.connectionEpoch,
100217
+ expectedRevision: step.expectedRevision,
100218
+ ...step.deviceId === void 0 ? {} : { deviceId: step.deviceId },
100219
+ ...step.runtimeLane === void 0 ? {} : { runtimeLane: step.runtimeLane },
100220
+ stepAttemptId: crypto.randomUUID(),
100221
+ stepId: step.stepId,
100222
+ status: step.status,
100223
+ ...step.reasonCode === void 0 ? {} : { reasonCode: step.reasonCode },
100224
+ ...step.localReadinessSnapshot === void 0 ? {} : { localReadinessSnapshot: step.localReadinessSnapshot },
100225
+ ...step.message === void 0 ? {} : { message: step.message }
100226
+ };
100227
+ if (step.diagnostics === void 0) {
100228
+ pendingStepWriteFallbackFrame = null;
100229
+ sendFrame({
100230
+ type: "terminal.step.write",
100231
+ payload: basePayload
100232
+ });
100233
+ return;
100234
+ }
100235
+ pendingStepWriteFallbackFrame = {
100236
+ type: "terminal.step.write",
100237
+ payload: basePayload
100238
+ };
99587
100239
  sendFrame({
99588
100240
  type: "terminal.step.write",
99589
100241
  payload: {
99590
- prepareSessionId: latestSnapshot.prepareSessionId,
99591
- connectionEpoch: step.connectionEpoch,
99592
- expectedRevision: step.expectedRevision,
99593
- ...step.deviceId === void 0 ? {} : { deviceId: step.deviceId },
99594
- ...step.runtimeLane === void 0 ? {} : { runtimeLane: step.runtimeLane },
99595
- stepAttemptId: crypto.randomUUID(),
99596
- stepId: step.stepId,
99597
- status: step.status,
99598
- ...step.reasonCode === void 0 ? {} : { reasonCode: step.reasonCode },
99599
- ...step.localReadinessSnapshot === void 0 ? {} : { localReadinessSnapshot: step.localReadinessSnapshot },
99600
- ...step.message === void 0 ? {} : { message: step.message }
100242
+ ...basePayload,
100243
+ diagnostics: step.diagnostics
99601
100244
  }
99602
100245
  });
99603
100246
  },
@@ -100502,11 +101145,21 @@ async function runSetupUnlocked(input) {
100502
101145
  readiness: initialReadiness,
100503
101146
  view: runtime.resolvedView
100504
101147
  });
101148
+ const localAgentsGuideUrl = buildLocalAgentsGuideUrl(gatewayUrl);
100505
101149
  const selectedLocalAgentIds = resolveSetupLocalAgentIds({
101150
+ guideUrl: localAgentsGuideUrl,
100506
101151
  localAgent: input.localAgent,
100507
101152
  localAgents: input.localAgents,
100508
101153
  readiness: initialReadiness
100509
101154
  });
101155
+ await confirmZeroLocalAgentSetupIfNeeded({
101156
+ explicitSelection: hasExplicitLocalAgentSelection(input),
101157
+ guideUrl: localAgentsGuideUrl,
101158
+ localAgentsMode: input.localAgents,
101159
+ presenter,
101160
+ runtime,
101161
+ selectedLocalAgentIds
101162
+ });
100510
101163
  if (selectedLocalAgentIds.length > 0) assertStartLocalAgentsEnableCompleted(await runWithSetupSpinner({
100511
101164
  code: "setup.progress.local_agents.enabling",
100512
101165
  message: setupCopy.cliProgressConnectingLocalAgents,
@@ -100648,12 +101301,79 @@ function resolveSetupLocalAgentIds(input) {
100648
101301
  const missingIds = localAgentIds.filter((agentId) => !selectableById.has(agentId));
100649
101302
  if (missingIds.length > 0) {
100650
101303
  const selectableIds = [...selectableById.keys()];
100651
- throw new Error([`ATS cannot set up local agent ${missingIds.join(", ")} on this computer.`, selectableIds.length > 0 ? `Available local agents: ${selectableIds.join(", ")}.` : "No available local agents were found on this computer."].join(" "));
101304
+ throw new Error([`ATS cannot set up local agent ${missingIds.join(", ")} on this computer.`, selectableIds.length > 0 ? `Available local agents: ${selectableIds.join(", ")}.` : formatNoAvailableLocalAgentsFound(input.guideUrl)].join(" "));
100652
101305
  }
100653
101306
  return localAgentIds;
100654
101307
  }
100655
101308
  return [...selectableById.keys()].sort((left, right) => left.localeCompare(right));
100656
101309
  }
101310
+ async function confirmZeroLocalAgentSetupIfNeeded(input) {
101311
+ if (input.selectedLocalAgentIds.length > 0 || normalizeOptionalString$1(input.localAgentsMode) === "none") return;
101312
+ if (input.explicitSelection) {
101313
+ emitSetupNoLocalAgentsWarning(input);
101314
+ return;
101315
+ }
101316
+ const terminal = input.runtime.resolvedView === "human" ? resolveControllingTerminalSession() : null;
101317
+ if (!terminal) {
101318
+ emitSetupNoLocalAgentsWarning(input);
101319
+ return;
101320
+ }
101321
+ try {
101322
+ if (await confirmContinueWithoutLocalAgents({
101323
+ guideUrl: input.guideUrl,
101324
+ streams: terminal.streams
101325
+ }) === "continue") return;
101326
+ emitSetupNoLocalAgentsCancelled(input);
101327
+ throw new Error("ATS setup was cancelled before choosing local agents.");
101328
+ } finally {
101329
+ terminal.close();
101330
+ }
101331
+ }
101332
+ function emitSetupNoLocalAgentsWarning(input) {
101333
+ const lines = buildNoLocalAgentsNoticeLines({ guideUrl: input.guideUrl });
101334
+ if (input.runtime.resolvedView === "human") {
101335
+ renderInfoCard({
101336
+ presenter: input.presenter,
101337
+ title: "No Local Agents Found",
101338
+ codePrefix: "setup.local_agents.none",
101339
+ rows: lines.map((line) => ({
101340
+ label: "",
101341
+ value: line
101342
+ })),
101343
+ sanitize: true,
101344
+ minContentWidth: 56
101345
+ });
101346
+ return;
101347
+ }
101348
+ for (const [index, line] of lines.entries()) input.presenter.line({
101349
+ code: `setup.local_agents.none.${index + 1}`,
101350
+ text: line
101351
+ });
101352
+ }
101353
+ function emitSetupNoLocalAgentsCancelled(input) {
101354
+ if (input.runtime.resolvedView !== "human") return;
101355
+ renderInfoCard({
101356
+ presenter: input.presenter,
101357
+ title: "Setup Cancelled",
101358
+ codePrefix: "setup.local_agents.cancelled",
101359
+ rows: [{
101360
+ label: "",
101361
+ value: "Install an agent CLI, then re-run the setup command from ATS Web."
101362
+ }, {
101363
+ label: "",
101364
+ value: `Guide: ${input.guideUrl}`
101365
+ }],
101366
+ sanitize: true,
101367
+ minContentWidth: 56
101368
+ });
101369
+ }
101370
+ function formatNoAvailableLocalAgentsFound(guideUrl) {
101371
+ const message = "No available local agents were found on this computer.";
101372
+ return guideUrl ? appendLocalAgentsGuideUrl({
101373
+ guideUrl,
101374
+ message
101375
+ }) : message;
101376
+ }
100657
101377
  function assertStartLocalAgentsEnableCompleted(result) {
100658
101378
  if (result.status !== "completed") throw new Error("ATS setup cannot continue until selected local agents are available on this computer.");
100659
101379
  const blockingError = result.summary.errors[0] ?? null;
@@ -100736,6 +101456,7 @@ async function resolveDelegatedSetupCompletionFacts(input) {
100736
101456
  selectedLocalAgentIds: []
100737
101457
  };
100738
101458
  const selectedLocalAgentIds = sessionSelectedLocalAgentIds ? [...sessionSelectedLocalAgentIds] : resolveSetupLocalAgentIds({
101459
+ guideUrl: buildLocalAgentsGuideUrl(input.gatewayUrl),
100739
101460
  localAgent: input.setupInput.localAgent,
100740
101461
  localAgents: input.setupInput.localAgents,
100741
101462
  readiness: await collectStartLocalReadiness({ auth: {
@@ -100822,6 +101543,7 @@ function emitSetupComplete(input) {
100822
101543
  if (input.view === "human") {
100823
101544
  const setupCopy = getSetupFlowCopy("setup");
100824
101545
  const serviceGuidance = buildSetupServiceGuidance({ cliCommandPrefix });
101546
+ const localAgentsGuideUrl = buildLocalAgentsGuideUrl(input.gatewayUrl);
100825
101547
  renderInfoCard({
100826
101548
  presenter: input.presenter,
100827
101549
  title: setupCopy.cliCompletionTitle,
@@ -100829,13 +101551,30 @@ function emitSetupComplete(input) {
100829
101551
  compact: true,
100830
101552
  minContentWidth: 44,
100831
101553
  sanitize: true,
100832
- rows: [{
100833
- label: "Agents",
100834
- value: formatSetupCompleteLocalAgents(input.selectedLocalAgentIds)
100835
- }, ...input.bootstrap.status === "completed" ? [] : [{
100836
- label: "Space",
100837
- value: formatSetupBootstrapHumanSummary(input.bootstrap)
100838
- }]]
101554
+ rows: [
101555
+ {
101556
+ label: "Agents",
101557
+ value: formatSetupCompleteLocalAgents({
101558
+ guideUrl: localAgentsGuideUrl,
101559
+ selectedLocalAgentIds: input.selectedLocalAgentIds
101560
+ })
101561
+ },
101562
+ ...input.selectedLocalAgentIds.length === 0 ? [{
101563
+ label: "Install guide",
101564
+ value: localAgentsGuideUrl
101565
+ }] : [],
101566
+ ...input.bootstrap.status === "completed" ? [] : [{
101567
+ label: "Space",
101568
+ value: formatSetupBootstrapHumanSummary(input.bootstrap)
101569
+ }]
101570
+ ]
101571
+ });
101572
+ if (input.selectedLocalAgentIds.length === 0) input.presenter.line({
101573
+ code: "setup.complete.local_agents.guide",
101574
+ text: `Open guide: ${formatTerminalHyperlink({
101575
+ label: "Local agent install guide",
101576
+ url: localAgentsGuideUrl
101577
+ })} (${localAgentsGuideUrl})`
100839
101578
  });
100840
101579
  renderSetupServiceGuidanceCard({
100841
101580
  atsServiceRuntimeIdentity: input.atsServiceRuntimeIdentity,
@@ -100992,9 +101731,9 @@ async function finalizeLocalComponentsSetupSnapshot() {
100992
101731
  await writeInstalledLocalComponentsSnapshot({ source: "setup" });
100993
101732
  return await resolveLocalComponentsStatus();
100994
101733
  }
100995
- function formatSetupCompleteLocalAgents(selectedLocalAgentIds) {
100996
- if (selectedLocalAgentIds.length === 0) return "No local agents selected";
100997
- return `${selectedLocalAgentIds.length} detected: ${selectedLocalAgentIds.join(", ")}`;
101734
+ function formatSetupCompleteLocalAgents(input) {
101735
+ if (input.selectedLocalAgentIds.length === 0) return `No local agents connected. Install one from the guide: ${input.guideUrl}`;
101736
+ return `${input.selectedLocalAgentIds.length} detected: ${input.selectedLocalAgentIds.join(", ")}`;
100998
101737
  }
100999
101738
  function formatSetupCompleteSpaceSetupHint(input) {
101000
101739
  if (input.bootstrap.status === "completed") return `${input.bootstrap.welcomingSpace.outcome === "reused" ? "Reused" : "Created"} ${input.bootstrap.welcomingSpace.name}`;
@@ -102764,8 +103503,17 @@ const LEADING_AT_PATTERN = /^@/u;
102764
103503
  const TRAILING_RELATION_PATTERN = /\((wake|reference|cc)\)$/iu;
102765
103504
  const WHITESPACE_PATTERN = /\s+/g;
102766
103505
  const DISPATCH_ACTION_CLI_PLACEHOLDER = "<DISPATCH_ACTION_CLI>";
103506
+ const SPACE_ACTION_REPLY_TIMING_EVENT = "ats.space_action.reply_timing";
102767
103507
  function runSpaceActionReply(input) {
103508
+ const timing = createSpaceActionReplyTiming();
103509
+ timing.emit("command_start", void 0, {
103510
+ ccTargetCount: input.ccTargets?.length ?? 0,
103511
+ messagePartCount: input.messageParts.length,
103512
+ referenceTargetCount: input.referenceTargets?.length ?? 0,
103513
+ wakeTargetCount: input.wakeTargets?.length ?? 0
103514
+ });
102768
103515
  const context = readDispatchSpaceActionContextFromEnv();
103516
+ timing.emit("context_ready", context);
102769
103517
  assertAllowedAction(context, "post_message");
102770
103518
  const text = normalizeRequiredJoinedText(input.messageParts, "Reply message is required.");
102771
103519
  const targetIds = resolveMessageEnvelopeTargetIds({
@@ -102774,7 +103522,13 @@ function runSpaceActionReply(input) {
102774
103522
  referenceTargets: input.referenceTargets ?? [],
102775
103523
  ccTargets: input.ccTargets ?? []
102776
103524
  });
102777
- recordAction({
103525
+ timing.emit("targets_resolved", context, {
103526
+ activationTargetCount: targetIds.activationTargets.length,
103527
+ ccTargetCount: targetIds.ccTargets.length,
103528
+ messageLength: text.length,
103529
+ referenceTargetCount: targetIds.referenceTargets.length
103530
+ });
103531
+ const record = recordAction({
102778
103532
  action: {
102779
103533
  type: "post_message",
102780
103534
  messageEnvelope: {
@@ -102788,6 +103542,8 @@ function runSpaceActionReply(input) {
102788
103542
  command: "reply",
102789
103543
  context
102790
103544
  });
103545
+ timing.emit("record_written", context, { actionType: record.action.type });
103546
+ timing.emit("done", context, { actionType: record.action.type });
102791
103547
  }
102792
103548
  function runSpaceActionWake(input) {
102793
103549
  const context = readDispatchSpaceActionContextFromEnv();
@@ -102886,7 +103642,33 @@ function formatSpaceActionHelpCommand(action, context) {
102886
103642
  return formatAtsCliCommand(`ats space action ${action}`);
102887
103643
  }
102888
103644
  function recordAction(input) {
102889
- outLine(`Posted to Space: ATS accepted this final action (${writeDispatchSpaceActionRecord(input).action.type}) for the current Wake.`);
103645
+ const record = writeDispatchSpaceActionRecord(input);
103646
+ outLine(`Posted to Space: ATS accepted this final action (${record.action.type}) for the current Wake.`);
103647
+ return record;
103648
+ }
103649
+ function createSpaceActionReplyTiming() {
103650
+ const startedAt = performance.now();
103651
+ let previousAt = startedAt;
103652
+ const commandStartProcessUptimeMs = Math.round(startedAt);
103653
+ return { emit: (phase, context, fields = {}) => {
103654
+ const now = performance.now();
103655
+ const elapsedMs = Math.max(0, Math.round(now - startedAt));
103656
+ const durationMs = Math.max(0, Math.round(now - previousAt));
103657
+ previousAt = now;
103658
+ process.stderr.write(`[${SPACE_ACTION_REPLY_TIMING_EVENT}] ${JSON.stringify({
103659
+ event: SPACE_ACTION_REPLY_TIMING_EVENT,
103660
+ phase,
103661
+ elapsedMs,
103662
+ durationMs,
103663
+ commandStartProcessUptimeMs,
103664
+ attemptId: context?.attemptId ?? null,
103665
+ dispatchId: context?.dispatchId ?? null,
103666
+ spaceId: context?.spaceId ?? null,
103667
+ targetProfileId: context?.targetProfileId ?? null,
103668
+ taskId: context?.taskId ?? null,
103669
+ ...fields
103670
+ })}\n`);
103671
+ } };
102890
103672
  }
102891
103673
  function resolveMessageEnvelopeTargetIds(input) {
102892
103674
  const targets = {
@@ -103453,7 +104235,7 @@ function normalizeOptionalString(value) {
103453
104235
  return normalized.length > 0 ? normalized : null;
103454
104236
  }
103455
104237
  async function runDefaultSpaceAddMeMembership(input) {
103456
- const { runSpaceAddMeMembership } = await import("./add-me-membership-Cf5nxrwV.js");
104238
+ const { runSpaceAddMeMembership } = await import("./add-me-membership-CT_vAgoU.js");
103457
104239
  return await runSpaceAddMeMembership(input);
103458
104240
  }
103459
104241