agent-transport-system 0.7.79 → 0.7.80

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
@@ -30,12 +30,12 @@ import { Box, Container, Editor, Key, ProcessTerminal, TUI, Text, getEditorKeybi
30
30
  import { ReadStream, WriteStream } from "node:tty";
31
31
 
32
32
  //#region package.json
33
- var version = "0.7.79";
33
+ var version = "0.7.80";
34
34
  var package_default = {
35
35
  $schema: "https://www.schemastore.org/package.json",
36
36
  name: "agent-transport-system",
37
37
  version,
38
- atsReleaseDate: "2026-06-22",
38
+ atsReleaseDate: "2026-06-23",
39
39
  description: "Agent Transport System CLI - https://ats.sh",
40
40
  license: "MIT",
41
41
  type: "module",
@@ -98,7 +98,7 @@ var package_default = {
98
98
  "unplugin-lightningcss": "^0.4.0",
99
99
  "vitest": "~3.2.0"
100
100
  },
101
- ats: { "minRequiredCliVersion": "0.7.76" }
101
+ ats: { "minRequiredCliVersion": "0.7.80" }
102
102
  };
103
103
 
104
104
  //#endregion
@@ -8715,7 +8715,10 @@ const WINDOWS_PATHEXT = [
8715
8715
  const SHEBANG_ARGS_SPLIT_RE = /\s+/;
8716
8716
  const FIRST_LINE_SPLIT_RE = /\r?\n/u;
8717
8717
  const NODE_VERSION_PATH_RE = /(?:^|\/)v?(\d+\.\d+\.\d+)(?:\/|$)/u;
8718
+ const MACOS_TEMP_FOLDER_RE = /^\/var\/folders\/[^/]+\/[^/]+\/t(?:\/|$)/u;
8719
+ const WRAPPER_PATH_SEGMENT_RE = /(?:^|[-_.])(?:shim|shims|wrapper|wrappers)(?:$|[-_.])/u;
8718
8720
  const HOME_DIR = normalizeOptionalText$50(homedir());
8721
+ const TEMP_DIR = normalizeOptionalText$50(tmpdir());
8719
8722
  function buildExecutableLaunchContract(input) {
8720
8723
  return {
8721
8724
  kind: "executable",
@@ -8814,14 +8817,15 @@ async function resolveInstalledNodeScriptLaunchCandidates(input) {
8814
8817
  }
8815
8818
  if (candidateIds.has(candidate.launchCandidate.installId)) continue;
8816
8819
  candidateIds.add(candidate.launchCandidate.installId);
8817
- candidates.push(candidate.launchCandidate);
8820
+ candidates.push(candidate);
8818
8821
  }
8819
8822
  if (candidates.length === 0) return {
8820
8823
  errorMessage: inspectionErrors[0] ?? `${input.displayName} is installed, but ATS could not inspect its launch files.`,
8821
8824
  ok: false
8822
8825
  };
8826
+ const stableCandidates = candidates.filter((candidate) => !candidate.transientWrapper);
8823
8827
  return {
8824
- candidates: finalizeLaunchCandidateDisplayMetadata(candidates),
8828
+ candidates: finalizeLaunchCandidateDisplayMetadata((stableCandidates.length > 0 ? stableCandidates : candidates).map((candidate) => candidate.launchCandidate)),
8825
8829
  ok: true
8826
8830
  };
8827
8831
  }
@@ -8829,9 +8833,16 @@ async function inspectInstalledNodeScriptLaunchCandidate(input) {
8829
8833
  try {
8830
8834
  await assertExecutablePath(input.commandPath);
8831
8835
  const scriptPath = await realpath(input.commandPath);
8836
+ const script = await readLaunchScriptInspection(scriptPath);
8832
8837
  const nodePath = await resolvePinnedNodePath({
8833
8838
  commandPath: scriptPath,
8834
- firstLine: await readFirstLine(scriptPath)
8839
+ firstLine: script.firstLine
8840
+ });
8841
+ const transientWrapper = isTransientPathWrapper({
8842
+ commandPath: input.commandPath,
8843
+ contents: script.contents,
8844
+ firstLine: script.firstLine,
8845
+ scriptPath
8835
8846
  });
8836
8847
  const launchContract = nodePath ? {
8837
8848
  kind: "node_script",
@@ -8841,9 +8852,11 @@ async function inspectInstalledNodeScriptLaunchCandidate(input) {
8841
8852
  return {
8842
8853
  launchCandidate: buildLaunchCandidate({
8843
8854
  commandPath: input.commandPath,
8844
- launchContract
8855
+ launchContract,
8856
+ transientWrapper
8845
8857
  }),
8846
- ok: true
8858
+ ok: true,
8859
+ transientWrapper
8847
8860
  };
8848
8861
  } catch (error) {
8849
8862
  return {
@@ -8913,9 +8926,6 @@ async function resolvePinnedNodePath(input) {
8913
8926
  return null;
8914
8927
  }
8915
8928
  }
8916
- async function readFirstLine(path) {
8917
- return normalizeOptionalText$50((await readFile(path, "utf8")).split(FIRST_LINE_SPLIT_RE, 1)[0] ?? "");
8918
- }
8919
8929
  async function assertExecutablePath(path) {
8920
8930
  await access(path, resolveRunnablePathAccessMode());
8921
8931
  }
@@ -8957,10 +8967,11 @@ function normalizeOptionalText$50(value) {
8957
8967
  function buildLaunchCandidate(input) {
8958
8968
  return {
8959
8969
  installId: buildLaunchCandidateInstallId(input.launchContract),
8960
- label: resolveLaunchCandidateSourceLabel(input.commandPath),
8970
+ label: input.transientWrapper ? "Temporary wrapper" : resolveLaunchCandidateSourceLabel(input.commandPath),
8961
8971
  detail: resolveLaunchCandidateDetail({
8962
8972
  commandPath: input.commandPath,
8963
- launchContract: input.launchContract
8973
+ launchContract: input.launchContract,
8974
+ transientWrapper: input.transientWrapper
8964
8975
  }),
8965
8976
  commandPath: input.commandPath,
8966
8977
  launchContract: input.launchContract
@@ -9030,6 +9041,7 @@ function resolveLaunchCandidateSourceLabel(commandPath) {
9030
9041
  function resolveLaunchCandidateDetail(input) {
9031
9042
  const nodeVersion = input.launchContract.kind === "node_script" ? resolveNodeVersionFromPath(input.launchContract.nodePath) : null;
9032
9043
  const commandDirectory = resolveLaunchCandidateDirectoryLabel(input.commandPath);
9044
+ if (input.transientWrapper) return `Temporary PATH wrapper · ${commandDirectory}`;
9033
9045
  if (nodeVersion) return `Node ${nodeVersion} · ${commandDirectory}`;
9034
9046
  return commandDirectory;
9035
9047
  }
@@ -9044,6 +9056,38 @@ function shortenPathForDisplay(path) {
9044
9056
  function resolveNodeVersionFromPath(path) {
9045
9057
  return normalizeOptionalText$50(path.match(NODE_VERSION_PATH_RE)?.[1]);
9046
9058
  }
9059
+ async function readLaunchScriptInspection(path) {
9060
+ const contents = await readFile(path, "utf8");
9061
+ return {
9062
+ contents,
9063
+ firstLine: normalizeOptionalText$50(contents.split(FIRST_LINE_SPLIT_RE, 1)[0] ?? "")
9064
+ };
9065
+ }
9066
+ function isTransientPathWrapper(input) {
9067
+ if (!(isInsideTemporaryDirectory(input.commandPath) || isInsideTemporaryDirectory(input.scriptPath))) return false;
9068
+ return hasWrapperPathSegment(input.commandPath) || hasWrapperPathSegment(input.scriptPath) || shellScriptLooksLikeWrapper(input);
9069
+ }
9070
+ function isInsideTemporaryDirectory(path) {
9071
+ const normalizedPath = normalizePathForDetection(path);
9072
+ const normalizedTempDir = TEMP_DIR ? normalizePathForDetection(TEMP_DIR) : null;
9073
+ if (normalizedTempDir && pathIsEqualOrDescendant(normalizedPath, normalizedTempDir)) return true;
9074
+ return pathIsEqualOrDescendant(normalizedPath, "/tmp") || pathIsEqualOrDescendant(normalizedPath, "/private/tmp") || MACOS_TEMP_FOLDER_RE.test(normalizedPath);
9075
+ }
9076
+ function hasWrapperPathSegment(path) {
9077
+ return normalizePathForDetection(path).split("/").filter((segment) => segment.length > 0).slice(-4).some((segment) => WRAPPER_PATH_SEGMENT_RE.test(segment));
9078
+ }
9079
+ function shellScriptLooksLikeWrapper(input) {
9080
+ const firstLine = normalizeOptionalText$50(input.firstLine)?.toLowerCase() ?? "";
9081
+ if (!(firstLine.includes("bash") || firstLine.includes("/sh") || firstLine.includes("zsh"))) return false;
9082
+ const contents = input.contents.toLowerCase();
9083
+ return contents.includes("wrapper_shim") || contents.includes("shim_root") || contents.includes("\nexec ") && (contents.includes("wrapper") || contents.includes("shim"));
9084
+ }
9085
+ function normalizePathForDetection(path) {
9086
+ return path.replaceAll("\\", "/").replace(/\/+/gu, "/").toLowerCase();
9087
+ }
9088
+ function pathIsEqualOrDescendant(path, parentPath) {
9089
+ return path === parentPath || path.startsWith(`${parentPath}/`);
9090
+ }
9047
9091
  function toErrorMessage$34(error) {
9048
9092
  return error instanceof Error ? error.message : String(error);
9049
9093
  }
@@ -33491,6 +33535,617 @@ function normalizeOptionalText$15(value) {
33491
33535
  return normalized.length > 0 ? normalized : null;
33492
33536
  }
33493
33537
 
33538
+ //#endregion
33539
+ //#region src/local-service/dispatch/execute-dispatch-conversation.ts
33540
+ function resolveCurrentConversationPolicy(routeConfig) {
33541
+ return { ...routeConfig?.conversationPolicy ?? {} };
33542
+ }
33543
+ function resolveDispatchContextIdForAgentControllerConversation(input) {
33544
+ if (input.agentControllerConversationResumePlan.status !== "continue_existing") return null;
33545
+ return normalizeOptionalContextId(input.agentControllerConversationOverride?.agentControllerConversationId ?? input.agentControllerConversationId ?? null);
33546
+ }
33547
+ function resolvePlannedAgentControllerConversation(input) {
33548
+ return buildAgentControllerConversationRefFromAgentControllerConversation(input);
33549
+ }
33550
+ function resolveObservedDispatchAgentControllerConversation(input) {
33551
+ return input.contextDelta?.agentControllerConversation ?? input.contextResolution?.agentControllerConversation ?? input.agentControllerConversationOverride ?? input.plannedAgentControllerConversation ?? null;
33552
+ }
33553
+ function buildAgentControllerConversationRefFromAgentControllerConversation(input) {
33554
+ const conversationId = normalizeOptionalContextId(input.agentControllerConversationId);
33555
+ const agentControllerRef = normalizeOptionalContextId(input.agentControllerRef);
33556
+ if (!(conversationId && agentControllerRef)) return null;
33557
+ if (normalizeKnownBuiltinAgentControllerId(agentControllerRef)) return buildAgentControllerConversationRef({
33558
+ agentControllerRef,
33559
+ agentControllerConversationKind: resolveBuiltinAgentControllerConversationKind(agentControllerRef) ?? "context",
33560
+ agentControllerConversationId: conversationId
33561
+ });
33562
+ return buildAgentControllerConversationRef({
33563
+ agentControllerRef,
33564
+ agentControllerConversationKind: "context",
33565
+ agentControllerConversationId: conversationId
33566
+ });
33567
+ }
33568
+ function areSameAgentControllerConversationRef(left, right) {
33569
+ if (!right) return false;
33570
+ return left.agentControllerRef === right.agentControllerRef && left.agentControllerConversationKind === right.agentControllerConversationKind && left.agentControllerConversationId === right.agentControllerConversationId;
33571
+ }
33572
+ function normalizeOptionalContextId(contextId) {
33573
+ if (typeof contextId !== "string") return null;
33574
+ const normalized = contextId.trim();
33575
+ return normalized.length > 0 ? normalized : null;
33576
+ }
33577
+ function resolveDispatchContextDeltaFromRuntimeResult(dispatchResult) {
33578
+ if (!dispatchResult.dispatched) return null;
33579
+ if (dispatchResult.adapterResult.status !== "success") return null;
33580
+ return dispatchResult.adapterResult.contextDelta ?? null;
33581
+ }
33582
+
33583
+ //#endregion
33584
+ //#region src/local-service/dispatch/execute-dispatch-bootstrap-plan.ts
33585
+ const BOOTSTRAP_IDLE_STALE_MS = 1440 * 60 * 1e3;
33586
+ const BOOTSTRAP_DISPATCH_STALE_THRESHOLD = 12;
33587
+ const isBootstrapExecutionStateMissing = (executionState) => !(executionState.bootstrapLastAppliedAt && executionState.lastAppliedTemplateVersion && executionState.lastAppliedContentFingerprint);
33588
+ const isBootstrapIdleStale = (lastActivatedAt, nowMs) => {
33589
+ if (!lastActivatedAt) return false;
33590
+ const lastActivatedMs = Date.parse(lastActivatedAt);
33591
+ if (!Number.isFinite(lastActivatedMs)) return false;
33592
+ return nowMs - lastActivatedMs >= BOOTSTRAP_IDLE_STALE_MS;
33593
+ };
33594
+ function resolveBootstrapPlan$1(input) {
33595
+ if (input.localRuntimeContextPlan.status === "recreate") return {
33596
+ reason: "compatibility_recreate",
33597
+ shouldInject: true
33598
+ };
33599
+ if (!input.executionState) return {
33600
+ reason: "missing_bootstrap_state",
33601
+ shouldInject: true
33602
+ };
33603
+ if (input.executionState.pendingBootstrapReason === "context_healed") return {
33604
+ reason: "context_healed",
33605
+ shouldInject: true
33606
+ };
33607
+ if (isBootstrapExecutionStateMissing(input.executionState)) return {
33608
+ reason: "missing_bootstrap_state",
33609
+ shouldInject: true
33610
+ };
33611
+ if (input.executionState.lastAppliedTemplateVersion !== input.bootstrapTemplateFacts.templateVersion || input.executionState.lastAppliedContentFingerprint !== input.bootstrapTemplateFacts.contentFingerprint) return {
33612
+ reason: "template_changed",
33613
+ shouldInject: true
33614
+ };
33615
+ if (isBootstrapIdleStale(input.executionState.bootstrapLastActivatedAt, input.nowMs)) return {
33616
+ reason: "idle_stale",
33617
+ shouldInject: true
33618
+ };
33619
+ if (input.executionState.dispatchesSinceBootstrapApplied >= BOOTSTRAP_DISPATCH_STALE_THRESHOLD) return {
33620
+ reason: "dispatch_count_stale",
33621
+ shouldInject: true
33622
+ };
33623
+ return {
33624
+ reason: null,
33625
+ shouldInject: false
33626
+ };
33627
+ }
33628
+ function markBootstrapInjectedContext$1(input) {
33629
+ const runtimeWorkspaceFingerprint = buildRuntimeWorkspaceFingerprint(input.effectiveRuntimeWorkingDirectory);
33630
+ return {
33631
+ agentContextLookupKey: input.agentContextLookupKey,
33632
+ activeContextId: normalizeOptionalContextId(input.existingContextId),
33633
+ dispatchesSinceBootstrapApplied: 0,
33634
+ bootstrapLastAppliedAt: input.nowIso,
33635
+ bootstrapLastActivatedAt: input.nowIso,
33636
+ lastAppliedTemplateVersion: input.bootstrapTemplateFacts.templateVersion,
33637
+ lastAppliedContentFingerprint: input.bootstrapTemplateFacts.contentFingerprint,
33638
+ lastRuntimeWorkspacePath: input.effectiveRuntimeWorkingDirectory,
33639
+ runtimeWorkspaceFingerprint,
33640
+ pendingBootstrapReason: void 0,
33641
+ updatedAt: input.nowIso,
33642
+ ...input.executionState?.lastResolvedAgentControllerConversation ? { lastResolvedAgentControllerConversation: { ...input.executionState.lastResolvedAgentControllerConversation } } : {}
33643
+ };
33644
+ }
33645
+ function reconcileBootstrapInjectedContextAfterDispatch$1(input) {
33646
+ if (!input.executionState) return null;
33647
+ const runtimeWorkspaceFingerprint = buildRuntimeWorkspaceFingerprint(input.effectiveRuntimeWorkingDirectory);
33648
+ const nextExecutionState = {
33649
+ ...input.executionState,
33650
+ bootstrapLastActivatedAt: input.nowIso,
33651
+ lastRuntimeWorkspacePath: input.effectiveRuntimeWorkingDirectory,
33652
+ runtimeWorkspaceFingerprint,
33653
+ updatedAt: input.nowIso,
33654
+ ...input.resolvedAgentControllerConversation ? { lastResolvedAgentControllerConversation: { ...input.resolvedAgentControllerConversation } } : {}
33655
+ };
33656
+ if (input.shouldInjectBootstrap) {
33657
+ const dispatchedContextId = normalizeOptionalContextId(input.dispatchedContextId);
33658
+ return {
33659
+ ...nextExecutionState,
33660
+ activeContextId: dispatchedContextId ?? nextExecutionState.activeContextId,
33661
+ dispatchesSinceBootstrapApplied: 0,
33662
+ bootstrapLastAppliedAt: nextExecutionState.bootstrapLastAppliedAt ?? input.nowIso,
33663
+ bootstrapLastActivatedAt: input.nowIso,
33664
+ lastAppliedTemplateVersion: input.bootstrapTemplateFacts.templateVersion,
33665
+ lastAppliedContentFingerprint: input.bootstrapTemplateFacts.contentFingerprint,
33666
+ pendingBootstrapReason: void 0
33667
+ };
33668
+ }
33669
+ if (input.contextHealed) return {
33670
+ ...nextExecutionState,
33671
+ activeContextId: normalizeOptionalContextId(input.dispatchedContextId) ?? nextExecutionState.activeContextId,
33672
+ dispatchesSinceBootstrapApplied: 0,
33673
+ bootstrapLastAppliedAt: void 0,
33674
+ lastAppliedTemplateVersion: void 0,
33675
+ lastAppliedContentFingerprint: void 0,
33676
+ pendingBootstrapReason: "context_healed"
33677
+ };
33678
+ if (input.continuityObservation?.status === "implicit_rotation") return {
33679
+ ...nextExecutionState,
33680
+ activeContextId: normalizeOptionalContextId(input.dispatchedContextId) ?? nextExecutionState.activeContextId,
33681
+ dispatchesSinceBootstrapApplied: nextExecutionState.dispatchesSinceBootstrapApplied + 1,
33682
+ pendingBootstrapReason: void 0
33683
+ };
33684
+ return {
33685
+ ...nextExecutionState,
33686
+ dispatchesSinceBootstrapApplied: nextExecutionState.dispatchesSinceBootstrapApplied + 1,
33687
+ pendingBootstrapReason: void 0
33688
+ };
33689
+ }
33690
+ function rollbackBootstrapExecutionStateAfterDispatchFailure$1(input) {
33691
+ const stateWithoutCurrentLookupKey = removeConversationExecutionState({
33692
+ agentContextLookupKey: input.agentContextLookupKey,
33693
+ state: input.state
33694
+ });
33695
+ if (input.executionStateBeforeDispatch) return upsertConversationExecutionState({
33696
+ state: stateWithoutCurrentLookupKey,
33697
+ executionState: input.executionStateBeforeDispatch
33698
+ });
33699
+ return stateWithoutCurrentLookupKey;
33700
+ }
33701
+
33702
+ //#endregion
33703
+ //#region src/local-service/dispatch/execute-dispatch-conversation-state.ts
33704
+ function upsertConversationExecutionStateForLookupKey(input) {
33705
+ let nextState = input.state;
33706
+ const staleLookupKeys = /* @__PURE__ */ new Set();
33707
+ if (input.executionState.agentContextLookupKey !== input.targetLookupKey) staleLookupKeys.add(input.executionState.agentContextLookupKey);
33708
+ if (input.replacedLookupKey && input.replacedLookupKey !== input.targetLookupKey) staleLookupKeys.add(input.replacedLookupKey);
33709
+ for (const agentContextLookupKey of staleLookupKeys) nextState = removeConversationExecutionState({
33710
+ agentContextLookupKey,
33711
+ state: nextState
33712
+ });
33713
+ return upsertConversationExecutionState({
33714
+ state: nextState,
33715
+ executionState: {
33716
+ ...input.executionState,
33717
+ agentContextLookupKey: input.targetLookupKey
33718
+ }
33719
+ });
33720
+ }
33721
+
33722
+ //#endregion
33723
+ //#region src/local-service/dispatch/execute-dispatch-observation.ts
33724
+ function resolveAdapterTelemetry(dispatchResult) {
33725
+ if (!dispatchResult.dispatched) return null;
33726
+ return dispatchResult.adapterResult.telemetry ?? null;
33727
+ }
33728
+ function buildRuntimeObservationPayload(input) {
33729
+ const telemetry = resolveAdapterTelemetry(input.runtimeResult.dispatchResult);
33730
+ const runtimeCompletedAtMs = Date.now();
33731
+ const runtimeTelemetryPayload = telemetry === null ? {} : buildAdapterRuntimeObservationPayload(telemetry);
33732
+ return {
33733
+ attemptId: input.runtimeResult.resultPayload.attemptId,
33734
+ daemonWorkingDirectory: input.daemonWorkingDirectory,
33735
+ dispatchId: input.dispatchId,
33736
+ ..."errorCode" in input.resultPayload && input.resultPayload.errorCode ? { errorCode: input.resultPayload.errorCode } : {},
33737
+ providerRuntimeWorkingDirectory: input.providerRuntimeWorkingDirectory,
33738
+ result: input.resultPayload.status,
33739
+ runtimeDurationMs: runtimeCompletedAtMs - input.runtimeStartedAtMs,
33740
+ taskId: input.taskId,
33741
+ ...input.deliveryRecoveryReason ? { deliveryRecoveryReason: input.deliveryRecoveryReason } : {},
33742
+ ...runtimeTelemetryPayload
33743
+ };
33744
+ }
33745
+ function buildAdapterRuntimeObservationPayload(telemetry) {
33746
+ const timeToMetric = (tsMs) => {
33747
+ return tsMs === void 0 || tsMs === null ? null : tsMs - telemetry.invokedAtMs;
33748
+ };
33749
+ const adapterDurationMs = timeToMetric(telemetry.completedAtMs);
33750
+ const timeToFirstOutputMs = timeToMetric(telemetry.firstOutputAtMs);
33751
+ const timeToFirstStderrMs = timeToMetric(telemetry.firstStderrAtMs);
33752
+ const timeToFirstStdoutMs = timeToMetric(telemetry.firstStdoutAtMs);
33753
+ const timeToProcessSpawnMs = timeToMetric(telemetry.processSpawnedAtMs);
33754
+ const timeToStdinClosedMs = timeToMetric(telemetry.stdinClosedAtMs);
33755
+ return {
33756
+ ...adapterDurationMs === null ? {} : { adapterDurationMs },
33757
+ ...telemetry.contextHealed === void 0 ? {} : { contextHealed: telemetry.contextHealed },
33758
+ resumedContext: telemetry.resumedContext,
33759
+ ...timeToFirstOutputMs === null ? {} : { timeToFirstOutputMs },
33760
+ ...timeToFirstStderrMs === null ? {} : { timeToFirstStderrMs },
33761
+ ...timeToFirstStdoutMs === null ? {} : { timeToFirstStdoutMs },
33762
+ ...timeToProcessSpawnMs === null ? {} : { timeToProcessSpawnMs },
33763
+ ...telemetry.processId === void 0 ? {} : { providerProcessId: telemetry.processId },
33764
+ ...timeToStdinClosedMs === null ? {} : { timeToStdinClosedMs },
33765
+ ...telemetry.timeoutTriggeredAtMs === void 0 ? {} : { providerTimedOut: true },
33766
+ ...telemetry.exitCode === void 0 ? {} : { providerExitCode: telemetry.exitCode },
33767
+ ...telemetry.exitSignal === void 0 ? {} : { providerExitSignal: telemetry.exitSignal }
33768
+ };
33769
+ }
33770
+ function emitProviderRuntimePhaseLine(input) {
33771
+ const sinceRuntimeStartedMs = input.event.tsMs - input.runtimeStartedAtMs;
33772
+ const basePayload = {
33773
+ agentControllerRef: input.agentControllerRef,
33774
+ dispatchId: input.dispatchId,
33775
+ phase: input.event.phase,
33776
+ processId: "processId" in input.event ? input.event.processId : null,
33777
+ sinceRuntimeStartedMs,
33778
+ targetProfileId: input.targetProfileId,
33779
+ taskId: input.taskId
33780
+ };
33781
+ switch (input.event.phase) {
33782
+ case "process_spawned":
33783
+ emitRunLine({
33784
+ presenter: input.presenter,
33785
+ code: "daemon.run.provider_process_spawned",
33786
+ text: `provider process spawned for task ${input.taskId}`,
33787
+ payload: basePayload
33788
+ });
33789
+ return;
33790
+ case "stdin_closed":
33791
+ emitRunLine({
33792
+ presenter: input.presenter,
33793
+ code: "daemon.run.provider_input_written",
33794
+ text: `provider input written for task ${input.taskId}`,
33795
+ payload: basePayload
33796
+ });
33797
+ return;
33798
+ case "first_stdout":
33799
+ emitRunLine({
33800
+ presenter: input.presenter,
33801
+ code: "daemon.run.provider_first_stdout",
33802
+ text: `provider first stdout observed for task ${input.taskId}`,
33803
+ payload: basePayload
33804
+ });
33805
+ return;
33806
+ case "first_stderr":
33807
+ emitRunLine({
33808
+ presenter: input.presenter,
33809
+ code: "daemon.run.provider_first_stderr",
33810
+ text: `provider first stderr observed for task ${input.taskId}`,
33811
+ payload: basePayload
33812
+ });
33813
+ return;
33814
+ case "timeout_triggered":
33815
+ emitRunLine({
33816
+ presenter: input.presenter,
33817
+ code: "daemon.run.provider_timeout_triggered",
33818
+ text: `provider timeout triggered for task ${input.taskId}`,
33819
+ payload: basePayload
33820
+ });
33821
+ return;
33822
+ case "process_exit":
33823
+ emitRunLine({
33824
+ presenter: input.presenter,
33825
+ code: "daemon.run.provider_process_exit",
33826
+ text: `provider process exited for task ${input.taskId}`,
33827
+ payload: {
33828
+ ...basePayload,
33829
+ exitCode: input.event.exitCode,
33830
+ exitSignal: input.event.signal
33831
+ }
33832
+ });
33833
+ return;
33834
+ case "provider_conversation_observed":
33835
+ emitRunLine({
33836
+ presenter: input.presenter,
33837
+ code: "daemon.run.provider_conversation_observed",
33838
+ text: `provider conversation observed for task ${input.taskId}`,
33839
+ payload: {
33840
+ ...basePayload,
33841
+ agentControllerConversationId: input.event.agentControllerConversationId
33842
+ }
33843
+ });
33844
+ return;
33845
+ default: return;
33846
+ }
33847
+ }
33848
+ function emitContinuityWarningIfNeeded(input) {
33849
+ if (!input.continuityObservation?.shouldWarn) return;
33850
+ emitRunLine({
33851
+ presenter: input.presenter,
33852
+ code: "daemon.run.continuity_warning",
33853
+ text: `implicit conversation rotation detected for task ${input.parsedTask.taskId}; ATS adopted the new context id`,
33854
+ payload: {
33855
+ agentControllerRef: input.parsedTask.agentControllerRef,
33856
+ dispatchId: input.parsedTask.dispatchId,
33857
+ existingContextId: input.continuityObservation.existingContextId,
33858
+ resolvedContextId: input.continuityObservation.resolvedContextId,
33859
+ status: input.continuityObservation.status,
33860
+ targetProfileId: input.parsedTask.targetProfileId,
33861
+ taskId: input.parsedTask.taskId
33862
+ }
33863
+ });
33864
+ }
33865
+ function emitRuntimeObservationSummaryLine(input) {
33866
+ const telemetry = resolveAdapterTelemetry(input.runtimeResult.dispatchResult);
33867
+ emitRunLine({
33868
+ presenter: input.presenter,
33869
+ code: "daemon.run.runtime_result_observed",
33870
+ text: `runtime result observed for task ${input.taskId}`,
33871
+ payload: {
33872
+ agentControllerRef: input.agentControllerRef,
33873
+ dispatchId: input.dispatchId,
33874
+ hasTelemetry: telemetry !== null,
33875
+ ...telemetry === null ? {} : {
33876
+ hasExitCode: telemetry.exitCode !== void 0,
33877
+ hasFirstOutputAtMs: telemetry.firstOutputAtMs !== void 0,
33878
+ hasFirstStderrAtMs: telemetry.firstStderrAtMs !== void 0,
33879
+ hasFirstStdoutAtMs: telemetry.firstStdoutAtMs !== void 0,
33880
+ hasInvokedAtMs: telemetry.invokedAtMs !== void 0,
33881
+ hasProcessId: telemetry.processId !== void 0,
33882
+ hasProcessSpawnedAtMs: telemetry.processSpawnedAtMs !== void 0,
33883
+ hasStdinClosedAtMs: telemetry.stdinClosedAtMs !== void 0,
33884
+ hasStreamingMode: telemetry.streamingMode !== void 0,
33885
+ resumedContext: telemetry.resumedContext
33886
+ },
33887
+ resultStatus: input.runtimeResult.resultPayload.status,
33888
+ targetProfileId: input.targetProfileId,
33889
+ taskId: input.taskId
33890
+ }
33891
+ });
33892
+ }
33893
+ function summarizeTaskResultPayload(payload) {
33894
+ if (payload.status === "failed") return {
33895
+ errorCode: payload.errorCode ?? null,
33896
+ errorMessage: payload.errorMessage ?? null,
33897
+ result: "failed"
33898
+ };
33899
+ if (payload.status === "partial_success") return {
33900
+ errorCode: payload.errorCode ?? null,
33901
+ errorMessage: payload.errorMessage ?? null,
33902
+ result: "partial_success"
33903
+ };
33904
+ return {
33905
+ errorCode: null,
33906
+ errorMessage: null,
33907
+ result: "success"
33908
+ };
33909
+ }
33910
+ function emitDispatchLocalPhaseJournalEvent(input) {
33911
+ const correlation = buildDispatchCorrelation({
33912
+ deliverRequest: input.deliverRequest,
33913
+ parsedTask: input.parsedTask
33914
+ });
33915
+ emitDaemonDispatchJournalEvent({
33916
+ attemptId: correlation.attemptId,
33917
+ connectionGeneration: input.deliverRequest.connectionGeneration,
33918
+ daemonSessionId: input.deliverRequest.daemonSessionId,
33919
+ dispatchId: correlation.dispatchId,
33920
+ leaseEpoch: input.deliverRequest.leaseEpoch,
33921
+ metadata: {
33922
+ phase: input.phase,
33923
+ ...input.metadata ?? {}
33924
+ },
33925
+ profileId: correlation.targetProfileId,
33926
+ result: input.result,
33927
+ taskId: correlation.taskId,
33928
+ type: "dispatch.local.phase"
33929
+ });
33930
+ }
33931
+ function buildResultDispatchJournalMetadata(payload) {
33932
+ const spaceAction = payload.spaceAction ?? null;
33933
+ const outputLength = "output" in payload ? payload.output.length : null;
33934
+ const errorCode = "errorCode" in payload ? payload.errorCode ?? null : null;
33935
+ const errorType = "errorType" in payload ? payload.errorType ?? null : null;
33936
+ const errorMessage = "errorMessage" in payload ? payload.errorMessage ?? null : null;
33937
+ return {
33938
+ agentId: payload.agentId,
33939
+ agentControllerRef: payload.agentControllerRef ?? null,
33940
+ errorCode,
33941
+ errorMessage,
33942
+ errorType,
33943
+ outputLength,
33944
+ sourceEventId: payload.sourceEventId,
33945
+ spaceActionProvenance: payload.spaceActionProvenance ?? null,
33946
+ spaceActionType: spaceAction?.type ?? null,
33947
+ suppressPublicOutcome: payload.suppressPublicOutcome ?? false,
33948
+ ...spaceAction?.type === "post_message" ? { postMessageTextLength: spaceAction.messageEnvelope.text.length } : {},
33949
+ ...spaceAction?.type === "post_status" ? {
33950
+ postStatus: spaceAction.status,
33951
+ postStatusTextLength: spaceAction.text.length
33952
+ } : {},
33953
+ ...spaceAction?.type === "stay_silent" ? { staySilentReasonLength: spaceAction.reason.length } : {}
33954
+ };
33955
+ }
33956
+
33957
+ //#endregion
33958
+ //#region src/local-service/dispatch/execute-dispatch-structured-action-repair.ts
33959
+ const STRUCTURED_SPACE_ACTION_BLOCK_HEADER_REGEX = /^\s*\r?\n?/u;
33960
+ function resolveStructuredActionRequirementFailure$1(input) {
33961
+ if (input.resolution.parseError) return {
33962
+ failureReason: input.resolution.parseError,
33963
+ kind: "repair"
33964
+ };
33965
+ if (!(input.requiresStructuredSpaceAction && !input.resolution.action)) return null;
33966
+ const payload = input.runtimeResult.resultPayload;
33967
+ if (payload.status === "failed") return {
33968
+ failureReason: resolvePublicAgentFailureReason({
33969
+ defaultReason: "The agent could not complete this reply right now.",
33970
+ errorCode: payload.errorCode,
33971
+ errorMessage: payload.errorMessage
33972
+ }) ?? "The agent could not complete this reply right now.",
33973
+ kind: "preserve_runtime_failure"
33974
+ };
33975
+ return {
33976
+ failureReason: "A valid ATS Space action is required in collaboration mode.",
33977
+ kind: "repair"
33978
+ };
33979
+ }
33980
+ function resolveStructuredActionOutputFallback(input) {
33981
+ const cleanedOutput = input.cleanedOutput.trim();
33982
+ if (cleanedOutput.length > 0) return cleanedOutput;
33983
+ switch (input.action.type) {
33984
+ case "post_message": return input.action.messageEnvelope.text;
33985
+ case "post_status": return input.action.text.trim() || `status:${input.action.status}`;
33986
+ case "stay_silent": return input.action.reason.trim() || "stay_silent";
33987
+ default: return "structured-action";
33988
+ }
33989
+ }
33990
+ function buildStructuredActionRepairPrompt$1(input) {
33991
+ const previousOutput = normalizeOptionalText$27(input.previousOutput);
33992
+ const normalizedSpaceId = normalizeOptionalText$27(input.spaceId);
33993
+ const cliEntry = normalizeOptionalText$27(input.cliEntry) ?? "ats";
33994
+ const historyCommand = normalizedSpaceId ? `${cliEntry} space history ${normalizedSpaceId} --kind text --limit 20` : `${cliEntry} space history <space-id> --kind text --limit 20`;
33995
+ const promptCommand = `${cliEntry} prompt`;
33996
+ const spaceGuideCommand = normalizedSpaceId ? `${cliEntry} space guide ${normalizedSpaceId}` : `${cliEntry} space guide <space-id>`;
33997
+ const publicationRequirement = resolveSpacePublicationRequirement(input.spaceContractSnapshot);
33998
+ return [
33999
+ "Your previous ATS Space structured action was invalid.",
34000
+ `Problem: ${input.parseError}`,
34001
+ ...previousOutput ? [
34002
+ "Your previous final answer was:",
34003
+ "```text",
34004
+ previousOutput,
34005
+ "```"
34006
+ ] : [],
34007
+ "This is a bounded repair of the public delivery action only. Do not redo the user's work.",
34008
+ "Do not change the user's intent.",
34009
+ ...SPACE_ACTION_CONTEXT_GUIDANCE_LINES,
34010
+ "ATS only consumes your final answer and at most one valid trailing ```ats-space-action``` JSON block.",
34011
+ "If an ATS Space Action CLI command is available, run that command instead of printing fallback JSON.",
34012
+ publicationRequirement.repairRequirementLine,
34013
+ ...SPACE_ACTION_TARGET_GUIDANCE_LINES,
34014
+ ...normalizeOptionalText$27(input.currentReplyToSignalId) ? [`post_message.messageEnvelope.replyToSignalId must match the current dispatch reply target: ${normalizeOptionalText$27(input.currentReplyToSignalId)}.`] : [],
34015
+ ...publicationRequirement.actionSchemaGuidanceLines,
34016
+ ...buildStructuredActionRepairSendTargetReferenceLines(input.sendTargetReferenceLines),
34017
+ `If you need recent public room context, use \`${historyCommand}\`.`,
34018
+ `If you need the ATS action rules again, read the official guidance with \`${promptCommand}\` or \`${spaceGuideCommand}\`.`,
34019
+ ...normalizedSpaceId ? [`For this room, you can inspect the current guide with \`${spaceGuideCommand}\`.`] : [],
34020
+ ...buildStructuredActionRepairCompletionLines({
34021
+ cliEntry,
34022
+ publicationRequirement
34023
+ })
34024
+ ].join("\n");
34025
+ }
34026
+ function buildStructuredActionRepairCompletionLines(input) {
34027
+ return [
34028
+ "Repair completion rule:",
34029
+ buildStructuredActionRepairPrimaryCommandLine(input),
34030
+ "If the command cannot run, finish with the corrected public answer followed by exactly one valid trailing ```ats-space-action``` block.",
34031
+ "Do not finish with an explanation of what you will do."
34032
+ ];
34033
+ }
34034
+ function buildStructuredActionRepairPrimaryCommandLine(input) {
34035
+ if (input.publicationRequirement.allowedActions.includes("post_message")) return `For a normal reply, run \`${input.cliEntry} space action reply "corrected public message"\` now and wait for it to finish.`;
34036
+ if (input.publicationRequirement.allowedActions.includes("post_status")) return `For a final status, run \`${input.cliEntry} space action status done "short completion update"\` now and wait for it to finish.`;
34037
+ if (input.publicationRequirement.allowedActions.includes("stay_silent")) return `If no public reply is needed, run \`${input.cliEntry} space action silent --reason "reason"\` now and wait for it to finish.`;
34038
+ return `Run \`${input.cliEntry} prompt space-action --raw\` now and return one valid trailing ats-space-action block.`;
34039
+ }
34040
+ function buildStructuredActionRepairSendTargetReferenceLines(sendTargetReferenceLines) {
34041
+ if (!(sendTargetReferenceLines && sendTargetReferenceLines.length > 0)) return [];
34042
+ return ["Current send target reference:", ...sendTargetReferenceLines.map((line) => line)];
34043
+ }
34044
+ function resolveStructuredActionRepairPreviousOutput(runtimeResult) {
34045
+ const payload = runtimeResult.resultPayload;
34046
+ if (payload.status !== "success" && payload.status !== "partial_success") return null;
34047
+ return normalizeOptionalText$27(payload.output);
34048
+ }
34049
+ function resolveStructuredActionRepairContinuation$1(input) {
34050
+ const contextDelta = resolveDispatchContextDeltaFromRuntimeResult(input.runtimeResult.dispatchResult);
34051
+ return {
34052
+ contextId: normalizeOptionalContextId(input.runtimeResult.contextResolution?.agentControllerConversationId ?? contextDelta?.agentControllerConversationId ?? null) ?? null,
34053
+ agentControllerConversationOverride: input.runtimeResult.contextResolution?.agentControllerConversation ?? contextDelta?.agentControllerConversation ?? input.agentControllerConversationOverride ?? null
34054
+ };
34055
+ }
34056
+ function buildSyntheticStructuredSpaceActionRepairResult$1(input) {
34057
+ const payload = input.runtimeResult.resultPayload;
34058
+ if (payload.status !== "success" && payload.status !== "partial_success") return null;
34059
+ const repairedAction = attemptLocalStructuredSpaceActionRepair(payload.output);
34060
+ if (!repairedAction) return null;
34061
+ const candidate = resolveTrailingStructuredSpaceActionCandidate(payload.output);
34062
+ return {
34063
+ ...input.runtimeResult,
34064
+ resultPayload: {
34065
+ ...payload,
34066
+ output: resolveStructuredActionOutputFallback({
34067
+ action: repairedAction,
34068
+ cleanedOutput: candidate?.cleanedOutput ?? payload.output
34069
+ }),
34070
+ spaceAction: repairedAction
34071
+ }
34072
+ };
34073
+ }
34074
+ function attemptLocalStructuredSpaceActionRepair(output) {
34075
+ const candidate = resolveTrailingStructuredSpaceActionCandidate(output);
34076
+ if (!candidate) return;
34077
+ const parsedBlock = tryParseStructuredSpaceActionBlockInput(candidate.blockText);
34078
+ if (!(parsedBlock.actionInput && !parsedBlock.parseError)) return;
34079
+ const normalizedAction = normalizeAtsSpaceEgressActionInput(hydrateAtsSpaceEgressActionInputFromCleanedOutput({
34080
+ action: parsedBlock.actionInput,
34081
+ cleanedOutput: candidate.cleanedOutput
34082
+ }));
34083
+ const parsedAction = atsSpaceEgressActionSchema.safeParse(normalizedAction);
34084
+ if (!parsedAction.success) return;
34085
+ return parsedAction.data;
34086
+ }
34087
+ function resolveTrailingStructuredSpaceActionCandidate(output) {
34088
+ const normalizedOutput = typeof output === "string" ? output : "";
34089
+ const markerIndex = normalizedOutput.lastIndexOf("```ats-space-action");
34090
+ if (markerIndex < 0) return null;
34091
+ const afterMarker = normalizedOutput.slice(markerIndex + 19);
34092
+ const blockStartOffset = STRUCTURED_SPACE_ACTION_BLOCK_HEADER_REGEX.exec(afterMarker)?.[0].length ?? 0;
34093
+ let blockText = afterMarker.slice(blockStartOffset).trim();
34094
+ if (blockText.endsWith("```")) blockText = blockText.slice(0, -3).trimEnd();
34095
+ if (blockText.length === 0) return null;
34096
+ return {
34097
+ blockText,
34098
+ cleanedOutput: normalizedOutput.slice(0, markerIndex).trimEnd()
34099
+ };
34100
+ }
34101
+ function buildInvalidStructuredActionOutputPreview(runtimeResult) {
34102
+ const payload = runtimeResult.resultPayload;
34103
+ if (payload.status !== "success" && payload.status !== "partial_success") return null;
34104
+ const normalizedOutput = normalizeOptionalText$27(payload.output);
34105
+ if (!normalizedOutput) return null;
34106
+ if (normalizedOutput.length <= 180) return normalizedOutput;
34107
+ return `${normalizedOutput.slice(0, 177).trimEnd()}...`;
34108
+ }
34109
+ function coerceRuntimeResultToStructuredActionFailure$1(input) {
34110
+ const payload = input.runtimeResult.resultPayload;
34111
+ const normalizedDiagnostics = input.diagnostics ? {
34112
+ ...input.diagnostics,
34113
+ publicFailureReason: input.diagnostics.publicFailureReason ?? normalizeOptionalText$27(input.failureReason)
34114
+ } : null;
34115
+ const normalizedPayload = atsdTaskResultPayloadSchema.safeParse({
34116
+ status: "failed",
34117
+ attemptId: payload.attemptId,
34118
+ taskId: payload.taskId,
34119
+ sourceEventId: payload.sourceEventId,
34120
+ agentId: payload.agentId,
34121
+ deduped: payload.deduped,
34122
+ ...payload.agentControllerRef ? { agentControllerRef: payload.agentControllerRef } : {},
34123
+ ...payload.agentControllerConversationId ? { agentControllerConversationId: payload.agentControllerConversationId } : {},
34124
+ ...payload.telemetry ? { telemetry: payload.telemetry } : {},
34125
+ ...payload.agentControllerConversation ? { agentControllerConversation: payload.agentControllerConversation } : {},
34126
+ ...payload.bootstrapTemplateFacts ? { bootstrapTemplateFacts: payload.bootstrapTemplateFacts } : {},
34127
+ ...payload.dispatchExecution ? { dispatchExecution: payload.dispatchExecution } : {},
34128
+ ...normalizedDiagnostics ? { spaceActionFailureDiagnostics: normalizedDiagnostics } : {},
34129
+ errorCode: "ats.space_action.repair_failed",
34130
+ errorMessage: input.failureReason,
34131
+ errorType: "policy"
34132
+ });
34133
+ if (normalizedPayload.success) return normalizedPayload.data;
34134
+ return {
34135
+ status: "failed",
34136
+ attemptId: payload.attemptId,
34137
+ taskId: payload.taskId,
34138
+ sourceEventId: payload.sourceEventId,
34139
+ agentId: payload.agentId,
34140
+ deduped: payload.deduped,
34141
+ ...payload.agentControllerRef ? { agentControllerRef: payload.agentControllerRef } : {},
34142
+ ...normalizedDiagnostics ? { spaceActionFailureDiagnostics: normalizedDiagnostics } : {},
34143
+ errorCode: "ats.space_action.repair_failed",
34144
+ errorMessage: input.failureReason,
34145
+ errorType: "policy"
34146
+ };
34147
+ }
34148
+
33494
34149
  //#endregion
33495
34150
  //#region src/space/cli-space-api.ts
33496
34151
  function createCliSpaceApi(baseUrl) {
@@ -33564,11 +34219,17 @@ function normalizeTargetProfileName(value) {
33564
34219
 
33565
34220
  //#endregion
33566
34221
  //#region src/local-service/dispatch/execute-dispatch-task.ts
33567
- const BOOTSTRAP_IDLE_STALE_MS = 1440 * 60 * 1e3;
33568
- const BOOTSTRAP_DISPATCH_STALE_THRESHOLD = 12;
34222
+ const markBootstrapInjectedContext = markBootstrapInjectedContext$1;
34223
+ const reconcileBootstrapInjectedContextAfterDispatch = reconcileBootstrapInjectedContextAfterDispatch$1;
34224
+ const resolveBootstrapPlan = resolveBootstrapPlan$1;
34225
+ const rollbackBootstrapExecutionStateAfterDispatchFailure = rollbackBootstrapExecutionStateAfterDispatchFailure$1;
34226
+ const buildStructuredActionRepairPrompt = buildStructuredActionRepairPrompt$1;
34227
+ const buildSyntheticStructuredSpaceActionRepairResult = buildSyntheticStructuredSpaceActionRepairResult$1;
34228
+ const coerceRuntimeResultToStructuredActionFailure = coerceRuntimeResultToStructuredActionFailure$1;
34229
+ const resolveStructuredActionRepairContinuation = resolveStructuredActionRepairContinuation$1;
34230
+ const resolveStructuredActionRequirementFailure = resolveStructuredActionRequirementFailure$1;
33569
34231
  const CLI_SPACE_ACTION_RECORD_POLL_INTERVAL_MS = 25;
33570
34232
  const CLI_SPACE_ACTION_RECORD_RUNTIME_COMPLETION_GRACE_MS = 1500;
33571
- const STRUCTURED_SPACE_ACTION_BLOCK_HEADER_REGEX = /^\s*\r?\n?/u;
33572
34233
  function enqueueDispatchDeliverFrame(input) {
33573
34234
  const currentSocketRef = input.currentSocketRef ?? {
33574
34235
  connectionGeneration: normalizePositiveInteger(input.payload.connectionGeneration),
@@ -35733,26 +36394,6 @@ function resolveStructuredSpaceActionFromRuntimePayload(runtimeResult) {
35733
36394
  parseError: extraction.parseError
35734
36395
  };
35735
36396
  }
35736
- function resolveStructuredActionRequirementFailure(input) {
35737
- if (input.resolution.parseError) return {
35738
- failureReason: input.resolution.parseError,
35739
- kind: "repair"
35740
- };
35741
- if (!(input.requiresStructuredSpaceAction && !input.resolution.action)) return null;
35742
- const payload = input.runtimeResult.resultPayload;
35743
- if (payload.status === "failed") return {
35744
- failureReason: resolvePublicAgentFailureReason({
35745
- defaultReason: "The agent could not complete this reply right now.",
35746
- errorCode: payload.errorCode,
35747
- errorMessage: payload.errorMessage
35748
- }) ?? "The agent could not complete this reply right now.",
35749
- kind: "preserve_runtime_failure"
35750
- };
35751
- return {
35752
- failureReason: "A valid ATS Space action is required in collaboration mode.",
35753
- kind: "repair"
35754
- };
35755
- }
35756
36397
  function applyStructuredSpaceActionResolutionToRuntimePayload(input) {
35757
36398
  const payload = input.runtimeResult.resultPayload;
35758
36399
  if (payload.status !== "success" && payload.status !== "partial_success") return input.runtimeResult;
@@ -35781,86 +36422,10 @@ function resolveStructuredSpaceActionProvenance(input) {
35781
36422
  if (!input.resolvedSpaceAction) return;
35782
36423
  return input.runtimeResult.resultPayload.spaceActionProvenance ?? "direct";
35783
36424
  }
35784
- function resolveStructuredActionOutputFallback(input) {
35785
- const cleanedOutput = input.cleanedOutput.trim();
35786
- if (cleanedOutput.length > 0) return cleanedOutput;
35787
- switch (input.action.type) {
35788
- case "post_message": return input.action.messageEnvelope.text;
35789
- case "post_status": return input.action.text.trim() || `status:${input.action.status}`;
35790
- case "stay_silent": return input.action.reason.trim() || "stay_silent";
35791
- default: return "structured-action";
35792
- }
35793
- }
35794
36425
  function resolvePostMessageInputKind(input) {
35795
36426
  if (input.runtimeResult.resultPayload.spaceAction?.type === "post_message") return "direct_payload";
35796
36427
  return input.structuredSpaceActionResolution.carrierKind === "trailing_json" ? "trailing_json" : "fenced_block";
35797
36428
  }
35798
- function buildStructuredActionRepairPrompt(input) {
35799
- const previousOutput = normalizeOptionalText$27(input.previousOutput);
35800
- const normalizedSpaceId = normalizeOptionalText$27(input.spaceId);
35801
- const cliEntry = normalizeOptionalText$27(input.cliEntry) ?? "ats";
35802
- const historyCommand = normalizedSpaceId ? `${cliEntry} space history ${normalizedSpaceId} --kind text --limit 20` : `${cliEntry} space history <space-id> --kind text --limit 20`;
35803
- const promptCommand = `${cliEntry} prompt`;
35804
- const spaceGuideCommand = normalizedSpaceId ? `${cliEntry} space guide ${normalizedSpaceId}` : `${cliEntry} space guide <space-id>`;
35805
- const publicationRequirement = resolveSpacePublicationRequirement(input.spaceContractSnapshot);
35806
- return [
35807
- "Your previous ATS Space structured action was invalid.",
35808
- `Problem: ${input.parseError}`,
35809
- ...previousOutput ? [
35810
- "Your previous final answer was:",
35811
- "```text",
35812
- previousOutput,
35813
- "```"
35814
- ] : [],
35815
- "This is a bounded repair of the public delivery action only. Do not redo the user's work.",
35816
- "Do not change the user's intent.",
35817
- ...SPACE_ACTION_CONTEXT_GUIDANCE_LINES,
35818
- "ATS only consumes your final answer and at most one valid trailing ```ats-space-action``` JSON block.",
35819
- "If an ATS Space Action CLI command is available, run that command instead of printing fallback JSON.",
35820
- publicationRequirement.repairRequirementLine,
35821
- ...SPACE_ACTION_TARGET_GUIDANCE_LINES,
35822
- ...normalizeOptionalText$27(input.currentReplyToSignalId) ? [`post_message.messageEnvelope.replyToSignalId must match the current dispatch reply target: ${normalizeOptionalText$27(input.currentReplyToSignalId)}.`] : [],
35823
- ...publicationRequirement.actionSchemaGuidanceLines,
35824
- ...buildStructuredActionRepairSendTargetReferenceLines(input.sendTargetReferenceLines),
35825
- `If you need recent public room context, use \`${historyCommand}\`.`,
35826
- `If you need the ATS action rules again, read the official guidance with \`${promptCommand}\` or \`${spaceGuideCommand}\`.`,
35827
- ...normalizedSpaceId ? [`For this room, you can inspect the current guide with \`${spaceGuideCommand}\`.`] : [],
35828
- ...buildStructuredActionRepairCompletionLines({
35829
- cliEntry,
35830
- publicationRequirement
35831
- })
35832
- ].join("\n");
35833
- }
35834
- function buildStructuredActionRepairCompletionLines(input) {
35835
- return [
35836
- "Repair completion rule:",
35837
- buildStructuredActionRepairPrimaryCommandLine(input),
35838
- "If the command cannot run, finish with the corrected public answer followed by exactly one valid trailing ```ats-space-action``` block.",
35839
- "Do not finish with an explanation of what you will do."
35840
- ];
35841
- }
35842
- function buildStructuredActionRepairPrimaryCommandLine(input) {
35843
- if (input.publicationRequirement.allowedActions.includes("post_message")) return `For a normal reply, run \`${input.cliEntry} space action reply "corrected public message"\` now and wait for it to finish.`;
35844
- if (input.publicationRequirement.allowedActions.includes("post_status")) return `For a final status, run \`${input.cliEntry} space action status done "short completion update"\` now and wait for it to finish.`;
35845
- if (input.publicationRequirement.allowedActions.includes("stay_silent")) return `If no public reply is needed, run \`${input.cliEntry} space action silent --reason "reason"\` now and wait for it to finish.`;
35846
- return `Run \`${input.cliEntry} prompt space-action --raw\` now and return one valid trailing ats-space-action block.`;
35847
- }
35848
- function buildStructuredActionRepairSendTargetReferenceLines(sendTargetReferenceLines) {
35849
- if (!(sendTargetReferenceLines && sendTargetReferenceLines.length > 0)) return [];
35850
- return ["Current send target reference:", ...sendTargetReferenceLines.map((line) => line)];
35851
- }
35852
- function resolveStructuredActionRepairPreviousOutput(runtimeResult) {
35853
- const payload = runtimeResult.resultPayload;
35854
- if (payload.status !== "success" && payload.status !== "partial_success") return null;
35855
- return normalizeOptionalText$27(payload.output);
35856
- }
35857
- function resolveStructuredActionRepairContinuation(input) {
35858
- const contextDelta = resolveDispatchContextDeltaFromRuntimeResult(input.runtimeResult.dispatchResult);
35859
- return {
35860
- contextId: normalizeOptionalContextId(input.runtimeResult.contextResolution?.agentControllerConversationId ?? contextDelta?.agentControllerConversationId ?? null) ?? null,
35861
- agentControllerConversationOverride: input.runtimeResult.contextResolution?.agentControllerConversation ?? contextDelta?.agentControllerConversation ?? input.agentControllerConversationOverride ?? null
35862
- };
35863
- }
35864
36429
  function runDispatchRuntimeExecution(input) {
35865
36430
  return runRuntimeTask({
35866
36431
  ...input.agentControllerConversationOverride ? { agentContextOverride: {
@@ -35933,98 +36498,6 @@ function buildDispatchRuntimeTask(input) {
35933
36498
  triggerMode: input.parsedTask.triggerMode
35934
36499
  };
35935
36500
  }
35936
- function buildSyntheticStructuredSpaceActionRepairResult(input) {
35937
- const payload = input.runtimeResult.resultPayload;
35938
- if (payload.status !== "success" && payload.status !== "partial_success") return null;
35939
- const repairedAction = attemptLocalStructuredSpaceActionRepair(payload.output);
35940
- if (!repairedAction) return null;
35941
- const candidate = resolveTrailingStructuredSpaceActionCandidate(payload.output);
35942
- return {
35943
- ...input.runtimeResult,
35944
- resultPayload: {
35945
- ...payload,
35946
- output: resolveStructuredActionOutputFallback({
35947
- action: repairedAction,
35948
- cleanedOutput: candidate?.cleanedOutput ?? payload.output
35949
- }),
35950
- spaceAction: repairedAction
35951
- }
35952
- };
35953
- }
35954
- function attemptLocalStructuredSpaceActionRepair(output) {
35955
- const candidate = resolveTrailingStructuredSpaceActionCandidate(output);
35956
- if (!candidate) return;
35957
- const parsedBlock = tryParseStructuredSpaceActionBlockInput(candidate.blockText);
35958
- if (!(parsedBlock.actionInput && !parsedBlock.parseError)) return;
35959
- const normalizedAction = normalizeAtsSpaceEgressActionInput(hydrateAtsSpaceEgressActionInputFromCleanedOutput({
35960
- action: parsedBlock.actionInput,
35961
- cleanedOutput: candidate.cleanedOutput
35962
- }));
35963
- const parsedAction = atsSpaceEgressActionSchema.safeParse(normalizedAction);
35964
- if (!parsedAction.success) return;
35965
- return parsedAction.data;
35966
- }
35967
- function resolveTrailingStructuredSpaceActionCandidate(output) {
35968
- const normalizedOutput = typeof output === "string" ? output : "";
35969
- const markerIndex = normalizedOutput.lastIndexOf("```ats-space-action");
35970
- if (markerIndex < 0) return null;
35971
- const afterMarker = normalizedOutput.slice(markerIndex + 19);
35972
- const blockStartOffset = STRUCTURED_SPACE_ACTION_BLOCK_HEADER_REGEX.exec(afterMarker)?.[0].length ?? 0;
35973
- let blockText = afterMarker.slice(blockStartOffset).trim();
35974
- if (blockText.endsWith("```")) blockText = blockText.slice(0, -3).trimEnd();
35975
- if (blockText.length === 0) return null;
35976
- return {
35977
- blockText,
35978
- cleanedOutput: normalizedOutput.slice(0, markerIndex).trimEnd()
35979
- };
35980
- }
35981
- function buildInvalidStructuredActionOutputPreview(runtimeResult) {
35982
- const payload = runtimeResult.resultPayload;
35983
- if (payload.status !== "success" && payload.status !== "partial_success") return null;
35984
- const normalizedOutput = normalizeOptionalText$27(payload.output);
35985
- if (!normalizedOutput) return null;
35986
- if (normalizedOutput.length <= 180) return normalizedOutput;
35987
- return `${normalizedOutput.slice(0, 177).trimEnd()}...`;
35988
- }
35989
- function coerceRuntimeResultToStructuredActionFailure(input) {
35990
- const payload = input.runtimeResult.resultPayload;
35991
- const normalizedDiagnostics = input.diagnostics ? {
35992
- ...input.diagnostics,
35993
- publicFailureReason: input.diagnostics.publicFailureReason ?? normalizeOptionalText$27(input.failureReason)
35994
- } : null;
35995
- const normalizedPayload = atsdTaskResultPayloadSchema.safeParse({
35996
- status: "failed",
35997
- attemptId: payload.attemptId,
35998
- taskId: payload.taskId,
35999
- sourceEventId: payload.sourceEventId,
36000
- agentId: payload.agentId,
36001
- deduped: payload.deduped,
36002
- ...payload.agentControllerRef ? { agentControllerRef: payload.agentControllerRef } : {},
36003
- ...payload.agentControllerConversationId ? { agentControllerConversationId: payload.agentControllerConversationId } : {},
36004
- ...payload.telemetry ? { telemetry: payload.telemetry } : {},
36005
- ...payload.agentControllerConversation ? { agentControllerConversation: payload.agentControllerConversation } : {},
36006
- ...payload.bootstrapTemplateFacts ? { bootstrapTemplateFacts: payload.bootstrapTemplateFacts } : {},
36007
- ...payload.dispatchExecution ? { dispatchExecution: payload.dispatchExecution } : {},
36008
- ...normalizedDiagnostics ? { spaceActionFailureDiagnostics: normalizedDiagnostics } : {},
36009
- errorCode: "ats.space_action.repair_failed",
36010
- errorMessage: input.failureReason,
36011
- errorType: "policy"
36012
- });
36013
- if (normalizedPayload.success) return normalizedPayload.data;
36014
- return {
36015
- status: "failed",
36016
- attemptId: payload.attemptId,
36017
- taskId: payload.taskId,
36018
- sourceEventId: payload.sourceEventId,
36019
- agentId: payload.agentId,
36020
- deduped: payload.deduped,
36021
- ...payload.agentControllerRef ? { agentControllerRef: payload.agentControllerRef } : {},
36022
- ...normalizedDiagnostics ? { spaceActionFailureDiagnostics: normalizedDiagnostics } : {},
36023
- errorCode: "ats.space_action.repair_failed",
36024
- errorMessage: input.failureReason,
36025
- errorType: "policy"
36026
- };
36027
- }
36028
36501
  function maybeRejectStaleLease(input) {
36029
36502
  if (input.activeLeaseEpoch === void 0 || input.activeLeaseEpoch === input.deliverRequest.leaseEpoch) return null;
36030
36503
  return sendDispatchRejectionResult({
@@ -36148,140 +36621,6 @@ function sendDispatchRejectionResult(input) {
36148
36621
  taskId: input.payload.taskId
36149
36622
  });
36150
36623
  }
36151
- function resolveCurrentConversationPolicy(routeConfig) {
36152
- return { ...routeConfig?.conversationPolicy ?? {} };
36153
- }
36154
- const isBootstrapExecutionStateMissing = (executionState) => !(executionState.bootstrapLastAppliedAt && executionState.lastAppliedTemplateVersion && executionState.lastAppliedContentFingerprint);
36155
- const isBootstrapIdleStale = (lastActivatedAt, nowMs) => {
36156
- if (!lastActivatedAt) return false;
36157
- const lastActivatedMs = Date.parse(lastActivatedAt);
36158
- if (!Number.isFinite(lastActivatedMs)) return false;
36159
- return nowMs - lastActivatedMs >= BOOTSTRAP_IDLE_STALE_MS;
36160
- };
36161
- function resolveBootstrapPlan(input) {
36162
- if (input.localRuntimeContextPlan.status === "recreate") return {
36163
- reason: "compatibility_recreate",
36164
- shouldInject: true
36165
- };
36166
- if (!input.executionState) return {
36167
- reason: "missing_bootstrap_state",
36168
- shouldInject: true
36169
- };
36170
- if (input.executionState.pendingBootstrapReason === "context_healed") return {
36171
- reason: "context_healed",
36172
- shouldInject: true
36173
- };
36174
- if (isBootstrapExecutionStateMissing(input.executionState)) return {
36175
- reason: "missing_bootstrap_state",
36176
- shouldInject: true
36177
- };
36178
- if (input.executionState.lastAppliedTemplateVersion !== input.bootstrapTemplateFacts.templateVersion || input.executionState.lastAppliedContentFingerprint !== input.bootstrapTemplateFacts.contentFingerprint) return {
36179
- reason: "template_changed",
36180
- shouldInject: true
36181
- };
36182
- if (isBootstrapIdleStale(input.executionState.bootstrapLastActivatedAt, input.nowMs)) return {
36183
- reason: "idle_stale",
36184
- shouldInject: true
36185
- };
36186
- if (input.executionState.dispatchesSinceBootstrapApplied >= BOOTSTRAP_DISPATCH_STALE_THRESHOLD) return {
36187
- reason: "dispatch_count_stale",
36188
- shouldInject: true
36189
- };
36190
- return {
36191
- reason: null,
36192
- shouldInject: false
36193
- };
36194
- }
36195
- function markBootstrapInjectedContext(input) {
36196
- const runtimeWorkspaceFingerprint = buildRuntimeWorkspaceFingerprint(input.effectiveRuntimeWorkingDirectory);
36197
- return {
36198
- agentContextLookupKey: input.agentContextLookupKey,
36199
- activeContextId: normalizeOptionalContextId(input.existingContextId),
36200
- dispatchesSinceBootstrapApplied: 0,
36201
- bootstrapLastAppliedAt: input.nowIso,
36202
- bootstrapLastActivatedAt: input.nowIso,
36203
- lastAppliedTemplateVersion: input.bootstrapTemplateFacts.templateVersion,
36204
- lastAppliedContentFingerprint: input.bootstrapTemplateFacts.contentFingerprint,
36205
- lastRuntimeWorkspacePath: input.effectiveRuntimeWorkingDirectory,
36206
- runtimeWorkspaceFingerprint,
36207
- pendingBootstrapReason: void 0,
36208
- updatedAt: input.nowIso,
36209
- ...input.executionState?.lastResolvedAgentControllerConversation ? { lastResolvedAgentControllerConversation: { ...input.executionState.lastResolvedAgentControllerConversation } } : {}
36210
- };
36211
- }
36212
- function reconcileBootstrapInjectedContextAfterDispatch(input) {
36213
- if (!input.executionState) return null;
36214
- const runtimeWorkspaceFingerprint = buildRuntimeWorkspaceFingerprint(input.effectiveRuntimeWorkingDirectory);
36215
- const nextExecutionState = {
36216
- ...input.executionState,
36217
- bootstrapLastActivatedAt: input.nowIso,
36218
- lastRuntimeWorkspacePath: input.effectiveRuntimeWorkingDirectory,
36219
- runtimeWorkspaceFingerprint,
36220
- updatedAt: input.nowIso,
36221
- ...input.resolvedAgentControllerConversation ? { lastResolvedAgentControllerConversation: { ...input.resolvedAgentControllerConversation } } : {}
36222
- };
36223
- if (input.shouldInjectBootstrap) {
36224
- const dispatchedContextId = normalizeOptionalContextId(input.dispatchedContextId);
36225
- return {
36226
- ...nextExecutionState,
36227
- activeContextId: dispatchedContextId ?? nextExecutionState.activeContextId,
36228
- dispatchesSinceBootstrapApplied: 0,
36229
- bootstrapLastAppliedAt: nextExecutionState.bootstrapLastAppliedAt ?? input.nowIso,
36230
- bootstrapLastActivatedAt: input.nowIso,
36231
- lastAppliedTemplateVersion: input.bootstrapTemplateFacts.templateVersion,
36232
- lastAppliedContentFingerprint: input.bootstrapTemplateFacts.contentFingerprint,
36233
- pendingBootstrapReason: void 0
36234
- };
36235
- }
36236
- if (input.contextHealed) return {
36237
- ...nextExecutionState,
36238
- activeContextId: normalizeOptionalContextId(input.dispatchedContextId) ?? nextExecutionState.activeContextId,
36239
- dispatchesSinceBootstrapApplied: 0,
36240
- bootstrapLastAppliedAt: void 0,
36241
- lastAppliedTemplateVersion: void 0,
36242
- lastAppliedContentFingerprint: void 0,
36243
- pendingBootstrapReason: "context_healed"
36244
- };
36245
- if (input.continuityObservation?.status === "implicit_rotation") return {
36246
- ...nextExecutionState,
36247
- activeContextId: normalizeOptionalContextId(input.dispatchedContextId) ?? nextExecutionState.activeContextId,
36248
- dispatchesSinceBootstrapApplied: nextExecutionState.dispatchesSinceBootstrapApplied + 1,
36249
- pendingBootstrapReason: void 0
36250
- };
36251
- return {
36252
- ...nextExecutionState,
36253
- dispatchesSinceBootstrapApplied: nextExecutionState.dispatchesSinceBootstrapApplied + 1,
36254
- pendingBootstrapReason: void 0
36255
- };
36256
- }
36257
- function rollbackBootstrapExecutionStateAfterDispatchFailure(input) {
36258
- const stateWithoutCurrentLookupKey = removeConversationExecutionState({
36259
- agentContextLookupKey: input.agentContextLookupKey,
36260
- state: input.state
36261
- });
36262
- if (input.executionStateBeforeDispatch) return upsertConversationExecutionState({
36263
- state: stateWithoutCurrentLookupKey,
36264
- executionState: input.executionStateBeforeDispatch
36265
- });
36266
- return stateWithoutCurrentLookupKey;
36267
- }
36268
- function upsertConversationExecutionStateForLookupKey(input) {
36269
- let nextState = input.state;
36270
- const staleLookupKeys = /* @__PURE__ */ new Set();
36271
- if (input.executionState.agentContextLookupKey !== input.targetLookupKey) staleLookupKeys.add(input.executionState.agentContextLookupKey);
36272
- if (input.replacedLookupKey && input.replacedLookupKey !== input.targetLookupKey) staleLookupKeys.add(input.replacedLookupKey);
36273
- for (const agentContextLookupKey of staleLookupKeys) nextState = removeConversationExecutionState({
36274
- agentContextLookupKey,
36275
- state: nextState
36276
- });
36277
- return upsertConversationExecutionState({
36278
- state: nextState,
36279
- executionState: {
36280
- ...input.executionState,
36281
- agentContextLookupKey: input.targetLookupKey
36282
- }
36283
- });
36284
- }
36285
36624
  function buildDispatchExecution(input) {
36286
36625
  const effectiveObservedAgentControllerConversation = input.observedAgentControllerConversation ?? input.plannedAgentControllerConversation;
36287
36626
  let agentControllerConversationResume;
@@ -36303,277 +36642,6 @@ function buildDispatchExecution(input) {
36303
36642
  agentControllerConversationResume
36304
36643
  };
36305
36644
  }
36306
- function resolveDispatchContextIdForAgentControllerConversation(input) {
36307
- if (input.agentControllerConversationResumePlan.status !== "continue_existing") return null;
36308
- return normalizeOptionalContextId(input.agentControllerConversationOverride?.agentControllerConversationId ?? input.agentControllerConversationId ?? null);
36309
- }
36310
- function resolvePlannedAgentControllerConversation(input) {
36311
- return buildAgentControllerConversationRefFromAgentControllerConversation(input);
36312
- }
36313
- function resolveObservedDispatchAgentControllerConversation(input) {
36314
- return input.contextDelta?.agentControllerConversation ?? input.contextResolution?.agentControllerConversation ?? input.agentControllerConversationOverride ?? input.plannedAgentControllerConversation ?? null;
36315
- }
36316
- function buildAgentControllerConversationRefFromAgentControllerConversation(input) {
36317
- const conversationId = normalizeOptionalContextId(input.agentControllerConversationId);
36318
- const agentControllerRef = normalizeOptionalContextId(input.agentControllerRef);
36319
- if (!(conversationId && agentControllerRef)) return null;
36320
- if (normalizeKnownBuiltinAgentControllerId(agentControllerRef)) return buildAgentControllerConversationRef({
36321
- agentControllerRef,
36322
- agentControllerConversationKind: resolveBuiltinAgentControllerConversationKind(agentControllerRef) ?? "context",
36323
- agentControllerConversationId: conversationId
36324
- });
36325
- return buildAgentControllerConversationRef({
36326
- agentControllerRef,
36327
- agentControllerConversationKind: "context",
36328
- agentControllerConversationId: conversationId
36329
- });
36330
- }
36331
- function areSameAgentControllerConversationRef(left, right) {
36332
- if (!right) return false;
36333
- return left.agentControllerRef === right.agentControllerRef && left.agentControllerConversationKind === right.agentControllerConversationKind && left.agentControllerConversationId === right.agentControllerConversationId;
36334
- }
36335
- function normalizeOptionalContextId(contextId) {
36336
- if (typeof contextId !== "string") return null;
36337
- const normalized = contextId.trim();
36338
- return normalized.length > 0 ? normalized : null;
36339
- }
36340
- function resolveDispatchContextDeltaFromRuntimeResult(dispatchResult) {
36341
- if (!dispatchResult.dispatched) return null;
36342
- if (dispatchResult.adapterResult.status !== "success") return null;
36343
- return dispatchResult.adapterResult.contextDelta ?? null;
36344
- }
36345
- function resolveAdapterTelemetry(dispatchResult) {
36346
- if (!dispatchResult.dispatched) return null;
36347
- return dispatchResult.adapterResult.telemetry ?? null;
36348
- }
36349
- function buildRuntimeObservationPayload(input) {
36350
- const telemetry = resolveAdapterTelemetry(input.runtimeResult.dispatchResult);
36351
- const runtimeCompletedAtMs = Date.now();
36352
- const runtimeTelemetryPayload = telemetry === null ? {} : buildAdapterRuntimeObservationPayload(telemetry);
36353
- return {
36354
- attemptId: input.runtimeResult.resultPayload.attemptId,
36355
- daemonWorkingDirectory: input.daemonWorkingDirectory,
36356
- dispatchId: input.dispatchId,
36357
- ..."errorCode" in input.resultPayload && input.resultPayload.errorCode ? { errorCode: input.resultPayload.errorCode } : {},
36358
- providerRuntimeWorkingDirectory: input.providerRuntimeWorkingDirectory,
36359
- result: input.resultPayload.status,
36360
- runtimeDurationMs: runtimeCompletedAtMs - input.runtimeStartedAtMs,
36361
- taskId: input.taskId,
36362
- ...input.deliveryRecoveryReason ? { deliveryRecoveryReason: input.deliveryRecoveryReason } : {},
36363
- ...runtimeTelemetryPayload
36364
- };
36365
- }
36366
- function buildAdapterRuntimeObservationPayload(telemetry) {
36367
- const timeToMetric = (tsMs) => {
36368
- return tsMs === void 0 || tsMs === null ? null : tsMs - telemetry.invokedAtMs;
36369
- };
36370
- const adapterDurationMs = timeToMetric(telemetry.completedAtMs);
36371
- const timeToFirstOutputMs = timeToMetric(telemetry.firstOutputAtMs);
36372
- const timeToFirstStderrMs = timeToMetric(telemetry.firstStderrAtMs);
36373
- const timeToFirstStdoutMs = timeToMetric(telemetry.firstStdoutAtMs);
36374
- const timeToProcessSpawnMs = timeToMetric(telemetry.processSpawnedAtMs);
36375
- const timeToStdinClosedMs = timeToMetric(telemetry.stdinClosedAtMs);
36376
- return {
36377
- ...adapterDurationMs === null ? {} : { adapterDurationMs },
36378
- ...telemetry.contextHealed === void 0 ? {} : { contextHealed: telemetry.contextHealed },
36379
- resumedContext: telemetry.resumedContext,
36380
- ...timeToFirstOutputMs === null ? {} : { timeToFirstOutputMs },
36381
- ...timeToFirstStderrMs === null ? {} : { timeToFirstStderrMs },
36382
- ...timeToFirstStdoutMs === null ? {} : { timeToFirstStdoutMs },
36383
- ...timeToProcessSpawnMs === null ? {} : { timeToProcessSpawnMs },
36384
- ...telemetry.processId === void 0 ? {} : { providerProcessId: telemetry.processId },
36385
- ...timeToStdinClosedMs === null ? {} : { timeToStdinClosedMs },
36386
- ...telemetry.timeoutTriggeredAtMs === void 0 ? {} : { providerTimedOut: true },
36387
- ...telemetry.exitCode === void 0 ? {} : { providerExitCode: telemetry.exitCode },
36388
- ...telemetry.exitSignal === void 0 ? {} : { providerExitSignal: telemetry.exitSignal }
36389
- };
36390
- }
36391
- function emitProviderRuntimePhaseLine(input) {
36392
- const sinceRuntimeStartedMs = input.event.tsMs - input.runtimeStartedAtMs;
36393
- const basePayload = {
36394
- agentControllerRef: input.agentControllerRef,
36395
- dispatchId: input.dispatchId,
36396
- phase: input.event.phase,
36397
- processId: "processId" in input.event ? input.event.processId : null,
36398
- sinceRuntimeStartedMs,
36399
- targetProfileId: input.targetProfileId,
36400
- taskId: input.taskId
36401
- };
36402
- switch (input.event.phase) {
36403
- case "process_spawned":
36404
- emitRunLine({
36405
- presenter: input.presenter,
36406
- code: "daemon.run.provider_process_spawned",
36407
- text: `provider process spawned for task ${input.taskId}`,
36408
- payload: basePayload
36409
- });
36410
- return;
36411
- case "stdin_closed":
36412
- emitRunLine({
36413
- presenter: input.presenter,
36414
- code: "daemon.run.provider_input_written",
36415
- text: `provider input written for task ${input.taskId}`,
36416
- payload: basePayload
36417
- });
36418
- return;
36419
- case "first_stdout":
36420
- emitRunLine({
36421
- presenter: input.presenter,
36422
- code: "daemon.run.provider_first_stdout",
36423
- text: `provider first stdout observed for task ${input.taskId}`,
36424
- payload: basePayload
36425
- });
36426
- return;
36427
- case "first_stderr":
36428
- emitRunLine({
36429
- presenter: input.presenter,
36430
- code: "daemon.run.provider_first_stderr",
36431
- text: `provider first stderr observed for task ${input.taskId}`,
36432
- payload: basePayload
36433
- });
36434
- return;
36435
- case "timeout_triggered":
36436
- emitRunLine({
36437
- presenter: input.presenter,
36438
- code: "daemon.run.provider_timeout_triggered",
36439
- text: `provider timeout triggered for task ${input.taskId}`,
36440
- payload: basePayload
36441
- });
36442
- return;
36443
- case "process_exit":
36444
- emitRunLine({
36445
- presenter: input.presenter,
36446
- code: "daemon.run.provider_process_exit",
36447
- text: `provider process exited for task ${input.taskId}`,
36448
- payload: {
36449
- ...basePayload,
36450
- exitCode: input.event.exitCode,
36451
- exitSignal: input.event.signal
36452
- }
36453
- });
36454
- return;
36455
- case "provider_conversation_observed":
36456
- emitRunLine({
36457
- presenter: input.presenter,
36458
- code: "daemon.run.provider_conversation_observed",
36459
- text: `provider conversation observed for task ${input.taskId}`,
36460
- payload: {
36461
- ...basePayload,
36462
- agentControllerConversationId: input.event.agentControllerConversationId
36463
- }
36464
- });
36465
- return;
36466
- default: return;
36467
- }
36468
- }
36469
- function emitContinuityWarningIfNeeded(input) {
36470
- if (!input.continuityObservation?.shouldWarn) return;
36471
- emitRunLine({
36472
- presenter: input.presenter,
36473
- code: "daemon.run.continuity_warning",
36474
- text: `implicit conversation rotation detected for task ${input.parsedTask.taskId}; ATS adopted the new context id`,
36475
- payload: {
36476
- agentControllerRef: input.parsedTask.agentControllerRef,
36477
- dispatchId: input.parsedTask.dispatchId,
36478
- existingContextId: input.continuityObservation.existingContextId,
36479
- resolvedContextId: input.continuityObservation.resolvedContextId,
36480
- status: input.continuityObservation.status,
36481
- targetProfileId: input.parsedTask.targetProfileId,
36482
- taskId: input.parsedTask.taskId
36483
- }
36484
- });
36485
- }
36486
- function emitRuntimeObservationSummaryLine(input) {
36487
- const telemetry = resolveAdapterTelemetry(input.runtimeResult.dispatchResult);
36488
- emitRunLine({
36489
- presenter: input.presenter,
36490
- code: "daemon.run.runtime_result_observed",
36491
- text: `runtime result observed for task ${input.taskId}`,
36492
- payload: {
36493
- agentControllerRef: input.agentControllerRef,
36494
- dispatchId: input.dispatchId,
36495
- hasTelemetry: telemetry !== null,
36496
- ...telemetry === null ? {} : {
36497
- hasExitCode: telemetry.exitCode !== void 0,
36498
- hasFirstOutputAtMs: telemetry.firstOutputAtMs !== void 0,
36499
- hasFirstStderrAtMs: telemetry.firstStderrAtMs !== void 0,
36500
- hasFirstStdoutAtMs: telemetry.firstStdoutAtMs !== void 0,
36501
- hasInvokedAtMs: telemetry.invokedAtMs !== void 0,
36502
- hasProcessId: telemetry.processId !== void 0,
36503
- hasProcessSpawnedAtMs: telemetry.processSpawnedAtMs !== void 0,
36504
- hasStdinClosedAtMs: telemetry.stdinClosedAtMs !== void 0,
36505
- hasStreamingMode: telemetry.streamingMode !== void 0,
36506
- resumedContext: telemetry.resumedContext
36507
- },
36508
- resultStatus: input.runtimeResult.resultPayload.status,
36509
- targetProfileId: input.targetProfileId,
36510
- taskId: input.taskId
36511
- }
36512
- });
36513
- }
36514
- function summarizeTaskResultPayload(payload) {
36515
- if (payload.status === "failed") return {
36516
- errorCode: payload.errorCode ?? null,
36517
- errorMessage: payload.errorMessage ?? null,
36518
- result: "failed"
36519
- };
36520
- if (payload.status === "partial_success") return {
36521
- errorCode: payload.errorCode ?? null,
36522
- errorMessage: payload.errorMessage ?? null,
36523
- result: "partial_success"
36524
- };
36525
- return {
36526
- errorCode: null,
36527
- errorMessage: null,
36528
- result: "success"
36529
- };
36530
- }
36531
- function emitDispatchLocalPhaseJournalEvent(input) {
36532
- const correlation = buildDispatchCorrelation({
36533
- deliverRequest: input.deliverRequest,
36534
- parsedTask: input.parsedTask
36535
- });
36536
- emitDaemonDispatchJournalEvent({
36537
- attemptId: correlation.attemptId,
36538
- connectionGeneration: input.deliverRequest.connectionGeneration,
36539
- daemonSessionId: input.deliverRequest.daemonSessionId,
36540
- dispatchId: correlation.dispatchId,
36541
- leaseEpoch: input.deliverRequest.leaseEpoch,
36542
- metadata: {
36543
- phase: input.phase,
36544
- ...input.metadata ?? {}
36545
- },
36546
- profileId: correlation.targetProfileId,
36547
- result: input.result,
36548
- taskId: correlation.taskId,
36549
- type: "dispatch.local.phase"
36550
- });
36551
- }
36552
- function buildResultDispatchJournalMetadata(payload) {
36553
- const spaceAction = payload.spaceAction ?? null;
36554
- const outputLength = "output" in payload ? payload.output.length : null;
36555
- const errorCode = "errorCode" in payload ? payload.errorCode ?? null : null;
36556
- const errorType = "errorType" in payload ? payload.errorType ?? null : null;
36557
- const errorMessage = "errorMessage" in payload ? payload.errorMessage ?? null : null;
36558
- return {
36559
- agentId: payload.agentId,
36560
- agentControllerRef: payload.agentControllerRef ?? null,
36561
- errorCode,
36562
- errorMessage,
36563
- errorType,
36564
- outputLength,
36565
- sourceEventId: payload.sourceEventId,
36566
- spaceActionProvenance: payload.spaceActionProvenance ?? null,
36567
- spaceActionType: spaceAction?.type ?? null,
36568
- suppressPublicOutcome: payload.suppressPublicOutcome ?? false,
36569
- ...spaceAction?.type === "post_message" ? { postMessageTextLength: spaceAction.messageEnvelope.text.length } : {},
36570
- ...spaceAction?.type === "post_status" ? {
36571
- postStatus: spaceAction.status,
36572
- postStatusTextLength: spaceAction.text.length
36573
- } : {},
36574
- ...spaceAction?.type === "stay_silent" ? { staySilentReasonLength: spaceAction.reason.length } : {}
36575
- };
36576
- }
36577
36645
  function sendResultAndSummarize(input) {
36578
36646
  try {
36579
36647
  emitDispatchLifecycleTransition({
@@ -51093,11 +51161,11 @@ function handleSearchPromptReturnKeypress(state) {
51093
51161
  status: "submitted"
51094
51162
  };
51095
51163
  }
51096
- function promptSearchSelect(input) {
51164
+ function promptSearchSelect(input, streams) {
51097
51165
  return runInteractiveSearchPrompt(createSearchPromptState({
51098
51166
  ...input,
51099
51167
  mode: "single"
51100
- })).then((result) => result);
51168
+ }), streams).then((result) => result);
51101
51169
  }
51102
51170
  function promptSearchMultiselect(input, streams) {
51103
51171
  return runInteractiveSearchPrompt(createSearchPromptState({
@@ -53170,7 +53238,8 @@ async function runAgentsRepair(input) {
53170
53238
  emitAgentsOverviewIfAgent({
53171
53239
  presenter,
53172
53240
  resolvedView: runtime.resolvedView,
53173
- command: "repair"
53241
+ command: "repair",
53242
+ handled: input.presentation === "handoff"
53174
53243
  });
53175
53244
  const explicitIds = normalizeAgentIds(input.agent ?? []);
53176
53245
  const explicitInstallId = normalizeOptionalString$11(input.install);
@@ -53236,25 +53305,27 @@ async function runAgentsRepair(input) {
53236
53305
  summary
53237
53306
  };
53238
53307
  }
53239
- renderAgentsInfoCard({
53240
- presenter,
53241
- codePrefix: "agents.repair.summary.card",
53242
- title: "Agents Repaired",
53243
- rows: buildRepairSummaryRows(summary),
53244
- minContentWidth: 38
53245
- });
53246
- for (const card of buildRepairDetailCards(summary, targetStateById)) {
53247
- presenter.line({
53248
- code: `agents.repair.${card.codeSuffix}.spacer`,
53249
- text: ""
53250
- });
53308
+ if (input.presentation !== "handoff") {
53251
53309
  renderAgentsInfoCard({
53252
53310
  presenter,
53253
- codePrefix: `agents.repair.${card.codeSuffix}.card`,
53254
- title: card.title,
53255
- rows: card.rows,
53256
- minContentWidth: 32
53311
+ codePrefix: "agents.repair.summary.card",
53312
+ title: "Agents Repaired",
53313
+ rows: buildRepairSummaryRows(summary),
53314
+ minContentWidth: 38
53257
53315
  });
53316
+ for (const card of buildRepairDetailCards(summary, targetStateById)) {
53317
+ presenter.line({
53318
+ code: `agents.repair.${card.codeSuffix}.spacer`,
53319
+ text: ""
53320
+ });
53321
+ renderAgentsInfoCard({
53322
+ presenter,
53323
+ codePrefix: `agents.repair.${card.codeSuffix}.card`,
53324
+ title: card.title,
53325
+ rows: card.rows,
53326
+ minContentWidth: 32
53327
+ });
53328
+ }
53258
53329
  }
53259
53330
  return {
53260
53331
  status: "completed",
@@ -92766,11 +92837,9 @@ function buildTerminalStep(input) {
92766
92837
  case "prepare_selected_agents": return {
92767
92838
  message: "Connecting selected local agents.",
92768
92839
  run: async () => {
92769
- assertSelectedLocalAgentsEnabledForPrepare(await runStartLocalAgentsEnable({
92770
- agent: [...input.localAgentIds],
92771
- interactive: input.input.interactive,
92772
- presentation: "handoff",
92773
- view: input.input.view
92840
+ assertSelectedLocalAgentsEnabledForPrepare(await prepareSelectedLocalAgentsForSetup({
92841
+ input: input.input,
92842
+ localAgentIds: input.localAgentIds
92774
92843
  }));
92775
92844
  }
92776
92845
  };
@@ -92827,6 +92896,131 @@ function buildTerminalStep(input) {
92827
92896
  default: throw new Error(`Terminal cannot run prepare step: ${input.stepId}`);
92828
92897
  }
92829
92898
  }
92899
+ async function prepareSelectedLocalAgentsForSetup(input) {
92900
+ const initialResult = await enableSelectedLocalAgentsForSetup(input);
92901
+ if (initialResult.status !== "completed") return initialResult;
92902
+ const recoverableErrors = initialResult.summary.errors.filter((error) => {
92903
+ return isSelectedLocalAgentNeedsRepairError(error) || error.code === "controller.launch.choice_required";
92904
+ });
92905
+ if (recoverableErrors.length === 0) return initialResult;
92906
+ for (const error of recoverableErrors) await recoverSelectedLocalAgentForSetup({
92907
+ error,
92908
+ input: input.input
92909
+ });
92910
+ return await enableSelectedLocalAgentsForSetup(input);
92911
+ }
92912
+ async function enableSelectedLocalAgentsForSetup(input) {
92913
+ return await runStartLocalAgentsEnable({
92914
+ agent: [...input.localAgentIds],
92915
+ ...input.installId ? { install: input.installId } : {},
92916
+ interactive: input.input.interactive,
92917
+ presentation: "handoff",
92918
+ view: input.input.view
92919
+ });
92920
+ }
92921
+ async function recoverSelectedLocalAgentForSetup(input) {
92922
+ if (isSelectedLocalAgentNeedsRepairError(input.error)) {
92923
+ await repairSelectedLocalAgentForSetup(input);
92924
+ return;
92925
+ }
92926
+ if (input.error.code === "controller.launch.choice_required") {
92927
+ const installId = await resolveSelectedLocalAgentInstallChoice({
92928
+ command: "enable",
92929
+ error: input.error,
92930
+ input: input.input
92931
+ });
92932
+ assertSelectedLocalAgentRecoveryCompleted({
92933
+ errorFormatter: formatSelectedLocalAgentEnableFailure,
92934
+ result: await enableSelectedLocalAgentsForSetup({
92935
+ input: input.input,
92936
+ installId,
92937
+ localAgentIds: [input.error.agentId]
92938
+ })
92939
+ });
92940
+ }
92941
+ }
92942
+ async function repairSelectedLocalAgentForSetup(input) {
92943
+ const blockingError = resolveRepairBlockingError(await runSelectedLocalAgentRepairForSetup({
92944
+ agentId: input.error.agentId,
92945
+ input: input.input
92946
+ }));
92947
+ if (!blockingError) {
92948
+ emitHumanStatus(input.input, "Local agent repaired", [`${formatLocalAgentDisplayName(input.error.agentId)} was moved or changed. ATS updated how it starts on this computer.`]);
92949
+ return;
92950
+ }
92951
+ if (blockingError.code === "controller.launch.choice_required") {
92952
+ const installId = await resolveSelectedLocalAgentInstallChoice({
92953
+ command: "repair",
92954
+ error: blockingError,
92955
+ input: input.input
92956
+ });
92957
+ const selectedBlockingError = resolveRepairBlockingError(await runSelectedLocalAgentRepairForSetup({
92958
+ agentId: input.error.agentId,
92959
+ input: input.input,
92960
+ installId
92961
+ }));
92962
+ if (!selectedBlockingError) return;
92963
+ throw new Error(formatSelectedLocalAgentRepairFailure(selectedBlockingError));
92964
+ }
92965
+ throw new Error(formatSelectedLocalAgentRepairFailure(blockingError));
92966
+ }
92967
+ async function runSelectedLocalAgentRepairForSetup(input) {
92968
+ return await runAgentsRepair({
92969
+ agent: [input.agentId],
92970
+ ...input.installId ? { install: input.installId } : {},
92971
+ interactive: input.input.interactive,
92972
+ presentation: "handoff",
92973
+ view: input.input.view
92974
+ });
92975
+ }
92976
+ function resolveRepairBlockingError(result) {
92977
+ if (result.status !== "completed") return {
92978
+ agentId: "selected-agent",
92979
+ code: "controller.launch.needs_repair",
92980
+ reason: "agent repair did not complete"
92981
+ };
92982
+ return result.summary.errors[0] ?? null;
92983
+ }
92984
+ function assertSelectedLocalAgentRecoveryCompleted(input) {
92985
+ if (input.result.status !== "completed") throw new Error("ATS setup cannot continue until the selected local agent is enabled.");
92986
+ const blockingError = input.result.summary.errors[0] ?? null;
92987
+ if (blockingError) throw new Error(input.errorFormatter(blockingError));
92988
+ }
92989
+ async function resolveSelectedLocalAgentInstallChoice(input) {
92990
+ const installChoices = input.error.installChoices ?? [];
92991
+ if (installChoices.length === 0) throw new Error(formatSelectedLocalAgentInstallChoiceFailure(input));
92992
+ if (installChoices.length === 1) {
92993
+ const installChoice = installChoices[0];
92994
+ if (!installChoice) throw new Error(formatSelectedLocalAgentInstallChoiceFailure(input));
92995
+ emitHumanStatus(input.input, "Choosing local agent install", [`ATS will use ${installChoice.label} for ${formatLocalAgentDisplayName(input.error.agentId)}.`]);
92996
+ return installChoice.installId;
92997
+ }
92998
+ const terminal = input.input.runtime.resolvedView === "human" ? resolveControllingTerminalSession() : null;
92999
+ if (!terminal) throw new Error(formatSelectedLocalAgentInstallChoiceFailure(input));
93000
+ try {
93001
+ const result = await promptSearchSelect({
93002
+ message: `Choose the ${formatLocalAgentDisplayName(input.error.agentId)} install ATS should use`,
93003
+ items: installChoices.map((installChoice) => ({
93004
+ value: installChoice.installId,
93005
+ label: installChoice.label,
93006
+ detail: installChoice.detail,
93007
+ searchText: [
93008
+ installChoice.label,
93009
+ installChoice.detail,
93010
+ installChoice.commandPath,
93011
+ installChoice.installId
93012
+ ].join(" ")
93013
+ }))
93014
+ }, terminal.streams);
93015
+ if (result.status === "submitted") return result.value;
93016
+ throw new Error("ATS setup was cancelled before choosing a local agent install.");
93017
+ } finally {
93018
+ terminal.close();
93019
+ }
93020
+ }
93021
+ function isSelectedLocalAgentNeedsRepairError(error) {
93022
+ return error.code === "controller.launch.needs_repair" || error.code === "agents.invalid_agent_id" && normalizeOptionalId(error.reason) === "needs repair";
93023
+ }
92830
93024
  function assertSelectedLocalAgentsEnabledForPrepare(result) {
92831
93025
  if (result.status !== "completed") throw new Error("ATS setup cannot continue until the selected local agents are enabled. Choose or enable them in Terminal, then run ATS setup again.");
92832
93026
  const blockingError = result.summary.errors[0] ?? null;
@@ -92844,6 +93038,22 @@ function formatSelectedLocalAgentEnableFailure(error) {
92844
93038
  if (nextStep) return `ATS could not connect ${error.agentId} on this computer. Run \`${formatAtsCliCommand(nextStep)}\`, then return to ATS Web setup. Detail: ${error.reason}`;
92845
93039
  return `ATS could not connect ${error.agentId} on this computer. Detail: ${error.reason}`;
92846
93040
  }
93041
+ function formatSelectedLocalAgentRepairFailure(error) {
93042
+ if (error.code === "controller.launch.choice_required") return formatSelectedLocalAgentInstallChoiceFailure({
93043
+ command: "repair",
93044
+ error
93045
+ });
93046
+ return `ATS could not repair ${error.agentId} on this computer. Run \`${formatAtsCliCommand(`ats agents repair --agent ${error.agentId}`)}\`, then return to ATS Web setup. Detail: ${error.reason}`;
93047
+ }
93048
+ function formatSelectedLocalAgentInstallChoiceFailure(input) {
93049
+ const commands = input.error.nextSteps && input.error.nextSteps.length > 0 ? input.error.nextSteps : (input.error.installChoices ?? []).map((installChoice) => `ats agents ${input.command} --agent ${input.error.agentId} --install ${installChoice.installId}`);
93050
+ const reason = normalizeOptionalId(input.error.reason) || `ATS found more than one ${input.error.agentId} install on this computer.`;
93051
+ if (commands.length > 0) return `${reason} Run one of these commands, then return to ATS Web setup: ${formatCommandChoiceList(commands)}.`;
93052
+ return `${reason} Run \`${formatAtsCliCommand(`ats agents ${input.command} --agent ${input.error.agentId}`)}\` in an interactive Terminal and choose one install, then return to ATS Web setup.`;
93053
+ }
93054
+ function formatLocalAgentDisplayName(agentId) {
93055
+ return agentId.split("-").filter((part) => part.length > 0).map((part) => `${part.slice(0, 1).toUpperCase()}${part.slice(1)}`).join(" ");
93056
+ }
92847
93057
  function resolveSelectedLocalAgentEnableNextSteps(error) {
92848
93058
  if (error.nextSteps && error.nextSteps.length > 0) return [...error.nextSteps];
92849
93059
  return (error.installChoices ?? []).map((installChoice) => `ats agents enable --agent ${error.agentId} --install ${installChoice.installId}`);