@zltquant/zlt-mcp 0.8.1 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12250,8 +12250,8 @@ async function updateRuntimeLeaseActiveJob(handle, runId, active2, options = {})
12250
12250
  async function releaseRuntimeLease(handle, options = {}) {
12251
12251
  const deps = options.deps ?? defaultRuntimeLifecycleDeps;
12252
12252
  return withLifecycleLock(handle.workRoot, deps, async (stateDir) => {
12253
- const record5 = readJson(leasePath(stateDir, handle.token));
12254
- if (record5 && sameIdentity(record5.holder, handle.holder)) {
12253
+ const record6 = readJson(leasePath(stateDir, handle.token));
12254
+ if (record6 && sameIdentity(record6.holder, handle.holder)) {
12255
12255
  fs8.rmSync(leasePath(stateDir, handle.token), { force: true });
12256
12256
  }
12257
12257
  const recordedOwner = readJson(ownerPath(stateDir));
@@ -12530,13 +12530,13 @@ function readAndPruneStore(stateDir, deps) {
12530
12530
  if (!entry.isFile() || !entry.name.endsWith(".json"))
12531
12531
  continue;
12532
12532
  const filePath = path7.join(leasesDir, entry.name);
12533
- const record5 = readJson(filePath);
12534
- const current = record5 ? deps.inspectProcess(record5.holder.pid) : null;
12535
- if (!record5 || !current || !sameIdentity(current, record5.holder)) {
12533
+ const record6 = readJson(filePath);
12534
+ const current = record6 ? deps.inspectProcess(record6.holder.pid) : null;
12535
+ if (!record6 || !current || !sameIdentity(current, record6.holder)) {
12536
12536
  fs8.rmSync(filePath, { force: true });
12537
12537
  continue;
12538
12538
  }
12539
- leases.push(record5);
12539
+ leases.push(record6);
12540
12540
  }
12541
12541
  let owner = normalizeRuntimeOwnerRecord(readJson(ownerPath(stateDir)));
12542
12542
  let ownerMismatch = false;
@@ -12563,24 +12563,24 @@ function readAndPruneStore(stateDir, deps) {
12563
12563
  }
12564
12564
  return { owner, ownerMismatch, leases };
12565
12565
  }
12566
- function normalizeRuntimeOwnerRecord(record5) {
12567
- if (!record5 || !isProcessIdentity(record5.process))
12566
+ function normalizeRuntimeOwnerRecord(record6) {
12567
+ if (!record6 || !isProcessIdentity(record6.process))
12568
12568
  return null;
12569
- if (record5.processes !== void 0 && (!Array.isArray(record5.processes) || record5.processes.length === 0 || !record5.processes.every(isProcessIdentity) || new Set(record5.processes.map((identity2) => identity2.pid)).size !== record5.processes.length))
12569
+ if (record6.processes !== void 0 && (!Array.isArray(record6.processes) || record6.processes.length === 0 || !record6.processes.every(isProcessIdentity) || new Set(record6.processes.map((identity2) => identity2.pid)).size !== record6.processes.length))
12570
12570
  return null;
12571
- const activeJobIds = new Set(normalizeRunIds(record5.activeJobIds));
12572
- const legacyBoundJobIds = normalizeRunIds(record5.legacyBoundJobIds);
12573
- const legacyResolvedJobIds = new Set(normalizeRunIds(record5.legacyResolvedJobIds));
12571
+ const activeJobIds = new Set(normalizeRunIds(record6.activeJobIds));
12572
+ const legacyBoundJobIds = normalizeRunIds(record6.legacyBoundJobIds);
12573
+ const legacyResolvedJobIds = new Set(normalizeRunIds(record6.legacyResolvedJobIds));
12574
12574
  for (const runId of legacyBoundJobIds) {
12575
12575
  activeJobIds.add(runId);
12576
12576
  legacyResolvedJobIds.delete(runId);
12577
12577
  }
12578
12578
  return {
12579
- process: record5.process,
12580
- ...record5.processes ? { processes: record5.processes } : {},
12581
- startedAt: record5.startedAt,
12579
+ process: record6.process,
12580
+ ...record6.processes ? { processes: record6.processes } : {},
12581
+ startedAt: record6.startedAt,
12582
12582
  activeJobIds: [...activeJobIds].sort(),
12583
- legacyActiveJobs: record5.legacyActiveJobs === void 0 ? normalizeLegacyActiveJobs(record5.activeJobs) : normalizeLegacyActiveJobs(record5.legacyActiveJobs),
12583
+ legacyActiveJobs: record6.legacyActiveJobs === void 0 ? normalizeLegacyActiveJobs(record6.activeJobs) : normalizeLegacyActiveJobs(record6.legacyActiveJobs),
12584
12584
  legacyBoundJobIds,
12585
12585
  legacyResolvedJobIds: [...legacyResolvedJobIds].sort()
12586
12586
  };
@@ -13135,7 +13135,7 @@ var init_shared_workspaces = __esm({
13135
13135
  throw new Error("Installation kind and release are required");
13136
13136
  return lock(this.home, () => {
13137
13137
  const data = this.installations();
13138
- const existing2 = data.records.find((record6) => physicalKey(record6.root) === physicalKey(root2));
13138
+ const existing2 = data.records.find((record7) => physicalKey(record7.root) === physicalKey(root2));
13139
13139
  if (existing2) {
13140
13140
  if (existing2.kind !== input.kind || input.release !== "unknown" && existing2.release !== input.release) {
13141
13141
  throw new Error(`Conflicting installation metadata for ${existing2.installationId}; existing registration is preserved. Native identity refresh/adoption is not supported yet.`);
@@ -13143,7 +13143,7 @@ var init_shared_workspaces = __esm({
13143
13143
  return existing2;
13144
13144
  }
13145
13145
  const now = (/* @__PURE__ */ new Date()).toISOString();
13146
- const record5 = {
13146
+ const record6 = {
13147
13147
  installationId: (0, import_node_crypto5.randomUUID)(),
13148
13148
  kind: input.kind,
13149
13149
  root: root2,
@@ -13154,10 +13154,10 @@ var init_shared_workspaces = __esm({
13154
13154
  registeredAt: now,
13155
13155
  updatedAt: now
13156
13156
  };
13157
- data.records.push(record5);
13157
+ data.records.push(record6);
13158
13158
  data.revision++;
13159
13159
  atomicWrite(path9.join(this.home, "installations.json"), data);
13160
- return record5;
13160
+ return record6;
13161
13161
  });
13162
13162
  }
13163
13163
  async registerWorkspace(input) {
@@ -13180,7 +13180,7 @@ var init_shared_workspaces = __esm({
13180
13180
  if (data.records.some((w2) => w2.selectedInstallationId === installation.installationId))
13181
13181
  throw new Error("Installation is already bound to another workspace");
13182
13182
  const now = (/* @__PURE__ */ new Date()).toISOString();
13183
- const record5 = {
13183
+ const record6 = {
13184
13184
  workspaceId: (0, import_node_crypto5.randomUUID)(),
13185
13185
  dataRoot,
13186
13186
  researchSchema: null,
@@ -13189,21 +13189,21 @@ var init_shared_workspaces = __esm({
13189
13189
  registeredAt: now,
13190
13190
  updatedAt: now
13191
13191
  };
13192
- data.records.push(record5);
13192
+ data.records.push(record6);
13193
13193
  data.revision++;
13194
13194
  if (!data.defaultWorkspaceId && input.selectIfFirst !== false)
13195
- data.defaultWorkspaceId = record5.workspaceId;
13195
+ data.defaultWorkspaceId = record6.workspaceId;
13196
13196
  atomicWrite(path9.join(this.home, "workspaces.json"), data);
13197
- return record5;
13197
+ return record6;
13198
13198
  });
13199
13199
  }
13200
13200
  async selectDefault(workspaceId) {
13201
13201
  return lock(this.home, () => {
13202
13202
  const data = this.workspaces();
13203
- const record5 = data.records.find((w2) => w2.workspaceId === workspaceId);
13204
- if (!record5)
13203
+ const record6 = data.records.find((w2) => w2.workspaceId === workspaceId);
13204
+ if (!record6)
13205
13205
  throw new Error(`Unknown workspace: ${workspaceId}`);
13206
- const installation = this.installations().records.find((i2) => i2.installationId === record5.selectedInstallationId);
13206
+ const installation = this.installations().records.find((i2) => i2.installationId === record6.selectedInstallationId);
13207
13207
  if (!installation)
13208
13208
  throw new Error("Selected installation is unregistered");
13209
13209
  this.validateInstallation(installation);
@@ -13212,15 +13212,15 @@ var init_shared_workspaces = __esm({
13212
13212
  data.revision++;
13213
13213
  atomicWrite(path9.join(this.home, "workspaces.json"), data);
13214
13214
  }
13215
- return record5;
13215
+ return record6;
13216
13216
  });
13217
13217
  }
13218
- validateInstallation(record5) {
13219
- if (record5.os !== process.platform || record5.architecture !== process.arch)
13220
- throw new Error(`Installation platform mismatch: ${record5.installationId}`);
13221
- const canonical2 = canonicalDirectory(record5.root);
13222
- if (!samePath(canonical2, record5.root))
13223
- throw new Error(`Installation root moved: ${record5.installationId}`);
13218
+ validateInstallation(record6) {
13219
+ if (record6.os !== process.platform || record6.architecture !== process.arch)
13220
+ throw new Error(`Installation platform mismatch: ${record6.installationId}`);
13221
+ const canonical2 = canonicalDirectory(record6.root);
13222
+ if (!samePath(canonical2, record6.root))
13223
+ throw new Error(`Installation root moved: ${record6.installationId}`);
13224
13224
  if (this.validateRoot && !this.validateRoot(canonical2))
13225
13225
  throw new Error(`Installation is not usable: ${canonical2}`);
13226
13226
  }
@@ -13676,18 +13676,18 @@ function serviceName(index) {
13676
13676
  }
13677
13677
  }
13678
13678
  function describeServiceStatus(response) {
13679
- const record5 = isRecord(response) ? response : {};
13680
- const data = isRecord(record5.data) ? record5.data : isRecord(record5.Data) ? record5.Data : record5;
13679
+ const record6 = isRecord(response) ? response : {};
13680
+ const data = isRecord(record6.data) ? record6.data : isRecord(record6.Data) ? record6.Data : record6;
13681
13681
  const rawStatus = data.status ?? data.Status;
13682
- const retCode = record5.iRet ?? record5.IRet ?? record5.ErrNo;
13682
+ const retCode = record6.iRet ?? record6.IRet ?? record6.ErrNo;
13683
13683
  const ready = isServiceReady(response);
13684
13684
  const reason = ready ? "\u670D\u52A1\u72B6\u6001\u4E3A2\u4E14\u5E94\u7B54\u901A\u8FC7\u6210\u529F\u5224\u5B9A" : rawStatus === void 0 ? "\u5E94\u7B54\u7F3A\u5C11\u670D\u52A1\u72B6\u6001\u5B57\u6BB5" : Number(rawStatus) !== 2 ? "\u670D\u52A1\u72B6\u6001\u5C1A\u672A\u8FBE\u5230\u5C31\u7EEA\u503C2" : "\u72B6\u6001\u4E3A2\u4F46\u5E94\u7B54\u9519\u8BEF\u7801\u672A\u901A\u8FC7\u6210\u529F\u5224\u5B9A";
13685
- const serviceMessage = data.msg ?? data.message ?? data.ErrMsg ?? record5.msg ?? record5.message ?? record5.ErrMsg;
13685
+ const serviceMessage = data.msg ?? data.message ?? data.ErrMsg ?? record6.msg ?? record6.message ?? record6.ErrMsg;
13686
13686
  return {
13687
13687
  ready,
13688
13688
  rawStatus: rawStatus ?? null,
13689
13689
  retCode: retCode ?? null,
13690
- success: record5.success ?? null,
13690
+ success: record6.success ?? null,
13691
13691
  serviceMessage,
13692
13692
  reason,
13693
13693
  result: `${ready ? "\u5DF2\u5C31\u7EEA" : "\u672A\u5C31\u7EEA"}\uFF1A${reason}${serviceMessage ? `\uFF1B\u670D\u52A1\u6D88\u606F\uFF1A${serviceMessage}` : ""}`
@@ -14520,9 +14520,9 @@ async function resolveAssistantInstallerDescriptor(config2, installType2, option
14520
14520
  const body = await response.json();
14521
14521
  if (!Array.isArray(body))
14522
14522
  throw new Error("\u5B89\u88C5\u5305\u7248\u672C\u5217\u8868\u4E0D\u662F JSON \u6570\u7EC4");
14523
- const records = body.filter((item) => Boolean(item) && typeof item === "object" && !Array.isArray(item)).flatMap((record5) => {
14524
- const version2 = normalizeStableProductVersion(record5.version);
14525
- return version2 ? [{ record: record5, version: version2 }] : [];
14523
+ const records = body.filter((item) => Boolean(item) && typeof item === "object" && !Array.isArray(item)).flatMap((record6) => {
14524
+ const version2 = normalizeStableProductVersion(record6.version);
14525
+ return version2 ? [{ record: record6, version: version2 }] : [];
14526
14526
  }).sort((left, right) => compareNumericVersion(right.version, left.version));
14527
14527
  if (records.length === 0)
14528
14528
  throw new Error("\u5B89\u88C5\u5305\u7248\u672C\u5217\u8868\u6CA1\u6709\u7A33\u5B9A\u8BED\u4E49\u7248\u672C");
@@ -14563,12 +14563,12 @@ function resolvePinnedAssistantInstallerDescriptor(config2, installType2) {
14563
14563
  sha256: config2.backserviceDownloadSha256[config2.envMode][normalized]?.trim() || void 0
14564
14564
  };
14565
14565
  }
14566
- function validateLatestRecord(record5, installType2) {
14567
- const internalVersion = typeof record5.internalVersion === "string" ? record5.internalVersion.trim() : "";
14566
+ function validateLatestRecord(record6, installType2) {
14567
+ const internalVersion = typeof record6.internalVersion === "string" ? record6.internalVersion.trim() : "";
14568
14568
  if (!/^\d+(?:\.\d+)+$/.test(internalVersion) || internalVersion.split(".").some((part) => !Number.isSafeInteger(Number(part)))) {
14569
14569
  return "internalVersion \u7F3A\u5931\u6216\u4E0D\u662F\u5B89\u5168\u7684\u6570\u5B57\u70B9\u5206\u7248\u672C";
14570
14570
  }
14571
- const fileName = typeof record5.fileName === "string" ? record5.fileName.trim() : "";
14571
+ const fileName = typeof record6.fileName === "string" ? record6.fileName.trim() : "";
14572
14572
  if (!fileName || path12.basename(fileName) !== fileName || !/^[A-Za-z0-9._-]+\.exe$/i.test(fileName)) {
14573
14573
  return "fileName \u5FC5\u987B\u662F\u7EAF\u6587\u4EF6\u540D";
14574
14574
  }
@@ -14576,8 +14576,8 @@ function validateLatestRecord(record5, installType2) {
14576
14576
  if (!fileName.toLowerCase().startsWith(prefix) || !fileName.toLowerCase().endsWith(".exe")) {
14577
14577
  return `fileName \u5FC5\u987B\u5339\u914D ${prefix}*.exe`;
14578
14578
  }
14579
- const fileSize = Number.isSafeInteger(record5.fileSize) && Number(record5.fileSize) > 0 ? Number(record5.fileSize) : void 0;
14580
- const sha2562 = typeof record5.sha256 === "string" ? record5.sha256.trim() : record5.sha256;
14579
+ const fileSize = Number.isSafeInteger(record6.fileSize) && Number(record6.fileSize) > 0 ? Number(record6.fileSize) : void 0;
14580
+ const sha2562 = typeof record6.sha256 === "string" ? record6.sha256.trim() : record6.sha256;
14581
14581
  if (sha2562 !== void 0 && !/^[a-fA-F0-9]{64}$/.test(String(sha2562))) {
14582
14582
  return "sha256 \u4E0D\u662F 64 \u4F4D\u5341\u516D\u8FDB\u5236\u6458\u8981";
14583
14583
  }
@@ -15666,9 +15666,9 @@ async function resolveSelectedRoot(config2, options, purpose) {
15666
15666
  throw new Error(`Invalid ZLT_CLIENT_ROOT: ${reason}`);
15667
15667
  }
15668
15668
  if (store) {
15669
- const registered = store.list().installations.records.find((record5) => {
15669
+ const registered = store.list().installations.records.find((record6) => {
15670
15670
  try {
15671
- return canonicalInstallationRoot(record5.root) === canonicalInstallationRoot(environmentRoot);
15671
+ return canonicalInstallationRoot(record6.root) === canonicalInstallationRoot(environmentRoot);
15672
15672
  } catch {
15673
15673
  return false;
15674
15674
  }
@@ -16374,7 +16374,7 @@ async function startDeviceAuthorization(options = {}) {
16374
16374
  const base = validatedBase(options.apiBase || DEFAULT_API_BASE);
16375
16375
  const issuedAt = (options.now ?? Date.now)();
16376
16376
  const value = await requestJson(options, base, "/api/v1/auth/device/start", {});
16377
- if (!record3(value) || !text(value.deviceId) || !text(value.userCode) || !text(value.verificationUri) || !text(value.verificationUriComplete) || !positive(value.expiresIn) || !positive(value.interval))
16377
+ if (!record4(value) || !text(value.deviceId) || !text(value.userCode) || !text(value.verificationUri) || !text(value.verificationUriComplete) || !positive(value.expiresIn) || !positive(value.interval))
16378
16378
  malformed("start");
16379
16379
  validateVerificationUri(value.verificationUri, base, false);
16380
16380
  validateVerificationUri(value.verificationUriComplete, base, true, value.userCode);
@@ -16410,7 +16410,7 @@ async function pollDeviceAuthorization(session, options = {}) {
16410
16410
  const value = await requestJson({ ...options, requestTimeoutMs: Math.min(options.requestTimeoutMs ?? 15e3, remaining) }, base, "/api/v1/auth/device/poll", { deviceId }, true);
16411
16411
  if (now() >= deadline)
16412
16412
  throw new DeviceAuthorizationError("expired_token", "Device authorization expired");
16413
- if (!record3(value))
16413
+ if (!record4(value))
16414
16414
  malformed("poll");
16415
16415
  if (value.error === "authorization_pending")
16416
16416
  continue;
@@ -16459,7 +16459,7 @@ async function requestJson(options, base, path47, payload, allowPoll400 = false)
16459
16459
  signal: controller.signal
16460
16460
  });
16461
16461
  const body = await readBoundedJson(response);
16462
- if (!response.ok && !(allowPoll400 && response.status === 400 && record3(body) && ["authorization_pending", "slow_down", "expired_token", "access_denied"].includes(String(body.error))))
16462
+ if (!response.ok && !(allowPoll400 && response.status === 400 && record4(body) && ["authorization_pending", "slow_down", "expired_token", "access_denied"].includes(String(body.error))))
16463
16463
  throw new DeviceAuthorizationError("http_error", "Device authorization request failed");
16464
16464
  return body;
16465
16465
  } catch (error2) {
@@ -16533,11 +16533,11 @@ function validateVerificationUri(value, base, complete, userCode) {
16533
16533
  if (!complete && keys.length || complete && (keys.length !== 1 || keys[0] !== "user_code"))
16534
16534
  throw new DeviceAuthorizationError("invalid_endpoint", "Verification URI query is invalid");
16535
16535
  }
16536
- function record3(value) {
16536
+ function record4(value) {
16537
16537
  return typeof value === "object" && value !== null;
16538
16538
  }
16539
16539
  function validSession(value) {
16540
- if (!record3(value))
16540
+ if (!record4(value))
16541
16541
  return false;
16542
16542
  try {
16543
16543
  const shape = text(value.deviceId) && text(value.userCode) && text(value.verificationUri) && text(value.verificationUriComplete) && positive(value.expiresIn) && positive(value.interval) && typeof value.issuedAt === "number" && Number.isFinite(value.issuedAt) && text(value.gatewayOrigin) && new URL(value.verificationUri).origin === value.gatewayOrigin && new URL(value.verificationUriComplete).origin === value.gatewayOrigin;
@@ -16776,6 +16776,66 @@ var init_workbuddy_toolchains = __esm({
16776
16776
  }
16777
16777
  });
16778
16778
 
16779
+ // ../zlt-runtime-core/dist/clientlite-download-progress.js
16780
+ function reportClientLiteDownloadProgress(onProgress, message) {
16781
+ try {
16782
+ onProgress?.(message);
16783
+ } catch {
16784
+ }
16785
+ }
16786
+ var ClientLiteDownloadProgress;
16787
+ var init_clientlite_download_progress = __esm({
16788
+ "../zlt-runtime-core/dist/clientlite-download-progress.js"() {
16789
+ "use strict";
16790
+ init_define_CLIENTLITE_NPM_RELEASE();
16791
+ ClientLiteDownloadProgress = class {
16792
+ label;
16793
+ onProgress;
16794
+ phase = "starting";
16795
+ received = 0;
16796
+ expected = 0;
16797
+ timer;
16798
+ constructor(label, onProgress) {
16799
+ this.label = label;
16800
+ this.onProgress = onProgress;
16801
+ if (onProgress)
16802
+ this.timer = setInterval(() => this.emit(), 3e4);
16803
+ }
16804
+ stage(phase, expectedBytes) {
16805
+ this.phase = phase;
16806
+ this.received = 0;
16807
+ this.expected = expectedBytes;
16808
+ this.emit();
16809
+ }
16810
+ bytes(received) {
16811
+ this.received = received;
16812
+ }
16813
+ verified() {
16814
+ this.phase = "verified";
16815
+ this.emit();
16816
+ }
16817
+ failed(error2, deadlineExpired = false) {
16818
+ const original = error2 instanceof Error ? error2.message : String(error2);
16819
+ const safe = original.replace(/https?:\/\/[^\s"'<>]+/gi, "[download URL]");
16820
+ const reason = deadlineExpired ? "download deadline exceeded (600 seconds)" : "download failed";
16821
+ const failure = new Error(`${this.label} ${reason}; ${this.snapshot()}: ${safe}`, { cause: error2 });
16822
+ reportClientLiteDownloadProgress(this.onProgress, failure.message);
16823
+ return failure;
16824
+ }
16825
+ close() {
16826
+ if (this.timer)
16827
+ clearInterval(this.timer);
16828
+ }
16829
+ snapshot() {
16830
+ return `stage=${this.phase} receivedBytes=${this.received} expectedBytes=${this.expected}`;
16831
+ }
16832
+ emit() {
16833
+ reportClientLiteDownloadProgress(this.onProgress, `${this.label} ${this.snapshot()}`);
16834
+ }
16835
+ };
16836
+ }
16837
+ });
16838
+
16779
16839
  // ../zlt-runtime-core/dist/clientlite-toolchains.js
16780
16840
  function validatePinnedClientLiteToolchains(expected) {
16781
16841
  for (const kind of ["python", "git"]) {
@@ -16905,10 +16965,16 @@ function tarExecutable(env) {
16905
16965
  function runTar(tar2, args, cwd) {
16906
16966
  return (0, import_node_child_process5.execFileSync)(tar2, args, { cwd, encoding: "utf8", timeout: 12e4, maxBuffer: 16 * 1024 * 1024, windowsHide: true });
16907
16967
  }
16908
- async function download(url2, destination, size, digest) {
16968
+ async function download(url2, destination, size, digest, kind, onProgress) {
16969
+ const progress = new ClientLiteDownloadProgress(`ClientLite toolchain ${kind} ${pins[kind].version}`, onProgress);
16970
+ let deadlineExpired = false;
16909
16971
  const controller = new AbortController();
16910
- const timeout = setTimeout(() => controller.abort(), 6e5);
16972
+ const timeout = setTimeout(() => {
16973
+ deadlineExpired = true;
16974
+ controller.abort();
16975
+ }, 6e5);
16911
16976
  try {
16977
+ progress.stage("archive-headers", size);
16912
16978
  let current = url2;
16913
16979
  let response;
16914
16980
  for (let redirect = 0; redirect <= 5; redirect++) {
@@ -16929,12 +16995,14 @@ async function download(url2, destination, size, digest) {
16929
16995
  const declared = response.headers.get("content-length");
16930
16996
  if (declared && Number(declared) !== size)
16931
16997
  throw new Error("Toolchain archive has unexpected size");
16998
+ progress.stage("archive-body", size);
16932
16999
  const handle = fs18.openSync(destination, "wx");
16933
17000
  const hash = (0, import_node_crypto6.createHash)("sha256");
16934
17001
  let received = 0;
16935
17002
  try {
16936
17003
  for await (const chunk of response.body) {
16937
17004
  received += chunk.length;
17005
+ progress.bytes(received);
16938
17006
  if (received > size)
16939
17007
  throw new Error("Toolchain archive exceeds pinned size");
16940
17008
  hash.update(chunk);
@@ -16948,21 +17016,28 @@ async function download(url2, destination, size, digest) {
16948
17016
  }
16949
17017
  if (received !== size || hash.digest("hex") !== digest)
16950
17018
  throw new Error("Toolchain archive size or SHA-256 mismatch");
17019
+ progress.verified();
17020
+ } catch (error2) {
17021
+ throw progress.failed(error2, deadlineExpired);
16951
17022
  } finally {
16952
17023
  clearTimeout(timeout);
17024
+ progress.close();
16953
17025
  }
16954
17026
  }
16955
- async function install(kind, root2, env) {
17027
+ async function install(kind, root2, env, onProgress) {
16956
17028
  const pin = pins[kind];
16957
17029
  const final = path18.join(root2, pin.directory);
16958
- if (existsEntry(final))
16959
- return inspectDownloaded(kind, root2);
17030
+ if (existsEntry(final)) {
17031
+ const cached2 = inspectDownloaded(kind, root2);
17032
+ reportClientLiteDownloadProgress(onProgress, `ClientLite toolchain ${kind} ${pin.version} verified-cache-hit`);
17033
+ return cached2;
17034
+ }
16960
17035
  const stage = fs18.mkdtempSync(path18.join(root2, `.stage-${kind}-`));
16961
17036
  try {
16962
17037
  const archive = path18.join(stage, "archive");
16963
17038
  const content = path18.join(stage, "content");
16964
17039
  fs18.mkdirSync(content);
16965
- await download(pin.url, archive, pin.size, pin.sha256);
17040
+ await download(pin.url, archive, pin.size, pin.sha256, kind, onProgress);
16966
17041
  const tar2 = tarExecutable(env);
16967
17042
  const names = runTar(tar2, ["-tf", archive], stage);
16968
17043
  const listing = runTar(tar2, ["-tvf", archive], stage);
@@ -17015,7 +17090,7 @@ async function prepareSelectedPinnedClientLiteToolchains(expected, kinds2, optio
17015
17090
  try {
17016
17091
  fs18.writeSync(fd, owner);
17017
17092
  fs18.fsyncSync(fd);
17018
- const results = await Promise.allSettled(kinds2.map((kind) => install(kind, root2, options.env ?? process.env)));
17093
+ const results = await Promise.allSettled(kinds2.map((kind) => install(kind, root2, options.env ?? process.env, options.onProgress)));
17019
17094
  const failure = results.find((result) => result.status === "rejected");
17020
17095
  if (failure?.status === "rejected")
17021
17096
  throw failure.reason;
@@ -17033,6 +17108,7 @@ var init_clientlite_toolchains = __esm({
17033
17108
  path18 = __toESM(require("node:path"), 1);
17034
17109
  import_node_crypto6 = require("node:crypto");
17035
17110
  import_node_child_process5 = require("node:child_process");
17111
+ init_clientlite_download_progress();
17036
17112
  init_workbuddy_toolchains();
17037
17113
  pins = {
17038
17114
  python: {
@@ -17316,6 +17392,10 @@ async function prepareClientLiteReleaseToolchains(expected, plan, options = {})
17316
17392
  validateClientLiteToolchainPlan(expected, plan, options);
17317
17393
  const snapshot = { ...plan, python: { ...plan.python, ...plan.python.workbuddyImage ? { workbuddyImage: { ...plan.python.workbuddyImage } } : {} }, git: { ...plan.git, ...plan.git.workbuddyImage ? { workbuddyImage: { ...plan.git.workbuddyImage } } : {} } };
17318
17394
  const downloads = ["python", "git"].filter((kind) => snapshot[kind].source === "download" && snapshot[kind].needsDownload);
17395
+ for (const kind of ["python", "git"])
17396
+ if (!downloads.includes(kind)) {
17397
+ reportClientLiteDownloadProgress(options.onProgress, `ClientLite toolchain ${kind} ${snapshot[kind].version} ${snapshot[kind].source === "download" ? "verified-cache-hit" : "verified-agent-reuse"}`);
17398
+ }
17319
17399
  await prepareSelectedPinnedClientLiteToolchains(expected, downloads, options);
17320
17400
  return validateClientLiteSelectedToolchains(expected, { platform: "win32/x64", ready: true, python: snapshot.python, git: snapshot.git, diagnostics: [] }, options);
17321
17401
  }
@@ -17324,6 +17404,7 @@ var init_clientlite_toolchain_plan = __esm({
17324
17404
  "../zlt-runtime-core/dist/clientlite-toolchain-plan.js"() {
17325
17405
  "use strict";
17326
17406
  init_define_CLIENTLITE_NPM_RELEASE();
17407
+ init_clientlite_download_progress();
17327
17408
  fs19 = __toESM(require("node:fs"), 1);
17328
17409
  os9 = __toESM(require("node:os"), 1);
17329
17410
  path19 = __toESM(require("node:path"), 1);
@@ -22086,37 +22167,35 @@ async function request(raw, fetchImpl, signal) {
22086
22167
  }
22087
22168
  throw new Error("ClientLite pip wheel redirect limit exceeded");
22088
22169
  }
22089
- async function downloadWheelAttempt(wheel, target, fetchImpl, signal) {
22170
+ async function downloadWheelAttempt(wheel, target, fetchImpl, signal, progress) {
22171
+ progress.stage("archive-headers", wheel.size);
22172
+ const response = await request(wheel.url, fetchImpl, signal);
22173
+ if (!response.ok || !response.body)
22174
+ throw new Error(`ClientLite pip wheel download failed: ${wheel.filename} (HTTP ${response.status})`);
22175
+ const length = response.headers.get("content-length");
22176
+ if (length !== null && Number(length) !== wheel.size)
22177
+ throw new Error(`ClientLite pip wheel size mismatch: ${wheel.filename}`);
22178
+ progress.stage("archive-body", wheel.size);
22179
+ const fd = fs22.openSync(target, "wx");
22180
+ const hash = (0, import_node_crypto9.createHash)("sha256");
22181
+ let count = 0;
22090
22182
  try {
22091
- const response = await request(wheel.url, fetchImpl, signal);
22092
- if (!response.ok || !response.body)
22093
- throw new Error(`ClientLite pip wheel download failed: ${wheel.filename} (HTTP ${response.status})`);
22094
- const length = response.headers.get("content-length");
22095
- if (length !== null && Number(length) !== wheel.size)
22096
- throw new Error(`ClientLite pip wheel size mismatch: ${wheel.filename}`);
22097
- const fd = fs22.openSync(target, "wx");
22098
- const hash = (0, import_node_crypto9.createHash)("sha256");
22099
- let count = 0;
22100
- try {
22101
- for await (const chunk of response.body) {
22102
- count += chunk.length;
22103
- if (count > wheel.size)
22104
- throw new Error(`ClientLite pip wheel exceeds pinned size: ${wheel.filename}`);
22105
- hash.update(chunk);
22106
- let offset = 0;
22107
- while (offset < chunk.length)
22108
- offset += fs22.writeSync(fd, chunk, offset, chunk.length - offset);
22109
- }
22110
- fs22.fsyncSync(fd);
22111
- } finally {
22112
- fs22.closeSync(fd);
22113
- }
22114
- if (count !== wheel.size || hash.digest("hex") !== wheel.sha256.toLowerCase())
22115
- throw new Error(`ClientLite pip wheel SHA-256 or size mismatch: ${wheel.filename}`);
22116
- } catch (error2) {
22117
- const failure = error2;
22118
- throw new Error(`ClientLite SDK download failed for ${wheel.filename}: ${failure.message}${failure.cause?.code ? ` (${failure.cause.code})` : ""}`, { cause: error2 });
22183
+ for await (const chunk of response.body) {
22184
+ count += chunk.length;
22185
+ progress.bytes(count);
22186
+ if (count > wheel.size)
22187
+ throw new Error(`ClientLite pip wheel exceeds pinned size: ${wheel.filename}`);
22188
+ hash.update(chunk);
22189
+ let offset = 0;
22190
+ while (offset < chunk.length)
22191
+ offset += fs22.writeSync(fd, chunk, offset, chunk.length - offset);
22192
+ }
22193
+ fs22.fsyncSync(fd);
22194
+ } finally {
22195
+ fs22.closeSync(fd);
22119
22196
  }
22197
+ if (count !== wheel.size || hash.digest("hex") !== wheel.sha256.toLowerCase())
22198
+ throw new Error(`ClientLite pip wheel SHA-256 or size mismatch: ${wheel.filename}`);
22120
22199
  }
22121
22200
  function transientTransportFailure(error2) {
22122
22201
  let current = error2;
@@ -22128,32 +22207,39 @@ function transientTransportFailure(error2) {
22128
22207
  }
22129
22208
  return false;
22130
22209
  }
22131
- async function downloadWheel(wheel, target, fetchImpl, parentSignal) {
22210
+ async function downloadWheel(wheel, target, fetchImpl, parentSignal, onProgress) {
22211
+ const progress = new ClientLiteDownloadProgress(`ClientLite SDK ${wheel.filename}`, onProgress);
22212
+ let deadlineExpired = false;
22132
22213
  const controller = new AbortController();
22133
22214
  const abortFromParent = () => controller.abort(parentSignal?.reason);
22134
22215
  if (parentSignal?.aborted)
22135
22216
  abortFromParent();
22136
22217
  else
22137
22218
  parentSignal?.addEventListener("abort", abortFromParent, { once: true });
22138
- const timeout = setTimeout(() => controller.abort(), MAX_DOWNLOAD_MS);
22219
+ const timeout = setTimeout(() => {
22220
+ deadlineExpired = true;
22221
+ controller.abort();
22222
+ }, MAX_DOWNLOAD_MS);
22139
22223
  try {
22140
22224
  for (let attempt = 0; attempt < 2; attempt++) {
22141
22225
  try {
22142
- await downloadWheelAttempt(wheel, target, fetchImpl, controller.signal);
22226
+ await downloadWheelAttempt(wheel, target, fetchImpl, controller.signal, progress);
22227
+ progress.verified();
22143
22228
  return;
22144
22229
  } catch (error2) {
22145
22230
  if (attempt !== 0 || controller.signal.aborted || !transientTransportFailure(error2))
22146
- throw error2;
22231
+ throw progress.failed(error2, deadlineExpired);
22147
22232
  if (exists(target))
22148
22233
  fs22.unlinkSync(target);
22149
22234
  }
22150
22235
  }
22151
22236
  } finally {
22152
22237
  clearTimeout(timeout);
22238
+ progress.close();
22153
22239
  parentSignal?.removeEventListener("abort", abortFromParent);
22154
22240
  }
22155
22241
  }
22156
- async function downloadWheels(wheels, wheelhouse, fetchImpl) {
22242
+ async function downloadWheels(wheels, wheelhouse, fetchImpl, onProgress) {
22157
22243
  const abort = new AbortController();
22158
22244
  let cursor = 0;
22159
22245
  let firstError;
@@ -22164,7 +22250,7 @@ async function downloadWheels(wheels, wheelhouse, fetchImpl) {
22164
22250
  return;
22165
22251
  const wheel = wheels[index];
22166
22252
  try {
22167
- await downloadWheel(wheel, path22.join(wheelhouse, wheel.filename), fetchImpl, abort.signal);
22253
+ await downloadWheel(wheel, path22.join(wheelhouse, wheel.filename), fetchImpl, abort.signal, onProgress);
22168
22254
  } catch (error2) {
22169
22255
  firstError ??= error2;
22170
22256
  abort.abort(error2);
@@ -22183,8 +22269,11 @@ async function acquireClientLitePipSdk(options) {
22183
22269
  requireRealAncestors(options.cacheDir);
22184
22270
  const key = (0, import_node_crypto9.createHash)("sha256").update(JSON.stringify(options.sdk)).digest("hex");
22185
22271
  const final = path22.join(options.cacheDir, `pip-sdk-${key}`);
22186
- if (exists(final))
22187
- return verifyCache(final, options.sdk);
22272
+ if (exists(final)) {
22273
+ const cached2 = verifyCache(final, options.sdk);
22274
+ reportClientLiteDownloadProgress(options.onProgress, `ClientLite SDK ${options.sdk.sdkVersion} verified-cache-hit (${options.sdk.wheels.length} artifacts)`);
22275
+ return cached2;
22276
+ }
22188
22277
  fs22.mkdirSync(options.cacheDir, { recursive: true });
22189
22278
  const lock3 = `${final}.lock`;
22190
22279
  const fd = fs22.openSync(lock3, "wx");
@@ -22197,7 +22286,7 @@ async function acquireClientLitePipSdk(options) {
22197
22286
  const wheelhouse = path22.join(stage, "wheelhouse");
22198
22287
  fs22.mkdirSync(wheelhouse);
22199
22288
  fs22.writeFileSync(path22.join(stage, "requirements.lock"), expectedLock(options.sdk), { flag: "wx" });
22200
- await downloadWheels(options.sdk.wheels, wheelhouse, options.fetchImpl ?? fetch);
22289
+ await downloadWheels(options.sdk.wheels, wheelhouse, options.fetchImpl ?? fetch, options.onProgress);
22201
22290
  verifyCache(stage, options.sdk);
22202
22291
  fs22.renameSync(stage, final);
22203
22292
  stage = void 0;
@@ -22218,6 +22307,7 @@ var init_clientlite_pip = __esm({
22218
22307
  fs22 = __toESM(require("node:fs"), 1);
22219
22308
  path22 = __toESM(require("node:path"), 1);
22220
22309
  import_node_crypto9 = require("node:crypto");
22310
+ init_clientlite_download_progress();
22221
22311
  SHA256 = /^[a-f0-9]{64}$/i;
22222
22312
  NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
22223
22313
  VERSION = /^[A-Za-z0-9][A-Za-z0-9.!+_-]*$/;
@@ -22379,7 +22469,7 @@ async function acquireClientLiteNativePayload(options) {
22379
22469
  const registryUrl = options.registryUrl ?? "https://registry.npmjs.org";
22380
22470
  if (new URL(registryUrl).protocol !== "https:")
22381
22471
  throw new Error("ClientLite npm registry requires HTTPS");
22382
- const nativeRoot = await acquireOne(options.release.packages.native, options.release, "native", options.cacheDir, registryUrl, options.fetchImpl ?? fetch);
22472
+ const nativeRoot = await acquireOne(options.release.packages.native, options.release, "native", options.cacheDir, registryUrl, options.fetchImpl ?? fetch, void 0, options.onProgress);
22383
22473
  return { archivePath: path23.join(nativeRoot, "clientlite.zip"), nativeRoot };
22384
22474
  }
22385
22475
  function cacheKey(pin) {
@@ -22461,11 +22551,17 @@ async function request2(url2, fetchImpl, signal) {
22461
22551
  }
22462
22552
  throw new Error("ClientLite npm redirect limit exceeded");
22463
22553
  }
22464
- async function download2(pin, registryUrl, target, fetchImpl) {
22554
+ async function download2(pin, registryUrl, target, fetchImpl, onProgress) {
22555
+ const progress = new ClientLiteDownloadProgress(`ClientLite npm ${pin.name}@${pin.version}`, onProgress);
22556
+ let deadlineExpired = false;
22465
22557
  const controller = new AbortController();
22466
- const timeout = setTimeout(() => controller.abort(), 6e5);
22558
+ const timeout = setTimeout(() => {
22559
+ deadlineExpired = true;
22560
+ controller.abort();
22561
+ }, 6e5);
22467
22562
  try {
22468
22563
  const metadataUrl = `${registryUrl.replace(/\/$/, "")}/${encodeURIComponent(pin.name)}/${encodeURIComponent(pin.version)}`;
22564
+ progress.stage("metadata-headers", 0);
22469
22565
  const metadataResponse = await request2(metadataUrl, fetchImpl, controller.signal);
22470
22566
  if (!metadataResponse.ok)
22471
22567
  throw new Error(`ClientLite npm metadata failed for ${pin.name}@${pin.version} (HTTP ${metadataResponse.status})`);
@@ -22474,10 +22570,12 @@ async function download2(pin, registryUrl, target, fetchImpl) {
22474
22570
  throw new Error("ClientLite npm metadata exceeds limit");
22475
22571
  if (!metadataResponse.body)
22476
22572
  throw new Error("ClientLite npm metadata has no body");
22573
+ progress.stage("metadata-body", metadataLength);
22477
22574
  const metadataChunks = [];
22478
22575
  let metadataBytes = 0;
22479
22576
  for await (const chunk of metadataResponse.body) {
22480
22577
  metadataBytes += chunk.length;
22578
+ progress.bytes(metadataBytes);
22481
22579
  if (metadataBytes > MAX_METADATA)
22482
22580
  throw new Error("ClientLite npm metadata exceeds limit");
22483
22581
  metadataChunks.push(Buffer.from(chunk));
@@ -22487,18 +22585,21 @@ async function download2(pin, registryUrl, target, fetchImpl) {
22487
22585
  const dist = ownObject(metadata.dist) ? metadata.dist : void 0;
22488
22586
  if (metadata.name !== pin.name || metadata.version !== pin.version || dist?.integrity !== pin.integrity || typeof dist?.tarball !== "string")
22489
22587
  throw new Error(`ClientLite npm exact-version metadata mismatch: ${pin.name}@${pin.version}`);
22588
+ progress.stage("archive-headers", pin.size);
22490
22589
  const response = await request2(dist.tarball, fetchImpl, controller.signal);
22491
22590
  if (!response.ok || !response.body)
22492
22591
  throw new Error(`ClientLite npm tarball failed for ${pin.name}@${pin.version} (HTTP ${response.status})`);
22493
22592
  const declared = response.headers.get("content-length");
22494
22593
  if (declared && Number(declared) !== pin.size)
22495
22594
  throw new Error(`ClientLite npm tarball size mismatch: ${pin.name}`);
22595
+ progress.stage("archive-body", pin.size);
22496
22596
  const fd = fs23.openSync(target, "wx");
22497
22597
  const hash = (0, import_node_crypto10.createHash)("sha512");
22498
22598
  let count = 0;
22499
22599
  try {
22500
22600
  for await (const chunk of response.body) {
22501
22601
  count += chunk.length;
22602
+ progress.bytes(count);
22502
22603
  if (count > pin.size)
22503
22604
  throw new Error(`ClientLite npm tarball exceeds pinned size: ${pin.name}`);
22504
22605
  hash.update(chunk);
@@ -22512,8 +22613,12 @@ async function download2(pin, registryUrl, target, fetchImpl) {
22512
22613
  }
22513
22614
  if (count !== pin.size || `sha512-${hash.digest("base64")}` !== pin.integrity)
22514
22615
  throw new Error(`ClientLite npm tarball integrity or size mismatch: ${pin.name}`);
22616
+ progress.verified();
22617
+ } catch (error2) {
22618
+ throw progress.failed(error2, deadlineExpired);
22515
22619
  } finally {
22516
22620
  clearTimeout(timeout);
22621
+ progress.close();
22517
22622
  }
22518
22623
  }
22519
22624
  async function extractVerified(tarball, target, pin) {
@@ -22602,12 +22707,13 @@ function rejectRedirectedAncestors2(target) {
22602
22707
  current = parent;
22603
22708
  }
22604
22709
  }
22605
- async function acquireOne(pin, release, kind, cacheDir, registryUrl, fetchImpl, sdkPart) {
22710
+ async function acquireOne(pin, release, kind, cacheDir, registryUrl, fetchImpl, sdkPart, onProgress) {
22606
22711
  const final = path23.join(cacheDir, cacheKey(pin));
22607
22712
  if (exists2(final)) {
22608
22713
  if (!fs23.lstatSync(final).isDirectory())
22609
22714
  throw new Error(`ClientLite npm cache is redirected: ${final}`);
22610
22715
  verifyContent(final, pin, release, kind, sdkPart);
22716
+ reportClientLiteDownloadProgress(onProgress, `ClientLite npm ${kind} ${pin.name}@${pin.version} verified-cache-hit`);
22611
22717
  return final;
22612
22718
  }
22613
22719
  fs23.mkdirSync(cacheDir, { recursive: true });
@@ -22622,7 +22728,7 @@ async function acquireOne(pin, release, kind, cacheDir, registryUrl, fetchImpl,
22622
22728
  const tarball = path23.join(stage, "payload.tgz");
22623
22729
  const content = path23.join(stage, "content");
22624
22730
  fs23.mkdirSync(content);
22625
- await download2(pin, registryUrl, tarball, fetchImpl);
22731
+ await download2(pin, registryUrl, tarball, fetchImpl, onProgress);
22626
22732
  await extractVerified(tarball, content, pin);
22627
22733
  verifyContent(content, pin, release, kind, sdkPart);
22628
22734
  fs23.renameSync(content, final);
@@ -22725,11 +22831,11 @@ async function acquireClientLiteNpmPayloads(options) {
22725
22831
  const registryUrl = options.registryUrl ?? "https://registry.npmjs.org";
22726
22832
  if (new URL(registryUrl).protocol !== "https:")
22727
22833
  throw new Error("ClientLite npm registry requires HTTPS");
22728
- const nativeRoot = await acquireOne(options.release.packages.native, options.release, "native", options.cacheDir, registryUrl, options.fetchImpl ?? fetch);
22834
+ const nativeRoot = await acquireOne(options.release.packages.native, options.release, "native", options.cacheDir, registryUrl, options.fetchImpl ?? fetch, void 0, options.onProgress);
22729
22835
  const sdkPins = [options.release.packages.sdk, ...options.release.packages.sdkParts ?? []];
22730
22836
  const sdkRoots = [];
22731
22837
  for (const [index, pin] of sdkPins.entries())
22732
- sdkRoots.push(await acquireOne(pin, options.release, "sdk", options.cacheDir, registryUrl, options.fetchImpl ?? fetch, sdkPins.length > 1 ? index : void 0));
22838
+ sdkRoots.push(await acquireOne(pin, options.release, "sdk", options.cacheDir, registryUrl, options.fetchImpl ?? fetch, sdkPins.length > 1 ? index : void 0, options.onProgress));
22733
22839
  const sdkRoot = sdkRoots[0];
22734
22840
  const wheelhouse = sdkPins.length > 1 ? path23.join(acquireMergedSdk(options.cacheDir, sdkPins, sdkRoots), "wheelhouse") : path23.join(sdkRoot, "wheelhouse");
22735
22841
  return { archivePath: path23.join(nativeRoot, "clientlite.zip"), lockPath: path23.join(sdkRoot, "requirements.lock"), wheelhouse, nativeRoot, sdkRoot };
@@ -22745,6 +22851,7 @@ var init_clientlite_npm = __esm({
22745
22851
  import_node_stream2 = require("node:stream");
22746
22852
  import_promises = require("node:stream/promises");
22747
22853
  import_tar_stream = __toESM(require_tar_stream(), 1);
22854
+ init_clientlite_download_progress();
22748
22855
  init_clientlite_toolchains();
22749
22856
  init_clientlite_pip();
22750
22857
  MAX_TARBALL = 8 * 1024 * 1024 * 1024;
@@ -23370,6 +23477,50 @@ function agentOutputFileArg(args) {
23370
23477
  }
23371
23478
  return file2;
23372
23479
  }
23480
+ var record = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
23481
+ function operationIdentity(source) {
23482
+ const identity2 = {};
23483
+ for (const key of [
23484
+ "runId",
23485
+ "backtestId",
23486
+ "strategyId",
23487
+ "codePath",
23488
+ "runDir",
23489
+ "localPath",
23490
+ "taskId",
23491
+ "uuid",
23492
+ "executionId",
23493
+ "calculateRecordId",
23494
+ "detectRecordId",
23495
+ "snapshotId",
23496
+ "recoveryToken",
23497
+ "attemptFence"
23498
+ ]) {
23499
+ if (source?.[key] !== void 0) identity2[key] = source[key];
23500
+ }
23501
+ return identity2;
23502
+ }
23503
+ function agentDecision(result, execution, recovery) {
23504
+ const envelope = record(result);
23505
+ const text3 = Array.isArray(envelope?.content) ? envelope.content.find((item) => record(item)?.type === "text") : void 0;
23506
+ const payload = record(envelope?.structuredContent) ?? record(record(record(text3)?.text)?.parsedJson);
23507
+ const data = record(payload?.Data);
23508
+ const code = payload?.ErrNo;
23509
+ const responseOutcome = envelope?.isError === true || code !== void 0 && code !== null && Number(code) !== 0 ? "error" : code === void 0 || code === null ? "not_reported" : "success";
23510
+ const recoveryDecision = { retry: execution.retry };
23511
+ for (const key of ["retryableByAgent", "requiresUserAction", "waitStopped", "reason", "failureCause", "recommendedAction"]) {
23512
+ if (data?.[key] !== void 0) recoveryDecision[key] = data[key];
23513
+ }
23514
+ if (recovery) recoveryDecision.handoff = operationIdentity(recovery);
23515
+ return {
23516
+ responseOutcome,
23517
+ isTerminal: typeof data?.isTerminal === "boolean" ? data.isTerminal : null,
23518
+ backtestOutcome: typeof data?.backtestOutcome === "string" ? data.backtestOutcome : null,
23519
+ nextAction: typeof data?.nextAction === "string" ? data.nextAction : null,
23520
+ identity: operationIdentity(data),
23521
+ recovery: recoveryDecision
23522
+ };
23523
+ }
23373
23524
  var CliAgentOutput = class {
23374
23525
  constructor(file2, provenance, command) {
23375
23526
  this.provenance = provenance;
@@ -23430,6 +23581,7 @@ var CliAgentOutput = class {
23430
23581
  return JSON.stringify({
23431
23582
  format: "zlt-agent-result-v1",
23432
23583
  command: this.command,
23584
+ decision: agentDecision(this.result, this.execution, this.recovery),
23433
23585
  cliProvenance: this.provenance,
23434
23586
  resultEncoding: "Text content containing JSON is expanded under text.parsedJson; envelope fields are retained. This is a semantic view, not the original text serialization.",
23435
23587
  execution: this.execution,
@@ -23609,19 +23761,19 @@ var REFERENCED_PROPERTIES_BY_TOOL = /* @__PURE__ */ new Map([
23609
23761
  ["mcp-get-cloud-data-list", ["exchange_id"]],
23610
23762
  ["mcp-get-data-range", ["exchange_id", "data_type"]]
23611
23763
  ]);
23612
- function record(value) {
23764
+ function record2(value) {
23613
23765
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
23614
23766
  }
23615
23767
  function cloneValue(value) {
23616
23768
  return value === void 0 ? value : JSON.parse(JSON.stringify(value));
23617
23769
  }
23618
23770
  function schemaProperty(tool, property2) {
23619
- const schema2 = record(tool.inputSchema);
23620
- const properties2 = record(schema2?.properties);
23621
- const params = record(properties2?.params);
23622
- const items = record(params?.items);
23623
- const itemProperties = record(items?.properties);
23624
- return record(itemProperties?.[property2]);
23771
+ const schema2 = record2(tool.inputSchema);
23772
+ const properties2 = record2(schema2?.properties);
23773
+ const params = record2(properties2?.params);
23774
+ const items = record2(params?.items);
23775
+ const itemProperties = record2(items?.properties);
23776
+ return record2(itemProperties?.[property2]);
23625
23777
  }
23626
23778
  var UNSUPPORTED_SCHEMA_KEYWORDS = [
23627
23779
  "oneOf",
@@ -23640,12 +23792,12 @@ var UNSUPPORTED_SCHEMA_KEYWORDS = [
23640
23792
  "unevaluatedProperties"
23641
23793
  ];
23642
23794
  function unsupportedSchemaConstraint(schemaValue, path47 = "inputSchema") {
23643
- const schema2 = record(schemaValue);
23795
+ const schema2 = record2(schemaValue);
23644
23796
  if (!schema2) return path47;
23645
23797
  for (const keyword of UNSUPPORTED_SCHEMA_KEYWORDS) {
23646
23798
  if (Object.prototype.hasOwnProperty.call(schema2, keyword)) return `${path47}.${keyword}`;
23647
23799
  }
23648
- const properties2 = record(schema2.properties);
23800
+ const properties2 = record2(schema2.properties);
23649
23801
  if (properties2) {
23650
23802
  for (const [name, property2] of Object.entries(properties2)) {
23651
23803
  const unsupported = unsupportedSchemaConstraint(property2, `${path47}.properties.${name}`);
@@ -23659,7 +23811,7 @@ function unsupportedSchemaConstraint(schemaValue, path47 = "inputSchema") {
23659
23811
  return void 0;
23660
23812
  }
23661
23813
  function explicitValue(schemaValue, path47) {
23662
- const schema2 = record(schemaValue);
23814
+ const schema2 = record2(schemaValue);
23663
23815
  if (!schema2) return { available: false, missing: [path47] };
23664
23816
  if (Object.prototype.hasOwnProperty.call(schema2, "example")) {
23665
23817
  return { available: true, value: cloneValue(schema2.example), missing: [] };
@@ -23677,7 +23829,7 @@ function explicitValue(schemaValue, path47) {
23677
23829
  return { available: true, value: cloneValue(schema2.enum[0]), missing: [] };
23678
23830
  }
23679
23831
  if (schema2.type === "object") {
23680
- const properties2 = record(schema2.properties) ?? {};
23832
+ const properties2 = record2(schema2.properties) ?? {};
23681
23833
  const required2 = Array.isArray(schema2.required) ? schema2.required.filter((item) => typeof item === "string") : [];
23682
23834
  const value = {};
23683
23835
  const missing = [];
@@ -23691,7 +23843,7 @@ function explicitValue(schemaValue, path47) {
23691
23843
  return { available: false, missing: [path47] };
23692
23844
  }
23693
23845
  function buildArgumentExample(tool) {
23694
- const schema2 = record(tool.inputSchema);
23846
+ const schema2 = record2(tool.inputSchema);
23695
23847
  const unsupported = unsupportedSchemaConstraint(schema2);
23696
23848
  if (!schema2 || unsupported) {
23697
23849
  return {
@@ -23704,7 +23856,7 @@ function buildArgumentExample(tool) {
23704
23856
  };
23705
23857
  }
23706
23858
  const generated = explicitValue(schema2, "");
23707
- const args = record(generated.value) ?? {};
23859
+ const args = record2(generated.value) ?? {};
23708
23860
  if (generated.available) {
23709
23861
  return {
23710
23862
  executable: true,
@@ -23768,7 +23920,8 @@ function buildCliUsage(tool, tools) {
23768
23920
  option: "--agent-output <new-file>",
23769
23921
  commands: ["call", "list"],
23770
23922
  mutuallyExclusiveWith: ["--output-json", "--evidence-dir"],
23771
- result: "One UTF-8 file contains execution, result and diagnostics. Read it once after completion; stdout is a short ASCII status receipt, and stderr is captured in diagnostics.",
23923
+ result: "One UTF-8 file contains a leading decision, execution, complete result and diagnostics. Read the first 60 lines for the decision, then read needed result ranges; stdout is a short ASCII status receipt, and stderr is captured in diagnostics.",
23924
+ decision: "decision.isTerminal, backtestOutcome and nextAction copy explicit business response fields; null means not reported. responseOutcome describes response success/error, not task completion. identity retains operation IDs and paths; recovery retains retry constraints and the original handoff. Never infer business completion from execution.state or numeric status.",
23772
23925
  encoding: "JSON in text content is expanded under text.parsedJson. All envelope fields are retained, but this semantic view does not preserve the original text serialization.",
23773
23926
  recovery: "Require saved=true and inspect execution.exitCode and business. Running/unknown after interruption requires inspection before retry. If saving fails after a response, emergency stdout contains the original response; do not repeat automatically.",
23774
23927
  boundary: "The file must be new. It is reserved before argument validation; unknown is saved before dispatch. No file can record failures before the CLI starts. Authentication commands do not support this mode."
@@ -29607,7 +29760,7 @@ var ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => {
29607
29760
  inst.keyType = def.keyType;
29608
29761
  inst.valueType = def.valueType;
29609
29762
  });
29610
- function record2(keyType, valueType, params) {
29763
+ function record3(keyType, valueType, params) {
29611
29764
  return new ZodRecord({
29612
29765
  type: "record",
29613
29766
  keyType,
@@ -30119,7 +30272,7 @@ var ImplementationSchema = BaseMetadataSchema.extend({
30119
30272
  });
30120
30273
  var FormElicitationCapabilitySchema = intersection(object3({
30121
30274
  applyDefaults: boolean2().optional()
30122
- }), record2(string2(), unknown()));
30275
+ }), record3(string2(), unknown()));
30123
30276
  var ElicitationCapabilitySchema = preprocess((value) => {
30124
30277
  if (value && typeof value === "object" && !Array.isArray(value)) {
30125
30278
  if (Object.keys(value).length === 0) {
@@ -30130,7 +30283,7 @@ var ElicitationCapabilitySchema = preprocess((value) => {
30130
30283
  }, intersection(object3({
30131
30284
  form: FormElicitationCapabilitySchema.optional(),
30132
30285
  url: AssertObjectSchema.optional()
30133
- }), record2(string2(), unknown()).optional()));
30286
+ }), record3(string2(), unknown()).optional()));
30134
30287
  var ClientTasksCapabilitySchema = looseObject({
30135
30288
  /**
30136
30289
  * Present if the client supports listing tasks.
@@ -30183,7 +30336,7 @@ var ClientCapabilitiesSchema = object3({
30183
30336
  /**
30184
30337
  * Experimental, non-standard capabilities that the client supports.
30185
30338
  */
30186
- experimental: record2(string2(), AssertObjectSchema).optional(),
30339
+ experimental: record3(string2(), AssertObjectSchema).optional(),
30187
30340
  /**
30188
30341
  * Present if the client supports sampling from an LLM.
30189
30342
  */
@@ -30218,7 +30371,7 @@ var ClientCapabilitiesSchema = object3({
30218
30371
  /**
30219
30372
  * Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name).
30220
30373
  */
30221
- extensions: record2(string2(), AssertObjectSchema).optional()
30374
+ extensions: record3(string2(), AssertObjectSchema).optional()
30222
30375
  });
30223
30376
  var InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({
30224
30377
  /**
@@ -30236,7 +30389,7 @@ var ServerCapabilitiesSchema = object3({
30236
30389
  /**
30237
30390
  * Experimental, non-standard capabilities that the server supports.
30238
30391
  */
30239
- experimental: record2(string2(), AssertObjectSchema).optional(),
30392
+ experimental: record3(string2(), AssertObjectSchema).optional(),
30240
30393
  /**
30241
30394
  * Present if the server supports sending log messages to the client.
30242
30395
  */
@@ -30283,7 +30436,7 @@ var ServerCapabilitiesSchema = object3({
30283
30436
  /**
30284
30437
  * Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name).
30285
30438
  */
30286
- extensions: record2(string2(), AssertObjectSchema).optional()
30439
+ extensions: record3(string2(), AssertObjectSchema).optional()
30287
30440
  });
30288
30441
  var InitializeResultSchema = ResultSchema.extend({
30289
30442
  /**
@@ -30422,7 +30575,7 @@ var ResourceContentsSchema = object3({
30422
30575
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
30423
30576
  * for notes on _meta usage.
30424
30577
  */
30425
- _meta: record2(string2(), unknown()).optional()
30578
+ _meta: record3(string2(), unknown()).optional()
30426
30579
  });
30427
30580
  var TextResourceContentsSchema = ResourceContentsSchema.extend({
30428
30581
  /**
@@ -30616,7 +30769,7 @@ var GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({
30616
30769
  /**
30617
30770
  * Arguments to use for templating the prompt.
30618
30771
  */
30619
- arguments: record2(string2(), string2()).optional()
30772
+ arguments: record3(string2(), string2()).optional()
30620
30773
  });
30621
30774
  var GetPromptRequestSchema = RequestSchema.extend({
30622
30775
  method: literal("prompts/get"),
@@ -30636,7 +30789,7 @@ var TextContentSchema = object3({
30636
30789
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
30637
30790
  * for notes on _meta usage.
30638
30791
  */
30639
- _meta: record2(string2(), unknown()).optional()
30792
+ _meta: record3(string2(), unknown()).optional()
30640
30793
  });
30641
30794
  var ImageContentSchema = object3({
30642
30795
  type: literal("image"),
@@ -30656,7 +30809,7 @@ var ImageContentSchema = object3({
30656
30809
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
30657
30810
  * for notes on _meta usage.
30658
30811
  */
30659
- _meta: record2(string2(), unknown()).optional()
30812
+ _meta: record3(string2(), unknown()).optional()
30660
30813
  });
30661
30814
  var AudioContentSchema = object3({
30662
30815
  type: literal("audio"),
@@ -30676,7 +30829,7 @@ var AudioContentSchema = object3({
30676
30829
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
30677
30830
  * for notes on _meta usage.
30678
30831
  */
30679
- _meta: record2(string2(), unknown()).optional()
30832
+ _meta: record3(string2(), unknown()).optional()
30680
30833
  });
30681
30834
  var ToolUseContentSchema = object3({
30682
30835
  type: literal("tool_use"),
@@ -30694,12 +30847,12 @@ var ToolUseContentSchema = object3({
30694
30847
  * Arguments to pass to the tool.
30695
30848
  * Must conform to the tool's inputSchema.
30696
30849
  */
30697
- input: record2(string2(), unknown()),
30850
+ input: record3(string2(), unknown()),
30698
30851
  /**
30699
30852
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
30700
30853
  * for notes on _meta usage.
30701
30854
  */
30702
- _meta: record2(string2(), unknown()).optional()
30855
+ _meta: record3(string2(), unknown()).optional()
30703
30856
  });
30704
30857
  var EmbeddedResourceSchema = object3({
30705
30858
  type: literal("resource"),
@@ -30712,7 +30865,7 @@ var EmbeddedResourceSchema = object3({
30712
30865
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
30713
30866
  * for notes on _meta usage.
30714
30867
  */
30715
- _meta: record2(string2(), unknown()).optional()
30868
+ _meta: record3(string2(), unknown()).optional()
30716
30869
  });
30717
30870
  var ResourceLinkSchema = ResourceSchema.extend({
30718
30871
  type: literal("resource_link")
@@ -30802,7 +30955,7 @@ var ToolSchema = object3({
30802
30955
  */
30803
30956
  inputSchema: object3({
30804
30957
  type: literal("object"),
30805
- properties: record2(string2(), AssertObjectSchema).optional(),
30958
+ properties: record3(string2(), AssertObjectSchema).optional(),
30806
30959
  required: array(string2()).optional()
30807
30960
  }).catchall(unknown()),
30808
30961
  /**
@@ -30812,7 +30965,7 @@ var ToolSchema = object3({
30812
30965
  */
30813
30966
  outputSchema: object3({
30814
30967
  type: literal("object"),
30815
- properties: record2(string2(), AssertObjectSchema).optional(),
30968
+ properties: record3(string2(), AssertObjectSchema).optional(),
30816
30969
  required: array(string2()).optional()
30817
30970
  }).catchall(unknown()).optional(),
30818
30971
  /**
@@ -30827,7 +30980,7 @@ var ToolSchema = object3({
30827
30980
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
30828
30981
  * for notes on _meta usage.
30829
30982
  */
30830
- _meta: record2(string2(), unknown()).optional()
30983
+ _meta: record3(string2(), unknown()).optional()
30831
30984
  });
30832
30985
  var ListToolsRequestSchema = PaginatedRequestSchema.extend({
30833
30986
  method: literal("tools/list")
@@ -30848,7 +31001,7 @@ var CallToolResultSchema = ResultSchema.extend({
30848
31001
  *
30849
31002
  * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema.
30850
31003
  */
30851
- structuredContent: record2(string2(), unknown()).optional(),
31004
+ structuredContent: record3(string2(), unknown()).optional(),
30852
31005
  /**
30853
31006
  * Whether the tool call ended in an error.
30854
31007
  *
@@ -30876,7 +31029,7 @@ var CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
30876
31029
  /**
30877
31030
  * Arguments to pass to the tool.
30878
31031
  */
30879
- arguments: record2(string2(), unknown()).optional()
31032
+ arguments: record3(string2(), unknown()).optional()
30880
31033
  });
30881
31034
  var CallToolRequestSchema = RequestSchema.extend({
30882
31035
  method: literal("tools/call"),
@@ -30978,7 +31131,7 @@ var ToolResultContentSchema = object3({
30978
31131
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
30979
31132
  * for notes on _meta usage.
30980
31133
  */
30981
- _meta: record2(string2(), unknown()).optional()
31134
+ _meta: record3(string2(), unknown()).optional()
30982
31135
  });
30983
31136
  var SamplingContentSchema = discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema]);
30984
31137
  var SamplingMessageContentBlockSchema = discriminatedUnion("type", [
@@ -30995,7 +31148,7 @@ var SamplingMessageSchema = object3({
30995
31148
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
30996
31149
  * for notes on _meta usage.
30997
31150
  */
30998
- _meta: record2(string2(), unknown()).optional()
31151
+ _meta: record3(string2(), unknown()).optional()
30999
31152
  });
31000
31153
  var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
31001
31154
  messages: array(SamplingMessageSchema),
@@ -31183,7 +31336,7 @@ var ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({
31183
31336
  */
31184
31337
  requestedSchema: object3({
31185
31338
  type: literal("object"),
31186
- properties: record2(string2(), PrimitiveSchemaDefinitionSchema),
31339
+ properties: record3(string2(), PrimitiveSchemaDefinitionSchema),
31187
31340
  required: array(string2()).optional()
31188
31341
  })
31189
31342
  });
@@ -31235,7 +31388,7 @@ var ElicitResultSchema = ResultSchema.extend({
31235
31388
  * Per MCP spec, content is "typically omitted" for decline/cancel actions.
31236
31389
  * We normalize null to undefined for leniency while maintaining type compatibility.
31237
31390
  */
31238
- content: preprocess((val) => val === null ? void 0 : val, record2(string2(), union([string2(), number2(), boolean2(), array(string2())])).optional())
31391
+ content: preprocess((val) => val === null ? void 0 : val, record3(string2(), union([string2(), number2(), boolean2(), array(string2())])).optional())
31239
31392
  });
31240
31393
  var ResourceTemplateReferenceSchema = object3({
31241
31394
  type: literal("ref/resource"),
@@ -31270,7 +31423,7 @@ var CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({
31270
31423
  /**
31271
31424
  * Previously-resolved variables in a URI template or prompt.
31272
31425
  */
31273
- arguments: record2(string2(), string2()).optional()
31426
+ arguments: record3(string2(), string2()).optional()
31274
31427
  }).optional()
31275
31428
  });
31276
31429
  var CompleteRequestSchema = RequestSchema.extend({
@@ -31306,7 +31459,7 @@ var RootSchema = object3({
31306
31459
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
31307
31460
  * for notes on _meta usage.
31308
31461
  */
31309
- _meta: record2(string2(), unknown()).optional()
31462
+ _meta: record3(string2(), unknown()).optional()
31310
31463
  });
31311
31464
  var ListRootsRequestSchema = RequestSchema.extend({
31312
31465
  method: literal("roots/list"),
@@ -34376,9 +34529,9 @@ var FACTOR_FAILURE_SIGNATURES = [
34376
34529
  function factorFailureMessage(data) {
34377
34530
  if (typeof data.errorMessage === "string" && data.errorMessage) return data.errorMessage;
34378
34531
  for (const key of ["calculateRecord", "detectRecord"]) {
34379
- const record5 = data[key];
34380
- if (isRecord4(record5) && typeof record5.errorMessage === "string" && record5.errorMessage) {
34381
- return record5.errorMessage;
34532
+ const record6 = data[key];
34533
+ if (isRecord4(record6) && typeof record6.errorMessage === "string" && record6.errorMessage) {
34534
+ return record6.errorMessage;
34382
34535
  }
34383
34536
  }
34384
34537
  return "";
@@ -36151,14 +36304,14 @@ function appendHistory(outputDir, uri, statusCode, contentSize, respFile) {
36151
36304
  fs30.writeFileSync(historyPath, kept.join("\n") + "\n", "utf-8");
36152
36305
  }
36153
36306
  }
36154
- const record5 = {
36307
+ const record6 = {
36155
36308
  time: getTimestampISO(),
36156
36309
  uri,
36157
36310
  status: statusCode,
36158
36311
  size: contentSize
36159
36312
  };
36160
- if (respFile) record5.file = respFile;
36161
- fs30.appendFileSync(historyPath, JSON.stringify(record5) + "\n", "utf-8");
36313
+ if (respFile) record6.file = respFile;
36314
+ fs30.appendFileSync(historyPath, JSON.stringify(record6) + "\n", "utf-8");
36162
36315
  }
36163
36316
  function cleanOutput(clientRootDir, maxDays = 1) {
36164
36317
  const outputDir = getOutputDir(clientRootDir);
@@ -36385,17 +36538,17 @@ function parseMcpResult(result) {
36385
36538
  function factorHandoff(result) {
36386
36539
  const data = parseMcpResult(result)?.Data;
36387
36540
  if (!data || typeof data !== "object" || Array.isArray(data)) return null;
36388
- const record5 = data;
36389
- if (record5.factorIdentityConflict === true) {
36541
+ const record6 = data;
36542
+ if (record6.factorIdentityConflict === true) {
36390
36543
  throw Object.assign(new Error("Factor response contains conflicting execution identities; inspect the original task before retrying."), {
36391
- factor: { ...record5 },
36544
+ factor: { ...record6 },
36392
36545
  factorResponse: result
36393
36546
  });
36394
36547
  }
36395
- if (typeof record5.executionId !== "string" || !record5.executionId.trim()) return null;
36396
- const recovery = { executionId: record5.executionId.trim() };
36548
+ if (typeof record6.executionId !== "string" || !record6.executionId.trim()) return null;
36549
+ const recovery = { executionId: record6.executionId.trim() };
36397
36550
  for (const key of ["calculateRecordId", "detectRecordId"]) {
36398
- if (typeof record5[key] === "string" && record5[key].trim()) recovery[key] = record5[key].trim();
36551
+ if (typeof record6[key] === "string" && record6[key].trim()) recovery[key] = record6[key].trim();
36399
36552
  }
36400
36553
  return recovery;
36401
36554
  }
@@ -36433,9 +36586,9 @@ function factorStartWithoutIdentity(result) {
36433
36586
  const payload = parseMcpResult(result);
36434
36587
  const data = payload?.Data;
36435
36588
  if (!payload || !data || typeof data !== "object" || Array.isArray(data)) return null;
36436
- const record5 = data;
36437
- if (record5.skipped === true) return null;
36438
- const status = Number(record5.status);
36589
+ const record6 = data;
36590
+ if (record6.skipped === true) return null;
36591
+ const status = Number(record6.status);
36439
36592
  if (Number.isFinite(status) && FACTOR_TERMINAL_STATUS.has(status)) {
36440
36593
  if (status === 3 || status === 4) return {
36441
36594
  ...result,
@@ -36448,9 +36601,9 @@ function factorStartWithoutIdentity(result) {
36448
36601
  };
36449
36602
  return result;
36450
36603
  }
36451
- const recovery = typeof record5.recoveryToken === "string" ? record5.recoveryToken : "";
36604
+ const recovery = typeof record6.recoveryToken === "string" ? record6.recoveryToken : "";
36452
36605
  throw Object.assign(new Error(`Factor start outcome is unknown${recovery ? ` (${recovery})` : ""}; inspect the original task before retrying and do not replay this start.`), {
36453
- factor: { ...record5, ...recovery ? { recoveryToken: recovery } : {} },
36606
+ factor: { ...record6, ...recovery ? { recoveryToken: recovery } : {} },
36454
36607
  factorResponse: result
36455
36608
  });
36456
36609
  }
@@ -36459,17 +36612,17 @@ function backtestHandoff(result) {
36459
36612
  const payload = parseMcpResult(result);
36460
36613
  const data = payload?.Data;
36461
36614
  if (!data || typeof data !== "object" || Array.isArray(data)) return null;
36462
- const record5 = data;
36463
- const status = Number(record5.status);
36615
+ const record6 = data;
36616
+ const status = Number(record6.status);
36464
36617
  if (Number.isFinite(status) && status !== 0 && status !== 1) return null;
36465
- const runId = typeof record5.runId === "string" ? record5.runId.trim() : "";
36618
+ const runId = typeof record6.runId === "string" ? record6.runId.trim() : "";
36466
36619
  if (!runId) return null;
36467
- const evidence = record5.evidence && typeof record5.evidence === "object" && !Array.isArray(record5.evidence) ? record5.evidence : void 0;
36468
- const rawCodePath = typeof record5.codePath === "string" ? record5.codePath.trim() : typeof evidence?.runDir === "string" ? evidence.runDir.trim() : "";
36620
+ const evidence = record6.evidence && typeof record6.evidence === "object" && !Array.isArray(record6.evidence) ? record6.evidence : void 0;
36621
+ const rawCodePath = typeof record6.codePath === "string" ? record6.codePath.trim() : typeof evidence?.runDir === "string" ? evidence.runDir.trim() : "";
36469
36622
  return {
36470
36623
  runId,
36471
36624
  ...rawCodePath && path30.isAbsolute(rawCodePath) ? { codePath: rawCodePath } : {},
36472
- ...record5.attemptFence !== void 0 ? { attemptFence: record5.attemptFence } : {}
36625
+ ...record6.attemptFence !== void 0 ? { attemptFence: record6.attemptFence } : {}
36473
36626
  };
36474
36627
  }
36475
36628
  function mcpErrorCode(result) {
@@ -37493,25 +37646,25 @@ function taskRoot() {
37493
37646
  function taskPath(taskId) {
37494
37647
  return path32.join(taskRoot(), `${taskId}.json`);
37495
37648
  }
37496
- function write(record5) {
37649
+ function write(record6) {
37497
37650
  fs32.mkdirSync(taskRoot(), { recursive: true });
37498
- const target = taskPath(record5.taskId);
37651
+ const target = taskPath(record6.taskId);
37499
37652
  const temporary = `${target}.${process.pid}.tmp`;
37500
- fs32.writeFileSync(temporary, `${JSON.stringify(record5)}
37653
+ fs32.writeFileSync(temporary, `${JSON.stringify(record6)}
37501
37654
  `, "utf8");
37502
37655
  fs32.renameSync(temporary, target);
37503
37656
  }
37504
37657
  function readRaw(taskId) {
37505
37658
  if (!/^[A-Za-z0-9_-]+$/.test(taskId)) return void 0;
37506
37659
  try {
37507
- const record5 = JSON.parse(fs32.readFileSync(taskPath(taskId), "utf8"));
37508
- return record5.taskId === taskId ? record5 : void 0;
37660
+ const record6 = JSON.parse(fs32.readFileSync(taskPath(taskId), "utf8"));
37661
+ return record6.taskId === taskId ? record6 : void 0;
37509
37662
  } catch {
37510
37663
  return void 0;
37511
37664
  }
37512
37665
  }
37513
- function active(record5) {
37514
- return record5.status === "queued" || record5.status === "running";
37666
+ function active(record6) {
37667
+ return record6.status === "queued" || record6.status === "running";
37515
37668
  }
37516
37669
  function alive(pid) {
37517
37670
  if (!Number.isInteger(pid) || pid <= 0) return false;
@@ -37600,7 +37753,7 @@ function launchLocked(entrypoint, argsJson, args, requestKey, spawnProcess) {
37600
37753
  }
37601
37754
  }
37602
37755
  const taskId = `install-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
37603
- const record5 = {
37756
+ const record6 = {
37604
37757
  taskId,
37605
37758
  status: "queued",
37606
37759
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -37610,10 +37763,10 @@ function launchLocked(entrypoint, argsJson, args, requestKey, spawnProcess) {
37610
37763
  installType: args.installType === "clientlite" ? "clientlite" : "assistant",
37611
37764
  ...typeof args.releaseIdentity === "string" ? { releaseIdentity: args.releaseIdentity } : {}
37612
37765
  };
37613
- write(record5);
37766
+ write(record6);
37614
37767
  let logFd;
37615
37768
  try {
37616
- logFd = fs32.openSync(record5.logPath, "a");
37769
+ logFd = fs32.openSync(record6.logPath, "a");
37617
37770
  const child = spawnProcess(process.execPath, [entrypoint, "__install-worker", taskId, argsJson], {
37618
37771
  detached: true,
37619
37772
  stdio: ["ignore", logFd, logFd],
@@ -37669,12 +37822,12 @@ var path33 = __toESM(require("node:path"), 1);
37669
37822
  var import_node_crypto12 = require("node:crypto");
37670
37823
  init_dist();
37671
37824
  function embeddedClientLiteRelease() {
37672
- const record5 = typeof define_CLIENTLITE_NPM_RELEASE_default === "undefined" ? null : define_CLIENTLITE_NPM_RELEASE_default;
37673
- if (!record5) throw new Error("This MCP artifact has no approved ClientLite npm release. Public installation is unavailable.");
37674
- const channel = record5.channel;
37825
+ const record6 = typeof define_CLIENTLITE_NPM_RELEASE_default === "undefined" ? null : define_CLIENTLITE_NPM_RELEASE_default;
37826
+ if (!record6) throw new Error("This MCP artifact has no approved ClientLite npm release. Public installation is unavailable.");
37827
+ const channel = record6.channel;
37675
37828
  if (channel !== "dev" && channel !== "latest") throw new Error("Invalid embedded ClientLite channel");
37676
- validateClientLiteRelease(record5, channel);
37677
- return record5;
37829
+ validateClientLiteRelease(record6, channel);
37830
+ return record6;
37678
37831
  }
37679
37832
  function clientLiteInstallProposal(installDir, release = embeddedClientLiteRelease(), frozenPlan) {
37680
37833
  if (installDir !== void 0 && !path33.isAbsolute(installDir)) throw new Error("ClientLite installDir must be absolute");
@@ -37805,7 +37958,7 @@ var FEE_KEYS = [
37805
37958
  "close_tax",
37806
37959
  "margin_ratio"
37807
37960
  ];
37808
- var record4 = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
37961
+ var record5 = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
37809
37962
  var pick2 = (v, keys) => Object.fromEntries(keys.filter((k2) => Object.prototype.hasOwnProperty.call(v, k2)).map((k2) => [k2, v[k2]]));
37810
37963
  function readBacktestBaseline(tool, args) {
37811
37964
  const create = tool === "mcp-create-and-run-backtest";
@@ -37825,28 +37978,28 @@ function readBacktestBaseline(tool, args) {
37825
37978
  } catch {
37826
37979
  throw new Error("Configuration baseline is not valid JSON");
37827
37980
  }
37828
- if (!record4(config2) || config2.strategy_id !== args.strategyId) throw new Error("Configuration baseline strategy_id is missing or mismatched");
37981
+ if (!record5(config2) || config2.strategy_id !== args.strategyId) throw new Error("Configuration baseline strategy_id is missing or mismatched");
37829
37982
  if (!create && (typeof args.runId !== "string" || config2.backtest_id !== args.runId)) {
37830
37983
  throw new Error("Configuration baseline backtest_id does not match the requested runId");
37831
37984
  }
37832
37985
  const params = pick2(config2, [...BACKTEST_CONFIG_KEYS, ...INTERNAL_CONFIG_KEYS]);
37833
37986
  for (const key of ["base_tpl_obj", "ratio_tpl_obj"]) {
37834
- if (params[key] !== void 0 && !record4(params[key])) throw new Error(`Configuration baseline ${key} must be an object`);
37987
+ if (params[key] !== void 0 && !record5(params[key])) throw new Error(`Configuration baseline ${key} must be an object`);
37835
37988
  }
37836
- if (record4(params.base_tpl_obj)) params.base_tpl_obj = pick2(params.base_tpl_obj, BASE_KEYS);
37837
- if (record4(params.ratio_tpl_obj)) {
37989
+ if (record5(params.base_tpl_obj)) params.base_tpl_obj = pick2(params.base_tpl_obj, BASE_KEYS);
37990
+ if (record5(params.ratio_tpl_obj)) {
37838
37991
  const fees = params.ratio_tpl_obj;
37839
37992
  for (const asset of ["stock", "future", "fund", "bond"]) {
37840
- if (fees[asset] !== void 0 && !record4(fees[asset])) throw new Error(`Configuration baseline fee section ${asset} must be an object`);
37993
+ if (fees[asset] !== void 0 && !record5(fees[asset])) throw new Error(`Configuration baseline fee section ${asset} must be an object`);
37841
37994
  }
37842
37995
  params.ratio_tpl_obj = {
37843
37996
  ...pick2(fees, ["name", "zhCnName"]),
37844
- ...Object.fromEntries(["stock", "future", "fund", "bond"].filter((k2) => record4(fees[k2])).map((k2) => [k2, pick2(fees[k2], FEE_KEYS)]))
37997
+ ...Object.fromEntries(["stock", "future", "fund", "bond"].filter((k2) => record5(fees[k2])).map((k2) => [k2, pick2(fees[k2], FEE_KEYS)]))
37845
37998
  };
37846
37999
  }
37847
38000
  if (Array.isArray(params.account_list)) {
37848
38001
  params.account_list = params.account_list.map((account) => {
37849
- if (!record4(account)) throw new Error("Configuration baseline account_list contains a non-object");
38002
+ if (!record5(account)) throw new Error("Configuration baseline account_list contains a non-object");
37850
38003
  const result = pick2(account, ["pindex", "account_id", "cash", "account_type"]);
37851
38004
  if (create && typeof result.account_id === "string" && /^RN-[A-Za-z0-9-]+_\d+$/.test(result.account_id)) result.account_id = "";
37852
38005
  return result;
@@ -37860,7 +38013,7 @@ function readBacktestBaseline(tool, args) {
37860
38013
  }
37861
38014
  function reconcileBaselineCapital(params, overrides) {
37862
38015
  const accounts = params.account_list;
37863
- if (!Array.isArray(accounts) || !accounts.length || accounts.some((a2) => !record4(a2) || typeof a2.cash !== "number" || !Number.isFinite(a2.cash) || a2.cash < 0)) {
38016
+ if (!Array.isArray(accounts) || !accounts.length || accounts.some((a2) => !record5(a2) || typeof a2.cash !== "number" || !Number.isFinite(a2.cash) || a2.cash < 0)) {
37864
38017
  throw new Error("Configuration baseline requires accounts with finite nonnegative cash");
37865
38018
  }
37866
38019
  const explicitCapital = Object.prototype.hasOwnProperty.call(overrides, "initial_capital");
@@ -44302,9 +44455,10 @@ async function installNpmClientLite(args, config2, onProgress) {
44302
44455
  acquireClientLiteNativePayload({
44303
44456
  release,
44304
44457
  cacheDir,
44458
+ onProgress,
44305
44459
  ...nativeNpmRegistry ? { registryUrl: nativeNpmRegistry } : {}
44306
44460
  }),
44307
- acquireClientLitePipSdk({ sdk: release.pipSdk, cacheDir: path44.join(sharedDiscoveryHome(), "cache", "clientlite-pip") })
44461
+ acquireClientLitePipSdk({ sdk: release.pipSdk, onProgress, cacheDir: path44.join(sharedDiscoveryHome(), "cache", "clientlite-pip") })
44308
44462
  ]).then((results) => {
44309
44463
  for (const result of results) if (result.status === "rejected") throw result.reason;
44310
44464
  const native = results[0].value;
@@ -44313,10 +44467,11 @@ async function installNpmClientLite(args, config2, onProgress) {
44313
44467
  }) : acquireClientLiteNpmPayloads({
44314
44468
  release,
44315
44469
  cacheDir,
44470
+ onProgress,
44316
44471
  ...nativeNpmRegistry ? { registryUrl: nativeNpmRegistry } : {}
44317
44472
  });
44318
44473
  const pinnedToolchains = { python: release.python, git: release.git };
44319
- const toolPreparation = prepareClientLiteReleaseToolchains(pinnedToolchains, proposal.toolchainPlan);
44474
+ const toolPreparation = prepareClientLiteReleaseToolchains(pinnedToolchains, proposal.toolchainPlan, { onProgress });
44320
44475
  const outcomes = await Promise.allSettled([inputsPromise, toolPreparation]);
44321
44476
  const failure = outcomes.find((result) => result.status === "rejected");
44322
44477
  if (failure?.status === "rejected") throw failure.reason;