agent-transport-system 0.7.31 → 0.7.32

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
@@ -27,7 +27,7 @@ import wrapAnsi from "wrap-ansi";
27
27
  import { Box, Container, Editor, Key, ProcessTerminal, TUI, Text, getEditorKeybindings, matchesKey } from "@mariozechner/pi-tui";
28
28
 
29
29
  //#region package.json
30
- var version = "0.7.31";
30
+ var version = "0.7.32";
31
31
  var package_default = {
32
32
  $schema: "https://www.schemastore.org/package.json",
33
33
  name: "agent-transport-system",
@@ -77,7 +77,7 @@ var package_default = {
77
77
  "@agent-transport-system/adapter-openclaw": "workspace:*",
78
78
  "@agent-transport-system/agent-runtime": "workspace:*",
79
79
  "@agent-transport-system/api-client": "workspace:*",
80
- "@agent-transport-system/atsd": "workspace:*",
80
+ "@agent-transport-system/local-execution": "workspace:*",
81
81
  "@agent-transport-system/gateway-contract": "workspace:*",
82
82
  "@agent-transport-system/protocol": "workspace:*",
83
83
  "@agent-transport-system/schemas": "workspace:*",
@@ -16267,6 +16267,56 @@ const createStartApi = (client) => {
16267
16267
  };
16268
16268
  };
16269
16269
 
16270
+ //#endregion
16271
+ //#region src/local-service/carrier/heartbeat-loop.ts
16272
+ function waitForHeartbeatResponse(input) {
16273
+ if (input.waiters.heartbeatResolver || input.waiters.heartbeatRejecter) return Promise.reject(new DaemonServiceRunError({
16274
+ code: "daemon.run.heartbeat_response_busy",
16275
+ message: "heartbeat response waiter is already pending"
16276
+ }));
16277
+ return new Promise((resolve, reject) => {
16278
+ const timeout = setTimeout(() => {
16279
+ input.waiters.heartbeatResolver = null;
16280
+ input.waiters.heartbeatRejecter = null;
16281
+ reject(new DaemonServiceRunError({
16282
+ code: "daemon.run.heartbeat_timeout",
16283
+ message: "heartbeat response timeout"
16284
+ }));
16285
+ }, input.timeoutMs);
16286
+ input.waiters.heartbeatResolver = (payload) => {
16287
+ clearTimeout(timeout);
16288
+ input.waiters.heartbeatRejecter = null;
16289
+ resolve(payload);
16290
+ };
16291
+ input.waiters.heartbeatRejecter = (error) => {
16292
+ clearTimeout(timeout);
16293
+ input.waiters.heartbeatResolver = null;
16294
+ input.waiters.heartbeatRejecter = null;
16295
+ reject(error);
16296
+ };
16297
+ });
16298
+ }
16299
+ function applyAcceptedLeases(input) {
16300
+ input.leasesByProfileId.clear();
16301
+ for (const lease of input.acceptedLeases) input.leasesByProfileId.set(lease.profileId, lease.leaseEpoch);
16302
+ }
16303
+ function pruneStaleLeases(input) {
16304
+ for (const staleLease of input.staleLeases) if (input.leasesByProfileId.get(staleLease.profileId) === staleLease.leaseEpoch) input.leasesByProfileId.delete(staleLease.profileId);
16305
+ }
16306
+ function resolveAdaptiveHeartbeatIntervalMs(input) {
16307
+ if (input.hasDispatchActivity) return MIN_HEARTBEAT_INTERVAL_MS;
16308
+ const growthFactor = typeof input.growthFactor === "number" && Number.isFinite(input.growthFactor) ? input.growthFactor : ADAPTIVE_HEARTBEAT_GROWTH_FACTOR;
16309
+ return clampInteger$1(input.currentIntervalMs * growthFactor, MIN_HEARTBEAT_INTERVAL_MS, MAX_HEARTBEAT_INTERVAL_MS);
16310
+ }
16311
+ function applyIntervalJitterMs(input) {
16312
+ const jitterRatio = typeof input.jitterRatio === "number" && Number.isFinite(input.jitterRatio) ? Math.max(0, input.jitterRatio) : 0;
16313
+ const jitterMultiplier = 1 + ((typeof input.randomValue === "number" && Number.isFinite(input.randomValue) ? Math.min(1, Math.max(0, input.randomValue)) : Math.random()) * 2 - 1) * jitterRatio;
16314
+ return clampInteger$1(input.baseIntervalMs * jitterMultiplier, input.minIntervalMs, input.maxIntervalMs);
16315
+ }
16316
+ function resolveCatalogSyncIntervalMs(input) {
16317
+ return clampInteger$1(input.heartbeatIntervalMs * CATALOG_SYNC_INTERVAL_MULTIPLIER, MIN_CATALOG_SYNC_INTERVAL_MS, MAX_CATALOG_SYNC_INTERVAL_MS);
16318
+ }
16319
+
16270
16320
  //#endregion
16271
16321
  //#region src/agents/controller-identity.ts
16272
16322
  function resolveLocalRegistryAgentIdFromAgentControllerRef(input) {
@@ -19856,56 +19906,6 @@ function resolveProfileWorkspaceStateReason(input) {
19856
19906
  return "projected agent profile workspaces look good";
19857
19907
  }
19858
19908
 
19859
- //#endregion
19860
- //#region src/daemon/session/heartbeat-loop.ts
19861
- function waitForHeartbeatResponse(input) {
19862
- if (input.waiters.heartbeatResolver || input.waiters.heartbeatRejecter) return Promise.reject(new DaemonServiceRunError({
19863
- code: "daemon.run.heartbeat_response_busy",
19864
- message: "heartbeat response waiter is already pending"
19865
- }));
19866
- return new Promise((resolve, reject) => {
19867
- const timeout = setTimeout(() => {
19868
- input.waiters.heartbeatResolver = null;
19869
- input.waiters.heartbeatRejecter = null;
19870
- reject(new DaemonServiceRunError({
19871
- code: "daemon.run.heartbeat_timeout",
19872
- message: "heartbeat response timeout"
19873
- }));
19874
- }, input.timeoutMs);
19875
- input.waiters.heartbeatResolver = (payload) => {
19876
- clearTimeout(timeout);
19877
- input.waiters.heartbeatRejecter = null;
19878
- resolve(payload);
19879
- };
19880
- input.waiters.heartbeatRejecter = (error) => {
19881
- clearTimeout(timeout);
19882
- input.waiters.heartbeatResolver = null;
19883
- input.waiters.heartbeatRejecter = null;
19884
- reject(error);
19885
- };
19886
- });
19887
- }
19888
- function applyAcceptedLeases(input) {
19889
- input.leasesByProfileId.clear();
19890
- for (const lease of input.acceptedLeases) input.leasesByProfileId.set(lease.profileId, lease.leaseEpoch);
19891
- }
19892
- function pruneStaleLeases(input) {
19893
- for (const staleLease of input.staleLeases) if (input.leasesByProfileId.get(staleLease.profileId) === staleLease.leaseEpoch) input.leasesByProfileId.delete(staleLease.profileId);
19894
- }
19895
- function resolveAdaptiveHeartbeatIntervalMs(input) {
19896
- if (input.hasDispatchActivity) return MIN_HEARTBEAT_INTERVAL_MS;
19897
- const growthFactor = typeof input.growthFactor === "number" && Number.isFinite(input.growthFactor) ? input.growthFactor : ADAPTIVE_HEARTBEAT_GROWTH_FACTOR;
19898
- return clampInteger$1(input.currentIntervalMs * growthFactor, MIN_HEARTBEAT_INTERVAL_MS, MAX_HEARTBEAT_INTERVAL_MS);
19899
- }
19900
- function applyIntervalJitterMs(input) {
19901
- const jitterRatio = typeof input.jitterRatio === "number" && Number.isFinite(input.jitterRatio) ? Math.max(0, input.jitterRatio) : 0;
19902
- const jitterMultiplier = 1 + ((typeof input.randomValue === "number" && Number.isFinite(input.randomValue) ? Math.min(1, Math.max(0, input.randomValue)) : Math.random()) * 2 - 1) * jitterRatio;
19903
- return clampInteger$1(input.baseIntervalMs * jitterMultiplier, input.minIntervalMs, input.maxIntervalMs);
19904
- }
19905
- function resolveCatalogSyncIntervalMs(input) {
19906
- return clampInteger$1(input.heartbeatIntervalMs * CATALOG_SYNC_INTERVAL_MULTIPLIER, MIN_CATALOG_SYNC_INTERVAL_MS, MAX_CATALOG_SYNC_INTERVAL_MS);
19907
- }
19908
-
19909
19909
  //#endregion
19910
19910
  //#region src/daemon/routing/resolve-controller-support.ts
19911
19911
  async function readLocalEnabledControllers() {
@@ -28448,7 +28448,7 @@ function shouldCheckNpmCliUpdate(context) {
28448
28448
  const ATS_ACCEPT_DISCLAIMER_ENV = "ATS_ACCEPT_DISCLAIMER";
28449
28449
  const ATS_ONBOARDING_DISCLAIMER_ACCEPT = "__onboarding_disclaimer_accept__";
28450
28450
  const ATS_ONBOARDING_DISCLAIMER_DECLINE = "__onboarding_disclaimer_decline__";
28451
- const ATS_ONBOARDING_DISCLAIMER_TEXT = "ATSD is experimental and changes rapidly. Breaking changes may occur. You are fully responsible for data security and sensitive information handling. Use ATSD only in trusted environments.";
28451
+ const ATS_ONBOARDING_DISCLAIMER_TEXT = "ATS local service is experimental and changes rapidly. Breaking changes may occur. You are fully responsible for data security and sensitive information handling. Use ATS only in trusted environments.";
28452
28452
  async function runOnboardingDisclaimerGate(input) {
28453
28453
  if (await getConfiguredOnboardingDisclaimerAcceptedAt().catch(() => null)) return true;
28454
28454
  if (shouldBypassDisclaimerWithEnv()) {
@@ -34925,47 +34925,7 @@ function buildDaemonAgentOverviewPayload(command) {
34925
34925
  }
34926
34926
 
34927
34927
  //#endregion
34928
- //#region src/transport/ws.ts
34929
- async function connectWebSocket(url, input) {
34930
- return await new Promise((resolve, reject) => {
34931
- const ws = new WebSocket(url, { headers: input?.headers });
34932
- const closePromise = new Promise((r) => {
34933
- ws.on("close", () => r());
34934
- ws.on("error", () => r());
34935
- });
34936
- ws.on("open", () => {
34937
- resolve({
34938
- send: (data) => ws.send(data),
34939
- close: (code, reason) => ws.close(code, reason),
34940
- terminate: () => ws.terminate(),
34941
- onMessage: (handler) => {
34942
- ws.on("message", (buf) => handler(toUtf8(buf)));
34943
- },
34944
- onClose: (handler) => {
34945
- ws.on("close", (code, reason) => handler(code, reason.toString("utf8")));
34946
- },
34947
- onError: (handler) => {
34948
- ws.on("error", handler);
34949
- },
34950
- waitUntilClosed: async () => {
34951
- await closePromise;
34952
- }
34953
- });
34954
- });
34955
- ws.on("error", (err) => {
34956
- reject(err);
34957
- });
34958
- });
34959
- }
34960
- function toUtf8(value) {
34961
- if (typeof value === "string") return value;
34962
- if (value instanceof Buffer) return value.toString("utf8");
34963
- if (Array.isArray(value)) return Buffer.concat(value).toString("utf8");
34964
- return String(value);
34965
- }
34966
-
34967
- //#endregion
34968
- //#region ../../runtime/atsd/dist/adapter-routing.js
34928
+ //#region ../../runtime/local-execution/dist/adapter-routing.js
34969
34929
  const ADAPTER_ROUTE_ERROR_CODES = {
34970
34930
  adapterUnreachable: "adapter.unreachable",
34971
34931
  controllerRuntimeMissing: "controller.runtime.missing",
@@ -35085,7 +35045,7 @@ const isAgentControllerRefRegexMatched = (agentControllerRef, matcherValue) => {
35085
35045
  };
35086
35046
 
35087
35047
  //#endregion
35088
- //#region ../../runtime/atsd/dist/agent-context-policy.js
35048
+ //#region ../../runtime/local-execution/dist/agent-context-policy.js
35089
35049
  const AGENT_CONTEXT_LOOKUP_KEY_SEPARATOR$1 = "|";
35090
35050
  const LEDGER_AGENT_CONTEXT_SOURCE_FIELD = "atsd.agent_context_ledger";
35091
35051
  const encodeLookupKeyPart = (value) => encodeURIComponent(value);
@@ -35285,7 +35245,7 @@ const resolveAgentContextForDispatch = (input) => {
35285
35245
  };
35286
35246
 
35287
35247
  //#endregion
35288
- //#region ../../runtime/atsd/dist/control-plane.js
35248
+ //#region ../../runtime/local-execution/dist/control-plane.js
35289
35249
  function parseControlPlaneRequest(input) {
35290
35250
  const parsed = atsdControlPlaneRequestSchema.safeParse(input);
35291
35251
  if (!parsed.success) throw new Error("invalid daemon control-plane request");
@@ -35467,7 +35427,7 @@ function parseControlPlaneResponse(input) {
35467
35427
  }
35468
35428
 
35469
35429
  //#endregion
35470
- //#region ../../runtime/atsd/dist/control-plane-auth.js
35430
+ //#region ../../runtime/local-execution/dist/control-plane-auth.js
35471
35431
  const verifyControlPlaneToken = (input) => input.providedToken === input.expectedToken;
35472
35432
  const buildAuthenticatedControlPlaneResponse = async (input) => {
35473
35433
  const request = parseControlPlaneRequest(input.request);
@@ -35482,7 +35442,7 @@ const buildAuthenticatedControlPlaneResponse = async (input) => {
35482
35442
  };
35483
35443
 
35484
35444
  //#endregion
35485
- //#region ../../runtime/atsd/dist/data-plane-contract.js
35445
+ //#region ../../runtime/local-execution/dist/data-plane-contract.js
35486
35446
  const buildIdempotencyKey = buildIdempotencyKey$1;
35487
35447
  const shouldDedupeWithinWindow = (input) => {
35488
35448
  return shouldDedupeWithinWindow$1({
@@ -35496,7 +35456,7 @@ const shouldBypassDedupeForDeliveryRecoveryReason = (reason) => {
35496
35456
  };
35497
35457
 
35498
35458
  //#endregion
35499
- //#region ../../runtime/atsd/dist/heartbeat-policy.js
35459
+ //#region ../../runtime/local-execution/dist/heartbeat-policy.js
35500
35460
  const HEARTBEAT_POLICY_DEFAULTS = {
35501
35461
  watchdogTimeoutMs: 45e3,
35502
35462
  heartbeatIdleIntervalMs: 6e4,
@@ -35513,7 +35473,7 @@ const HEARTBEAT_POLICY_DEFAULTS = {
35513
35473
  };
35514
35474
 
35515
35475
  //#endregion
35516
- //#region ../../runtime/atsd/dist/ledger-store.js
35476
+ //#region ../../runtime/local-execution/dist/ledger-store.js
35517
35477
  const LEDGER_STATE_VERSION = 1;
35518
35478
  const LEDGER_STATE_INVALID_JSON_ERROR = "ledger.state.invalid_json";
35519
35479
  const LEDGER_STATE_SCHEMA_ERROR = "ledger.state.schema_invalid";
@@ -36080,7 +36040,7 @@ function resolveStoredAgentControllerRef(agentControllerRef) {
36080
36040
  }
36081
36041
 
36082
36042
  //#endregion
36083
- //#region ../../runtime/atsd/dist/trigger-policy.js
36043
+ //#region ../../runtime/local-execution/dist/trigger-policy.js
36084
36044
  const shouldDispatchForMentionOnly = (input) => {
36085
36045
  const triggerMode = input.triggerMode ?? LEGACY_RUNTIME_DISPATCH_POLICY;
36086
36046
  if (triggerMode === "listen_all") return true;
@@ -36088,7 +36048,7 @@ const shouldDispatchForMentionOnly = (input) => {
36088
36048
  };
36089
36049
 
36090
36050
  //#endregion
36091
- //#region ../../runtime/atsd/dist/mention-dispatch-integration.js
36051
+ //#region ../../runtime/local-execution/dist/mention-dispatch-integration.js
36092
36052
  const dispatchMentionOnlyTask = async (input) => {
36093
36053
  if (!shouldDispatchForMentionOnly({
36094
36054
  mentioned: input.mentioned,
@@ -36164,7 +36124,7 @@ const normalizeAgentControllerConversationId = (value) => {
36164
36124
  };
36165
36125
 
36166
36126
  //#endregion
36167
- //#region ../../runtime/atsd/dist/recovery-policy.js
36127
+ //#region ../../runtime/local-execution/dist/recovery-policy.js
36168
36128
  const cloneLedgerState = (state) => ({
36169
36129
  dedupeFirstSeenByKey: { ...state.dedupeFirstSeenByKey },
36170
36130
  inflightByTaskId: Object.fromEntries(Object.entries(state.inflightByTaskId).map(([taskId, inflight]) => [taskId, { ...inflight }])),
@@ -36263,7 +36223,7 @@ const buildTaskResultPayloadFromOutcome = (input) => {
36263
36223
  };
36264
36224
 
36265
36225
  //#endregion
36266
- //#region ../../runtime/atsd/dist/result-envelope.js
36226
+ //#region ../../runtime/local-execution/dist/result-envelope.js
36267
36227
  const buildTaskResultEnvelope = (payload) => {
36268
36228
  const parsed = atsdTaskResultEnvelopeWriteSchema.safeParse({
36269
36229
  v: ATSD_TASK_RESULT_SCHEMA_VERSION,
@@ -36275,14 +36235,14 @@ const buildTaskResultEnvelope = (payload) => {
36275
36235
  };
36276
36236
 
36277
36237
  //#endregion
36278
- //#region ../../runtime/atsd/dist/runtime-health-contract.js
36238
+ //#region ../../runtime/local-execution/dist/runtime-health-contract.js
36279
36239
  const RUNTIME_HEALTH_SEVERITY = {
36280
36240
  error: "error",
36281
36241
  warn: "warn"
36282
36242
  };
36283
36243
 
36284
36244
  //#endregion
36285
- //#region ../../runtime/atsd/dist/runtime-task-lifecycle-contract.js
36245
+ //#region ../../runtime/local-execution/dist/runtime-task-lifecycle-contract.js
36286
36246
  const RUNTIME_INFLIGHT_TASK_TRANSITION_MATRIX = {
36287
36247
  trackNewInflightTask: {
36288
36248
  kind: "track_new_inflight_task",
@@ -36343,7 +36303,7 @@ const resolveTaskResultTransitionForPayloadStatus = (input) => {
36343
36303
  const resolveRuntimeTaskResultDeliverySemantic = (input) => resolveTaskResultDeliverySemantic({ payloadStatus: input.payloadStatus });
36344
36304
 
36345
36305
  //#endregion
36346
- //#region ../../runtime/atsd/dist/runtime-health-invariant-policy.js
36306
+ //#region ../../runtime/local-execution/dist/runtime-health-invariant-policy.js
36347
36307
  const normalizeHumanContext = (humanContext) => humanContext && Object.keys(humanContext).length > 0 ? humanContext : null;
36348
36308
  const buildRuntimeReplayStuckFinding = (input) => ({
36349
36309
  reasonCode: "runtime.replay_stuck",
@@ -36389,7 +36349,7 @@ const resolveRuntimeResultMappingViolation = (input) => {
36389
36349
  };
36390
36350
 
36391
36351
  //#endregion
36392
- //#region ../../runtime/atsd/dist/runtime-health-view.js
36352
+ //#region ../../runtime/local-execution/dist/runtime-health-view.js
36393
36353
  const emitRuntimeHealthFinding = (input) => {
36394
36354
  emitHealthFinding({
36395
36355
  eventName: input.eventName,
@@ -36399,7 +36359,7 @@ const emitRuntimeHealthFinding = (input) => {
36399
36359
  };
36400
36360
 
36401
36361
  //#endregion
36402
- //#region ../../runtime/atsd/dist/runtime-workspace-fingerprint.js
36362
+ //#region ../../runtime/local-execution/dist/runtime-workspace-fingerprint.js
36403
36363
  const SHA256_PREFIX = "sha256:";
36404
36364
  function normalizeWorkspacePath(workspacePath) {
36405
36365
  const trimmed = workspacePath.trim();
@@ -36412,7 +36372,7 @@ function buildRuntimeWorkspaceFingerprint(workspacePath) {
36412
36372
  }
36413
36373
 
36414
36374
  //#endregion
36415
- //#region ../../runtime/atsd/dist/runtime-task-orchestrator.js
36375
+ //#region ../../runtime/local-execution/dist/runtime-task-orchestrator.js
36416
36376
  const mapAdapterErrorType = (errorType) => {
36417
36377
  if (errorType === "adapter") return "adapter";
36418
36378
  if (errorType === "auth") return "auth";
@@ -37987,6 +37947,286 @@ function buildDispatchCorrelation(input) {
37987
37947
  };
37988
37948
  }
37989
37949
 
37950
+ //#endregion
37951
+ //#region src/daemon/state/context-store.ts
37952
+ async function loadContextStore(contextStorePath) {
37953
+ const raw = await readFile(contextStorePath, "utf8").catch(() => "");
37954
+ if (!raw) return /* @__PURE__ */ new Map();
37955
+ let parsed;
37956
+ try {
37957
+ parsed = JSON.parse(raw);
37958
+ } catch {
37959
+ return /* @__PURE__ */ new Map();
37960
+ }
37961
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return /* @__PURE__ */ new Map();
37962
+ const contextStore = /* @__PURE__ */ new Map();
37963
+ for (const [key, value] of Object.entries(parsed)) {
37964
+ const normalizedKey = normalizeOptionalText$50(key);
37965
+ const normalizedValue = normalizeOptionalText$50(value);
37966
+ if (!(normalizedKey && normalizedValue)) continue;
37967
+ contextStore.set(normalizedKey, normalizedValue);
37968
+ }
37969
+ return contextStore;
37970
+ }
37971
+
37972
+ //#endregion
37973
+ //#region src/daemon/state/daemon-runtime-state.ts
37974
+ function resolveDaemonRunMode$1(inputMode) {
37975
+ if (process.env[DAEMON_SERVICE_RUNTIME_DETACHED_ENV] === "1") return "background";
37976
+ const envMode = parseDaemonRunMode$1(process.env[DAEMON_SERVICE_RUNTIME_MODE_ENV]);
37977
+ if (envMode) return envMode;
37978
+ if (inputMode === "foreground") return "foreground";
37979
+ return "background";
37980
+ }
37981
+ function parseDaemonRunMode$1(value) {
37982
+ const normalized = normalizeText$9(value).toLowerCase();
37983
+ if (normalized === "foreground" || normalized === "background") return normalized;
37984
+ return null;
37985
+ }
37986
+ function shouldPersistDaemonRuntimeState(input) {
37987
+ if (input.forcePersist) return true;
37988
+ if ("stopRequestedAt" in input.updates) return true;
37989
+ return input.nowMs - input.lastPersistedAtMs >= RUNTIME_STATE_PERSIST_MIN_INTERVAL_MS;
37990
+ }
37991
+ function resolveReconnectBackoffMs(attempt) {
37992
+ const next = DEFAULT_RECONNECT_DELAY_MS * 2 ** (Math.max(1, attempt) - 1);
37993
+ return Math.min(MAX_RECONNECT_DELAY_MS, next);
37994
+ }
37995
+ function toDaemonStreamUrl(baseUrl) {
37996
+ const url = new URL(baseUrl);
37997
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
37998
+ url.pathname = "/v1/daemon/stream";
37999
+ url.search = "";
38000
+ url.hash = "";
38001
+ return url.toString();
38002
+ }
38003
+ function buildDaemonProcessCommand() {
38004
+ const script = normalizeText$9(process.argv[1]);
38005
+ const args = process.argv.slice(2);
38006
+ const values = script ? [script, ...args] : args;
38007
+ if (values.length === 0) return process.execPath;
38008
+ return `${process.execPath} ${values.join(" ")}`;
38009
+ }
38010
+ function createDaemonRuntimeState(input) {
38011
+ return {
38012
+ v: 1,
38013
+ schema: DAEMON_SERVICE_RUNTIME_STATE_SCHEMA,
38014
+ status: "running",
38015
+ mode: input.mode,
38016
+ pid: input.pid,
38017
+ command: input.command,
38018
+ gatewayUrl: input.gatewayUrl,
38019
+ atsProfileId: input.atsProfileId,
38020
+ workingDirectory: input.workingDirectory,
38021
+ stopRequestedAt: input.stopRequestedAt,
38022
+ startedAt: input.startedAt,
38023
+ updatedAt: input.updatedAt,
38024
+ heartbeatAt: input.heartbeatAt,
38025
+ managedBySystemService: input.runtimeMetadata.managedBySystemService,
38026
+ serviceController: input.runtimeMetadata.serviceController,
38027
+ autoStart: input.runtimeMetadata.autoStart
38028
+ };
38029
+ }
38030
+
38031
+ //#endregion
38032
+ //#region src/daemon/state/route-catalog-cache.ts
38033
+ const ROUTE_CATALOG_CACHE_FILE = "route-catalog-cache.json";
38034
+ async function readDaemonRouteCatalogCache(input) {
38035
+ const lane = normalizeCacheLane(input.lane);
38036
+ const ownerUserId = normalizeCacheIdentityField(input.ownerUserId);
38037
+ const serviceBundleId = normalizeServiceBundleId(input.serviceBundleId);
38038
+ if (!(lane && ownerUserId && serviceBundleId)) return null;
38039
+ const cached = await readDaemonLocalStateFile({
38040
+ path: daemonRouteCatalogCachePath(),
38041
+ schema: daemonRouteCatalogCacheSchema
38042
+ });
38043
+ if (!cached || cached.ownerUserId !== ownerUserId || cached.lane !== lane || cached.serviceBundleId !== serviceBundleId) return null;
38044
+ return deserializeRouteCatalog(cached);
38045
+ }
38046
+ async function writeDaemonRouteCatalogCache(input) {
38047
+ const lane = normalizeCacheLane(input.lane);
38048
+ const ownerUserId = normalizeCacheIdentityField(input.ownerUserId);
38049
+ const serviceBundleId = normalizeServiceBundleId(input.serviceBundleId);
38050
+ if (!(lane && ownerUserId && serviceBundleId)) return;
38051
+ if (input.routeCatalog.profileIds.length === 0) {
38052
+ await clearDaemonRouteCatalogCache();
38053
+ return;
38054
+ }
38055
+ const value = {
38056
+ v: DAEMON_ROUTE_CATALOG_CACHE_SCHEMA_VERSION,
38057
+ schema: DAEMON_ROUTE_CATALOG_CACHE_SCHEMA_NAME,
38058
+ cachedAt: (/* @__PURE__ */ new Date()).toISOString(),
38059
+ runtimeContractEpoch: CURRENT_DAEMON_EXECUTION_CONTRACT_EPOCH,
38060
+ ownerUserId,
38061
+ lane,
38062
+ serviceBundleId,
38063
+ profileIds: [...input.routeCatalog.profileIds],
38064
+ routes: input.routeCatalog.profileIds.map((profileId) => {
38065
+ const route = input.routeCatalog.routeByProfileId.get(profileId);
38066
+ if (!route) throw new Error(`route catalog is missing route for ${profileId}`);
38067
+ return serializeRouteConfig(route);
38068
+ }),
38069
+ skippedProfiles: [...input.routeCatalog.skippedProfiles]
38070
+ };
38071
+ await writeDaemonLocalStateFile({
38072
+ path: daemonRouteCatalogCachePath(),
38073
+ schema: daemonRouteCatalogCacheSchema,
38074
+ value,
38075
+ mode: 384
38076
+ });
38077
+ }
38078
+ async function clearDaemonRouteCatalogCache() {
38079
+ await rm(daemonRouteCatalogCachePath(), { force: true });
38080
+ }
38081
+ function daemonRouteCatalogCachePath() {
38082
+ return join(daemonRuntimeDataPath(), ROUTE_CATALOG_CACHE_FILE);
38083
+ }
38084
+ function normalizeServiceBundleId(value) {
38085
+ return String(value ?? "").trim();
38086
+ }
38087
+ function normalizeCacheIdentityField(value) {
38088
+ return String(value ?? "").trim();
38089
+ }
38090
+ function normalizeCacheLane(value) {
38091
+ const parsed = daemonServiceLaneSchema.safeParse(normalizeCacheIdentityField(value));
38092
+ return parsed.success ? parsed.data : null;
38093
+ }
38094
+ function serializeRouteConfig(route) {
38095
+ return {
38096
+ agentControllerRef: route.agentControllerRef,
38097
+ contextIdMappingSpec: route.contextIdMappingSpec,
38098
+ ...route.launchContract ? { launchContract: route.launchContract } : {},
38099
+ profileId: route.profileId,
38100
+ streamingMode: route.streamingMode,
38101
+ transportMode: route.transportMode
38102
+ };
38103
+ }
38104
+ function deserializeRouteCatalog(cache) {
38105
+ const routeByProfileId = /* @__PURE__ */ new Map();
38106
+ for (const route of cache.routes) routeByProfileId.set(route.profileId, {
38107
+ agentControllerRef: route.agentControllerRef,
38108
+ contextIdMappingSpec: route.contextIdMappingSpec,
38109
+ ...route.launchContract ? { launchContract: route.launchContract } : {},
38110
+ profileId: route.profileId,
38111
+ streamingMode: route.streamingMode,
38112
+ transportMode: route.transportMode
38113
+ });
38114
+ return {
38115
+ profileIds: [...cache.profileIds],
38116
+ routeByProfileId,
38117
+ skippedProfiles: [...cache.skippedProfiles]
38118
+ };
38119
+ }
38120
+
38121
+ //#endregion
38122
+ //#region src/daemon/state/runtime-state-tracker.ts
38123
+ function createDaemonRuntimeStateTracker(input) {
38124
+ let runtimeState = input.initialState;
38125
+ let lastRuntimeStatePersistAtMs = Date.now();
38126
+ const touchRuntimeState = async (updates, options) => {
38127
+ const nowAt = nowIsoString();
38128
+ runtimeState = {
38129
+ ...runtimeState,
38130
+ ...updates,
38131
+ updatedAt: updates.updatedAt ?? nowAt
38132
+ };
38133
+ if (!shouldPersistDaemonRuntimeState({
38134
+ forcePersist: options?.forcePersist === true,
38135
+ nowMs: Date.now(),
38136
+ lastPersistedAtMs: lastRuntimeStatePersistAtMs,
38137
+ updates
38138
+ })) return;
38139
+ await setDaemonServiceRuntimeState(runtimeState);
38140
+ if (input.leaseDescriptor) await writeDaemonRuntimeLease(buildDaemonRuntimeLease({
38141
+ descriptor: input.leaseDescriptor,
38142
+ runtimeState
38143
+ }));
38144
+ lastRuntimeStatePersistAtMs = Date.now();
38145
+ };
38146
+ return {
38147
+ getRuntimeState: () => runtimeState,
38148
+ touchRuntimeState
38149
+ };
38150
+ }
38151
+ async function resolveDaemonRuntimeLeaseDescriptor(input) {
38152
+ const [contract, activeBundle] = await Promise.all([readDaemonServiceContract().catch(() => null), readDaemonActiveBundleState().catch(() => null)]);
38153
+ if (contract) return {
38154
+ generation: contract.generation,
38155
+ bundleId: contract.bundleId
38156
+ };
38157
+ const activeBundleEntryPath = await resolveDaemonBundleEntryPathFromState(activeBundle).catch(() => null);
38158
+ const commandEntryPath = extractDaemonCommandEntryPath(input.command);
38159
+ const bundleId = (commandEntryPath ? resolveDaemonBundleIdFromEntryPath(commandEntryPath) : null) ?? (activeBundleEntryPath ? resolveDaemonBundleIdFromEntryPath(activeBundleEntryPath) : null) ?? activeBundle?.bundleId ?? null;
38160
+ if (!bundleId) return null;
38161
+ return {
38162
+ generation: 0,
38163
+ bundleId
38164
+ };
38165
+ }
38166
+ function buildDaemonRuntimeLease(input) {
38167
+ return {
38168
+ schema: "ats-daemon-runtime-lease-v1",
38169
+ v: 1,
38170
+ generation: input.descriptor.generation,
38171
+ bundleId: input.descriptor.bundleId,
38172
+ pid: input.runtimeState.pid,
38173
+ mode: input.runtimeState.mode,
38174
+ startedAt: input.runtimeState.startedAt,
38175
+ updatedAt: input.runtimeState.updatedAt,
38176
+ heartbeatAt: input.runtimeState.heartbeatAt,
38177
+ serviceController: input.runtimeState.serviceController,
38178
+ managedBySystemService: input.runtimeState.managedBySystemService
38179
+ };
38180
+ }
38181
+
38182
+ //#endregion
38183
+ //#region src/transport/ws.ts
38184
+ async function connectWebSocket(url, input) {
38185
+ return await new Promise((resolve, reject) => {
38186
+ const ws = new WebSocket(url, { headers: input?.headers });
38187
+ const closePromise = new Promise((r) => {
38188
+ ws.on("close", () => r());
38189
+ ws.on("error", () => r());
38190
+ });
38191
+ ws.on("open", () => {
38192
+ resolve({
38193
+ send: (data) => ws.send(data),
38194
+ close: (code, reason) => ws.close(code, reason),
38195
+ terminate: () => ws.terminate(),
38196
+ onMessage: (handler) => {
38197
+ ws.on("message", (buf) => handler(toUtf8(buf)));
38198
+ },
38199
+ onClose: (handler) => {
38200
+ ws.on("close", (code, reason) => handler(code, reason.toString("utf8")));
38201
+ },
38202
+ onError: (handler) => {
38203
+ ws.on("error", handler);
38204
+ },
38205
+ waitUntilClosed: async () => {
38206
+ await closePromise;
38207
+ }
38208
+ });
38209
+ });
38210
+ ws.on("error", (err) => {
38211
+ reject(err);
38212
+ });
38213
+ });
38214
+ }
38215
+ function toUtf8(value) {
38216
+ if (typeof value === "string") return value;
38217
+ if (value instanceof Buffer) return value.toString("utf8");
38218
+ if (Array.isArray(value)) return Buffer.concat(value).toString("utf8");
38219
+ return String(value);
38220
+ }
38221
+
38222
+ //#endregion
38223
+ //#region src/daemon/adapters/resolve-daemon-capabilities.ts
38224
+ function resolveDaemonCapabilities(input) {
38225
+ const runtimeAdapters = input.localAdapterContainer.listAdapters().map((entry) => resolveRegistryRuntimeAdapterCapabilitySnapshot(entry.adapterId)).filter((entry) => entry !== null).sort((left, right) => left.adapterId.localeCompare(right.adapterId));
38226
+ if (runtimeAdapters.length === 0) return {};
38227
+ return { runtimeAdapters };
38228
+ }
38229
+
37990
38230
  //#endregion
37991
38231
  //#region src/local-service/dispatch/daemon-dispatch-journal.ts
37992
38232
  const DAEMON_DISPATCH_EVENT_TYPES = [
@@ -38069,423 +38309,6 @@ function toJournalErrorMessage(error) {
38069
38309
  return error instanceof Error ? error.message : String(error);
38070
38310
  }
38071
38311
 
38072
- //#endregion
38073
- //#region src/local-service/execution/local-execution-slots.ts
38074
- const LOCAL_EXECUTION_LANE_CONCURRENCY_LIMIT = 1;
38075
- function createLocalExecutionSlots(input) {
38076
- const pendingTasks = [];
38077
- const activeCountByLaneKey = /* @__PURE__ */ new Map();
38078
- const ownedAttemptKeys = /* @__PURE__ */ new Set();
38079
- const ownedTaskIds = /* @__PURE__ */ new Map();
38080
- const drainWaiters = [];
38081
- let activeGlobal = 0;
38082
- const resolveActiveForLane = (localExecutionLaneKey) => {
38083
- return activeCountByLaneKey.get(localExecutionLaneKey) ?? 0;
38084
- };
38085
- const buildSnapshot = (localExecutionLaneKey) => {
38086
- return {
38087
- activeForLane: resolveActiveForLane(localExecutionLaneKey),
38088
- activeGlobal,
38089
- limits: input.limits,
38090
- queueDepth: pendingTasks.length
38091
- };
38092
- };
38093
- const resolveWaitReason = (inputWait) => {
38094
- if (activeGlobal >= input.limits.globalConcurrency) return "global_concurrency";
38095
- if (resolveActiveForLane(inputWait.localExecutionLaneKey) >= LOCAL_EXECUTION_LANE_CONCURRENCY_LIMIT) return "local_execution_lane_concurrency";
38096
- return "none";
38097
- };
38098
- const buildLocalQueueDiagnostics = (inputDiagnostics) => {
38099
- const waitReason = inputDiagnostics.waitReason ?? resolveWaitReason({ localExecutionLaneKey: inputDiagnostics.localExecutionLaneKey });
38100
- const status = inputDiagnostics.status ?? (waitReason === "none" ? "starting_runtime" : "queued");
38101
- return {
38102
- ...buildSnapshot(inputDiagnostics.localExecutionLaneKey),
38103
- queuePosition: status === "queued" ? inputDiagnostics.queuePosition : null,
38104
- status,
38105
- waitReason
38106
- };
38107
- };
38108
- const buildTaskOwnerSnapshot = (owner) => {
38109
- return {
38110
- attemptId: owner.attemptId,
38111
- dispatchId: owner.dispatchId,
38112
- executionTokenRunId: owner.executionTokenRunId,
38113
- runtimeCoordinatorExecutionId: owner.runtimeCoordinatorExecutionId,
38114
- taskId: owner.taskId
38115
- };
38116
- };
38117
- const clearQueuedLifecycle = (pendingTask) => {
38118
- pendingTask.stopQueuedLifecycle?.();
38119
- pendingTask.stopQueuedLifecycle = null;
38120
- };
38121
- const releaseTaskOwnership = (task) => {
38122
- ownedAttemptKeys.delete(buildAttemptKey(task.dispatchId, task.attemptId));
38123
- const activeOwner = ownedTaskIds.get(task.taskId);
38124
- if (activeOwner && activeOwner.attemptId === task.attemptId && activeOwner.dispatchId === task.dispatchId) ownedTaskIds.delete(task.taskId);
38125
- };
38126
- const notifyDrainWaitersIfIdle = () => {
38127
- if (pendingTasks.length > 0 || activeGlobal > 0) return;
38128
- while (drainWaiters.length > 0) drainWaiters.shift()?.();
38129
- };
38130
- const pump = () => {
38131
- while (activeGlobal < input.limits.globalConcurrency) {
38132
- const nextTaskIndex = pendingTasks.findIndex((candidate) => {
38133
- return resolveActiveForLane(candidate.task.localExecutionLaneKey) < LOCAL_EXECUTION_LANE_CONCURRENCY_LIMIT;
38134
- });
38135
- if (nextTaskIndex < 0) break;
38136
- const selectedPendingTask = pendingTasks.splice(nextTaskIndex, 1)[0];
38137
- if (!selectedPendingTask) continue;
38138
- clearQueuedLifecycle(selectedPendingTask);
38139
- const selectedTask = selectedPendingTask.task;
38140
- activeGlobal += 1;
38141
- activeCountByLaneKey.set(selectedTask.localExecutionLaneKey, resolveActiveForLane(selectedTask.localExecutionLaneKey) + 1);
38142
- const startedEvent = {
38143
- adapterId: selectedTask.adapterId,
38144
- attemptId: selectedTask.attemptId,
38145
- controllerKey: selectedTask.controllerKey,
38146
- dispatchId: selectedTask.dispatchId,
38147
- localExecutionLaneKey: selectedTask.localExecutionLaneKey,
38148
- localQueue: buildLocalQueueDiagnostics({
38149
- localExecutionLaneKey: selectedTask.localExecutionLaneKey,
38150
- queuePosition: null,
38151
- status: "starting_runtime",
38152
- waitReason: "none"
38153
- }),
38154
- profileId: selectedTask.profileId,
38155
- spaceId: selectedTask.spaceId,
38156
- taskId: selectedTask.taskId,
38157
- targetLabel: selectedTask.targetLabel,
38158
- transportMode: selectedTask.transportMode,
38159
- ...buildSnapshot(selectedTask.localExecutionLaneKey)
38160
- };
38161
- input.onTaskStarted?.(startedEvent);
38162
- const startedAtMs = Date.now();
38163
- Promise.resolve().then(async () => {
38164
- const completionResult = resolveTaskCompletionResult(await selectedTask.run());
38165
- input.onTaskCompleted?.({
38166
- adapterId: selectedTask.adapterId,
38167
- attemptId: selectedTask.attemptId,
38168
- ...buildSnapshot(selectedTask.localExecutionLaneKey),
38169
- controllerKey: selectedTask.controllerKey,
38170
- dispatchId: selectedTask.dispatchId,
38171
- durationMs: Math.max(0, Date.now() - startedAtMs),
38172
- errorCode: completionResult.errorCode,
38173
- errorMessage: completionResult.errorMessage,
38174
- localExecutionLaneKey: selectedTask.localExecutionLaneKey,
38175
- localQueue: buildLocalQueueDiagnostics({
38176
- localExecutionLaneKey: selectedTask.localExecutionLaneKey,
38177
- queuePosition: null,
38178
- status: "starting_runtime",
38179
- waitReason: "none"
38180
- }),
38181
- profileId: selectedTask.profileId,
38182
- result: completionResult.result,
38183
- spaceId: selectedTask.spaceId,
38184
- taskId: selectedTask.taskId,
38185
- targetLabel: selectedTask.targetLabel,
38186
- transportMode: selectedTask.transportMode
38187
- });
38188
- }).catch((error) => {
38189
- input.onTaskCompleted?.({
38190
- adapterId: selectedTask.adapterId,
38191
- attemptId: selectedTask.attemptId,
38192
- ...buildSnapshot(selectedTask.localExecutionLaneKey),
38193
- controllerKey: selectedTask.controllerKey,
38194
- dispatchId: selectedTask.dispatchId,
38195
- durationMs: Math.max(0, Date.now() - startedAtMs),
38196
- errorCode: null,
38197
- errorMessage: toErrorMessage$14(error),
38198
- localExecutionLaneKey: selectedTask.localExecutionLaneKey,
38199
- localQueue: buildLocalQueueDiagnostics({
38200
- localExecutionLaneKey: selectedTask.localExecutionLaneKey,
38201
- queuePosition: null,
38202
- status: "starting_runtime",
38203
- waitReason: "none"
38204
- }),
38205
- profileId: selectedTask.profileId,
38206
- result: "failed",
38207
- spaceId: selectedTask.spaceId,
38208
- taskId: selectedTask.taskId,
38209
- targetLabel: selectedTask.targetLabel,
38210
- transportMode: selectedTask.transportMode
38211
- });
38212
- }).finally(() => {
38213
- releaseTaskOwnership(selectedTask);
38214
- activeGlobal = Math.max(0, activeGlobal - 1);
38215
- const remainingActiveForLane = Math.max(0, resolveActiveForLane(selectedTask.localExecutionLaneKey) - 1);
38216
- if (remainingActiveForLane === 0) activeCountByLaneKey.delete(selectedTask.localExecutionLaneKey);
38217
- else activeCountByLaneKey.set(selectedTask.localExecutionLaneKey, remainingActiveForLane);
38218
- notifyDrainWaitersIfIdle();
38219
- pump();
38220
- });
38221
- }
38222
- };
38223
- return {
38224
- request(task) {
38225
- const attemptKey = buildAttemptKey(task.dispatchId, task.attemptId);
38226
- if (ownedAttemptKeys.has(attemptKey)) return {
38227
- accepted: true,
38228
- deduped: true,
38229
- snapshot: buildSnapshot(task.localExecutionLaneKey)
38230
- };
38231
- const activeOwner = ownedTaskIds.get(task.taskId);
38232
- if (activeOwner) return {
38233
- accepted: false,
38234
- activeOwner: buildTaskOwnerSnapshot(activeOwner),
38235
- reason: "task.owner_conflict",
38236
- snapshot: buildSnapshot(task.localExecutionLaneKey)
38237
- };
38238
- if (pendingTasks.length >= input.limits.queueMax) return {
38239
- accepted: false,
38240
- reason: "queue.full",
38241
- snapshot: buildSnapshot(task.localExecutionLaneKey)
38242
- };
38243
- ownedAttemptKeys.add(attemptKey);
38244
- ownedTaskIds.set(task.taskId, {
38245
- attemptId: task.attemptId,
38246
- dispatchId: task.dispatchId,
38247
- executionTokenRunId: task.executionTokenRunId ?? null,
38248
- runtimeCoordinatorExecutionId: task.runtimeCoordinatorExecutionId ?? null,
38249
- taskId: task.taskId
38250
- });
38251
- const pendingTask = {
38252
- stopQueuedLifecycle: null,
38253
- task
38254
- };
38255
- pendingTasks.push(pendingTask);
38256
- const snapshot = buildSnapshot(task.localExecutionLaneKey);
38257
- if (task.onQueued) try {
38258
- const queuePosition = pendingTasks.indexOf(pendingTask) + 1;
38259
- const stopQueuedLifecycle = task.onQueued({
38260
- adapterId: task.adapterId,
38261
- attemptId: task.attemptId,
38262
- controllerKey: task.controllerKey,
38263
- dispatchId: task.dispatchId,
38264
- localExecutionLaneKey: task.localExecutionLaneKey,
38265
- localQueue: buildLocalQueueDiagnostics({
38266
- localExecutionLaneKey: task.localExecutionLaneKey,
38267
- queuePosition
38268
- }),
38269
- profileId: task.profileId,
38270
- spaceId: task.spaceId,
38271
- taskId: task.taskId,
38272
- targetLabel: task.targetLabel,
38273
- transportMode: task.transportMode,
38274
- ...snapshot
38275
- });
38276
- pendingTask.stopQueuedLifecycle = typeof stopQueuedLifecycle === "function" ? stopQueuedLifecycle : null;
38277
- } catch (error) {
38278
- pendingTasks.pop();
38279
- releaseTaskOwnership(task);
38280
- throw error;
38281
- }
38282
- pump();
38283
- return {
38284
- accepted: true,
38285
- deduped: false,
38286
- snapshot
38287
- };
38288
- },
38289
- dropPendingTasks(inputDrop) {
38290
- const reason = toPendingDropReason(inputDrop?.reason);
38291
- const shouldDrop = inputDrop?.shouldDrop ?? (() => true);
38292
- let droppedCount = 0;
38293
- for (let index = pendingTasks.length - 1; index >= 0; index -= 1) {
38294
- const pendingTask = pendingTasks[index];
38295
- if (!(pendingTask && shouldDrop(pendingTask.task))) continue;
38296
- pendingTasks.splice(index, 1);
38297
- clearQueuedLifecycle(pendingTask);
38298
- releaseTaskOwnership(pendingTask.task);
38299
- droppedCount += 1;
38300
- input.onTaskDropped?.({
38301
- adapterId: pendingTask.task.adapterId,
38302
- attemptId: pendingTask.task.attemptId,
38303
- controllerKey: pendingTask.task.controllerKey,
38304
- dispatchId: pendingTask.task.dispatchId,
38305
- localExecutionLaneKey: pendingTask.task.localExecutionLaneKey,
38306
- localQueue: buildLocalQueueDiagnostics({
38307
- localExecutionLaneKey: pendingTask.task.localExecutionLaneKey,
38308
- queuePosition: null,
38309
- status: "queued"
38310
- }),
38311
- profileId: pendingTask.task.profileId,
38312
- reason,
38313
- spaceId: pendingTask.task.spaceId,
38314
- taskId: pendingTask.task.taskId,
38315
- targetLabel: pendingTask.task.targetLabel,
38316
- transportMode: pendingTask.task.transportMode,
38317
- ...buildSnapshot(pendingTask.task.profileId)
38318
- });
38319
- }
38320
- notifyDrainWaitersIfIdle();
38321
- return { droppedCount };
38322
- },
38323
- drain() {
38324
- if (pendingTasks.length === 0 && activeGlobal === 0) return Promise.resolve();
38325
- return new Promise((resolve) => {
38326
- drainWaiters.push(resolve);
38327
- });
38328
- },
38329
- getDrainState() {
38330
- return {
38331
- activeGlobal,
38332
- pendingCount: pendingTasks.length
38333
- };
38334
- },
38335
- getSnapshot(localExecutionLaneKey) {
38336
- return buildSnapshot(localExecutionLaneKey);
38337
- }
38338
- };
38339
- }
38340
- function buildAttemptKey(dispatchId, attemptId) {
38341
- return `${dispatchId}::${attemptId}`;
38342
- }
38343
- function toErrorMessage$14(error) {
38344
- if (error instanceof Error && error.message.trim().length > 0) return error.message;
38345
- if (typeof error === "string" && error.trim().length > 0) return error;
38346
- return "unknown error";
38347
- }
38348
- function resolveTaskCompletionResult(result) {
38349
- if (!result || typeof result !== "object") return {
38350
- errorCode: null,
38351
- errorMessage: null,
38352
- result: "success"
38353
- };
38354
- const normalizedResult = result.result === "failed" || result.result === "partial_success" || result.result === "success" ? result.result : "success";
38355
- return {
38356
- errorCode: toOptionalText(result.errorCode),
38357
- errorMessage: toOptionalText(result.errorMessage),
38358
- result: normalizedResult
38359
- };
38360
- }
38361
- function toOptionalText(value) {
38362
- if (typeof value !== "string") return null;
38363
- const normalized = value.trim();
38364
- return normalized.length > 0 ? normalized : null;
38365
- }
38366
- function toPendingDropReason(value) {
38367
- if (typeof value !== "string") return "queue.drop";
38368
- const normalized = value.trim();
38369
- return normalized.length > 0 ? normalized : "queue.drop";
38370
- }
38371
-
38372
- //#endregion
38373
- //#region src/local-service/inventory/agent-controller-inventory.ts
38374
- async function collectLocalAgentControllerInventory(input = {}) {
38375
- return { capabilities: (await listAgentTargetStates()).filter((state) => state.targetKind === "builtin").map((state) => resolveLocalAgentControllerInventoryItem({
38376
- localAdapterContainer: input.localAdapterContainer,
38377
- state
38378
- })) };
38379
- }
38380
- function resolveLocalAgentControllerInventoryItem(input) {
38381
- const agentControllerRef = buildAgentControllerRef({
38382
- kind: "builtin",
38383
- id: input.state.agentId
38384
- });
38385
- const adapterSupport = input.localAdapterContainer ? resolveLocalRuntimeControllerSupport({
38386
- agentControllerRef,
38387
- localAdapterContainer: input.localAdapterContainer
38388
- }) : null;
38389
- const launchStatus = input.state.launchStatus ?? (input.state.selectable ? "ready" : "not_available");
38390
- const launchability = resolveLocalAgentControllerLaunchability({
38391
- adapterSupported: adapterSupport?.supported ?? true,
38392
- detected: input.state.detected,
38393
- launchStatus,
38394
- runtimeSupported: input.state.runtimeSupported,
38395
- selectable: input.state.selectable,
38396
- selectableReason: input.state.selectableReason
38397
- });
38398
- return {
38399
- agentId: input.state.agentId,
38400
- blockerReasonCodes: resolveLocalAgentControllerBlockerReasonCodes({
38401
- launchability,
38402
- selectableReason: input.state.selectableReason
38403
- }),
38404
- agentControllerRef,
38405
- detected: input.state.detected,
38406
- displayName: input.state.displayName,
38407
- enabled: input.state.enabled,
38408
- launchability,
38409
- launchStatus,
38410
- launchStatusDetail: input.state.launchStatusDetail ?? null,
38411
- registered: input.state.registered,
38412
- selectable: input.state.selectable,
38413
- selectableReason: input.state.selectableReason
38414
- };
38415
- }
38416
- function resolveLocalAgentControllerReportDecision(capability, input) {
38417
- if (input.requireEnabled && !capability.enabled) return {
38418
- localParticipationState: "needs_agent_prepare",
38419
- reasonCodes: ["local_agent_preparation.not_enabled"]
38420
- };
38421
- if (capability.launchability !== "launchable" || !capability.selectable) return {
38422
- localParticipationState: "needs_agent_prepare",
38423
- reasonCodes: capability.blockerReasonCodes.length > 0 ? capability.blockerReasonCodes : [capability.selectableReason ? `local_agent_preparation.${capability.selectableReason}` : "local_agent_preparation.not_selectable"]
38424
- };
38425
- return {
38426
- localParticipationState: "ready",
38427
- reasonCodes: []
38428
- };
38429
- }
38430
- function resolveLocalAgentControllerLaunchability(input) {
38431
- if (!input.detected) return "not_detected";
38432
- if (!input.runtimeSupported || input.selectableReason === "not_supported_yet") return "not_supported";
38433
- if (input.launchStatus === "needs_choice") return "needs_choice";
38434
- if (input.launchStatus === "needs_repair") return "needs_repair";
38435
- if (input.launchStatus === "ready" && input.selectable && input.adapterSupported !== false) return "launchable";
38436
- return "blocked";
38437
- }
38438
- function resolveLocalAgentControllerBlockerReasonCodes(input) {
38439
- if (input.launchability === "launchable") return [];
38440
- if (input.launchability === "needs_choice") return ["controller.launch.choice_required"];
38441
- if (input.launchability === "needs_repair") return ["controller.launch.needs_repair"];
38442
- if (input.launchability === "not_detected") return ["local_agent_preparation.not_detected"];
38443
- if (input.launchability === "not_supported") return ["local_agent_preparation.not_supported_yet"];
38444
- if (input.selectableReason) return [`local_agent_preparation.${input.selectableReason}`];
38445
- return ["local_agent_preparation.not_enabled"];
38446
- }
38447
-
38448
- //#endregion
38449
- //#region src/local-service/reporting/runtime-agent-controller-report-sync.ts
38450
- async function syncLocalServiceRuntimeAgentControllerReports(input) {
38451
- const reports = (await collectLocalAgentControllerInventory({ localAdapterContainer: input.localAdapterContainer })).capabilities.filter((capability) => capability.registered).map((capability) => {
38452
- if (!capability.agentControllerRef) return null;
38453
- const reportDecision = resolveLocalAgentControllerReportDecision(capability, { requireEnabled: true });
38454
- return {
38455
- agentControllerRef: capability.agentControllerRef,
38456
- localParticipationState: reportDecision.localParticipationState,
38457
- reasonCodes: reportDecision.reasonCodes
38458
- };
38459
- }).filter((report) => report !== null);
38460
- if (reports.length === 0) return {
38461
- status: "skipped",
38462
- reasonCodes: ["runtime.agent_controller_report.no_local_controllers"],
38463
- reportCount: 0,
38464
- submittedCount: 0,
38465
- failedCount: 0
38466
- };
38467
- return summarizeSubmissions(await submitRuntimeAgentControllerReports({ reports }));
38468
- }
38469
- function summarizeSubmissions(submissions) {
38470
- const submittedCount = submissions.filter((submission) => submission.status === "submitted" && submission.agentControllerReportStatus === "accepted").length;
38471
- const failedCount = submissions.length - submittedCount;
38472
- return {
38473
- status: "submitted",
38474
- reasonCodes: [...new Set(submissions.flatMap((submission) => submission.reasonCodes).filter((reasonCode) => reasonCode.trim()))],
38475
- reportCount: submissions.length,
38476
- submittedCount,
38477
- failedCount
38478
- };
38479
- }
38480
-
38481
- //#endregion
38482
- //#region src/daemon/adapters/resolve-daemon-capabilities.ts
38483
- function resolveDaemonCapabilities(input) {
38484
- const runtimeAdapters = input.localAdapterContainer.listAdapters().map((entry) => resolveRegistryRuntimeAdapterCapabilitySnapshot(entry.adapterId)).filter((entry) => entry !== null).sort((left, right) => left.adapterId.localeCompare(right.adapterId));
38485
- if (runtimeAdapters.length === 0) return {};
38486
- return { runtimeAdapters };
38487
- }
38488
-
38489
38312
  //#endregion
38490
38313
  //#region src/daemon/dispatch/send-dispatch-result.ts
38491
38314
  function sendDispatchResultEnvelopeFrame(input) {
@@ -38838,74 +38661,483 @@ function flushDispatchResultOutbox(input) {
38838
38661
  taskId: record.taskId,
38839
38662
  type: "dispatch.result.sent"
38840
38663
  });
38841
- changed = true;
38664
+ changed = true;
38665
+ return {
38666
+ ...record,
38667
+ attemptCount: record.attemptCount + 1,
38668
+ connectionGeneration: activeConnectionGeneration,
38669
+ lastFailureReason: null,
38670
+ lastSendAtMs: nowMs,
38671
+ nextAttemptAtMs: nowMs + resolveOutboxBackoffMs(record.attemptCount + 1),
38672
+ updatedAtMs: nowMs
38673
+ };
38674
+ } catch (error) {
38675
+ changed = true;
38676
+ return {
38677
+ ...record,
38678
+ attemptCount: record.attemptCount + 1,
38679
+ lastFailureReason: toErrorMessage$34(error),
38680
+ nextAttemptAtMs: nowMs + resolveOutboxBackoffMs(record.attemptCount + 1),
38681
+ updatedAtMs: nowMs
38682
+ };
38683
+ }
38684
+ });
38685
+ if (changed) writeOutboxRecords(input.ledgerPaths, nextRecords);
38686
+ }
38687
+ const sanitizeTaskResultPayload = (payload) => {
38688
+ const { bootstrapTemplateFacts: _bootstrapTemplateFacts, promptTrace: _promptTrace, ...safePayload } = payload;
38689
+ return safePayload;
38690
+ };
38691
+ const resolveOutboxBackoffMs = (attemptCount) => {
38692
+ const backoffMs = BACKOFF_MS[Math.min(BACKOFF_MS.length - 1, Math.max(0, attemptCount - 1))];
38693
+ return typeof backoffMs === "number" ? backoffMs : 3e4;
38694
+ };
38695
+ const upsertOutboxRecord = (ledgerPaths, record) => {
38696
+ const records = readOutboxRecords(ledgerPaths);
38697
+ const key = buildRecordKey(record);
38698
+ writeOutboxRecords(ledgerPaths, [...records.filter((candidate) => buildRecordKey(candidate) !== key), record].sort((left, right) => left.createdAtMs - right.createdAtMs));
38699
+ };
38700
+ const readOutboxRecords = (ledgerPaths) => {
38701
+ const outboxPath = resolveOutboxPath(ledgerPaths);
38702
+ if (!existsSync(outboxPath)) return [];
38703
+ const parsed = JSON.parse(readFileSync(outboxPath, "utf8"));
38704
+ if (parsed.schema !== OUTBOX_SCHEMA || !Array.isArray(parsed.records)) return [];
38705
+ return parsed.records.filter(isDispatchResultOutboxRecord);
38706
+ };
38707
+ const writeOutboxRecords = (ledgerPaths, records) => {
38708
+ const outboxPath = resolveOutboxPath(ledgerPaths);
38709
+ const tempPath = join(ledgerPaths.rootDirPath, RESULT_OUTBOX_TEMP_FILE_NAME);
38710
+ mkdirSync(dirname(outboxPath), { recursive: true });
38711
+ writeFileSync(tempPath, JSON.stringify({
38712
+ schema: OUTBOX_SCHEMA,
38713
+ v: 1,
38714
+ records,
38715
+ updatedAtMs: Date.now()
38716
+ }, null, 2), "utf8");
38717
+ renameSync(tempPath, outboxPath);
38718
+ };
38719
+ const resolveOutboxPath = (ledgerPaths) => {
38720
+ return join(ledgerPaths.rootDirPath, RESULT_OUTBOX_FILE_NAME);
38721
+ };
38722
+ const buildRecordKey = (record) => {
38723
+ return `${record.dispatchId}::${record.attemptId}`;
38724
+ };
38725
+ const isDispatchResultOutboxRecord = (value) => {
38726
+ const candidate = value;
38727
+ return candidate.schema === OUTBOX_RECORD_SCHEMA && typeof candidate.attemptId === "string" && typeof candidate.dispatchId === "string" && typeof candidate.daemonSessionId === "string" && typeof candidate.executionIdentityEcho === "object" && candidate.executionIdentityEcho !== null && typeof candidate.leaseEpoch === "number" && typeof candidate.connectionGeneration === "number" && typeof candidate.taskId === "string" && typeof candidate.taskResult === "object" && candidate.taskResult !== null && typeof candidate.createdAtMs === "number" && typeof candidate.updatedAtMs === "number" && typeof candidate.nextAttemptAtMs === "number" && typeof candidate.attemptCount === "number";
38728
+ };
38729
+
38730
+ //#endregion
38731
+ //#region src/local-service/execution/local-execution-slots.ts
38732
+ const LOCAL_EXECUTION_LANE_CONCURRENCY_LIMIT = 1;
38733
+ function createLocalExecutionSlots(input) {
38734
+ const pendingTasks = [];
38735
+ const activeCountByLaneKey = /* @__PURE__ */ new Map();
38736
+ const ownedAttemptKeys = /* @__PURE__ */ new Set();
38737
+ const ownedTaskIds = /* @__PURE__ */ new Map();
38738
+ const drainWaiters = [];
38739
+ let activeGlobal = 0;
38740
+ const resolveActiveForLane = (localExecutionLaneKey) => {
38741
+ return activeCountByLaneKey.get(localExecutionLaneKey) ?? 0;
38742
+ };
38743
+ const buildSnapshot = (localExecutionLaneKey) => {
38744
+ return {
38745
+ activeForLane: resolveActiveForLane(localExecutionLaneKey),
38746
+ activeGlobal,
38747
+ limits: input.limits,
38748
+ queueDepth: pendingTasks.length
38749
+ };
38750
+ };
38751
+ const resolveWaitReason = (inputWait) => {
38752
+ if (activeGlobal >= input.limits.globalConcurrency) return "global_concurrency";
38753
+ if (resolveActiveForLane(inputWait.localExecutionLaneKey) >= LOCAL_EXECUTION_LANE_CONCURRENCY_LIMIT) return "local_execution_lane_concurrency";
38754
+ return "none";
38755
+ };
38756
+ const buildLocalQueueDiagnostics = (inputDiagnostics) => {
38757
+ const waitReason = inputDiagnostics.waitReason ?? resolveWaitReason({ localExecutionLaneKey: inputDiagnostics.localExecutionLaneKey });
38758
+ const status = inputDiagnostics.status ?? (waitReason === "none" ? "starting_runtime" : "queued");
38759
+ return {
38760
+ ...buildSnapshot(inputDiagnostics.localExecutionLaneKey),
38761
+ queuePosition: status === "queued" ? inputDiagnostics.queuePosition : null,
38762
+ status,
38763
+ waitReason
38764
+ };
38765
+ };
38766
+ const buildTaskOwnerSnapshot = (owner) => {
38767
+ return {
38768
+ attemptId: owner.attemptId,
38769
+ dispatchId: owner.dispatchId,
38770
+ executionTokenRunId: owner.executionTokenRunId,
38771
+ runtimeCoordinatorExecutionId: owner.runtimeCoordinatorExecutionId,
38772
+ taskId: owner.taskId
38773
+ };
38774
+ };
38775
+ const clearQueuedLifecycle = (pendingTask) => {
38776
+ pendingTask.stopQueuedLifecycle?.();
38777
+ pendingTask.stopQueuedLifecycle = null;
38778
+ };
38779
+ const releaseTaskOwnership = (task) => {
38780
+ ownedAttemptKeys.delete(buildAttemptKey(task.dispatchId, task.attemptId));
38781
+ const activeOwner = ownedTaskIds.get(task.taskId);
38782
+ if (activeOwner && activeOwner.attemptId === task.attemptId && activeOwner.dispatchId === task.dispatchId) ownedTaskIds.delete(task.taskId);
38783
+ };
38784
+ const notifyDrainWaitersIfIdle = () => {
38785
+ if (pendingTasks.length > 0 || activeGlobal > 0) return;
38786
+ while (drainWaiters.length > 0) drainWaiters.shift()?.();
38787
+ };
38788
+ const pump = () => {
38789
+ while (activeGlobal < input.limits.globalConcurrency) {
38790
+ const nextTaskIndex = pendingTasks.findIndex((candidate) => {
38791
+ return resolveActiveForLane(candidate.task.localExecutionLaneKey) < LOCAL_EXECUTION_LANE_CONCURRENCY_LIMIT;
38792
+ });
38793
+ if (nextTaskIndex < 0) break;
38794
+ const selectedPendingTask = pendingTasks.splice(nextTaskIndex, 1)[0];
38795
+ if (!selectedPendingTask) continue;
38796
+ clearQueuedLifecycle(selectedPendingTask);
38797
+ const selectedTask = selectedPendingTask.task;
38798
+ activeGlobal += 1;
38799
+ activeCountByLaneKey.set(selectedTask.localExecutionLaneKey, resolveActiveForLane(selectedTask.localExecutionLaneKey) + 1);
38800
+ const startedEvent = {
38801
+ adapterId: selectedTask.adapterId,
38802
+ attemptId: selectedTask.attemptId,
38803
+ controllerKey: selectedTask.controllerKey,
38804
+ dispatchId: selectedTask.dispatchId,
38805
+ localExecutionLaneKey: selectedTask.localExecutionLaneKey,
38806
+ localQueue: buildLocalQueueDiagnostics({
38807
+ localExecutionLaneKey: selectedTask.localExecutionLaneKey,
38808
+ queuePosition: null,
38809
+ status: "starting_runtime",
38810
+ waitReason: "none"
38811
+ }),
38812
+ profileId: selectedTask.profileId,
38813
+ spaceId: selectedTask.spaceId,
38814
+ taskId: selectedTask.taskId,
38815
+ targetLabel: selectedTask.targetLabel,
38816
+ transportMode: selectedTask.transportMode,
38817
+ ...buildSnapshot(selectedTask.localExecutionLaneKey)
38818
+ };
38819
+ input.onTaskStarted?.(startedEvent);
38820
+ const startedAtMs = Date.now();
38821
+ Promise.resolve().then(async () => {
38822
+ const completionResult = resolveTaskCompletionResult(await selectedTask.run());
38823
+ input.onTaskCompleted?.({
38824
+ adapterId: selectedTask.adapterId,
38825
+ attemptId: selectedTask.attemptId,
38826
+ ...buildSnapshot(selectedTask.localExecutionLaneKey),
38827
+ controllerKey: selectedTask.controllerKey,
38828
+ dispatchId: selectedTask.dispatchId,
38829
+ durationMs: Math.max(0, Date.now() - startedAtMs),
38830
+ errorCode: completionResult.errorCode,
38831
+ errorMessage: completionResult.errorMessage,
38832
+ localExecutionLaneKey: selectedTask.localExecutionLaneKey,
38833
+ localQueue: buildLocalQueueDiagnostics({
38834
+ localExecutionLaneKey: selectedTask.localExecutionLaneKey,
38835
+ queuePosition: null,
38836
+ status: "starting_runtime",
38837
+ waitReason: "none"
38838
+ }),
38839
+ profileId: selectedTask.profileId,
38840
+ result: completionResult.result,
38841
+ spaceId: selectedTask.spaceId,
38842
+ taskId: selectedTask.taskId,
38843
+ targetLabel: selectedTask.targetLabel,
38844
+ transportMode: selectedTask.transportMode
38845
+ });
38846
+ }).catch((error) => {
38847
+ input.onTaskCompleted?.({
38848
+ adapterId: selectedTask.adapterId,
38849
+ attemptId: selectedTask.attemptId,
38850
+ ...buildSnapshot(selectedTask.localExecutionLaneKey),
38851
+ controllerKey: selectedTask.controllerKey,
38852
+ dispatchId: selectedTask.dispatchId,
38853
+ durationMs: Math.max(0, Date.now() - startedAtMs),
38854
+ errorCode: null,
38855
+ errorMessage: toErrorMessage$14(error),
38856
+ localExecutionLaneKey: selectedTask.localExecutionLaneKey,
38857
+ localQueue: buildLocalQueueDiagnostics({
38858
+ localExecutionLaneKey: selectedTask.localExecutionLaneKey,
38859
+ queuePosition: null,
38860
+ status: "starting_runtime",
38861
+ waitReason: "none"
38862
+ }),
38863
+ profileId: selectedTask.profileId,
38864
+ result: "failed",
38865
+ spaceId: selectedTask.spaceId,
38866
+ taskId: selectedTask.taskId,
38867
+ targetLabel: selectedTask.targetLabel,
38868
+ transportMode: selectedTask.transportMode
38869
+ });
38870
+ }).finally(() => {
38871
+ releaseTaskOwnership(selectedTask);
38872
+ activeGlobal = Math.max(0, activeGlobal - 1);
38873
+ const remainingActiveForLane = Math.max(0, resolveActiveForLane(selectedTask.localExecutionLaneKey) - 1);
38874
+ if (remainingActiveForLane === 0) activeCountByLaneKey.delete(selectedTask.localExecutionLaneKey);
38875
+ else activeCountByLaneKey.set(selectedTask.localExecutionLaneKey, remainingActiveForLane);
38876
+ notifyDrainWaitersIfIdle();
38877
+ pump();
38878
+ });
38879
+ }
38880
+ };
38881
+ return {
38882
+ request(task) {
38883
+ const attemptKey = buildAttemptKey(task.dispatchId, task.attemptId);
38884
+ if (ownedAttemptKeys.has(attemptKey)) return {
38885
+ accepted: true,
38886
+ deduped: true,
38887
+ snapshot: buildSnapshot(task.localExecutionLaneKey)
38888
+ };
38889
+ const activeOwner = ownedTaskIds.get(task.taskId);
38890
+ if (activeOwner) return {
38891
+ accepted: false,
38892
+ activeOwner: buildTaskOwnerSnapshot(activeOwner),
38893
+ reason: "task.owner_conflict",
38894
+ snapshot: buildSnapshot(task.localExecutionLaneKey)
38895
+ };
38896
+ if (pendingTasks.length >= input.limits.queueMax) return {
38897
+ accepted: false,
38898
+ reason: "queue.full",
38899
+ snapshot: buildSnapshot(task.localExecutionLaneKey)
38900
+ };
38901
+ ownedAttemptKeys.add(attemptKey);
38902
+ ownedTaskIds.set(task.taskId, {
38903
+ attemptId: task.attemptId,
38904
+ dispatchId: task.dispatchId,
38905
+ executionTokenRunId: task.executionTokenRunId ?? null,
38906
+ runtimeCoordinatorExecutionId: task.runtimeCoordinatorExecutionId ?? null,
38907
+ taskId: task.taskId
38908
+ });
38909
+ const pendingTask = {
38910
+ stopQueuedLifecycle: null,
38911
+ task
38912
+ };
38913
+ pendingTasks.push(pendingTask);
38914
+ const snapshot = buildSnapshot(task.localExecutionLaneKey);
38915
+ if (task.onQueued) try {
38916
+ const queuePosition = pendingTasks.indexOf(pendingTask) + 1;
38917
+ const stopQueuedLifecycle = task.onQueued({
38918
+ adapterId: task.adapterId,
38919
+ attemptId: task.attemptId,
38920
+ controllerKey: task.controllerKey,
38921
+ dispatchId: task.dispatchId,
38922
+ localExecutionLaneKey: task.localExecutionLaneKey,
38923
+ localQueue: buildLocalQueueDiagnostics({
38924
+ localExecutionLaneKey: task.localExecutionLaneKey,
38925
+ queuePosition
38926
+ }),
38927
+ profileId: task.profileId,
38928
+ spaceId: task.spaceId,
38929
+ taskId: task.taskId,
38930
+ targetLabel: task.targetLabel,
38931
+ transportMode: task.transportMode,
38932
+ ...snapshot
38933
+ });
38934
+ pendingTask.stopQueuedLifecycle = typeof stopQueuedLifecycle === "function" ? stopQueuedLifecycle : null;
38935
+ } catch (error) {
38936
+ pendingTasks.pop();
38937
+ releaseTaskOwnership(task);
38938
+ throw error;
38939
+ }
38940
+ pump();
38842
38941
  return {
38843
- ...record,
38844
- attemptCount: record.attemptCount + 1,
38845
- connectionGeneration: activeConnectionGeneration,
38846
- lastFailureReason: null,
38847
- lastSendAtMs: nowMs,
38848
- nextAttemptAtMs: nowMs + resolveOutboxBackoffMs(record.attemptCount + 1),
38849
- updatedAtMs: nowMs
38942
+ accepted: true,
38943
+ deduped: false,
38944
+ snapshot
38850
38945
  };
38851
- } catch (error) {
38852
- changed = true;
38946
+ },
38947
+ dropPendingTasks(inputDrop) {
38948
+ const reason = toPendingDropReason(inputDrop?.reason);
38949
+ const shouldDrop = inputDrop?.shouldDrop ?? (() => true);
38950
+ let droppedCount = 0;
38951
+ for (let index = pendingTasks.length - 1; index >= 0; index -= 1) {
38952
+ const pendingTask = pendingTasks[index];
38953
+ if (!(pendingTask && shouldDrop(pendingTask.task))) continue;
38954
+ pendingTasks.splice(index, 1);
38955
+ clearQueuedLifecycle(pendingTask);
38956
+ releaseTaskOwnership(pendingTask.task);
38957
+ droppedCount += 1;
38958
+ input.onTaskDropped?.({
38959
+ adapterId: pendingTask.task.adapterId,
38960
+ attemptId: pendingTask.task.attemptId,
38961
+ controllerKey: pendingTask.task.controllerKey,
38962
+ dispatchId: pendingTask.task.dispatchId,
38963
+ localExecutionLaneKey: pendingTask.task.localExecutionLaneKey,
38964
+ localQueue: buildLocalQueueDiagnostics({
38965
+ localExecutionLaneKey: pendingTask.task.localExecutionLaneKey,
38966
+ queuePosition: null,
38967
+ status: "queued"
38968
+ }),
38969
+ profileId: pendingTask.task.profileId,
38970
+ reason,
38971
+ spaceId: pendingTask.task.spaceId,
38972
+ taskId: pendingTask.task.taskId,
38973
+ targetLabel: pendingTask.task.targetLabel,
38974
+ transportMode: pendingTask.task.transportMode,
38975
+ ...buildSnapshot(pendingTask.task.profileId)
38976
+ });
38977
+ }
38978
+ notifyDrainWaitersIfIdle();
38979
+ return { droppedCount };
38980
+ },
38981
+ drain() {
38982
+ if (pendingTasks.length === 0 && activeGlobal === 0) return Promise.resolve();
38983
+ return new Promise((resolve) => {
38984
+ drainWaiters.push(resolve);
38985
+ });
38986
+ },
38987
+ getDrainState() {
38853
38988
  return {
38854
- ...record,
38855
- attemptCount: record.attemptCount + 1,
38856
- lastFailureReason: toErrorMessage$34(error),
38857
- nextAttemptAtMs: nowMs + resolveOutboxBackoffMs(record.attemptCount + 1),
38858
- updatedAtMs: nowMs
38989
+ activeGlobal,
38990
+ pendingCount: pendingTasks.length
38859
38991
  };
38992
+ },
38993
+ getSnapshot(localExecutionLaneKey) {
38994
+ return buildSnapshot(localExecutionLaneKey);
38860
38995
  }
38996
+ };
38997
+ }
38998
+ function buildAttemptKey(dispatchId, attemptId) {
38999
+ return `${dispatchId}::${attemptId}`;
39000
+ }
39001
+ function toErrorMessage$14(error) {
39002
+ if (error instanceof Error && error.message.trim().length > 0) return error.message;
39003
+ if (typeof error === "string" && error.trim().length > 0) return error;
39004
+ return "unknown error";
39005
+ }
39006
+ function resolveTaskCompletionResult(result) {
39007
+ if (!result || typeof result !== "object") return {
39008
+ errorCode: null,
39009
+ errorMessage: null,
39010
+ result: "success"
39011
+ };
39012
+ const normalizedResult = result.result === "failed" || result.result === "partial_success" || result.result === "success" ? result.result : "success";
39013
+ return {
39014
+ errorCode: toOptionalText(result.errorCode),
39015
+ errorMessage: toOptionalText(result.errorMessage),
39016
+ result: normalizedResult
39017
+ };
39018
+ }
39019
+ function toOptionalText(value) {
39020
+ if (typeof value !== "string") return null;
39021
+ const normalized = value.trim();
39022
+ return normalized.length > 0 ? normalized : null;
39023
+ }
39024
+ function toPendingDropReason(value) {
39025
+ if (typeof value !== "string") return "queue.drop";
39026
+ const normalized = value.trim();
39027
+ return normalized.length > 0 ? normalized : "queue.drop";
39028
+ }
39029
+
39030
+ //#endregion
39031
+ //#region src/local-service/inventory/agent-controller-inventory.ts
39032
+ async function collectLocalAgentControllerInventory(input = {}) {
39033
+ return { capabilities: (await listAgentTargetStates()).filter((state) => state.targetKind === "builtin").map((state) => resolveLocalAgentControllerInventoryItem({
39034
+ localAdapterContainer: input.localAdapterContainer,
39035
+ state
39036
+ })) };
39037
+ }
39038
+ function resolveLocalAgentControllerInventoryItem(input) {
39039
+ const agentControllerRef = buildAgentControllerRef({
39040
+ kind: "builtin",
39041
+ id: input.state.agentId
38861
39042
  });
38862
- if (changed) writeOutboxRecords(input.ledgerPaths, nextRecords);
39043
+ const adapterSupport = input.localAdapterContainer ? resolveLocalRuntimeControllerSupport({
39044
+ agentControllerRef,
39045
+ localAdapterContainer: input.localAdapterContainer
39046
+ }) : null;
39047
+ const launchStatus = input.state.launchStatus ?? (input.state.selectable ? "ready" : "not_available");
39048
+ const launchability = resolveLocalAgentControllerLaunchability({
39049
+ adapterSupported: adapterSupport?.supported ?? true,
39050
+ detected: input.state.detected,
39051
+ launchStatus,
39052
+ runtimeSupported: input.state.runtimeSupported,
39053
+ selectable: input.state.selectable,
39054
+ selectableReason: input.state.selectableReason
39055
+ });
39056
+ return {
39057
+ agentId: input.state.agentId,
39058
+ blockerReasonCodes: resolveLocalAgentControllerBlockerReasonCodes({
39059
+ launchability,
39060
+ selectableReason: input.state.selectableReason
39061
+ }),
39062
+ agentControllerRef,
39063
+ detected: input.state.detected,
39064
+ displayName: input.state.displayName,
39065
+ enabled: input.state.enabled,
39066
+ launchability,
39067
+ launchStatus,
39068
+ launchStatusDetail: input.state.launchStatusDetail ?? null,
39069
+ registered: input.state.registered,
39070
+ selectable: input.state.selectable,
39071
+ selectableReason: input.state.selectableReason
39072
+ };
39073
+ }
39074
+ function resolveLocalAgentControllerReportDecision(capability, input) {
39075
+ if (input.requireEnabled && !capability.enabled) return {
39076
+ localParticipationState: "needs_agent_prepare",
39077
+ reasonCodes: ["local_agent_preparation.not_enabled"]
39078
+ };
39079
+ if (capability.launchability !== "launchable" || !capability.selectable) return {
39080
+ localParticipationState: "needs_agent_prepare",
39081
+ reasonCodes: capability.blockerReasonCodes.length > 0 ? capability.blockerReasonCodes : [capability.selectableReason ? `local_agent_preparation.${capability.selectableReason}` : "local_agent_preparation.not_selectable"]
39082
+ };
39083
+ return {
39084
+ localParticipationState: "ready",
39085
+ reasonCodes: []
39086
+ };
39087
+ }
39088
+ function resolveLocalAgentControllerLaunchability(input) {
39089
+ if (!input.detected) return "not_detected";
39090
+ if (!input.runtimeSupported || input.selectableReason === "not_supported_yet") return "not_supported";
39091
+ if (input.launchStatus === "needs_choice") return "needs_choice";
39092
+ if (input.launchStatus === "needs_repair") return "needs_repair";
39093
+ if (input.launchStatus === "ready" && input.selectable && input.adapterSupported !== false) return "launchable";
39094
+ return "blocked";
39095
+ }
39096
+ function resolveLocalAgentControllerBlockerReasonCodes(input) {
39097
+ if (input.launchability === "launchable") return [];
39098
+ if (input.launchability === "needs_choice") return ["controller.launch.choice_required"];
39099
+ if (input.launchability === "needs_repair") return ["controller.launch.needs_repair"];
39100
+ if (input.launchability === "not_detected") return ["local_agent_preparation.not_detected"];
39101
+ if (input.launchability === "not_supported") return ["local_agent_preparation.not_supported_yet"];
39102
+ if (input.selectableReason) return [`local_agent_preparation.${input.selectableReason}`];
39103
+ return ["local_agent_preparation.not_enabled"];
39104
+ }
39105
+
39106
+ //#endregion
39107
+ //#region src/local-service/reporting/runtime-agent-controller-report-sync.ts
39108
+ async function syncLocalServiceRuntimeAgentControllerReports(input) {
39109
+ const reports = (await collectLocalAgentControllerInventory({ localAdapterContainer: input.localAdapterContainer })).capabilities.filter((capability) => capability.registered).map((capability) => {
39110
+ if (!capability.agentControllerRef) return null;
39111
+ const reportDecision = resolveLocalAgentControllerReportDecision(capability, { requireEnabled: true });
39112
+ return {
39113
+ agentControllerRef: capability.agentControllerRef,
39114
+ localParticipationState: reportDecision.localParticipationState,
39115
+ reasonCodes: reportDecision.reasonCodes
39116
+ };
39117
+ }).filter((report) => report !== null);
39118
+ if (reports.length === 0) return {
39119
+ status: "skipped",
39120
+ reasonCodes: ["runtime.agent_controller_report.no_local_controllers"],
39121
+ reportCount: 0,
39122
+ submittedCount: 0,
39123
+ failedCount: 0
39124
+ };
39125
+ return summarizeSubmissions(await submitRuntimeAgentControllerReports({ reports }));
39126
+ }
39127
+ function summarizeSubmissions(submissions) {
39128
+ const submittedCount = submissions.filter((submission) => submission.status === "submitted" && submission.agentControllerReportStatus === "accepted").length;
39129
+ const failedCount = submissions.length - submittedCount;
39130
+ return {
39131
+ status: "submitted",
39132
+ reasonCodes: [...new Set(submissions.flatMap((submission) => submission.reasonCodes).filter((reasonCode) => reasonCode.trim()))],
39133
+ reportCount: submissions.length,
39134
+ submittedCount,
39135
+ failedCount
39136
+ };
38863
39137
  }
38864
- const sanitizeTaskResultPayload = (payload) => {
38865
- const { bootstrapTemplateFacts: _bootstrapTemplateFacts, promptTrace: _promptTrace, ...safePayload } = payload;
38866
- return safePayload;
38867
- };
38868
- const resolveOutboxBackoffMs = (attemptCount) => {
38869
- const backoffMs = BACKOFF_MS[Math.min(BACKOFF_MS.length - 1, Math.max(0, attemptCount - 1))];
38870
- return typeof backoffMs === "number" ? backoffMs : 3e4;
38871
- };
38872
- const upsertOutboxRecord = (ledgerPaths, record) => {
38873
- const records = readOutboxRecords(ledgerPaths);
38874
- const key = buildRecordKey(record);
38875
- writeOutboxRecords(ledgerPaths, [...records.filter((candidate) => buildRecordKey(candidate) !== key), record].sort((left, right) => left.createdAtMs - right.createdAtMs));
38876
- };
38877
- const readOutboxRecords = (ledgerPaths) => {
38878
- const outboxPath = resolveOutboxPath(ledgerPaths);
38879
- if (!existsSync(outboxPath)) return [];
38880
- const parsed = JSON.parse(readFileSync(outboxPath, "utf8"));
38881
- if (parsed.schema !== OUTBOX_SCHEMA || !Array.isArray(parsed.records)) return [];
38882
- return parsed.records.filter(isDispatchResultOutboxRecord);
38883
- };
38884
- const writeOutboxRecords = (ledgerPaths, records) => {
38885
- const outboxPath = resolveOutboxPath(ledgerPaths);
38886
- const tempPath = join(ledgerPaths.rootDirPath, RESULT_OUTBOX_TEMP_FILE_NAME);
38887
- mkdirSync(dirname(outboxPath), { recursive: true });
38888
- writeFileSync(tempPath, JSON.stringify({
38889
- schema: OUTBOX_SCHEMA,
38890
- v: 1,
38891
- records,
38892
- updatedAtMs: Date.now()
38893
- }, null, 2), "utf8");
38894
- renameSync(tempPath, outboxPath);
38895
- };
38896
- const resolveOutboxPath = (ledgerPaths) => {
38897
- return join(ledgerPaths.rootDirPath, RESULT_OUTBOX_FILE_NAME);
38898
- };
38899
- const buildRecordKey = (record) => {
38900
- return `${record.dispatchId}::${record.attemptId}`;
38901
- };
38902
- const isDispatchResultOutboxRecord = (value) => {
38903
- const candidate = value;
38904
- return candidate.schema === OUTBOX_RECORD_SCHEMA && typeof candidate.attemptId === "string" && typeof candidate.dispatchId === "string" && typeof candidate.daemonSessionId === "string" && typeof candidate.executionIdentityEcho === "object" && candidate.executionIdentityEcho !== null && typeof candidate.leaseEpoch === "number" && typeof candidate.connectionGeneration === "number" && typeof candidate.taskId === "string" && typeof candidate.taskResult === "object" && candidate.taskResult !== null && typeof candidate.createdAtMs === "number" && typeof candidate.updatedAtMs === "number" && typeof candidate.nextAttemptAtMs === "number" && typeof candidate.attemptCount === "number";
38905
- };
38906
39138
 
38907
39139
  //#endregion
38908
- //#region src/daemon/session/catalog-sync-skipped-profiles.ts
39140
+ //#region src/local-service/carrier/catalog-sync-skipped-profiles.ts
38909
39141
  function resolveCatalogSyncSkippedProfilesLogState(input) {
38910
39142
  if (input.hasProfiles || input.skippedProfiles.length === 0) return {
38911
39143
  fingerprint: null,
@@ -43078,7 +43310,7 @@ function failMissingCurrentSocket(dispatchId) {
43078
43310
  }
43079
43311
 
43080
43312
  //#endregion
43081
- //#region src/daemon/session/frame-router.ts
43313
+ //#region src/local-service/carrier/frame-router.ts
43082
43314
  function parseDaemonFrame(raw) {
43083
43315
  let parsedJson;
43084
43316
  try {
@@ -43281,7 +43513,7 @@ function normalizeResultAckStatus(value) {
43281
43513
  }
43282
43514
 
43283
43515
  //#endregion
43284
- //#region src/daemon/session/register-session.ts
43516
+ //#region src/local-service/carrier/register-session.ts
43285
43517
  function waitForRegisterResponse(input) {
43286
43518
  if (input.waiters.registerResolver || input.waiters.registerRejecter) return Promise.reject(new DaemonServiceRunError({
43287
43519
  code: "daemon.run.register_response_busy",
@@ -43311,7 +43543,7 @@ function waitForRegisterResponse(input) {
43311
43543
  }
43312
43544
 
43313
43545
  //#endregion
43314
- //#region src/daemon/session/run-socket-session.ts
43546
+ //#region src/local-service/carrier/run-socket-session.ts
43315
43547
  async function runDaemonSocketSession(input) {
43316
43548
  const currentSocketRef = input.currentSocketRef ?? {
43317
43549
  connectionGeneration: null,
@@ -44166,239 +44398,7 @@ function normalizeFrameInteger(value) {
44166
44398
  }
44167
44399
 
44168
44400
  //#endregion
44169
- //#region src/daemon/state/context-store.ts
44170
- async function loadContextStore(contextStorePath) {
44171
- const raw = await readFile(contextStorePath, "utf8").catch(() => "");
44172
- if (!raw) return /* @__PURE__ */ new Map();
44173
- let parsed;
44174
- try {
44175
- parsed = JSON.parse(raw);
44176
- } catch {
44177
- return /* @__PURE__ */ new Map();
44178
- }
44179
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return /* @__PURE__ */ new Map();
44180
- const contextStore = /* @__PURE__ */ new Map();
44181
- for (const [key, value] of Object.entries(parsed)) {
44182
- const normalizedKey = normalizeOptionalText$50(key);
44183
- const normalizedValue = normalizeOptionalText$50(value);
44184
- if (!(normalizedKey && normalizedValue)) continue;
44185
- contextStore.set(normalizedKey, normalizedValue);
44186
- }
44187
- return contextStore;
44188
- }
44189
-
44190
- //#endregion
44191
- //#region src/daemon/state/daemon-runtime-state.ts
44192
- function resolveDaemonRunMode$1(inputMode) {
44193
- if (process.env[DAEMON_SERVICE_RUNTIME_DETACHED_ENV] === "1") return "background";
44194
- const envMode = parseDaemonRunMode$1(process.env[DAEMON_SERVICE_RUNTIME_MODE_ENV]);
44195
- if (envMode) return envMode;
44196
- if (inputMode === "foreground") return "foreground";
44197
- return "background";
44198
- }
44199
- function parseDaemonRunMode$1(value) {
44200
- const normalized = normalizeText$9(value).toLowerCase();
44201
- if (normalized === "foreground" || normalized === "background") return normalized;
44202
- return null;
44203
- }
44204
- function shouldPersistDaemonRuntimeState(input) {
44205
- if (input.forcePersist) return true;
44206
- if ("stopRequestedAt" in input.updates) return true;
44207
- return input.nowMs - input.lastPersistedAtMs >= RUNTIME_STATE_PERSIST_MIN_INTERVAL_MS;
44208
- }
44209
- function resolveReconnectBackoffMs(attempt) {
44210
- const next = DEFAULT_RECONNECT_DELAY_MS * 2 ** (Math.max(1, attempt) - 1);
44211
- return Math.min(MAX_RECONNECT_DELAY_MS, next);
44212
- }
44213
- function toDaemonStreamUrl(baseUrl) {
44214
- const url = new URL(baseUrl);
44215
- url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
44216
- url.pathname = "/v1/daemon/stream";
44217
- url.search = "";
44218
- url.hash = "";
44219
- return url.toString();
44220
- }
44221
- function buildDaemonProcessCommand() {
44222
- const script = normalizeText$9(process.argv[1]);
44223
- const args = process.argv.slice(2);
44224
- const values = script ? [script, ...args] : args;
44225
- if (values.length === 0) return process.execPath;
44226
- return `${process.execPath} ${values.join(" ")}`;
44227
- }
44228
- function createDaemonRuntimeState(input) {
44229
- return {
44230
- v: 1,
44231
- schema: DAEMON_SERVICE_RUNTIME_STATE_SCHEMA,
44232
- status: "running",
44233
- mode: input.mode,
44234
- pid: input.pid,
44235
- command: input.command,
44236
- gatewayUrl: input.gatewayUrl,
44237
- atsProfileId: input.atsProfileId,
44238
- workingDirectory: input.workingDirectory,
44239
- stopRequestedAt: input.stopRequestedAt,
44240
- startedAt: input.startedAt,
44241
- updatedAt: input.updatedAt,
44242
- heartbeatAt: input.heartbeatAt,
44243
- managedBySystemService: input.runtimeMetadata.managedBySystemService,
44244
- serviceController: input.runtimeMetadata.serviceController,
44245
- autoStart: input.runtimeMetadata.autoStart
44246
- };
44247
- }
44248
-
44249
- //#endregion
44250
- //#region src/daemon/state/route-catalog-cache.ts
44251
- const ROUTE_CATALOG_CACHE_FILE = "route-catalog-cache.json";
44252
- async function readDaemonRouteCatalogCache(input) {
44253
- const lane = normalizeCacheLane(input.lane);
44254
- const ownerUserId = normalizeCacheIdentityField(input.ownerUserId);
44255
- const serviceBundleId = normalizeServiceBundleId(input.serviceBundleId);
44256
- if (!(lane && ownerUserId && serviceBundleId)) return null;
44257
- const cached = await readDaemonLocalStateFile({
44258
- path: daemonRouteCatalogCachePath(),
44259
- schema: daemonRouteCatalogCacheSchema
44260
- });
44261
- if (!cached || cached.ownerUserId !== ownerUserId || cached.lane !== lane || cached.serviceBundleId !== serviceBundleId) return null;
44262
- return deserializeRouteCatalog(cached);
44263
- }
44264
- async function writeDaemonRouteCatalogCache(input) {
44265
- const lane = normalizeCacheLane(input.lane);
44266
- const ownerUserId = normalizeCacheIdentityField(input.ownerUserId);
44267
- const serviceBundleId = normalizeServiceBundleId(input.serviceBundleId);
44268
- if (!(lane && ownerUserId && serviceBundleId)) return;
44269
- if (input.routeCatalog.profileIds.length === 0) {
44270
- await clearDaemonRouteCatalogCache();
44271
- return;
44272
- }
44273
- const value = {
44274
- v: DAEMON_ROUTE_CATALOG_CACHE_SCHEMA_VERSION,
44275
- schema: DAEMON_ROUTE_CATALOG_CACHE_SCHEMA_NAME,
44276
- cachedAt: (/* @__PURE__ */ new Date()).toISOString(),
44277
- runtimeContractEpoch: CURRENT_DAEMON_EXECUTION_CONTRACT_EPOCH,
44278
- ownerUserId,
44279
- lane,
44280
- serviceBundleId,
44281
- profileIds: [...input.routeCatalog.profileIds],
44282
- routes: input.routeCatalog.profileIds.map((profileId) => {
44283
- const route = input.routeCatalog.routeByProfileId.get(profileId);
44284
- if (!route) throw new Error(`route catalog is missing route for ${profileId}`);
44285
- return serializeRouteConfig(route);
44286
- }),
44287
- skippedProfiles: [...input.routeCatalog.skippedProfiles]
44288
- };
44289
- await writeDaemonLocalStateFile({
44290
- path: daemonRouteCatalogCachePath(),
44291
- schema: daemonRouteCatalogCacheSchema,
44292
- value,
44293
- mode: 384
44294
- });
44295
- }
44296
- async function clearDaemonRouteCatalogCache() {
44297
- await rm(daemonRouteCatalogCachePath(), { force: true });
44298
- }
44299
- function daemonRouteCatalogCachePath() {
44300
- return join(daemonRuntimeDataPath(), ROUTE_CATALOG_CACHE_FILE);
44301
- }
44302
- function normalizeServiceBundleId(value) {
44303
- return String(value ?? "").trim();
44304
- }
44305
- function normalizeCacheIdentityField(value) {
44306
- return String(value ?? "").trim();
44307
- }
44308
- function normalizeCacheLane(value) {
44309
- const parsed = daemonServiceLaneSchema.safeParse(normalizeCacheIdentityField(value));
44310
- return parsed.success ? parsed.data : null;
44311
- }
44312
- function serializeRouteConfig(route) {
44313
- return {
44314
- agentControllerRef: route.agentControllerRef,
44315
- contextIdMappingSpec: route.contextIdMappingSpec,
44316
- ...route.launchContract ? { launchContract: route.launchContract } : {},
44317
- profileId: route.profileId,
44318
- streamingMode: route.streamingMode,
44319
- transportMode: route.transportMode
44320
- };
44321
- }
44322
- function deserializeRouteCatalog(cache) {
44323
- const routeByProfileId = /* @__PURE__ */ new Map();
44324
- for (const route of cache.routes) routeByProfileId.set(route.profileId, {
44325
- agentControllerRef: route.agentControllerRef,
44326
- contextIdMappingSpec: route.contextIdMappingSpec,
44327
- ...route.launchContract ? { launchContract: route.launchContract } : {},
44328
- profileId: route.profileId,
44329
- streamingMode: route.streamingMode,
44330
- transportMode: route.transportMode
44331
- });
44332
- return {
44333
- profileIds: [...cache.profileIds],
44334
- routeByProfileId,
44335
- skippedProfiles: [...cache.skippedProfiles]
44336
- };
44337
- }
44338
-
44339
- //#endregion
44340
- //#region src/daemon/state/runtime-state-tracker.ts
44341
- function createDaemonRuntimeStateTracker(input) {
44342
- let runtimeState = input.initialState;
44343
- let lastRuntimeStatePersistAtMs = Date.now();
44344
- const touchRuntimeState = async (updates, options) => {
44345
- const nowAt = nowIsoString();
44346
- runtimeState = {
44347
- ...runtimeState,
44348
- ...updates,
44349
- updatedAt: updates.updatedAt ?? nowAt
44350
- };
44351
- if (!shouldPersistDaemonRuntimeState({
44352
- forcePersist: options?.forcePersist === true,
44353
- nowMs: Date.now(),
44354
- lastPersistedAtMs: lastRuntimeStatePersistAtMs,
44355
- updates
44356
- })) return;
44357
- await setDaemonServiceRuntimeState(runtimeState);
44358
- if (input.leaseDescriptor) await writeDaemonRuntimeLease(buildDaemonRuntimeLease({
44359
- descriptor: input.leaseDescriptor,
44360
- runtimeState
44361
- }));
44362
- lastRuntimeStatePersistAtMs = Date.now();
44363
- };
44364
- return {
44365
- getRuntimeState: () => runtimeState,
44366
- touchRuntimeState
44367
- };
44368
- }
44369
- async function resolveDaemonRuntimeLeaseDescriptor(input) {
44370
- const [contract, activeBundle] = await Promise.all([readDaemonServiceContract().catch(() => null), readDaemonActiveBundleState().catch(() => null)]);
44371
- if (contract) return {
44372
- generation: contract.generation,
44373
- bundleId: contract.bundleId
44374
- };
44375
- const activeBundleEntryPath = await resolveDaemonBundleEntryPathFromState(activeBundle).catch(() => null);
44376
- const commandEntryPath = extractDaemonCommandEntryPath(input.command);
44377
- const bundleId = (commandEntryPath ? resolveDaemonBundleIdFromEntryPath(commandEntryPath) : null) ?? (activeBundleEntryPath ? resolveDaemonBundleIdFromEntryPath(activeBundleEntryPath) : null) ?? activeBundle?.bundleId ?? null;
44378
- if (!bundleId) return null;
44379
- return {
44380
- generation: 0,
44381
- bundleId
44382
- };
44383
- }
44384
- function buildDaemonRuntimeLease(input) {
44385
- return {
44386
- schema: "ats-daemon-runtime-lease-v1",
44387
- v: 1,
44388
- generation: input.descriptor.generation,
44389
- bundleId: input.descriptor.bundleId,
44390
- pid: input.runtimeState.pid,
44391
- mode: input.runtimeState.mode,
44392
- startedAt: input.runtimeState.startedAt,
44393
- updatedAt: input.runtimeState.updatedAt,
44394
- heartbeatAt: input.runtimeState.heartbeatAt,
44395
- serviceController: input.runtimeState.serviceController,
44396
- managedBySystemService: input.runtimeState.managedBySystemService
44397
- };
44398
- }
44399
-
44400
- //#endregion
44401
- //#region src/daemon/service-runner.ts
44401
+ //#region src/local-service/carrier/service-runner.ts
44402
44402
  async function resolveDaemonServiceOwnerContext(input) {
44403
44403
  const explicitAtsProfileId = normalizeText$9(input.atsProfileId);
44404
44404
  if (explicitAtsProfileId) return resolveDaemonServiceOwnerContextFromProfile(await requireAtsProfile({