agent-transport-system 0.3.44 → 0.3.45

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,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { $ as currentDeviceTargetResponseSchema, $t as resolveSpaceMentionLabels, A as SPACE_MEMBER_REMOVE_NOTICE_PURPOSE, An as writeCurrentDeviceBootstrapObservationResponseSchema, At as normalizeBuiltinControllerAgentId, B as atsdTaskResultOpenClawGatewayVisibilityStatusSchema, Bt as patchStartSessionBodySchema, C as DISPATCH_ACTIVITY_DISPATCHING_PURPOSE, Cn as startSessionSpaceChoiceResponseSchema, Ct as getSpaceDispatchResultResponseSchema, D as MAX_PROFILE_WORKING_DIRECTORY_LENGTH, Dn as upsertProfileSpaceHistoryResponseSchema, Dt as isExplicitBuiltinControllerRef, E as LEGACY_RUNTIME_DISPATCH_POLICY, En as structuredGuidePayloadFromInputSchema, Et as incomingServerMessageSchema, F as atsRuntimeProfileIdSchema, Fn as writeStartObservedDeviceMetadataBodySchema, Ft as ownedDevicesResponseSchema, G as canonicalizeControllerRefForKind, Gt as profileWorkspaceModeSchema, H as buildControllerRoutingKeyForKind, Ht as postNormalMessageResponseSchema, I as atsSpaceEgressActionSchema, In as writeStartObservedDeviceMetadataResponseSchema, It as parseOptionalClientMessageId, J as continuitySchema, Jt as removeSpaceMembersResponseSchema, K as catchupResponseSchema, Kt as providerDispatchRuntimeContextSchema, L as atsdControlPlaneRequestSchema, Ln as writeStartSessionProgressBodySchema, Lt as patchProfileSpaceHistoryStatusResponseSchema, M as SPACE_PASSWORD_MIN_LENGTH, Mn as writeCurrentDeviceObservedMetadataResponseSchema, Mt as normalizeListSignalsReadQuerySemantics, N as SPACE_UPDATES_MAX_LIMIT, Nn as writeStartObservationBodySchema, Nt as normalizeMessageEnvelope, O as SPACE_DISPATCH_TRACE_PROMPT_PREVIEW_MAX_CHARS, On as upsertSpaceDeletionTombstoneResponseSchema, Ot as leaveSpaceResponseSchema, P as atsProfileIdSchema, Pn as writeStartObservationResponseSchema, Pt as normalizeOptionalWorkingDirectory, Q as createStartSessionBodySchema, Qt as resolveSingleSpaceMentionLabels, R as atsdControlPlaneResponseSchema, Rn as writeStartSessionProgressResponseSchema, Rt as patchSpaceContractBodySchema, S as DAEMON_HUB_SCHEMA_VERSION, Sn as startSessionSpaceChoiceBodySchema, St as getSpaceDispatchLookupResponseSchema, T as DISPATCH_ACTIVITY_RETRYING_PURPOSE, Tn as startStateResponseSchema, Tt as getSpaceUpdatesResponseSchema, U as buildUpstreamConversationRef, Ut as postSpaceMembersBodySchema, V as atsdTaskResultPayloadSchema, Vt as postNormalMessageBodySchema, W as canonicalizeBuiltinControllerRef, Wt as postSpaceMembersResponseSchema, X as createSpaceBodySchema, Xt as resolveBuiltinUpstreamConversationRefKind, Y as conversationExecutionStateSchema, Yt as resolveBuiltinProviderConversationCapability, Z as createSpaceResponseSchema, Zt as resolveMessageEnvelopeTargetField, _ as AGENT_REPLY_PREVIEW_END_PURPOSE, _n as spaceMetaSchema, _t as gatewayErrorCodeSchema, a as runWithHeldLock, an as serverErrorFrameSchema, at as daemonHubHeartbeatResponseSchema, b as ATSD_TASK_RESULT_SCHEMA_VERSION, bn as startSessionProgressSchema, bt as getSpaceConversationRemoteStatusResponseSchema, c as LEGACY_ATS_RUNTIME_SESSION_ENV_KEY, cn as signalEnvelopeSchema, ct as daemonHubSubmitTaskResultRequestSchema, d as resolveRuntimeSession, dn as spaceConversationBindingImportResponseSchema, dt as daemonServiceContractSchema, en as resolveStartHandoffBodySchema, et as daemonHubDeliverDispatchRequestSchema, f as resolveRuntimeSessionId, fn as spaceConversationBindingResponseSchema, ft as daemonStreamFrameSchema, g as AGENT_REPLYING_PURPOSE, gn as spaceMembersSnapshotSchema, gt as formatCanonicalMentionLiteral, h as AGENT_REPLYING_END_PURPOSE, hn as spaceDispatchTraceResponseSchema, ht as forgetCurrentComputerResponseSchema, i as releaseLock, in as sanitizeSignalTextPreview, it as daemonHubHeartbeatRequestSchema, j as SPACE_MENTION_REJECT_NOTICE_PURPOSE, jn as writeCurrentDeviceObservedMetadataBodySchema, jt as normalizeBuiltinControllerProviderId, k as SPACE_MEMBER_JOIN_NOTICE_PURPOSE, kn as writeCurrentDeviceBootstrapObservationBodySchema, kt as listProfileSpaceHistoryResponseSchema, l as listRuntimeSessionStates, ln as spaceConversationBindingConflictResponseSchema, lt as daemonRouteObservationResponseSchema, m as resolveBuiltinAgentControllerBrand, mn as spaceCreatorSchema, mt as entryBriefSchema, n as isAtsLockError, nt as daemonHubDispatchPreviewEndRequestSchema, o as tryCleanupStaleLock, on as setCurrentDeviceTargetBodySchema, ot as daemonHubRegisterSessionRequestSchema, p as writeRuntimeSessionState, pn as spaceConversationBindingUpsertResponseSchema, pt as dispatchBriefSchema, q as collectCanonicalMentionTextFragments, qt as querySpaceDeletionTombstonesResponseSchema, r as readLockMeta, rt as daemonHubDispatchPreviewRequestSchema, s as ATS_RUNTIME_SESSION_ENV_KEY, sn as setOwnedDeviceDisplayNameBodySchema, st as daemonHubRegisterSessionResponseSchema, t as acquireLock, tn as resolveStartHandoffResponseSchema, tt as daemonHubDispatchLifecycleRequestSchema, u as readRuntimeSessionState, un as spaceConversationBindingDeleteResponseSchema, ut as daemonRuntimeLeaseSchema, v as AGENT_REPLY_PREVIEW_PURPOSE, vn as startDeviceProjectionSchema, vt as gatewayErrorEnvelopeSchema, w as DISPATCH_ACTIVITY_FAILED_PURPOSE, wn as startSessionWithTokenResponseSchema, wt as getSpaceStatusResponseSchema, x as CONVERSATION_CONTINUITY_WARNING_PURPOSE, xn as startSessionResponseSchema, xt as getSpaceConversationStatusResponseSchema, y as ATSD_CONTROL_PLANE_SCHEMA_VERSION, yn as startProfileReadinessSummarySchema, yt as getSpaceContractResponseSchema, z as atsdTaskResultEnvelopeWriteSchema, zn as createDaemonRouteObservationSummary, zt as patchSpaceContractResponseSchema } from "./lock-XN4kQrxs.js";
3
+ import { $ as currentDeviceTargetResponseSchema, $t as resolveSpaceMentionLabels, A as SPACE_MEMBER_REMOVE_NOTICE_PURPOSE, An as writeCurrentDeviceBootstrapObservationResponseSchema, At as normalizeBuiltinControllerAgentId, B as atsdTaskResultOpenClawGatewayVisibilityStatusSchema, Bt as patchStartSessionBodySchema, C as DISPATCH_ACTIVITY_DISPATCHING_PURPOSE, Cn as startSessionSpaceChoiceResponseSchema, Ct as getSpaceDispatchResultResponseSchema, D as MAX_PROFILE_WORKING_DIRECTORY_LENGTH, Dn as upsertProfileSpaceHistoryResponseSchema, Dt as isExplicitBuiltinControllerRef, E as LEGACY_RUNTIME_DISPATCH_POLICY, En as structuredGuidePayloadFromInputSchema, Et as incomingServerMessageSchema, F as atsRuntimeProfileIdSchema, Fn as writeStartObservedDeviceMetadataBodySchema, Ft as ownedDevicesResponseSchema, G as canonicalizeControllerRefForKind, Gt as profileWorkspaceModeSchema, H as buildControllerRoutingKeyForKind, Ht as postNormalMessageResponseSchema, I as atsSpaceEgressActionSchema, In as writeStartObservedDeviceMetadataResponseSchema, It as parseOptionalClientMessageId, J as continuitySchema, Jt as removeSpaceMembersResponseSchema, K as catchupResponseSchema, Kt as providerDispatchRuntimeContextSchema, L as atsdControlPlaneRequestSchema, Ln as writeStartSessionProgressBodySchema, Lt as patchProfileSpaceHistoryStatusResponseSchema, M as SPACE_PASSWORD_MIN_LENGTH, Mn as writeCurrentDeviceObservedMetadataResponseSchema, Mt as normalizeListSignalsReadQuerySemantics, N as SPACE_UPDATES_MAX_LIMIT, Nn as writeStartObservationBodySchema, Nt as normalizeMessageEnvelope, O as SPACE_DISPATCH_TRACE_PROMPT_PREVIEW_MAX_CHARS, On as upsertSpaceDeletionTombstoneResponseSchema, Ot as leaveSpaceResponseSchema, P as atsProfileIdSchema, Pn as writeStartObservationResponseSchema, Pt as normalizeOptionalWorkingDirectory, Q as createStartSessionBodySchema, Qt as resolveSingleSpaceMentionLabels, R as atsdControlPlaneResponseSchema, Rn as writeStartSessionProgressResponseSchema, Rt as patchSpaceContractBodySchema, S as DAEMON_HUB_SCHEMA_VERSION, Sn as startSessionSpaceChoiceBodySchema, St as getSpaceDispatchLookupResponseSchema, T as DISPATCH_ACTIVITY_RETRYING_PURPOSE, Tn as startStateResponseSchema, Tt as getSpaceUpdatesResponseSchema, U as buildUpstreamConversationRef, Ut as postSpaceMembersBodySchema, V as atsdTaskResultPayloadSchema, Vt as postNormalMessageBodySchema, W as canonicalizeBuiltinControllerRef, Wt as postSpaceMembersResponseSchema, X as createSpaceBodySchema, Xt as resolveBuiltinUpstreamConversationRefKind, Y as conversationExecutionStateSchema, Yt as resolveBuiltinProviderConversationCapability, Z as createSpaceResponseSchema, Zt as resolveMessageEnvelopeTargetField, _ as AGENT_REPLY_PREVIEW_END_PURPOSE, _n as spaceMetaSchema, _t as gatewayErrorCodeSchema, a as runWithHeldLock, an as serverErrorFrameSchema, at as daemonHubHeartbeatResponseSchema, b as ATSD_TASK_RESULT_SCHEMA_VERSION, bn as startSessionProgressSchema, bt as getSpaceConversationRemoteStatusResponseSchema, c as LEGACY_ATS_RUNTIME_SESSION_ENV_KEY, cn as signalEnvelopeSchema, ct as daemonHubSubmitTaskResultRequestSchema, d as resolveRuntimeSession, dn as spaceConversationBindingImportResponseSchema, dt as daemonServiceContractSchema, en as resolveStartHandoffBodySchema, et as daemonHubDeliverDispatchRequestSchema, f as resolveRuntimeSessionId, fn as spaceConversationBindingResponseSchema, ft as daemonStreamFrameSchema, g as AGENT_REPLYING_PURPOSE, gn as spaceMembersSnapshotSchema, gt as formatCanonicalMentionLiteral, h as AGENT_REPLYING_END_PURPOSE, hn as spaceDispatchTraceResponseSchema, ht as forgetCurrentComputerResponseSchema, i as releaseLock, in as sanitizeSignalTextPreview, it as daemonHubHeartbeatRequestSchema, j as SPACE_MENTION_REJECT_NOTICE_PURPOSE, jn as writeCurrentDeviceObservedMetadataBodySchema, jt as normalizeBuiltinControllerProviderId, k as SPACE_MEMBER_JOIN_NOTICE_PURPOSE, kn as writeCurrentDeviceBootstrapObservationBodySchema, kt as listProfileSpaceHistoryResponseSchema, l as listRuntimeSessionStates, ln as spaceConversationBindingConflictResponseSchema, lt as daemonRouteObservationResponseSchema, m as resolveBuiltinAgentControllerBrand, mn as spaceCreatorSchema, mt as entryBriefSchema, n as isAtsLockError, nt as daemonHubDispatchPreviewEndRequestSchema, o as tryCleanupStaleLock, on as setCurrentDeviceTargetBodySchema, ot as daemonHubRegisterSessionRequestSchema, p as writeRuntimeSessionState, pn as spaceConversationBindingUpsertResponseSchema, pt as dispatchBriefSchema, q as collectCanonicalMentionTextFragments, qt as querySpaceDeletionTombstonesResponseSchema, r as readLockMeta, rt as daemonHubDispatchPreviewRequestSchema, s as ATS_RUNTIME_SESSION_ENV_KEY, sn as setOwnedDeviceDisplayNameBodySchema, st as daemonHubRegisterSessionResponseSchema, t as acquireLock, tn as resolveStartHandoffResponseSchema, tt as daemonHubDispatchLifecycleRequestSchema, u as readRuntimeSessionState, un as spaceConversationBindingDeleteResponseSchema, ut as daemonRuntimeLeaseSchema, v as AGENT_REPLY_PREVIEW_PURPOSE, vn as startDeviceProjectionSchema, vt as gatewayErrorEnvelopeSchema, w as DISPATCH_ACTIVITY_FAILED_PURPOSE, wn as startSessionWithTokenResponseSchema, wt as getSpaceStatusResponseSchema, x as CONVERSATION_CONTINUITY_WARNING_PURPOSE, xn as startSessionResponseSchema, xt as getSpaceConversationStatusResponseSchema, y as ATSD_CONTROL_PLANE_SCHEMA_VERSION, yn as startProfileReadinessSummarySchema, yt as getSpaceContractResponseSchema, z as atsdTaskResultEnvelopeWriteSchema, zn as createDaemonRouteObservationSummary, zt as patchSpaceContractResponseSchema } from "./lock-CA3rSDod.js";
4
4
  import { C as normalizeAtsProfileId, D as resolveAtsRootDir, E as resolveAtsEnvPreset, M as spacesDir, N as systemDir, O as runtimeDir, S as normalizeAccountKey, T as profileViewPath, a as accountProfileWorkspacePath, c as atsRootDir, d as deviceOpenClawProfileBootstrapPath, f as deviceOpenClawProfileDir, i as accountProfileViewPath, j as skillsDir, k as runtimeLogsDir, 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-B2sqzP1x.js";
5
- import { A as toSpaceDispatchTraceUrl, C as normalizeBaseUrl, D as toSpaceCursorUrl, E as toSpaceCreateUrl, F as toSpaceRemoveMembersUrl, I as toSpaceResultUrl, L as toSpaceSignalsUrl, M as toSpaceMembersUrl, N as toSpaceMetaUrl, O as toSpaceDeleteUrl, P as toSpacePasswordUrl, R as toSpaceUpdatesUrl, S as resolveExplicitGatewayUrlOrThrow, T as toSpaceContractUrl, _ as updateConfiguredStartV1OnboardingState, a as getConfiguredDeviceRuntimeState, b as resolveBaseUrl, c as getConfiguredStartV1OnboardingState, d as resolveRuntimeSkillsCustomTargetId, f as setConfiguredBaseUrl, g as updateConfiguredSkillsConfig, h as updateConfiguredOnboardingConfig, i as getConfiguredDaemonDispatchLimits, j as toSpaceLeaveUrl, k as toSpaceDispatchLookupUrl, l as getConfiguredViewCustomization, m as updateConfiguredDeviceRuntimeState, n as alignRuntimeConfigStorage, o as getConfiguredOnboardingDisclaimerAcceptedAt, p as setConfiguredSkillsConfig, r as createDefaultRuntimeAgentControllerSettings, s as getConfiguredSkillsConfig, t as DEFAULT_RUNTIME_AGENT_TRANSPORT_MODE, u as getRuntimeConfigReadHealth, w as toDaemonRouteObservationUrl, x as resolveBaseUrlOrNull, y as normalizeGatewayBaseUrlOrNull, z as toSpaceWsUrl } from "./runtime-config-ZeQuipxB.js";
5
+ import { A as toSpaceDispatchTraceUrl, C as normalizeBaseUrl, D as toSpaceCursorUrl, E as toSpaceCreateUrl, F as toSpaceRemoveMembersUrl, I as toSpaceResultUrl, L as toSpaceSignalsUrl, M as toSpaceMembersUrl, N as toSpaceMetaUrl, O as toSpaceDeleteUrl, P as toSpacePasswordUrl, R as toSpaceUpdatesUrl, S as resolveExplicitGatewayUrlOrThrow, T as toSpaceContractUrl, _ as updateConfiguredStartV1OnboardingState, a as getConfiguredDeviceRuntimeState, b as resolveBaseUrl, c as getConfiguredStartV1OnboardingState, d as resolveRuntimeSkillsCustomTargetId, f as setConfiguredBaseUrl, g as updateConfiguredSkillsConfig, h as updateConfiguredOnboardingConfig, i as getConfiguredDaemonDispatchLimits, j as toSpaceLeaveUrl, k as toSpaceDispatchLookupUrl, l as getConfiguredViewCustomization, m as updateConfiguredDeviceRuntimeState, n as alignRuntimeConfigStorage, o as getConfiguredOnboardingDisclaimerAcceptedAt, p as setConfiguredSkillsConfig, r as createDefaultRuntimeAgentControllerSettings, s as getConfiguredSkillsConfig, t as DEFAULT_RUNTIME_AGENT_TRANSPORT_MODE, u as getRuntimeConfigReadHealth, w as toDaemonRouteObservationUrl, x as resolveBaseUrlOrNull, y as normalizeGatewayBaseUrlOrNull, z as toSpaceWsUrl } from "./runtime-config-Bp7NfBtS.js";
6
6
  import { createRequire } from "node:module";
7
7
  import { Command, Option } from "commander";
8
- import { accessSync, chmodSync, constants, existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
8
+ import { accessSync, appendFileSync, chmodSync, constants, existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
9
9
  import { homedir, hostname, release, tmpdir, userInfo } from "node:os";
10
10
  import path, { basename, delimiter, dirname, extname, isAbsolute, join, normalize, relative, resolve } from "node:path";
11
11
  import { fileURLToPath } from "node:url";
@@ -27,7 +27,7 @@ import wrapAnsi from "wrap-ansi";
27
27
  import { Box, Container, Editor, Key, ProcessTerminal, TUI, Text, getEditorKeybindings, matchesKey } from "@mariozechner/pi-tui";
28
28
 
29
29
  //#region package.json
30
- var version = "0.3.44";
30
+ var version = "0.3.45";
31
31
  var package_default = {
32
32
  name: "agent-transport-system",
33
33
  version,
@@ -1643,9 +1643,9 @@ function createAuthenticationError(input) {
1643
1643
  return new AtsAuthenticationError(resolveAuthenticationGuidance(input));
1644
1644
  }
1645
1645
  function resolveAuthenticationGuidance(input) {
1646
- const action = normalizeOptionalString$22(input.action);
1647
- const authBaseUrl = normalizeOptionalString$22(input.authBaseUrl);
1648
- const gatewayUrl = normalizeOptionalString$22(input.gatewayUrl);
1646
+ const action = normalizeOptionalString$23(input.action);
1647
+ const authBaseUrl = normalizeOptionalString$23(input.authBaseUrl);
1648
+ const gatewayUrl = normalizeOptionalString$23(input.gatewayUrl);
1649
1649
  if (input.reason === "mismatch") return {
1650
1650
  reason: input.reason,
1651
1651
  action,
@@ -1669,7 +1669,7 @@ function resolveAuthenticationGuidance(input) {
1669
1669
  };
1670
1670
  }
1671
1671
  function buildCommandAuthenticationPromptMessage$1(action) {
1672
- const normalizedAction = normalizeOptionalString$22(action);
1672
+ const normalizedAction = normalizeOptionalString$23(action);
1673
1673
  if (!normalizedAction) return "Sign in is required to continue. What do you want to do?";
1674
1674
  return `Sign in is required before ${normalizedAction}. What do you want to do?`;
1675
1675
  }
@@ -1758,7 +1758,7 @@ function resolveAuthenticationGuidanceFromMessage(message) {
1758
1758
  function extractAuthenticationPromptAction(promptMessage) {
1759
1759
  const normalizedMessage = String(promptMessage ?? "").trim();
1760
1760
  if (normalizedMessage.length === 0) return null;
1761
- return normalizeOptionalString$22(AUTH_PROMPT_ACTION_RE.exec(normalizedMessage)?.groups?.action);
1761
+ return normalizeOptionalString$23(AUTH_PROMPT_ACTION_RE.exec(normalizedMessage)?.groups?.action);
1762
1762
  }
1763
1763
  function resolveRequiredAuthenticationGuidance(reason) {
1764
1764
  switch (reason) {
@@ -1828,7 +1828,7 @@ function buildAgentAuthenticationNotes(guidance) {
1828
1828
  if (guidance.gatewayUrl) notes.push(`Current gateway: ${guidance.gatewayUrl}`);
1829
1829
  return notes;
1830
1830
  }
1831
- function normalizeOptionalString$22(value) {
1831
+ function normalizeOptionalString$23(value) {
1832
1832
  const normalized = String(value ?? "").trim();
1833
1833
  return normalized.length > 0 ? normalized : null;
1834
1834
  }
@@ -3544,13 +3544,13 @@ function resolveAtsAccountContext(input) {
3544
3544
  key: normalizeAccountKey({}),
3545
3545
  source: "fallback"
3546
3546
  };
3547
- const normalizedBaseUrl = normalizeOptionalString$21(session.authBaseUrl);
3547
+ const normalizedBaseUrl = normalizeOptionalString$22(session.authBaseUrl);
3548
3548
  const hostKey = resolveHostKey(normalizedBaseUrl);
3549
3549
  const user = normalizeUser(session.user);
3550
3550
  const userKey = user?.id ?? user?.email ?? buildSessionScopedUserKey({
3551
3551
  authBaseUrl: normalizedBaseUrl,
3552
- clientId: normalizeOptionalString$21(session.clientId),
3553
- createdAt: normalizeOptionalString$21(session.createdAt)
3552
+ clientId: normalizeOptionalString$22(session.clientId),
3553
+ createdAt: normalizeOptionalString$22(session.createdAt)
3554
3554
  });
3555
3555
  return {
3556
3556
  key: normalizeAccountKey({
@@ -3586,9 +3586,9 @@ function buildSessionScopedUserKey(input) {
3586
3586
  function normalizeUser(value) {
3587
3587
  if (!(value && typeof value === "object")) return null;
3588
3588
  const record = value;
3589
- const id = normalizeOptionalString$21(record.id);
3590
- const email = normalizeOptionalString$21(record.email);
3591
- const name = normalizeOptionalString$21(record.name);
3589
+ const id = normalizeOptionalString$22(record.id);
3590
+ const email = normalizeOptionalString$22(record.email);
3591
+ const name = normalizeOptionalString$22(record.name);
3592
3592
  if (!(id || email || name)) return null;
3593
3593
  return {
3594
3594
  ...id ? { id } : {},
@@ -3596,7 +3596,7 @@ function normalizeUser(value) {
3596
3596
  ...name ? { name } : {}
3597
3597
  };
3598
3598
  }
3599
- function normalizeOptionalString$21(value) {
3599
+ function normalizeOptionalString$22(value) {
3600
3600
  if (typeof value !== "string") return null;
3601
3601
  const normalized = value.trim();
3602
3602
  return normalized.length > 0 ? normalized : null;
@@ -3840,15 +3840,15 @@ function parseLegacySelectionPayload(raw) {
3840
3840
  try {
3841
3841
  const payload = JSON.parse(raw);
3842
3842
  if (payload.v !== 1) return null;
3843
- const sessionId = normalizeOptionalString$20(payload.sessionId);
3844
- const atsProfileId = normalizeOptionalString$20(payload.atsProfileId);
3843
+ const sessionId = normalizeOptionalString$21(payload.sessionId);
3844
+ const atsProfileId = normalizeOptionalString$21(payload.atsProfileId);
3845
3845
  if (!(sessionId && atsProfileId)) return null;
3846
3846
  return {
3847
3847
  v: 1,
3848
3848
  sessionId,
3849
- sessionSource: normalizeOptionalString$20(payload.sessionSource) ?? "manual",
3849
+ sessionSource: normalizeOptionalString$21(payload.sessionSource) ?? "manual",
3850
3850
  atsProfileId,
3851
- updatedAt: normalizeOptionalString$20(payload.updatedAt) ?? (/* @__PURE__ */ new Date(0)).toISOString()
3851
+ updatedAt: normalizeOptionalString$21(payload.updatedAt) ?? (/* @__PURE__ */ new Date(0)).toISOString()
3852
3852
  };
3853
3853
  } catch {
3854
3854
  return null;
@@ -3878,12 +3878,12 @@ function toSafeSessionFile(value) {
3878
3878
  const maxBaseLength = Math.max(1, SESSION_FILE_MAX_LENGTH - SESSION_FILE_HASH_LENGTH - 1);
3879
3879
  return `${safeBase.slice(0, maxBaseLength)}-${hash}`;
3880
3880
  }
3881
- function normalizeOptionalString$20(value) {
3881
+ function normalizeOptionalString$21(value) {
3882
3882
  const normalized = String(value ?? "").trim();
3883
3883
  return normalized.length > 0 ? normalized : null;
3884
3884
  }
3885
3885
  function normalizeRequiredString$1(value, field) {
3886
- const normalized = normalizeOptionalString$20(value);
3886
+ const normalized = normalizeOptionalString$21(value);
3887
3887
  if (!normalized) throw new Error(`${field} is required`);
3888
3888
  return normalized;
3889
3889
  }
@@ -3914,6 +3914,7 @@ const DAEMON_TOKEN_SCHEMA = "ats-daemon-token-v1";
3914
3914
  const DAEMON_TOKEN_ROTATE_MAX_AGE_MS = 1440 * 60 * 1e3;
3915
3915
  const DAEMON_HEARTBEAT_STALE_MS = 180 * 1e3;
3916
3916
  const DAEMON_ACTIVE_BUNDLE_STATE_FILENAME = "active-bundle.json";
3917
+ const DAEMON_DISPATCH_JOURNAL_FILENAME = "daemon-dispatch-journal.jsonl";
3917
3918
  const DAEMON_LIFECYCLE_JOURNAL_FILENAME = "daemon-lifecycle-journal.jsonl";
3918
3919
  const DAEMON_REPAIR_JOURNAL_FILENAME = "repair-journal.json";
3919
3920
  const DAEMON_SERVICE_LOCK_PROFILE = "daemon-service";
@@ -4006,7 +4007,7 @@ async function setDaemonServiceRuntimeState(state, pathInput = {}) {
4006
4007
  await writeDaemonServiceRuntimeState(state, pathInput);
4007
4008
  }
4008
4009
  async function clearDaemonServiceRuntimeState(pathInput = {}) {
4009
- const { clearDaemonRuntimeLease } = await import("./daemon-runtime-lease-BVetym_b.js");
4010
+ const { clearDaemonRuntimeLease } = await import("./daemon-runtime-lease-BF-4jUcH.js");
4010
4011
  await Promise.all([rm(daemonServiceRuntimeStatePath(pathInput), { force: true }), clearDaemonRuntimeLease(pathInput)]);
4011
4012
  }
4012
4013
  async function withDaemonServiceRunLock(callback, meta = {
@@ -4145,6 +4146,9 @@ function daemonRuntimeStateRootPath(pathInput = {}) {
4145
4146
  function daemonLifecycleJournalPath(pathInput = {}) {
4146
4147
  return join(daemonRuntimeRootPath(pathInput), "logs", DAEMON_LIFECYCLE_JOURNAL_FILENAME);
4147
4148
  }
4149
+ function daemonDispatchJournalPath(pathInput = {}) {
4150
+ return join(daemonRuntimeRootPath(pathInput), "logs", DAEMON_DISPATCH_JOURNAL_FILENAME);
4151
+ }
4148
4152
  function daemonServiceActiveBundleStatePath(pathInput = {}) {
4149
4153
  return join(daemonRuntimeStateRootPath(pathInput), DAEMON_ACTIVE_BUNDLE_STATE_FILENAME);
4150
4154
  }
@@ -5079,9 +5083,9 @@ async function getAuthSession() {
5079
5083
  async function getAuthSessionMetadata() {
5080
5084
  const payload = await readSessionPayload();
5081
5085
  if (!payload || payload.v !== 1) return null;
5082
- const authBaseUrl = normalizeOptionalString$19(payload.authBaseUrl);
5083
- const clientId = normalizeOptionalString$19(payload.clientId);
5084
- const createdAt = normalizeOptionalString$19(payload.createdAt);
5086
+ const authBaseUrl = normalizeOptionalString$20(payload.authBaseUrl);
5087
+ const clientId = normalizeOptionalString$20(payload.clientId);
5088
+ const createdAt = normalizeOptionalString$20(payload.createdAt);
5085
5089
  if (!(authBaseUrl && clientId && createdAt)) return null;
5086
5090
  return {
5087
5091
  authBaseUrl,
@@ -5111,10 +5115,10 @@ async function getLocalAuthSessionState() {
5111
5115
  session: null
5112
5116
  };
5113
5117
  }
5114
- const tokenType = normalizeOptionalString$19(payload.tokenType);
5115
- const authBaseUrl = normalizeOptionalString$19(payload.authBaseUrl);
5116
- const clientId = normalizeOptionalString$19(payload.clientId);
5117
- const createdAt = normalizeOptionalString$19(payload.createdAt);
5118
+ const tokenType = normalizeOptionalString$20(payload.tokenType);
5119
+ const authBaseUrl = normalizeOptionalString$20(payload.authBaseUrl);
5120
+ const clientId = normalizeOptionalString$20(payload.clientId);
5121
+ const createdAt = normalizeOptionalString$20(payload.createdAt);
5118
5122
  if (!(tokenType && authBaseUrl && clientId && createdAt)) {
5119
5123
  await clearCorruptSession(payload);
5120
5124
  return {
@@ -5236,9 +5240,9 @@ async function writeSessionPayloadAtomically(path, payload) {
5236
5240
  function buildAuthUserPayload(value) {
5237
5241
  if (!(value && typeof value === "object")) return {};
5238
5242
  const record = value;
5239
- const id = normalizeOptionalString$19(record.id);
5240
- const email = normalizeOptionalString$19(record.email);
5241
- const name = normalizeOptionalString$19(record.name);
5243
+ const id = normalizeOptionalString$20(record.id);
5244
+ const email = normalizeOptionalString$20(record.email);
5245
+ const name = normalizeOptionalString$20(record.name);
5242
5246
  if (!(id || email || name)) return {};
5243
5247
  return { user: {
5244
5248
  ...id ? { id } : {},
@@ -5250,7 +5254,7 @@ function normalizeTokenType$2(value) {
5250
5254
  const normalized = value.trim();
5251
5255
  return normalized.length > 0 ? normalized : "Bearer";
5252
5256
  }
5253
- function normalizeOptionalString$19(value) {
5257
+ function normalizeOptionalString$20(value) {
5254
5258
  const normalized = String(value ?? "").trim();
5255
5259
  return normalized.length > 0 ? normalized : null;
5256
5260
  }
@@ -5298,7 +5302,7 @@ var AuthProfilesApiError = class extends Error {
5298
5302
  this.name = "AuthProfilesApiError";
5299
5303
  this.status = input.status;
5300
5304
  this.endpoint = input.endpoint;
5301
- this.code = normalizeOptionalString$18(input.code);
5305
+ this.code = normalizeOptionalString$19(input.code);
5302
5306
  }
5303
5307
  };
5304
5308
  async function listAtsProfiles() {
@@ -5312,15 +5316,15 @@ async function resolveAtsProfile(input) {
5312
5316
  method: "POST",
5313
5317
  path: "/v1/profiles/resolve",
5314
5318
  body: {
5315
- ...normalizeOptionalString$18(input.atsProfileId) ? { atsProfileId: normalizeOptionalString$18(input.atsProfileId) } : {},
5319
+ ...normalizeOptionalString$19(input.atsProfileId) ? { atsProfileId: normalizeOptionalString$19(input.atsProfileId) } : {},
5316
5320
  ...input.profileKind ? { profileKind: input.profileKind } : {}
5317
5321
  }
5318
5322
  }), "profile"));
5319
5323
  }
5320
5324
  function createAtsAgentProfile(input) {
5321
- const profileName = normalizeOptionalString$18(input.profileName);
5322
- const creatorProfileId = normalizeOptionalString$18(input.creatorProfileId) ?? void 0;
5323
- const controllerRef = normalizeOptionalString$18(input.controllerRef) ?? void 0;
5325
+ const profileName = normalizeOptionalString$19(input.profileName);
5326
+ const creatorProfileId = normalizeOptionalString$19(input.creatorProfileId) ?? void 0;
5327
+ const controllerRef = normalizeOptionalString$19(input.controllerRef) ?? void 0;
5324
5328
  if (!profileName) throw new Error("profile name is required");
5325
5329
  return createAtsAgentProfileRequest({
5326
5330
  profileName,
@@ -5331,8 +5335,8 @@ function createAtsAgentProfile(input) {
5331
5335
  });
5332
5336
  }
5333
5337
  async function createAtsHumanProfile(input) {
5334
- const profileName = normalizeOptionalString$18(input.profileName);
5335
- const creatorProfileId = normalizeOptionalString$18(input.creatorProfileId) ?? void 0;
5338
+ const profileName = normalizeOptionalString$19(input.profileName);
5339
+ const creatorProfileId = normalizeOptionalString$19(input.creatorProfileId) ?? void 0;
5336
5340
  if (!profileName) throw new Error("profile name is required");
5337
5341
  const created = parseAtsProfileItem(readRecordField(await requestAtsProfilesApi({
5338
5342
  method: "POST",
@@ -5346,13 +5350,13 @@ async function createAtsHumanProfile(input) {
5346
5350
  return created;
5347
5351
  }
5348
5352
  async function updateAtsProfile(input) {
5349
- const atsProfileId = normalizeOptionalString$18(input.atsProfileId);
5353
+ const atsProfileId = normalizeOptionalString$19(input.atsProfileId);
5350
5354
  if (!atsProfileId) throw new Error("atsProfileId is required");
5351
- const profileName = normalizeOptionalString$18(input.profileName);
5355
+ const profileName = normalizeOptionalString$19(input.profileName);
5352
5356
  const hasProfileName = Boolean(profileName);
5353
5357
  const hasControllerKind = input.controllerKind !== void 0 && input.controllerKind !== null;
5354
5358
  const hasControllerRef = input.controllerRef !== void 0;
5355
- const normalizedControllerRef = input.controllerRef === null ? null : normalizeOptionalString$18(input.controllerRef) ?? null;
5359
+ const normalizedControllerRef = input.controllerRef === null ? null : normalizeOptionalString$19(input.controllerRef) ?? null;
5356
5360
  const hasControllerEnabled = typeof input.controllerEnabled === "boolean";
5357
5361
  const hasControllerPayload = input.controllerKind === null || hasControllerKind || hasControllerRef || hasControllerEnabled;
5358
5362
  if (!(hasProfileName || hasControllerPayload)) throw new Error("at least one field is required: profileName or controller binding");
@@ -5370,7 +5374,7 @@ async function updateAtsProfile(input) {
5370
5374
  return updated;
5371
5375
  }
5372
5376
  async function deleteAtsProfile(input) {
5373
- const atsProfileId = normalizeOptionalString$18(input.atsProfileId);
5377
+ const atsProfileId = normalizeOptionalString$19(input.atsProfileId);
5374
5378
  if (!atsProfileId) throw new Error("atsProfileId is required");
5375
5379
  const deleted = parseAtsProfileItem(readRecordField(await requestAtsProfilesApi({
5376
5380
  method: "DELETE",
@@ -5574,7 +5578,7 @@ function readArrayField(input, field) {
5574
5578
  return value.filter(isRecord$5);
5575
5579
  }
5576
5580
  function readRequiredStringField(input, field) {
5577
- const value = normalizeOptionalString$18(input[field]);
5581
+ const value = normalizeOptionalString$19(input[field]);
5578
5582
  if (!value) throw new Error(`invalid profile payload: missing ${field}`);
5579
5583
  return value;
5580
5584
  }
@@ -5584,7 +5588,7 @@ function readRequiredBooleanField(input, field, displayField = field) {
5584
5588
  return value;
5585
5589
  }
5586
5590
  function readOptionalStringField$1(input, field) {
5587
- return normalizeOptionalString$18(input[field]);
5591
+ return normalizeOptionalString$19(input[field]);
5588
5592
  }
5589
5593
  function readBooleanField(input, field) {
5590
5594
  return input[field] === true;
@@ -5594,7 +5598,7 @@ function readOptionalBooleanField(input, field) {
5594
5598
  if (typeof value === "boolean") return value;
5595
5599
  return null;
5596
5600
  }
5597
- function normalizeOptionalString$18(value) {
5601
+ function normalizeOptionalString$19(value) {
5598
5602
  const normalized = String(value ?? "").trim();
5599
5603
  return normalized.length > 0 ? normalized : null;
5600
5604
  }
@@ -5620,7 +5624,7 @@ async function parseResponseJson$1(response) {
5620
5624
  }
5621
5625
  function extractApiErrorMessage$1(payload, status) {
5622
5626
  const record = isRecord$5(payload) ? payload : {};
5623
- const message = normalizeOptionalString$18(record.message) ?? normalizeOptionalString$18(record.error_description) ?? normalizeOptionalString$18(record.error);
5627
+ const message = normalizeOptionalString$19(record.message) ?? normalizeOptionalString$19(record.error_description) ?? normalizeOptionalString$19(record.error);
5624
5628
  if (message) return message;
5625
5629
  return `request failed with status ${status}`;
5626
5630
  }
@@ -5653,7 +5657,7 @@ function isSelectedAtsProfileRequiredError(error) {
5653
5657
  return error.message.startsWith(PROFILE_REQUIRED_ERROR_PREFIX) && error.message.endsWith(PROFILE_REQUIRED_ERROR_SUFFIX);
5654
5658
  }
5655
5659
  async function resolveAtsProfileOrNull(input = {}) {
5656
- const explicitAtsProfileId = normalizeOptionalString$17(input.atsProfileId);
5660
+ const explicitAtsProfileId = normalizeOptionalString$18(input.atsProfileId);
5657
5661
  if (explicitAtsProfileId) return await resolveExplicitAtsProfile(explicitAtsProfileId, {
5658
5662
  profileKind: input.profileKind,
5659
5663
  allowUnauthenticated: input.allowUnauthenticated === true,
@@ -5722,7 +5726,7 @@ async function resolveSelectedAtsProfile(selectedAtsProfileId, input) {
5722
5726
  throw error;
5723
5727
  }
5724
5728
  }
5725
- function normalizeOptionalString$17(value) {
5729
+ function normalizeOptionalString$18(value) {
5726
5730
  const normalized = String(value ?? "").trim();
5727
5731
  return normalized.length > 0 ? normalized : null;
5728
5732
  }
@@ -5737,13 +5741,13 @@ function isProfileMissingError(error) {
5737
5741
  //#endregion
5738
5742
  //#region src/config/view-profile-key.ts
5739
5743
  async function resolveViewProfileKey(inputProfile) {
5740
- const explicit = normalizeOptionalString$16(inputProfile);
5744
+ const explicit = normalizeOptionalString$17(inputProfile);
5741
5745
  if (explicit) return explicit;
5742
5746
  const selected = await getSelectedAtsProfileId();
5743
5747
  if (selected) return selected;
5744
5748
  return null;
5745
5749
  }
5746
- function normalizeOptionalString$16(value) {
5750
+ function normalizeOptionalString$17(value) {
5747
5751
  const normalized = String(value ?? "").trim();
5748
5752
  return normalized.length > 0 ? normalized : null;
5749
5753
  }
@@ -19074,7 +19078,7 @@ const DAEMON_LIFECYCLE_EVENT_TYPES = [
19074
19078
  "process_stop.action",
19075
19079
  "service_contract.write"
19076
19080
  ];
19077
- function toJournalErrorMessage(error) {
19081
+ function toJournalErrorMessage$1(error) {
19078
19082
  return error instanceof Error ? error.message : String(error);
19079
19083
  }
19080
19084
  function normalizeSessionId(value) {
@@ -19120,7 +19124,7 @@ async function emitDaemonLifecycleEvent(input) {
19120
19124
  await mkdir(dirname(journalPath), { recursive: true });
19121
19125
  await appendFile(journalPath, `${JSON.stringify(event)}\n`, "utf8");
19122
19126
  } catch (error) {
19123
- console.warn(`[ats:lifecycle-journal] failed to append event ${input.type}: ${toJournalErrorMessage(error)}`);
19127
+ console.warn(`[ats:lifecycle-journal] failed to append event ${input.type}: ${toJournalErrorMessage$1(error)}`);
19124
19128
  }
19125
19129
  }
19126
19130
  async function runWithDaemonLifecycleCommandJournal(input) {
@@ -19148,7 +19152,7 @@ async function runWithDaemonLifecycleCommandJournal(input) {
19148
19152
  await emitDaemonLifecycleEvent({
19149
19153
  type: "lifecycle.command.end",
19150
19154
  result: "failed",
19151
- metadata: { errorMessage: toJournalErrorMessage(error) },
19155
+ metadata: { errorMessage: toJournalErrorMessage$1(error) },
19152
19156
  pathInput: input.pathInput,
19153
19157
  command: input.command,
19154
19158
  intent: input.intent
@@ -19179,7 +19183,7 @@ async function runDaemonServiceManagerAction(input) {
19179
19183
  metadata: {
19180
19184
  action: input.action,
19181
19185
  controller: input.controller,
19182
- errorMessage: toJournalErrorMessage(error),
19186
+ errorMessage: toJournalErrorMessage$1(error),
19183
19187
  ...input.metadata ?? {}
19184
19188
  },
19185
19189
  pathInput: input.pathInput,
@@ -19240,7 +19244,7 @@ const NOT_INSTALLED_DAEMON_STATUS = {
19240
19244
  };
19241
19245
  async function resolveDaemonLocalServiceDemand(input) {
19242
19246
  const projection = await syncDeviceRuntimeStateProjection({ mode: "check" }).catch(() => null);
19243
- const ownerUserId = normalizeOptionalString$15(input.ownerUserId);
19247
+ const ownerUserId = normalizeOptionalString$16(input.ownerUserId);
19244
19248
  if (!ownerUserId) return {
19245
19249
  decision: "indeterminate",
19246
19250
  hasWakeableLocalRoute: false,
@@ -19414,7 +19418,7 @@ function formatDaemonAutoStoppedMessage(localDemand) {
19414
19418
  if (localDemand.projection?.status === "ok" && localDemand.projection.projectedControllerIds.length === 0) return "ATS stopped the background service because this device currently has no projected local agents to wake.";
19415
19419
  return "ATS stopped the background service because this device currently has no wakeable local agents.";
19416
19420
  }
19417
- function normalizeOptionalString$15(value) {
19421
+ function normalizeOptionalString$16(value) {
19418
19422
  const normalized = String(value ?? "").trim();
19419
19423
  return normalized.length > 0 ? normalized : null;
19420
19424
  }
@@ -27313,7 +27317,7 @@ function buildAuthStatusSnapshot(input) {
27313
27317
  expiresIn: null,
27314
27318
  expired: false
27315
27319
  };
27316
- const expiresAt = normalizeOptionalString$14(session.expiresAt);
27320
+ const expiresAt = normalizeOptionalString$15(session.expiresAt);
27317
27321
  const expiresAtMs = expiresAt ? Date.parse(expiresAt) : NaN;
27318
27322
  const hasValidExpiresAt = Number.isFinite(expiresAtMs);
27319
27323
  const expiresInMs = hasValidExpiresAt ? expiresAtMs - Date.now() : NaN;
@@ -27321,14 +27325,14 @@ function buildAuthStatusSnapshot(input) {
27321
27325
  return {
27322
27326
  signedIn: input.state === "valid",
27323
27327
  state: input.state,
27324
- userId: normalizeOptionalString$14(session.user?.id),
27325
- userEmail: normalizeOptionalString$14(session.user?.email),
27326
- userName: normalizeOptionalString$14(session.user?.name),
27327
- clientId: normalizeOptionalString$14(session.clientId),
27328
- authBaseUrl: normalizeOptionalString$14(session.authBaseUrl),
27329
- tokenType: normalizeOptionalString$14(session.tokenType),
27330
- scope: normalizeOptionalString$14(session.scope),
27331
- createdAt: normalizeOptionalString$14(session.createdAt),
27328
+ userId: normalizeOptionalString$15(session.user?.id),
27329
+ userEmail: normalizeOptionalString$15(session.user?.email),
27330
+ userName: normalizeOptionalString$15(session.user?.name),
27331
+ clientId: normalizeOptionalString$15(session.clientId),
27332
+ authBaseUrl: normalizeOptionalString$15(session.authBaseUrl),
27333
+ tokenType: normalizeOptionalString$15(session.tokenType),
27334
+ scope: normalizeOptionalString$15(session.scope),
27335
+ createdAt: normalizeOptionalString$15(session.createdAt),
27332
27336
  expiresAt,
27333
27337
  expiresIn: hasValidExpiresAt ? formatRemainingDuration(expiresInMs) : null,
27334
27338
  expired
@@ -27391,7 +27395,7 @@ function appendRowIfValue(rows, label, value) {
27391
27395
  value
27392
27396
  });
27393
27397
  }
27394
- function normalizeOptionalString$14(value) {
27398
+ function normalizeOptionalString$15(value) {
27395
27399
  const normalized = String(value ?? "").trim();
27396
27400
  return normalized.length > 0 ? normalized : null;
27397
27401
  }
@@ -31360,6 +31364,65 @@ function resolveControlPlaneErrorCode(error) {
31360
31364
  return "service.internal";
31361
31365
  }
31362
31366
 
31367
+ //#endregion
31368
+ //#region src/system/daemon-dispatch-journal.ts
31369
+ const DAEMON_DISPATCH_EVENT_TYPES = [
31370
+ "dispatch.deliver.received",
31371
+ "dispatch.lifecycle.sent",
31372
+ "dispatch.lifecycle.send_failed",
31373
+ "dispatch.result.sent",
31374
+ "dispatch.result.send_failed",
31375
+ "dispatch.result.accepted"
31376
+ ];
31377
+ function emitDaemonDispatchJournalEvent(input) {
31378
+ const event = {
31379
+ schema: "ats-daemon-dispatch-event-v1",
31380
+ v: 1,
31381
+ type: input.type,
31382
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
31383
+ lane: resolveAtsEnvPreset(input.pathInput),
31384
+ pid: process$1.pid,
31385
+ sessionId: resolveRuntimeSessionId(),
31386
+ attemptId: normalizeOptionalString$14(input.attemptId),
31387
+ connectionGeneration: normalizeOptionalInteger(input.connectionGeneration),
31388
+ daemonSessionId: normalizeOptionalString$14(input.daemonSessionId),
31389
+ dispatchId: input.dispatchId,
31390
+ leaseEpoch: normalizeOptionalInteger(input.leaseEpoch),
31391
+ profileId: normalizeOptionalString$14(input.profileId),
31392
+ result: normalizeOptionalString$14(input.result),
31393
+ taskId: normalizeOptionalString$14(input.taskId),
31394
+ ...input.metadata ? { metadata: input.metadata } : {}
31395
+ };
31396
+ if (!isDaemonDispatchJournalEvent(event)) {
31397
+ console.warn(`[ats:dispatch-journal] rejected invalid event ${input.type}`);
31398
+ return;
31399
+ }
31400
+ try {
31401
+ const journalPath = daemonDispatchJournalPath(input.pathInput);
31402
+ mkdirSync(dirname(journalPath), { recursive: true });
31403
+ appendFileSync(journalPath, `${JSON.stringify(event)}\n`, "utf8");
31404
+ } catch (error) {
31405
+ console.warn(`[ats:dispatch-journal] failed to append event ${input.type}: ${toJournalErrorMessage(error)}`);
31406
+ }
31407
+ }
31408
+ function isDaemonDispatchJournalEvent(value) {
31409
+ if (!value || typeof value !== "object") return false;
31410
+ const candidate = value;
31411
+ return candidate.schema === "ats-daemon-dispatch-event-v1" && candidate.v === 1 && DAEMON_DISPATCH_EVENT_TYPES.includes(candidate.type) && typeof candidate.timestamp === "string" && candidate.timestamp.length > 0 && typeof candidate.lane === "string" && candidate.lane.length > 0 && typeof candidate.pid === "number" && Number.isInteger(candidate.pid) && candidate.pid > 0 && (candidate.sessionId === null || typeof candidate.sessionId === "string" && candidate.sessionId.length > 0) && (candidate.attemptId === null || typeof candidate.attemptId === "string" && candidate.attemptId.length > 0) && (candidate.connectionGeneration === null || typeof candidate.connectionGeneration === "number" && Number.isInteger(candidate.connectionGeneration)) && (candidate.daemonSessionId === null || typeof candidate.daemonSessionId === "string" && candidate.daemonSessionId.length > 0) && typeof candidate.dispatchId === "string" && candidate.dispatchId.length > 0 && (candidate.leaseEpoch === null || typeof candidate.leaseEpoch === "number" && Number.isInteger(candidate.leaseEpoch)) && (candidate.profileId === null || typeof candidate.profileId === "string" && candidate.profileId.length > 0) && (candidate.result === null || typeof candidate.result === "string" && candidate.result.length > 0) && (candidate.taskId === null || typeof candidate.taskId === "string" && candidate.taskId.length > 0);
31412
+ }
31413
+ function normalizeOptionalString$14(value) {
31414
+ const normalized = String(value ?? "").trim();
31415
+ return normalized.length > 0 ? normalized : null;
31416
+ }
31417
+ function normalizeOptionalInteger(value) {
31418
+ if (typeof value !== "number") return null;
31419
+ if (!Number.isInteger(value)) return null;
31420
+ return value;
31421
+ }
31422
+ function toJournalErrorMessage(error) {
31423
+ return error instanceof Error ? error.message : String(error);
31424
+ }
31425
+
31363
31426
  //#endregion
31364
31427
  //#region src/daemon/adapters/resolve-daemon-capabilities.ts
31365
31428
  function resolveDaemonCapabilities(input) {
@@ -33432,6 +33495,18 @@ function enqueueDispatchDeliverFrame(input) {
33432
33495
  payload: queueRejectPayload,
33433
33496
  socket: input.socket
33434
33497
  });
33498
+ emitDaemonDispatchJournalEvent({
33499
+ attemptId: correlation.attemptId,
33500
+ connectionGeneration: deliverRequest.connectionGeneration,
33501
+ daemonSessionId: input.daemonSessionId,
33502
+ dispatchId: correlation.dispatchId,
33503
+ leaseEpoch: deliverRequest.leaseEpoch,
33504
+ metadata: buildResultDispatchJournalMetadata(queueRejectPayload),
33505
+ profileId: deliverRequest.profileId,
33506
+ result: queueRejectPayload.status,
33507
+ taskId: correlation.taskId,
33508
+ type: "dispatch.result.sent"
33509
+ });
33435
33510
  emitRunLine({
33436
33511
  presenter: input.presenter,
33437
33512
  code: "daemon.run.dispatch_queue_rejected",
@@ -35484,6 +35559,31 @@ function summarizeTaskResultPayload(payload) {
35484
35559
  result: "success"
35485
35560
  };
35486
35561
  }
35562
+ function buildResultDispatchJournalMetadata(payload) {
35563
+ const spaceAction = payload.spaceAction ?? null;
35564
+ const outputLength = "output" in payload ? payload.output.length : null;
35565
+ const errorCode = "errorCode" in payload ? payload.errorCode ?? null : null;
35566
+ const errorType = "errorType" in payload ? payload.errorType ?? null : null;
35567
+ const errorMessage = "errorMessage" in payload ? payload.errorMessage ?? null : null;
35568
+ return {
35569
+ agentId: payload.agentId,
35570
+ controllerRef: payload.controllerRef ?? null,
35571
+ errorCode,
35572
+ errorMessage,
35573
+ errorType,
35574
+ outputLength,
35575
+ sourceEventId: payload.sourceEventId,
35576
+ spaceActionProvenance: payload.spaceActionProvenance ?? null,
35577
+ spaceActionType: spaceAction?.type ?? null,
35578
+ suppressPublicOutcome: payload.suppressPublicOutcome ?? false,
35579
+ ...spaceAction?.type === "post_message" ? { postMessageTextLength: spaceAction.messageEnvelope.text.length } : {},
35580
+ ...spaceAction?.type === "post_status" ? {
35581
+ postStatus: spaceAction.status,
35582
+ postStatusTextLength: spaceAction.text.length
35583
+ } : {},
35584
+ ...spaceAction?.type === "stay_silent" ? { staySilentReasonLength: spaceAction.reason.length } : {}
35585
+ };
35586
+ }
35487
35587
  function sendResultAndSummarize(input) {
35488
35588
  try {
35489
35589
  emitDispatchLifecycleTransition({
@@ -35498,6 +35598,17 @@ function sendResultAndSummarize(input) {
35498
35598
  taskId: input.taskId
35499
35599
  });
35500
35600
  sendDispatchResultFrame(input);
35601
+ emitDaemonDispatchJournalEvent({
35602
+ attemptId: input.attemptId,
35603
+ connectionGeneration: input.connectionGeneration,
35604
+ daemonSessionId: input.daemonSessionId,
35605
+ dispatchId: input.dispatchId,
35606
+ leaseEpoch: input.leaseEpoch,
35607
+ metadata: buildResultDispatchJournalMetadata(input.payload),
35608
+ result: input.payload.status,
35609
+ taskId: input.taskId,
35610
+ type: "dispatch.result.sent"
35611
+ });
35501
35612
  emitRunLine({
35502
35613
  presenter: input.presenter,
35503
35614
  code: "daemon.run.result_sent",
@@ -35513,10 +35624,24 @@ function sendResultAndSummarize(input) {
35513
35624
  }
35514
35625
  });
35515
35626
  } catch (error) {
35627
+ emitDaemonDispatchJournalEvent({
35628
+ attemptId: input.attemptId,
35629
+ connectionGeneration: input.connectionGeneration,
35630
+ daemonSessionId: input.daemonSessionId,
35631
+ dispatchId: input.dispatchId,
35632
+ leaseEpoch: input.leaseEpoch,
35633
+ metadata: {
35634
+ ...buildResultDispatchJournalMetadata(input.payload),
35635
+ errorMessage: toErrorMessage$32(error)
35636
+ },
35637
+ result: input.payload.status,
35638
+ taskId: input.taskId,
35639
+ type: "dispatch.result.send_failed"
35640
+ });
35516
35641
  emitRunLine({
35517
35642
  presenter: input.presenter,
35518
35643
  code: "daemon.run.result_send_failed",
35519
- text: `daemon result send failed for dispatch ${input.dispatchId}: ${error instanceof Error ? error.message : String(error)}`,
35644
+ text: `daemon result send failed for dispatch ${input.dispatchId}: ${toErrorMessage$32(error)}`,
35520
35645
  payload: {
35521
35646
  attemptId: input.attemptId,
35522
35647
  connectionGeneration: input.connectionGeneration,
@@ -35543,10 +35668,24 @@ function emitDispatchLifecycleTransition(input) {
35543
35668
  socket: input.socket
35544
35669
  });
35545
35670
  } catch (error) {
35671
+ emitDaemonDispatchJournalEvent({
35672
+ attemptId: input.attemptId,
35673
+ connectionGeneration: input.connectionGeneration,
35674
+ daemonSessionId: input.daemonSessionId,
35675
+ dispatchId: input.dispatchId,
35676
+ leaseEpoch: input.leaseEpoch,
35677
+ metadata: {
35678
+ errorMessage: toErrorMessage$32(error),
35679
+ phase: input.phase
35680
+ },
35681
+ result: "failed",
35682
+ taskId: input.taskId,
35683
+ type: "dispatch.lifecycle.send_failed"
35684
+ });
35546
35685
  emitRunLine({
35547
35686
  presenter: input.presenter,
35548
35687
  code: "daemon.run.lifecycle_send_failed",
35549
- text: `daemon lifecycle ${input.phase} send failed for dispatch ${input.dispatchId}: ${error instanceof Error ? error.message : String(error)}`,
35688
+ text: `daemon lifecycle ${input.phase} send failed for dispatch ${input.dispatchId}: ${toErrorMessage$32(error)}`,
35550
35689
  payload: {
35551
35690
  attemptId: input.attemptId,
35552
35691
  dispatchId: input.dispatchId,
@@ -35556,6 +35695,17 @@ function emitDispatchLifecycleTransition(input) {
35556
35695
  });
35557
35696
  return;
35558
35697
  }
35698
+ emitDaemonDispatchJournalEvent({
35699
+ attemptId: input.attemptId,
35700
+ connectionGeneration: input.connectionGeneration,
35701
+ daemonSessionId: input.daemonSessionId,
35702
+ dispatchId: input.dispatchId,
35703
+ leaseEpoch: input.leaseEpoch,
35704
+ metadata: { phase: input.phase },
35705
+ result: "sent",
35706
+ taskId: input.taskId,
35707
+ type: "dispatch.lifecycle.sent"
35708
+ });
35559
35709
  emitRunLine({
35560
35710
  presenter: input.presenter,
35561
35711
  code: "daemon.run.lifecycle_sent",
@@ -36338,38 +36488,20 @@ async function runDaemonSocketSession(input) {
36338
36488
  });
36339
36489
  return;
36340
36490
  }
36341
- if (parsedFrame.code === "daemon.dispatch.deliver") {
36342
- lastDispatchActivityAtMs = Date.now();
36343
- updateHeartbeatInterval({
36344
- nextIntervalMs: MIN_HEARTBEAT_INTERVAL_MS,
36345
- reason: "dispatch_activity"
36346
- });
36347
- scheduleHeartbeat({
36348
- delayMs: MIN_HEARTBEAT_INTERVAL_MS,
36349
- reason: "dispatch_activity"
36350
- });
36351
- const payload = parsedFrame.payload;
36352
- emitRunLine({
36353
- presenter: input.presenter,
36354
- code: "daemon.run.deliver_frame_received",
36355
- text: `daemon deliver frame received for dispatch ${String(payload.dispatchId ?? "unknown")}`,
36356
- payload: {
36357
- attemptId: payload.attemptId ?? null,
36358
- connectionGeneration: payload.connectionGeneration ?? null,
36359
- dispatchId: payload.dispatchId ?? null,
36360
- leaseEpoch: payload.leaseEpoch ?? null,
36361
- profileId: payload.profileId ?? null
36362
- }
36363
- });
36364
- } else if (parsedFrame.code === "daemon.dispatch.accepted") emitRunLine({
36365
- presenter: input.presenter,
36366
- code: "daemon.run.result_accepted",
36367
- text: `daemon result frame accepted for dispatch ${String(parsedFrame.payload.dispatchId ?? "unknown")}`,
36368
- payload: {
36369
- attemptId: parsedFrame.payload.attemptId ?? null,
36370
- dispatchId: parsedFrame.payload.dispatchId ?? null,
36371
- ok: parsedFrame.payload.ok ?? null
36372
- }
36491
+ observeDispatchFrame({
36492
+ onDispatchActivity: () => {
36493
+ lastDispatchActivityAtMs = Date.now();
36494
+ updateHeartbeatInterval({
36495
+ nextIntervalMs: MIN_HEARTBEAT_INTERVAL_MS,
36496
+ reason: "dispatch_activity"
36497
+ });
36498
+ scheduleHeartbeat({
36499
+ delayMs: MIN_HEARTBEAT_INTERVAL_MS,
36500
+ reason: "dispatch_activity"
36501
+ });
36502
+ },
36503
+ parsedFrame,
36504
+ presenter: input.presenter
36373
36505
  });
36374
36506
  handleDaemonSocketFrame({
36375
36507
  contextStore: input.contextStore,
@@ -36459,6 +36591,84 @@ async function runDaemonSocketSession(input) {
36459
36591
  message: `daemon stream closed (code=${String(closeCode)}, reason=${closeReason})`
36460
36592
  });
36461
36593
  }
36594
+ function observeDispatchFrame(input) {
36595
+ switch (input.parsedFrame.code) {
36596
+ case "daemon.dispatch.deliver":
36597
+ observeDispatchDeliverFrame({
36598
+ onDispatchActivity: input.onDispatchActivity,
36599
+ parsedFrame: input.parsedFrame,
36600
+ presenter: input.presenter
36601
+ });
36602
+ return;
36603
+ case "daemon.dispatch.accepted":
36604
+ observeDispatchAcceptedFrame(input.parsedFrame, input.presenter);
36605
+ return;
36606
+ default: return;
36607
+ }
36608
+ }
36609
+ function observeDispatchDeliverFrame(input) {
36610
+ input.onDispatchActivity();
36611
+ const payload = input.parsedFrame.payload;
36612
+ const dispatchId = normalizeFrameString(payload.dispatchId) ?? "unknown";
36613
+ emitDaemonDispatchJournalEvent({
36614
+ attemptId: normalizeFrameString(payload.attemptId),
36615
+ connectionGeneration: normalizeFrameInteger(payload.connectionGeneration),
36616
+ daemonSessionId: normalizeFrameString(payload.daemonSessionId),
36617
+ dispatchId,
36618
+ leaseEpoch: normalizeFrameInteger(payload.leaseEpoch),
36619
+ metadata: { deliveryRecoveryReason: payload.deliveryRecoveryReason ?? null },
36620
+ profileId: normalizeFrameString(payload.profileId),
36621
+ result: "received",
36622
+ taskId: resolveDeliveredTaskId(payload.payload),
36623
+ type: "dispatch.deliver.received"
36624
+ });
36625
+ emitRunLine({
36626
+ presenter: input.presenter,
36627
+ code: "daemon.run.deliver_frame_received",
36628
+ text: `daemon deliver frame received for dispatch ${dispatchId}`,
36629
+ payload: {
36630
+ attemptId: payload.attemptId ?? null,
36631
+ connectionGeneration: payload.connectionGeneration ?? null,
36632
+ dispatchId: payload.dispatchId ?? null,
36633
+ leaseEpoch: payload.leaseEpoch ?? null,
36634
+ profileId: payload.profileId ?? null
36635
+ }
36636
+ });
36637
+ }
36638
+ function observeDispatchAcceptedFrame(parsedFrame, presenter) {
36639
+ const dispatchId = normalizeFrameString(parsedFrame.payload.dispatchId) ?? "unknown";
36640
+ const accepted = parsedFrame.payload.ok === true;
36641
+ emitDaemonDispatchJournalEvent({
36642
+ attemptId: normalizeFrameString(parsedFrame.payload.attemptId),
36643
+ dispatchId,
36644
+ metadata: { ok: parsedFrame.payload.ok ?? null },
36645
+ result: accepted ? "accepted" : "rejected",
36646
+ type: "dispatch.result.accepted"
36647
+ });
36648
+ emitRunLine({
36649
+ presenter,
36650
+ code: "daemon.run.result_accepted",
36651
+ text: `daemon result frame accepted for dispatch ${dispatchId}`,
36652
+ payload: {
36653
+ attemptId: parsedFrame.payload.attemptId ?? null,
36654
+ dispatchId: parsedFrame.payload.dispatchId ?? null,
36655
+ ok: parsedFrame.payload.ok ?? null
36656
+ }
36657
+ });
36658
+ }
36659
+ function resolveDeliveredTaskId(payload) {
36660
+ if (!(payload && typeof payload === "object" && "taskId" in payload)) return null;
36661
+ const taskId = payload.taskId;
36662
+ return typeof taskId === "string" && taskId.length > 0 ? taskId : null;
36663
+ }
36664
+ function normalizeFrameString(value) {
36665
+ const normalized = String(value ?? "").trim();
36666
+ return normalized.length > 0 ? normalized : null;
36667
+ }
36668
+ function normalizeFrameInteger(value) {
36669
+ if (!(typeof value === "number" && Number.isInteger(value))) return null;
36670
+ return value;
36671
+ }
36462
36672
 
36463
36673
  //#endregion
36464
36674
  //#region src/daemon/state/context-store.ts