engine7 7.1.149 → 7.1.151

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.
@@ -782,11 +782,13 @@ function secretsCandidates(stateDir, configName) {
782
782
  join4(stateDir, "configs", `.env.${configName}`),
783
783
  join4(stateDir, "configs", ".env")
784
784
  ];
785
- if (isDefaultStateDir(stateDir)) return [shared, ...inState];
785
+ const travel = join4(stateDir, "secrets.env");
786
+ if (isDefaultStateDir(stateDir)) return [shared, ...inState, travel];
786
787
  return [
787
788
  join4(secretsHome(), ".engine7-secrets", `${configName}-${stateKey(stateDir)}.env`),
788
789
  shared,
789
- ...inState
790
+ ...inState,
791
+ travel
790
792
  ];
791
793
  }
792
794
  function readSecretsEntries(stateDir, configName) {
@@ -5334,7 +5336,7 @@ var init_recovery_deletion = __esm({
5334
5336
  add(table, row) {
5335
5337
  this.affected = void 0;
5336
5338
  const { owners, parents } = this.links(table, row);
5337
- for (const parent of parents) for (const owner of owners) this.edge(parent, owner);
5339
+ for (const parent of parents) for (const owner2 of owners) this.edge(parent, owner2);
5338
5340
  if (table === "memory_artifact_publications") {
5339
5341
  const medium = text(row, "medium"), path37 = text(row, "path"), physicalId = text(row, "physical_id"), kind = text(row, "kind");
5340
5342
  const identity3 = medium === "markdown" && path37 ? "file:mem7/" + path37 : medium === "vector" && physicalId && kind ? "vector:" + kind + "/rows/" + createHash12("sha256").update(physicalId).digest("hex") + ".arrow" : void 0;
@@ -8112,6 +8114,8 @@ function attachmentToMessage(attachment) {
8112
8114
  ${attachment.notifications.join("\n\n")}`
8113
8115
  )
8114
8116
  };
8117
+ case "coldstart_hint":
8118
+ return { role: "user", content: wrapInSystemReminder(attachment.text) };
8115
8119
  case "teammate_messages": {
8116
8120
  const lines = attachment.messages.map(
8117
8121
  (m) => m.summary ? `[From: ${m.from}] ${m.summary}
@@ -12002,11 +12006,11 @@ ${e.outcome}
12002
12006
  const out = [];
12003
12007
  const usersDir = join16(this.root, "users");
12004
12008
  if (!existsSync6(usersDir)) return out;
12005
- for (const owner of readdirSync2(usersDir, { withFileTypes: true })) {
12006
- if (!owner.isDirectory()) continue;
12007
- if (scope && owner.name !== scope.ownerId) continue;
12008
- if (!scope && this.tombstones.anyForOwner(owner.name)) continue;
12009
- const dir = join16(usersDir, owner.name, ".foresights");
12009
+ for (const owner2 of readdirSync2(usersDir, { withFileTypes: true })) {
12010
+ if (!owner2.isDirectory()) continue;
12011
+ if (scope && owner2.name !== scope.ownerId) continue;
12012
+ if (!scope && this.tombstones.anyForOwner(owner2.name)) continue;
12013
+ const dir = join16(usersDir, owner2.name, ".foresights");
12010
12014
  if (!existsSync6(dir)) continue;
12011
12015
  for (const f of readdirSync2(dir)) {
12012
12016
  if (!/^foresight-\d{4}-\d{2}-\d{2}\.md$/.test(f)) continue;
@@ -12030,7 +12034,7 @@ ${e.outcome}
12030
12034
  if (!end || !start || !text2) continue;
12031
12035
  if (end < today) continue;
12032
12036
  out.push({
12033
- ownerId: owner.name,
12037
+ ownerId: owner2.name,
12034
12038
  ...scope ? { entryId, version: this.dependencies.version(scope, "foresight", entryId) } : {},
12035
12039
  startDate: start,
12036
12040
  endDate: end,
@@ -13608,10 +13612,10 @@ function projectReadSnapshots(messages, context, options = {}) {
13608
13612
  const returned = new Set(messages.flatMap((m) => "role" in m && m.role === "tool" && m.tool_call_id ? [m.tool_call_id] : []));
13609
13613
  const protectedImage = unobservedImageIndex(messages);
13610
13614
  let turnStart = 0;
13611
- let finished = false;
13615
+ let finished2 = false;
13612
13616
  let unresolved = false;
13613
13617
  const finishTurn = (end) => {
13614
- if ((finished || options.includeLastTurn) && !unresolved) completed.fill(1, turnStart, end);
13618
+ if ((finished2 || options.includeLastTurn) && !unresolved) completed.fill(1, turnStart, end);
13615
13619
  };
13616
13620
  for (let i = 0; i < messages.length; i++) {
13617
13621
  const message = messages[i];
@@ -13619,9 +13623,9 @@ function projectReadSnapshots(messages, context, options = {}) {
13619
13623
  if (message.role === "user") {
13620
13624
  finishTurn(i);
13621
13625
  turnStart = i;
13622
- finished = false;
13626
+ finished2 = false;
13623
13627
  unresolved = false;
13624
- } else if (message.role === "assistant" && !message.tool_calls?.length && message.content) finished = true;
13628
+ } else if (message.role === "assistant" && !message.tool_calls?.length && message.content) finished2 = true;
13625
13629
  if (message.tool_calls?.some((call) => !returned.has(call.id))) unresolved = true;
13626
13630
  }
13627
13631
  finishTurn(messages.length);
@@ -14811,6 +14815,255 @@ ${filenames.join("\n")}${truncatedNote}`
14811
14815
  }
14812
14816
  });
14813
14817
 
14818
+ // src/tools/cc-ask-jobs.ts
14819
+ import { randomUUID as randomUUID12 } from "node:crypto";
14820
+ async function runCcAskJob(options) {
14821
+ const { ctx, target, mode, timeoutMs, signal, run, stop } = options;
14822
+ if (signal?.aborted) return { content: "CC \u8BF7\u6C42\u5DF2\u53D6\u6D88\uFF0C\u5C1A\u672A\u6295\u9012\u3002", isError: true };
14823
+ const jobId = randomUUID12();
14824
+ const job = { owner: owner(ctx), target, status: "accepted", stop: () => stop(jobId) };
14825
+ const transport = new AbortController();
14826
+ const timer = setTimeout(() => transport.abort(new Error("\u672A\u6536\u5230 CC \u5165\u961F\u56DE\u6267\uFF0C\u4EFB\u52A1\u53EF\u80FD\u5DF2\u9001\u8FBE\uFF0C\u8BF7\u5148\u67E5\u770B\u76EE\u6807\u4F1A\u8BDD\u3002")), ACCEPT_TIMEOUT_MS);
14827
+ let accept;
14828
+ let rejectAcceptance;
14829
+ const accepted = new Promise((resolve47, reject) => {
14830
+ accept = resolve47;
14831
+ rejectAcceptance = reject;
14832
+ });
14833
+ const onAccepted = () => {
14834
+ clearTimeout(timer);
14835
+ jobs.set(jobId, job);
14836
+ accept();
14837
+ };
14838
+ const result = Promise.resolve().then(() => run({ jobId, onAccepted }, transport.signal)).catch((error) => {
14839
+ rejectAcceptance(error);
14840
+ return { content: `CC \u6295\u9012\u6216\u7ED3\u679C\u8BFB\u53D6\u5931\u8D25\uFF1A${describeError(error)}`, isError: true };
14841
+ }).then((output) => {
14842
+ clearTimeout(timer);
14843
+ if (!jobs.has(jobId)) rejectAcceptance(new Error(output.isError ? output.content : "CC \u672A\u786E\u8BA4\u4EFB\u52A1\u5165\u961F\u3002"));
14844
+ else {
14845
+ job.status = output.isError ? job.status === "stopping" ? "stopped" : "failed" : "completed";
14846
+ job.result = output;
14847
+ job.stop = void 0;
14848
+ finished.add(jobId);
14849
+ if (finished.size > MAX_FINISHED) {
14850
+ const oldest = finished.values().next().value;
14851
+ jobs.delete(oldest);
14852
+ finished.delete(oldest);
14853
+ }
14854
+ }
14855
+ return output;
14856
+ });
14857
+ try {
14858
+ await accepted;
14859
+ } catch (error) {
14860
+ return { content: describeError(error), isError: true };
14861
+ }
14862
+ const receipt2 = (status) => ({
14863
+ content: JSON.stringify({ jobId, status, target: target.key, workDir: target.workDir, sessionId: target.sessionId }),
14864
+ isError: false
14865
+ });
14866
+ if (mode === "async") return receipt2("accepted");
14867
+ const waitSignals = [signal, ctx.yieldSignal].filter((item) => !!item);
14868
+ let endWait;
14869
+ const waiting = new Promise((resolve47) => {
14870
+ endWait = resolve47;
14871
+ });
14872
+ const cancelWait = () => {
14873
+ if (signal?.aborted && signal.reason !== "interrupt") {
14874
+ endWait(requestStop(jobId, job));
14875
+ } else {
14876
+ endWait(receipt2("waiting_yielded"));
14877
+ }
14878
+ };
14879
+ if (waitSignals.some((item) => item.aborted)) cancelWait();
14880
+ else for (const item of waitSignals) item.addEventListener("abort", cancelWait, { once: true });
14881
+ const waitTimer = timeoutMs > 0 ? setTimeout(() => endWait(receipt2("waiting_timed_out")), timeoutMs) : void 0;
14882
+ try {
14883
+ return await Promise.race([result, waiting]);
14884
+ } finally {
14885
+ clearTimeout(waitTimer);
14886
+ for (const item of waitSignals) item.removeEventListener("abort", cancelWait);
14887
+ }
14888
+ }
14889
+ function jobFor(id2, ctx) {
14890
+ const job = typeof id2 === "string" ? jobs.get(id2) : void 0;
14891
+ return job?.owner === owner(ctx) ? job : void 0;
14892
+ }
14893
+ function ccAskJobProgress(id2, ctx, readSession) {
14894
+ const job = jobFor(id2, ctx);
14895
+ if (!job) return { content: "\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u627E\u5230\u8FD9\u4E2A CC \u4EFB\u52A1\u3002", isError: true };
14896
+ const sessionRecent = job.stop ? readSession(job.target) : void 0;
14897
+ return { content: JSON.stringify({
14898
+ jobId: id2,
14899
+ target: job.target.key,
14900
+ workDir: job.target.workDir,
14901
+ sessionId: job.target.sessionId,
14902
+ status: job.status,
14903
+ sessionRecent,
14904
+ result: job.result?.content
14905
+ }) };
14906
+ }
14907
+ async function requestStop(id2, job) {
14908
+ if (!job.stop || job.status === "stopping") return { content: JSON.stringify({ jobId: id2, status: job.status }) };
14909
+ job.status = "stopping";
14910
+ try {
14911
+ if (await job.stop()) return { content: JSON.stringify({ jobId: id2, status: "stop_requested" }), isError: false };
14912
+ if (job.status === "stopping") job.status = "accepted";
14913
+ if (!job.stop) return { content: JSON.stringify({ jobId: id2, status: job.status }) };
14914
+ return { content: `CC \u672A\u786E\u8BA4\u505C\u6B62\u4EFB\u52A1 ${id2}\uFF0C\u53EF\u7528 cc_progress({jobId}) \u67E5\u770B\u3002`, isError: true };
14915
+ } catch (error) {
14916
+ if (job.status === "stopping") job.status = "accepted";
14917
+ return { content: `\u505C\u6B62 CC \u5931\u8D25\uFF1A${describeError(error)}`, isError: true };
14918
+ }
14919
+ }
14920
+ async function stopCcAskJob(id2, ctx) {
14921
+ const job = jobFor(id2, ctx);
14922
+ return job ? requestStop(String(id2), job) : { content: "\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u627E\u5230\u8FD9\u4E2A CC \u4EFB\u52A1\u3002", isError: true };
14923
+ }
14924
+ var jobs, finished, MAX_FINISHED, ACCEPT_TIMEOUT_MS, owner, describeError;
14925
+ var init_cc_ask_jobs = __esm({
14926
+ "src/tools/cc-ask-jobs.ts"() {
14927
+ "use strict";
14928
+ jobs = /* @__PURE__ */ new Map();
14929
+ finished = /* @__PURE__ */ new Set();
14930
+ MAX_FINISHED = 100;
14931
+ ACCEPT_TIMEOUT_MS = 1e4;
14932
+ owner = (ctx) => JSON.stringify([ctx.stateDir || ctx.workspace, ctx.sessionId || ctx.channel]);
14933
+ describeError = (error) => error instanceof Error ? error.message : String(error);
14934
+ }
14935
+ });
14936
+
14937
+ // src/cc-driver/peer-tunnel.ts
14938
+ import { execFile as execFile3, spawn } from "node:child_process";
14939
+ import { promisify as promisify3 } from "node:util";
14940
+ var exec2, validSshHost;
14941
+ var init_peer_tunnel = __esm({
14942
+ "src/cc-driver/peer-tunnel.ts"() {
14943
+ "use strict";
14944
+ exec2 = promisify3(execFile3);
14945
+ validSshHost = (name) => typeof name === "string" && /^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,62}$/.test(name);
14946
+ }
14947
+ });
14948
+
14949
+ // src/tools/cc-peer.ts
14950
+ import { execFile as execFile4 } from "node:child_process";
14951
+ import { randomUUID as randomUUID13 } from "node:crypto";
14952
+ import { setTimeout as delay2 } from "node:timers/promises";
14953
+ function ccPeerTarget(remoteTargets, alias) {
14954
+ if (typeof alias !== "string" || !validAlias(alias)) return void 0;
14955
+ const targets = remoteTargets?.targets;
14956
+ const host = targets && typeof targets === "object" && Object.hasOwn(targets, alias) ? targets[alias] : void 0;
14957
+ return typeof host === "string" && validSshHost(host) ? { alias, host } : void 0;
14958
+ }
14959
+ function resolvePeer(alias) {
14960
+ const target = ccPeerTarget(peerConfig(), alias);
14961
+ if (!target) throw new Error(`\u8FDC\u7A0B CC \u76EE\u6807\u672A\u914D\u7F6E\uFF1A${alias}`);
14962
+ return target;
14963
+ }
14964
+ function selectCcPeer(target, useDefault = true) {
14965
+ if (typeof target === "string" && target.startsWith("remote:")) return resolvePeer(target.slice(7));
14966
+ const configured = peerConfig()?.default;
14967
+ if (!target && useDefault && configured) return resolvePeer(configured);
14968
+ return void 0;
14969
+ }
14970
+ function parsePeerJob(id2) {
14971
+ if (typeof id2 !== "string" || !id2.startsWith("remote:")) return void 0;
14972
+ const [alias, jobId, extra] = id2.slice(7).split(":");
14973
+ if (extra !== void 0 || !jobId) throw new Error("\u8FDC\u7A0B CC \u4EFB\u52A1 ID \u65E0\u6548");
14974
+ return { peer: resolvePeer(alias), jobId };
14975
+ }
14976
+ function callPeer(peer, ctx, input, signal) {
14977
+ return new Promise((resolve47, reject) => {
14978
+ const child = execFile4("/usr/bin/ssh", [
14979
+ "-T",
14980
+ "-o",
14981
+ "BatchMode=yes",
14982
+ "-o",
14983
+ "ConnectTimeout=4",
14984
+ "-o",
14985
+ "StrictHostKeyChecking=yes",
14986
+ "-o",
14987
+ "ClearAllForwardings=yes",
14988
+ peer.host,
14989
+ "cc-peer"
14990
+ ], { timeout: 8e3, maxBuffer: 160 * 1024, signal }, (error, stdout) => {
14991
+ if (error) {
14992
+ reject(new Error("\u8FDC\u7A0B CC \u94FE\u8DEF\u4E0D\u53EF\u7528\u6216\u672A\u786E\u8BA4\u56DE\u6267"));
14993
+ return;
14994
+ }
14995
+ try {
14996
+ const reply = JSON.parse(stdout);
14997
+ if (!reply || typeof reply !== "object") throw new Error("\u8FDC\u7A0B CC \u56DE\u6267\u683C\u5F0F\u65E0\u6548");
14998
+ if (reply.error) throw new Error(reply.error);
14999
+ resolve47(reply);
15000
+ } catch (cause) {
15001
+ reject(cause);
15002
+ }
15003
+ });
15004
+ child.stdin?.on("error", () => {
15005
+ });
15006
+ child.stdin?.end(JSON.stringify({ ...input, conversation: String(ctx.sessionId ?? ctx.channel ?? "default") }));
15007
+ });
15008
+ }
15009
+ async function askRemoteCc(peer, args, ctx, timeoutMs, signal) {
15010
+ const id2 = requestId(args.requestId);
15011
+ let receipt2;
15012
+ try {
15013
+ receipt2 = await callPeer(peer, ctx, { op: "submit", prompt: args.prompt, workDir: args.workDir, requestId: id2 }, signal);
15014
+ } catch (error) {
15015
+ return { content: `${error.message}\u3002\u672C\u6B21 requestId ${id2}\uFF0C\u9700\u8981\u6838\u5B9E\u6216\u91CD\u8BD5\u65F6\u6CBF\u7528\u8BE5 ID\u3002`, isError: true };
15016
+ }
15017
+ if (args.mode === "async" || !receipt2.jobId || !["accepted", "running", "stopping"].includes(receipt2.status ?? "")) return format(peer, receipt2);
15018
+ const deadline = timeoutMs > 0 ? AbortSignal.timeout(Math.min(Math.ceil(timeoutMs), 2147483647)) : void 0;
15019
+ const wait = AbortSignal.any([deadline, signal, ctx.yieldSignal].filter((item) => !!item));
15020
+ try {
15021
+ while (true) {
15022
+ await delay2(2e3, void 0, { signal: wait });
15023
+ const update = await callPeer(peer, ctx, { op: "progress", jobId: receipt2.jobId, includeTranscript: false }, wait);
15024
+ if (update.status === "completed") return { content: update.result || "" };
15025
+ if (!["accepted", "running", "stopping"].includes(update.status ?? "")) return format(peer, update);
15026
+ }
15027
+ } catch {
15028
+ return format(peer, { ...receipt2, status: deadline?.aborted ? "waiting_timed_out" : wait.aborted ? "waiting_yielded" : "waiting_disconnected" });
15029
+ }
15030
+ }
15031
+ async function observeRemoteCc(op, args, ctx, signal) {
15032
+ try {
15033
+ const job = parsePeerJob(args.jobId);
15034
+ if (job) return format(job.peer, await callPeer(job.peer, ctx, { op, jobId: job.jobId }, signal));
15035
+ if (op !== "progress" || args.jobId !== void 0) return void 0;
15036
+ const peer = selectCcPeer(args.target, !args.workDir && args.view !== "sessions");
15037
+ return peer ? format(peer, await callPeer(peer, ctx, { op }, signal)) : void 0;
15038
+ } catch (error) {
15039
+ return asError(error);
15040
+ }
15041
+ }
15042
+ async function newRemoteCc(peer, args, ctx, signal) {
15043
+ const id2 = requestId(args.requestId);
15044
+ try {
15045
+ return format(peer, await callPeer(peer, ctx, { op: "new", requestId: id2, workDir: args.workDir }, signal));
15046
+ } catch (error) {
15047
+ return { content: `${error.message}\u3002\u672C\u6B21 requestId ${id2}\uFF0C\u9700\u8981\u91CD\u8BD5\u65F6\u6CBF\u7528\u8BE5 ID\u3002`, isError: true };
15048
+ }
15049
+ }
15050
+ var validAlias, peerConfig, asError, format, requestId;
15051
+ var init_cc_peer = __esm({
15052
+ "src/tools/cc-peer.ts"() {
15053
+ "use strict";
15054
+ init_live();
15055
+ init_peer_tunnel();
15056
+ validAlias = (s) => /^[a-z0-9_-]{1,32}$/.test(s);
15057
+ peerConfig = () => liveConfig.get("channels.ccDriver.remoteTargets");
15058
+ asError = (error) => ({ content: error.message, isError: true });
15059
+ format = (peer, reply) => ({
15060
+ content: JSON.stringify({ ...reply, target: `remote:${peer.alias}`, ...reply.jobId ? { jobId: `remote:${peer.alias}:${reply.jobId}` } : {} }),
15061
+ isError: ["failed", "rejected", "stopped", "unknown"].includes(reply.status ?? "")
15062
+ });
15063
+ requestId = (arg) => typeof arg === "string" ? arg : `${Date.now()}:${randomUUID13()}`;
15064
+ }
15065
+ });
15066
+
14814
15067
  // src/cc-driver/project-sessions.ts
14815
15068
  import fs8 from "node:fs";
14816
15069
  import os from "node:os";
@@ -15077,15 +15330,63 @@ var init_project_sessions = __esm({
15077
15330
  }
15078
15331
  });
15079
15332
 
15333
+ // src/cc-driver/progress-transcript.ts
15334
+ function extractBlocks(content) {
15335
+ if (typeof content === "string") return [{ type: "text", text: content }];
15336
+ if (Array.isArray(content)) return content;
15337
+ return [];
15338
+ }
15339
+ function snippet(text2, max = 220) {
15340
+ const t = text2.replace(/\s+/g, " ").trim();
15341
+ return t.length > max ? t.slice(0, max) + "\u2026" : t;
15342
+ }
15343
+ function summarizeTranscript(file2) {
15344
+ const lines = tailSessionLines(file2, 65536);
15345
+ const recent = [];
15346
+ let lastTs = "";
15347
+ for (let i = lines.length - 1; i >= 0 && recent.length < 8; i--) {
15348
+ let entry;
15349
+ try {
15350
+ entry = JSON.parse(lines[i]);
15351
+ } catch {
15352
+ continue;
15353
+ }
15354
+ if (entry.type !== "user" && entry.type !== "assistant") continue;
15355
+ if (!lastTs && entry.timestamp) lastTs = entry.timestamp;
15356
+ const blocks = extractBlocks(entry.message?.content);
15357
+ for (const b of blocks) {
15358
+ if (entry.type === "user" && b.type === "text" && b.text && !b.text.includes("tool_result")) {
15359
+ recent.push(`\u{1F464} ${snippet(b.text)}`);
15360
+ } else if (entry.type === "assistant" && b.type === "text" && b.text) {
15361
+ recent.push(`\u{1F916} ${snippet(b.text)}`);
15362
+ } else if (entry.type === "assistant" && b.type === "tool_use" && b.name) {
15363
+ recent.push(`\u{1F527} ${b.name}`);
15364
+ }
15365
+ }
15366
+ }
15367
+ recent.reverse();
15368
+ return { recent, lastTs };
15369
+ }
15370
+ var init_progress_transcript = __esm({
15371
+ "src/cc-driver/progress-transcript.ts"() {
15372
+ "use strict";
15373
+ init_project_sessions();
15374
+ }
15375
+ });
15376
+
15080
15377
  // src/cc-driver/long-http.ts
15081
15378
  import { request } from "node:http";
15082
- function longPostJson(url, body, headers = {}, signal) {
15379
+ function longPostJson(url, body, headers = {}, signal, acknowledgment) {
15083
15380
  const data = Buffer.from(JSON.stringify(body));
15084
15381
  return new Promise((resolve47, reject) => {
15085
15382
  const req = request(url, { method: "POST", headers: { ...headers, "Content-Length": String(data.byteLength) } }, (res) => {
15383
+ if (acknowledgment && res.statusCode === 200 && res.headers[CC_JOB_HEADER] === acknowledgment.jobId) acknowledgment.onAccepted();
15086
15384
  const chunks = [];
15087
15385
  res.on("data", (chunk) => chunks.push(chunk));
15088
- res.on("error", reject);
15386
+ res.on("error", (err) => {
15387
+ cleanup();
15388
+ reject(err);
15389
+ });
15089
15390
  res.on("end", () => {
15090
15391
  cleanup();
15091
15392
  const text2 = Buffer.concat(chunks).toString("utf8");
@@ -15117,9 +15418,11 @@ function longPostJson(url, body, headers = {}, signal) {
15117
15418
  req.end(data);
15118
15419
  });
15119
15420
  }
15421
+ var CC_JOB_HEADER;
15120
15422
  var init_long_http = __esm({
15121
15423
  "src/cc-driver/long-http.ts"() {
15122
15424
  "use strict";
15425
+ CC_JOB_HEADER = "x-engine7-cc-job-id";
15123
15426
  }
15124
15427
  });
15125
15428
 
@@ -15173,19 +15476,31 @@ async function findDesktopTargets(workDir, sessionId) {
15173
15476
  }
15174
15477
  return targets;
15175
15478
  }
15176
- async function askDesktop(target, prompt, source, signal) {
15479
+ async function askDesktop(target, prompt, source, signal, acknowledgment) {
15480
+ const endpoint2 = acknowledgment ? "submit" : "ask";
15177
15481
  const { status, json: result } = await longPostJson(
15178
- `http://127.0.0.1:${target.port}/ask`,
15179
- { prompt, source, sessionId: target.sessionId, instance: target.instance, workDir: target.workDir },
15482
+ `http://127.0.0.1:${target.port}/${endpoint2}`,
15483
+ { prompt, source, jobId: acknowledgment?.jobId, sessionId: target.sessionId, instance: target.instance, workDir: target.workDir },
15180
15484
  { authorization: `Bearer ${target.token}` },
15181
- signal
15485
+ signal,
15486
+ acknowledgment
15182
15487
  );
15183
- if (status !== 200) throw failure(result?.error || `Desktop CC HTTP ${status}`, status);
15488
+ if (status !== 200 || result?.error) throw failure(result?.error || `Desktop CC HTTP ${status}`, status);
15184
15489
  if (result.sessionId !== target.sessionId || typeof result.text !== "string" || typeof result.isError !== "boolean") {
15185
15490
  throw failure("Desktop CC returned an invalid result");
15186
15491
  }
15187
15492
  return result;
15188
15493
  }
15494
+ async function stopDesktopJob(target, jobId) {
15495
+ const { status, json } = await longPostJson(
15496
+ `http://127.0.0.1:${target.port}/stop`,
15497
+ { jobId, sessionId: target.sessionId, instance: target.instance, workDir: target.workDir },
15498
+ { authorization: `Bearer ${target.token}` },
15499
+ AbortSignal.timeout(5e3)
15500
+ );
15501
+ if (status !== 200) throw failure(json?.error || `Desktop CC HTTP ${status}`, status);
15502
+ return json?.stopped === true;
15503
+ }
15189
15504
  var registryDir, canonical3, failure, alive;
15190
15505
  var init_desktop = __esm({
15191
15506
  "src/cc-driver/desktop.ts"() {
@@ -15286,8 +15601,8 @@ var init_session_activity = __esm({
15286
15601
  import fs10 from "node:fs";
15287
15602
  import os3 from "node:os";
15288
15603
  import path12 from "node:path";
15289
- import { execFile as execFile3 } from "node:child_process";
15290
- import { promisify as promisify3 } from "node:util";
15604
+ import { execFile as execFile5 } from "node:child_process";
15605
+ import { promisify as promisify4 } from "node:util";
15291
15606
  async function listOpenCcSessions(workDir) {
15292
15607
  const configDir = process.env.CLAUDE_CONFIG_DIR || path12.join(os3.homedir(), ".claude");
15293
15608
  const dir = path12.join(configDir, "sessions");
@@ -15357,7 +15672,7 @@ var init_open_sessions = __esm({
15357
15672
  init_desktop();
15358
15673
  init_project_sessions();
15359
15674
  init_session_activity();
15360
- execFileAsync = promisify3(execFile3);
15675
+ execFileAsync = promisify4(execFile5);
15361
15676
  uuid = /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i;
15362
15677
  canonical4 = (dir) => {
15363
15678
  try {
@@ -16927,6 +17242,7 @@ var init_driver = __esm({
16927
17242
  revision = 0;
16928
17243
  idleWaiters = [];
16929
17244
  abort = null;
17245
+ activeJob;
16930
17246
  /** 当前流式 chunk 的 steer 口(仅用户消息路径开;外部 ask/桌面路径为 null) */
16931
17247
  feeder = null;
16932
17248
  sessionId = null;
@@ -16971,13 +17287,17 @@ var init_driver = __esm({
16971
17287
  void this.drain();
16972
17288
  }
16973
17289
  /** External callers use the same FIFO; they never answer a pending permission card. */
16974
- ask(prompt, source, expectedSessionId, signal) {
16975
- if (this.closed) return Promise.reject(requestError("CC binding is stopping", 503));
16976
- if (!prompt.trim()) return Promise.reject(requestError("prompt is required", 400));
16977
- if (signal?.aborted) return Promise.reject(requestError("CC request cancelled", 499));
16978
- if (this.sessionId !== expectedSessionId) return Promise.reject(requestError("CC session changed; select the current binding again"));
16979
- if (this.queue.length >= MAX_QUEUE) return Promise.reject(requestError("CC queue is full", 429));
16980
- const job = { prompt: prompt.trim(), source, expectedSessionId, signal };
17290
+ async ask(prompt, source, expectedSessionId, signal) {
17291
+ return this.submit(prompt, source, expectedSessionId, signal);
17292
+ }
17293
+ submit(prompt, source, expectedSessionId, signal, id2, onSession) {
17294
+ if (this.closed) throw requestError("CC binding is stopping", 503);
17295
+ if (!prompt.trim()) throw requestError("prompt is required", 400);
17296
+ if (signal?.aborted) throw requestError("CC request cancelled", 499);
17297
+ if (this.sessionId !== expectedSessionId) throw requestError("CC session changed; select the current binding again");
17298
+ if (id2 && (this.activeJob?.id === id2 || this.queue.some((job2) => job2.id === id2))) throw requestError("CC job already exists");
17299
+ if (this.queue.length >= MAX_QUEUE) throw requestError("CC queue is full", 429);
17300
+ const job = { id: id2, prompt: prompt.trim(), source, expectedSessionId, expectedRevision: id2 ? this.revision : void 0, signal, onSession };
16981
17301
  const cancel = () => {
16982
17302
  const index = this.queue.indexOf(job);
16983
17303
  if (index >= 0) {
@@ -16992,7 +17312,16 @@ var init_driver = __esm({
16992
17312
  signal?.addEventListener("abort", cancel, { once: true });
16993
17313
  void this.drain();
16994
17314
  });
16995
- return pending.finally(() => signal?.removeEventListener("abort", cancel));
17315
+ return signal ? pending.finally(() => signal.removeEventListener("abort", cancel)) : pending;
17316
+ }
17317
+ stopJob(id2) {
17318
+ const index = this.queue.findIndex((job) => job.id === id2);
17319
+ if (index >= 0) {
17320
+ this.queue.splice(index, 1)[0].reject?.(requestError("CC request cancelled (stop)", 499));
17321
+ return true;
17322
+ }
17323
+ if (this.activeJob?.id === id2) return this.activeJob.stop?.() ?? false;
17324
+ return false;
16996
17325
  }
16997
17326
  /** Reload/stop must not leave the old hub executing queued work. */
16998
17327
  shutdown() {
@@ -17018,6 +17347,9 @@ var init_driver = __esm({
17018
17347
  stop() {
17019
17348
  this.abort?.abort();
17020
17349
  }
17350
+ get queued() {
17351
+ return this.queue.length;
17352
+ }
17021
17353
  get busy() {
17022
17354
  return this.draining;
17023
17355
  }
@@ -17031,15 +17363,17 @@ var init_driver = __esm({
17031
17363
  await this.predecessor;
17032
17364
  while (!this.closed && this.queue.length > 0) {
17033
17365
  const job = this.queue.shift();
17366
+ this.activeJob = job;
17034
17367
  try {
17035
17368
  if (job.signal?.aborted) throw requestError("CC request cancelled", 499);
17036
- if (job.expectedSessionId !== void 0 && job.expectedSessionId !== this.sessionId) {
17369
+ const changed = job.expectedRevision !== void 0 ? job.expectedRevision !== this.revision : job.expectedSessionId !== void 0 && job.expectedSessionId !== this.sessionId;
17370
+ if (changed) {
17037
17371
  throw requestError("CC session changed while this request was queued");
17038
17372
  }
17039
17373
  if (job.source) {
17040
17374
  const prompt = `[cc_ask from ${job.source.replace(/[\r\n]/g, " ").slice(0, 160)}]
17041
17375
  ${job.prompt}`;
17042
- const result = await this.runTurn(prompt, job.signal, true);
17376
+ const result = await this.runTurn(prompt, job.signal, true, job);
17043
17377
  job.resolve?.(result);
17044
17378
  } else {
17045
17379
  await this.runStreaming(job);
@@ -17048,6 +17382,8 @@ ${job.prompt}`;
17048
17382
  job.reject?.(err);
17049
17383
  console.error(`[cc-driver] turn \u5931\u8D25 key=${this.key}: ${err?.stack || err}`);
17050
17384
  await this.sendText(`[cc-driver] \u8FD9\u6B21\u4EFB\u52A1\u5931\u8D25\uFF1A${err?.message || String(err)}`);
17385
+ } finally {
17386
+ this.activeJob = void 0;
17051
17387
  }
17052
17388
  }
17053
17389
  } finally {
@@ -17055,12 +17391,24 @@ ${job.prompt}`;
17055
17391
  for (const resolve47 of this.idleWaiters.splice(0)) resolve47();
17056
17392
  }
17057
17393
  }
17058
- async runTurn(prompt, signal, external = false) {
17394
+ async runTurn(prompt, signal, external = false, job) {
17059
17395
  const ac = new AbortController();
17060
17396
  this.abort = ac;
17397
+ if (job?.id) job.stop = () => {
17398
+ ac.abort();
17399
+ return true;
17400
+ };
17061
17401
  const resumedFrom = this.sessionId;
17062
17402
  const revision = this.revision;
17063
17403
  let turnSessionId = resumedFrom;
17404
+ const observeSession = (id2) => {
17405
+ try {
17406
+ job?.onSession?.(id2);
17407
+ } catch (error) {
17408
+ console.error("[cc-driver] task session update failed:", error.message);
17409
+ }
17410
+ };
17411
+ observeSession(turnSessionId);
17064
17412
  const cancel = () => ac.abort();
17065
17413
  signal?.addEventListener("abort", cancel, { once: true });
17066
17414
  if (signal?.aborted) ac.abort();
@@ -17084,13 +17432,31 @@ ${job.prompt}`;
17084
17432
  const acc = this.makeStreamAccumulator();
17085
17433
  try {
17086
17434
  const desktops = resumedFrom ? await findDesktopTargets(this.workDir, resumedFrom) : [];
17435
+ ac.signal.throwIfAborted();
17087
17436
  if (desktops.length > 1) throw new Error("Multiple desktop writers claim this CC session; close the duplicate");
17088
17437
  if (desktops[0]) {
17089
- const result2 = await askDesktop(desktops[0], prompt, this.key, ac.signal);
17438
+ const desktop = desktops[0];
17439
+ let result2;
17440
+ if (job?.id) {
17441
+ const jobId = job.id;
17442
+ let acknowledge;
17443
+ const accepted = new Promise((resolve47) => {
17444
+ acknowledge = resolve47;
17445
+ });
17446
+ job.stop = async () => await accepted && stopDesktopJob(desktop, jobId);
17447
+ try {
17448
+ result2 = await askDesktop(desktop, prompt, this.key, ac.signal, { jobId, onAccepted: () => acknowledge(true) });
17449
+ } finally {
17450
+ acknowledge(false);
17451
+ }
17452
+ } else {
17453
+ result2 = await askDesktop(desktop, prompt, this.key, ac.signal);
17454
+ }
17090
17455
  finalText = result2.text;
17091
17456
  isError = result2.isError;
17092
17457
  gotResult = true;
17093
17458
  turnSessionId = result2.sessionId;
17459
+ observeSession(turnSessionId);
17094
17460
  if (this.revision === revision) this.sessionId = result2.sessionId;
17095
17461
  } else {
17096
17462
  if (resumedFrom && nativeSessionOwners(resumedFrom).length) {
@@ -17103,6 +17469,7 @@ ${job.prompt}`;
17103
17469
  const mb = total ? `\u7EA6 ${Math.round(total / 1024 / 1024)}M` : "\u7EA6 350M";
17104
17470
  void this.sendText(`[cc-driver] \u9996\u6B21\u4F7F\u7528\uFF1A\u6B63\u5728\u4E0B\u8F7D ${label}\uFF08${mb}\uFF0C\u53EA\u6B64\u4E00\u6B21\uFF09\uFF0C\u5B8C\u6210\u540E\u81EA\u52A8\u7EE7\u7EED\u2026`);
17105
17471
  });
17472
+ ac.signal.throwIfAborted();
17106
17473
  const stream = query({
17107
17474
  prompt,
17108
17475
  options: {
@@ -17145,6 +17512,7 @@ ${job.prompt}`;
17145
17512
  const r = msg2;
17146
17513
  if (r.session_id) {
17147
17514
  turnSessionId = r.session_id;
17515
+ observeSession(turnSessionId);
17148
17516
  if (this.revision === revision) this.sessionId = r.session_id;
17149
17517
  }
17150
17518
  isError = r.is_error === true;
@@ -17155,6 +17523,7 @@ ${job.prompt}`;
17155
17523
  const sid = msg2.session_id;
17156
17524
  if (sid) {
17157
17525
  turnSessionId = sid;
17526
+ observeSession(turnSessionId);
17158
17527
  if (this.revision === revision) this.sessionId = sid;
17159
17528
  }
17160
17529
  } else {
@@ -17164,6 +17533,7 @@ ${job.prompt}`;
17164
17533
  }
17165
17534
  if (turnSessionId && gotResult && this.revision === revision) this.map.switchTo(this.key, turnSessionId, this.workDir);
17166
17535
  } finally {
17536
+ if (job) job.stop = void 0;
17167
17537
  this.abort = null;
17168
17538
  signal?.removeEventListener("abort", cancel);
17169
17539
  }
@@ -17589,29 +17959,32 @@ async function findBoundCcTargets(workDir, key3) {
17589
17959
  }));
17590
17960
  return lists.flat();
17591
17961
  }
17592
- async function askBoundCc(target, prompt, source, signal) {
17962
+ async function askBoundCc(target, prompt, source, signal, acknowledgment) {
17963
+ const endpoint2 = acknowledgment ? "submit" : "ask";
17593
17964
  const { status, json: result } = await longPostJson(
17594
- `http://127.0.0.1:${target.endpoint.port}/api/cc-driver/ask`,
17965
+ `http://127.0.0.1:${target.endpoint.port}/api/cc-driver/${endpoint2}`,
17595
17966
  {
17596
17967
  key: target.key,
17597
17968
  workDir: target.workDir,
17598
17969
  prompt,
17599
17970
  source,
17971
+ jobId: acknowledgment?.jobId,
17600
17972
  expectedSessionId: target.sessionId,
17601
17973
  expectedPid: target.endpoint.pid,
17602
17974
  expectedStateDir: target.endpoint.stateDir
17603
17975
  },
17604
17976
  { "x-engine-console": "1" },
17605
- signal
17977
+ signal,
17978
+ acknowledgment
17606
17979
  );
17607
- if (status !== 200) throw new Error(result?.error || `CC hub handoff failed (HTTP ${status})`);
17980
+ if (status !== 200 || result?.error) throw new Error(result?.error || `CC hub handoff failed (HTTP ${status})`);
17608
17981
  if (typeof result.text !== "string" || typeof result.isError !== "boolean" || result.sessionId !== null && typeof result.sessionId !== "string") throw new Error("CC hub returned an invalid result");
17609
17982
  return result;
17610
17983
  }
17611
- async function stopBoundCc(target) {
17984
+ async function stopBoundCc(target, jobId) {
17612
17985
  const { status, json } = await longPostJson(
17613
17986
  `http://127.0.0.1:${target.endpoint.port}/api/cc-driver/stop`,
17614
- { key: target.key, workDir: target.workDir, expectedPid: target.endpoint.pid, expectedStateDir: target.endpoint.stateDir },
17987
+ { key: target.key, workDir: target.workDir, jobId, expectedPid: target.endpoint.pid, expectedStateDir: target.endpoint.stateDir },
17615
17988
  { "x-engine-console": "1" },
17616
17989
  AbortSignal.timeout(5e3)
17617
17990
  );
@@ -17720,9 +18093,9 @@ __export(router_exports, {
17720
18093
  import { existsSync as existsSync16 } from "node:fs";
17721
18094
  function autoBindHit(inbound) {
17722
18095
  if (inbound.channel !== "feishu" || inbound.channelType !== "dm") return null;
17723
- const owner = liveConfig.get("channels.feishu.ownerOpenId");
18096
+ const owner2 = liveConfig.get("channels.feishu.ownerOpenId");
17724
18097
  const workDir = liveConfig.get("channels.ccDriver.autoBind.workDir");
17725
- if (!owner || !workDir || inbound.from !== owner) return null;
18098
+ if (!owner2 || !workDir || inbound.from !== owner2) return null;
17726
18099
  const cur = liveConfig.get("channels.ccDriver");
17727
18100
  if (cur?.enabled === false) return null;
17728
18101
  if ((cur?.bindings ?? []).length > 0) return null;
@@ -17841,11 +18214,6 @@ var init_router = __esm({
17841
18214
  // src/tools/cc-progress.ts
17842
18215
  var cc_progress_exports = {};
17843
18216
  import path16 from "node:path";
17844
- function extractBlocks(content) {
17845
- if (typeof content === "string") return [{ type: "text", text: content }];
17846
- if (Array.isArray(content)) return content;
17847
- return [];
17848
- }
17849
18217
  function fmtTime(ts) {
17850
18218
  if (!ts) return "?";
17851
18219
  const d = new Date(ts);
@@ -17855,33 +18223,44 @@ function fmtTime(ts) {
17855
18223
  if (diff < 3600) return `${Math.floor(diff / 60)}\u5206\u949F\u524D`;
17856
18224
  return d.toLocaleString("zh-CN", { hour12: false });
17857
18225
  }
17858
- function snippet(text2, max = 220) {
17859
- const t = text2.replace(/\s+/g, " ").trim();
17860
- return t.length > max ? t.slice(0, max) + "\u2026" : t;
17861
- }
17862
18226
  var init_cc_progress = __esm({
17863
18227
  "src/tools/cc-progress.ts"() {
17864
18228
  "use strict";
17865
18229
  init_registry();
18230
+ init_cc_ask_jobs();
18231
+ init_cc_peer();
17866
18232
  init_project_sessions();
18233
+ init_progress_transcript();
17867
18234
  init_open_sessions();
17868
18235
  registry.register({
17869
18236
  name: "cc_progress",
17870
- description: `Read-only Claude Code discovery and progress. For "\u684C\u9762\u6709\u54EA\u4E9B CC / \u54EA\u4E2A session \u5F00\u7740 / \u770B\u4E0B\u684C\u9762 CC", use view="sessions": lists ALL live native interactive sessions plus Engine7 desktop bridges, with full UUID, project, PID, terminal and connection status. Ordinary claude sessions are visible even without cc-desktop; never equate bridge registration with all open sessions. No arguments also lists sessions. workDir optionally filters the inventory. To inspect the latest transcript in a project, use view="progress" with workDir (existing workDir-only calls retain this behavior); recent transcript activity is not proof of an open window. Discovery sends no messages and changes no bindings. Only sessions marked \u53EF\u6295\u9012 accept cc_ask in the existing process; unbridged sessions require reopening through cc-desktop before sending. If the user's context identifies a target select it yourself; otherwise ask which session.`,
18237
+ description: `Read-only Claude Code discovery and progress. Use jobId from a cc_ask receipt for that task's status and final answer. For "\u684C\u9762\u6709\u54EA\u4E9B CC / \u54EA\u4E2A session \u5F00\u7740 / \u770B\u4E0B\u684C\u9762 CC", use view="sessions": lists ALL live native interactive sessions plus Engine7 desktop bridges, with full UUID, project, PID, terminal and connection status. Ordinary claude sessions are visible even without cc-desktop. No arguments also lists sessions. workDir optionally filters the inventory. Use view="progress" with workDir to inspect the latest project transcript (workDir alone retains this behavior). Only sessions marked \u53EF\u6295\u9012 accept cc_ask in the existing process. If the user's context identifies a target select it yourself; otherwise ask which session.`,
17871
18238
  schema: {
17872
18239
  type: "object",
17873
18240
  properties: {
17874
18241
  view: { type: "string", enum: ["sessions", "progress"], description: "sessions = \u5217\u51FA\u6240\u6709\u6253\u5F00\u7684\u539F\u751F\uFF0F\u5DF2\u63A5\u5165\u4F1A\u8BDD\uFF1Bprogress = \u8BFB\u53D6\u9879\u76EE\u6700\u65B0\u5386\u53F2\u3002\u7701\u7565\u4E14\u65E0 workDir \u65F6\u9ED8\u8BA4 sessions" },
17875
- workDir: { type: "string", description: "CC \u9879\u76EE\u7EDD\u5BF9\u8DEF\u5F84\u3002sessions \u6A21\u5F0F\u7701\u7565\u5219\u67E5\u672C\u673A\u6240\u6709\u9879\u76EE\uFF1Bprogress \u6A21\u5F0F\u7528\u4E8E\u9009\u62E9\u5386\u53F2\u8BB0\u5F55" }
18242
+ workDir: { type: "string", description: "CC \u9879\u76EE\u7EDD\u5BF9\u8DEF\u5F84\u3002sessions \u6A21\u5F0F\u7701\u7565\u5219\u67E5\u672C\u673A\u6240\u6709\u9879\u76EE\uFF1Bprogress \u6A21\u5F0F\u7528\u4E8E\u9009\u62E9\u5386\u53F2\u8BB0\u5F55" },
18243
+ target: { type: "string", description: "remote:\u5DF2\u914D\u7F6E\u7684 CC \u522B\u540D\uFF0C\u7528\u4E8E\u67E5\u8FDC\u7A0B\u7ED1\u5B9A\u72B6\u6001\u3002" },
18244
+ jobId: { type: "string", description: "cc_ask \u56DE\u6267\u4E2D\u7684\u4EFB\u52A1 ID\uFF0C\u7528\u4E8E\u67E5\u770B\u8BE5\u4EFB\u52A1\u7684\u72B6\u6001\u548C\u7ED3\u679C\u3002" }
17876
18245
  },
17877
18246
  required: []
17878
18247
  },
17879
- handler: async (args, ctx) => {
18248
+ handler: async (args, ctx, signal) => {
18249
+ const remote = await observeRemoteCc("progress", args, ctx, signal);
18250
+ if (remote) return remote;
18251
+ if (args.jobId !== void 0) return ccAskJobProgress(args.jobId, ctx, ({ workDir: workDir2, sessionId }) => {
18252
+ if (!sessionId || !/^[a-zA-Z0-9_-]+$/.test(sessionId)) return void 0;
18253
+ try {
18254
+ return summarizeTranscript(path16.join(projectDirFor(workDir2), `${sessionId}.jsonl`)).recent;
18255
+ } catch {
18256
+ return void 0;
18257
+ }
18258
+ });
17880
18259
  let workDir = typeof args.workDir === "string" && args.workDir.trim() ? args.workDir.trim() : "";
17881
18260
  if (args.view !== void 0 && !["sessions", "progress"].includes(args.view)) return { content: "view \u9700\u8981 sessions \u6216 progress\u3002", isError: true };
17882
18261
  if (args.view === "sessions" || !args.view && !workDir) {
17883
18262
  const { sessions: sessions3, warning } = await listOpenCcSessions(workDir || void 0);
17884
- const lines2 = sessions3.map((s, i) => {
18263
+ const lines = sessions3.map((s, i) => {
17885
18264
  const status = s.connection === "ready" ? `\u5DF2\u63A5\u5165\uFF0C\u53EF\u6295\u9012${s.busy ? "\uFF08\u5FD9\uFF0C\u6D88\u606F\u6392\u961F\uFF09" : ""}` : s.connection === "starting" ? "\u5DF2\u63A5\u5165\uFF0C\u5C1A\u672A\u5C31\u7EEA" : s.connection === "unknown" ? "\u63A5\u5165\u72B6\u6001\u672A\u77E5" : "\u672A\u63A5\u5165\uFF08\u53EA\u8BFB\u53EF\u89C1\uFF09";
17886
18265
  const activity = s.lastActiveAt === void 0 ? "\u672A\u77E5" : `${new Date(s.lastActiveAt).toISOString()}\uFF08${fmtTime(new Date(s.lastActiveAt).toISOString())}\uFF0C\u65E5\u5FD7\u5199\u5165\uFF09`;
17887
18266
  return `${i + 1}. ${s.sessionId}
@@ -17894,7 +18273,7 @@ var init_cc_progress = __esm({
17894
18273
  return { content: [
17895
18274
  sessions3.length ? `\u5F53\u524D\u53D1\u73B0 ${sessions3.length} \u4E2A\u6253\u5F00\u7684 CC \u4F1A\u8BDD\uFF1A` : "\u5F53\u524D\u6CA1\u6709\u53D1\u73B0\u5DF2\u767B\u8BB0\u4E14\u8FDB\u7A0B\u5B58\u6D3B\u7684\u4EA4\u4E92 CC \u4F1A\u8BDD\u3002",
17896
18275
  warning,
17897
- ...lines2,
18276
+ ...lines,
17898
18277
  "\u4F1A\u8BDD\u6E05\u5355\u5305\u542B\u666E\u901A claude \u4E0E\u5DF2\u63A5\u5165\u7684 cc-desktop\uFF1B\u4E0D\u4EE3\u8868\u7A97\u53E3\u662F\u5426\u5728\u5C4F\u5E55\u524D\u53F0\u3002\u6700\u540E\u6D3B\u8DC3\u662F\u65E5\u5FD7\u5199\u5165\u65F6\u95F4\uFF0C\u957F\u671F\u65E0\u5199\u5165\u4E0D\u80FD\u5355\u72EC\u5224\u65AD\u6302\u6B7B\uFF0C\u8FDB\u7A0B\u5B58\u6D3B\u53E6\u5217\u3002\u672A\u63A5\u5165\u4F1A\u8BDD\u53EF\u4EE5\u53D1\u73B0\uFF0C\u4F46\u9700\u9996\u6B21\u7528 cc-desktop \u6062\u590D\u540E\u624D\u80FD\u5411\u539F\u8FDB\u7A0B\u53D1\u6D88\u606F\u3002\u672C\u6B21\u53EA\u8BFB\u67E5\u8BE2\uFF0C\u6CA1\u6709\u53D1\u9001\u6D88\u606F\u6216\u5207\u6362\u7ED1\u5B9A\u3002"
17899
18278
  ].filter(Boolean).join("\n") };
17900
18279
  }
@@ -17915,30 +18294,7 @@ ${dirs.join("\n")}`, isError: true };
17915
18294
  return { content: `${workDir} \u4E0B\u6CA1\u6709\u627E\u5230\u4EFB\u4F55 CC \u4F1A\u8BDD\u8BB0\u5F55\uFF08~/.claude/projects \u91CC\u6CA1\u6709\u8FD9\u4E2A\u76EE\u5F55\u7684\u4F1A\u8BDD\uFF09`, isError: true };
17916
18295
  }
17917
18296
  const latest = sessions2[0];
17918
- const lines = tailSessionLines(latest.file, 65536);
17919
- const recent = [];
17920
- let lastTs = "";
17921
- for (let i = lines.length - 1; i >= 0 && recent.length < 8; i--) {
17922
- let entry;
17923
- try {
17924
- entry = JSON.parse(lines[i]);
17925
- } catch {
17926
- continue;
17927
- }
17928
- if (entry.type !== "user" && entry.type !== "assistant") continue;
17929
- if (!lastTs && entry.timestamp) lastTs = entry.timestamp;
17930
- const blocks = extractBlocks(entry.message?.content);
17931
- for (const b of blocks) {
17932
- if (entry.type === "user" && b.type === "text" && b.text && !b.text.includes("tool_result")) {
17933
- recent.push(`\u{1F464} ${snippet(b.text)}`);
17934
- } else if (entry.type === "assistant" && b.type === "text" && b.text) {
17935
- recent.push(`\u{1F916} ${snippet(b.text)}`);
17936
- } else if (entry.type === "assistant" && b.type === "tool_use" && b.name) {
17937
- recent.push(`\u{1F527} ${b.name}`);
17938
- }
17939
- }
17940
- }
17941
- recent.reverse();
18297
+ const { recent, lastTs } = summarizeTranscript(latest.file);
17942
18298
  const idleMs = Date.now() - latest.modifiedAt;
17943
18299
  const state2 = idleMs < 3e4 ? "\u{1F7E2} \u6D3B\u8DC3\uFF08<30s \u5185\u6709\u5199\u5165\uFF09" : idleMs < 5 * 6e4 ? "\u{1F7E1} \u8FD1\u671F\u6709\u6D3B\u52A8" : "\u26AA \u7A7A\u95F2";
17944
18300
  const out = [
@@ -17960,8 +18316,15 @@ var cc_ask_exports = {};
17960
18316
  __export(cc_ask_exports, {
17961
18317
  ccAskOnce: () => ccAskOnce
17962
18318
  });
17963
- import { existsSync as existsSync17 } from "node:fs";
18319
+ import { existsSync as existsSync17, realpathSync as realpathSync12, statSync as statSync7 } from "node:fs";
17964
18320
  import path17 from "node:path";
18321
+ async function drainStandalone(directory2, queue) {
18322
+ while (queue.length) {
18323
+ await queue[0].run();
18324
+ queue.shift();
18325
+ }
18326
+ standaloneQueues.delete(directory2);
18327
+ }
17965
18328
  async function ccAskOnce(prompt, workDir, timeoutMs = ccAskTimeoutMs()) {
17966
18329
  const { query } = await loadOptionalModule("cc-runtime");
17967
18330
  const ac = new AbortController();
@@ -17998,7 +18361,104 @@ async function ccAskOnce(prompt, workDir, timeoutMs = ccAskTimeoutMs()) {
17998
18361
  if (!resultText.trim()) return { ok: false, text: "CC \u7ED3\u675F\u4F46\u6CA1\u6709\u4EA7\u51FA\u6587\u672C" + (isError ? "\uFF08\u51FA\u9519\uFF09" : ""), sessionId };
17999
18362
  return { ok: !isError, text: resultText, sessionId };
18000
18363
  }
18001
- var CC_ASK_TIMEOUT_MS, ccAskTimeoutMs;
18364
+ async function runStandalone(args, ctx, prompt, workDir, resumeLatest, ac, onSession) {
18365
+ if (ac.signal.aborted) return standaloneStopped;
18366
+ const stateDir = typeof ctx.stateDir === "string" && ctx.stateDir ? ctx.stateDir : typeof ctx.workspace === "string" ? ctx.workspace : "";
18367
+ let store = null;
18368
+ if (stateDir) {
18369
+ try {
18370
+ store = new CcSessionMapStore(stateDir, path17.join("agents", "cc-ask", "session-map.json"));
18371
+ } catch {
18372
+ store = null;
18373
+ }
18374
+ }
18375
+ const mapKey = `ask:${String(ctx.sessionId ?? ctx.channel ?? "anon")}@${workDir}`;
18376
+ let sessionId;
18377
+ let resumedFrom = "";
18378
+ const forceNew = args.newSession === true;
18379
+ if (forceNew) {
18380
+ store?.clear(mapKey);
18381
+ } else if (resumeLatest) {
18382
+ const sessions2 = listProjectSessions(workDir, void 0, 3);
18383
+ const candidate = sessions2.find((s) => s.messageCount > 0);
18384
+ if (!candidate) return { content: `${workDir} \u4E0B\u6CA1\u6709\u53EF\u63A5\u7EED\u7684 CC \u4F1A\u8BDD\uFF08\u53BB\u6389 resumeLatest \u5F00\u65B0\u4F1A\u8BDD\uFF09`, isError: true };
18385
+ if (await checkActive(candidate.file, 300)) {
18386
+ return { content: `\u8BE5\u9879\u76EE\u6700\u65B0\u4F1A\u8BDD\u6B63\u88AB\u522B\u5904\u9A71\u52A8\uFF08\u25CFlive\uFF1A\u63A7\u5236\u53F0\u6216\u98DE\u4E66 hub\uFF09\u2014\u2014\u7B49\u5B83\u7A7A\u95F2\u518D\u63A5\u624B\uFF0C\u6216\u53BB\u6389 resumeLatest \u5F00\u65B0\u4F1A\u8BDD\u3002`, isError: true };
18387
+ }
18388
+ sessionId = candidate.id;
18389
+ resumedFrom = "latest";
18390
+ } else {
18391
+ const mapped = store?.get(mapKey);
18392
+ if (mapped?.sessionId) {
18393
+ const hit = listProjectSessions(workDir, void 0, 30).find((s) => s.id === mapped.sessionId);
18394
+ if (hit) {
18395
+ if (await isActiveConfirmed(hit.file, 2e3)) {
18396
+ return { content: `\u4F60\u4E0A\u6B21\u7684 CC \u4F1A\u8BDD\uFF08${mapped.sessionId.slice(0, 8)}\uFF09\u6B63\u88AB\u522B\u5904\u9A71\u52A8\uFF08\u25CFlive\uFF1A\u63A7\u5236\u53F0\u6216\u98DE\u4E66 hub\uFF09\u2014\u2014\u7B49\u5B83\u7A7A\u95F2\u518D cc_ask\uFF0C\u6216 newSession=true \u5F00\u65B0\u4F1A\u8BDD\u3002`, isError: true };
18397
+ }
18398
+ sessionId = mapped.sessionId;
18399
+ resumedFrom = "own";
18400
+ }
18401
+ }
18402
+ }
18403
+ if (!sessionId) {
18404
+ const sessions2 = listProjectSessions(workDir, void 0, 1);
18405
+ const latest = sessions2[0];
18406
+ if (latest && await checkActive(latest.file, 300)) {
18407
+ return { content: `\u8BE5\u9879\u76EE\u6709\u4F1A\u8BDD\u6B63\u88AB\u522B\u5904\u9A71\u52A8\uFF08\u25CFlive\uFF09\u2014\u2014\u4E3A\u907F\u514D CC \u62FF\u7740\u8FC7\u65F6\u4E0A\u4E0B\u6587\u5E72\u6D3B\uFF0C\u7A0D\u7B49\u5B83\u7A7A\u95F2\uFF0C\u6216\u6307\u5B9A\u5176\u4ED6 workDir\u3002`, isError: true };
18408
+ }
18409
+ }
18410
+ if (sessionId && (nativeSessionOwners(sessionId).length || (await findDesktopTargets(workDir, sessionId)).length)) {
18411
+ return { content: "\u8BE5 CC \u4F1A\u8BDD\u4ECD\u7531\u684C\u9762\u8FDB\u7A0B\u6301\u6709\uFF1B\u8BF7\u7528 sessionId \u6295\u9012\u5230 cc-desktop\uFF0C\u4E0D\u80FD\u53E6\u8D77\u72EC\u7ACB CLI \u5199\u5165\u3002", isError: true };
18412
+ }
18413
+ if (ac.signal.aborted) return standaloneStopped;
18414
+ if (sessionId) onSession(sessionId);
18415
+ const { query } = await loadOptionalModule("cc-runtime");
18416
+ if (ac.signal.aborted) return standaloneStopped;
18417
+ let resultText = "";
18418
+ let newSessionId;
18419
+ let isError = false;
18420
+ try {
18421
+ const stream = query({
18422
+ prompt,
18423
+ options: {
18424
+ abortController: ac,
18425
+ cwd: workDir,
18426
+ permissionMode: "bypassPermissions",
18427
+ ...sessionId ? { resume: sessionId } : {},
18428
+ env: { CC_ASK_DEPTH: "1" }
18429
+ }
18430
+ });
18431
+ for await (const msg2 of stream) {
18432
+ if (msg2.parent_tool_use_id) continue;
18433
+ if (msg2.type === "system" && msg2.subtype === "init" && typeof msg2.session_id === "string") onSession(msg2.session_id);
18434
+ if (msg2.type === "result") {
18435
+ const r = msg2;
18436
+ resultText = typeof r.result === "string" ? r.result : "";
18437
+ isError = r.is_error === true;
18438
+ if (r.session_id) {
18439
+ newSessionId = r.session_id;
18440
+ onSession(r.session_id);
18441
+ }
18442
+ }
18443
+ }
18444
+ } catch (err) {
18445
+ if (ac.signal.aborted) return standaloneStopped;
18446
+ return { content: `CC \u9A71\u52A8\u5931\u8D25\uFF1A${err?.message ?? err}`, isError: true };
18447
+ }
18448
+ if (ac.signal.aborted) return standaloneStopped;
18449
+ const text2 = resultText.trim();
18450
+ if (!text2) return { content: "CC \u7ED3\u675F\u4F46\u6CA1\u6709\u4EA7\u51FA\u6587\u672C" + (isError ? "\uFF08\u51FA\u9519\uFF09" : ""), isError: true };
18451
+ if (newSessionId && store) {
18452
+ try {
18453
+ store.set(mapKey, newSessionId, workDir);
18454
+ } catch {
18455
+ }
18456
+ }
18457
+ const tail = resumedFrom === "own" ? `\uFF08\u63A5\u7EED\u4F60\u4E0A\u6B21\u7684\u4F1A\u8BDD ${newSessionId?.slice(0, 8)}\uFF0C\u4E4B\u524D cc_ask \u5F3A\u8C03\u8FC7\u7684\u8981\u6C42\u90FD\u5728\u4E0A\u4E0B\u6587\u91CC\uFF09` : newSessionId ? `\uFF08${resumedFrom === "latest" ? "\u63A5\u7EED\u9879\u76EE\u6700\u8FD1\u4F1A\u8BDD" : "\u65B0\u4F1A\u8BDD"} ${newSessionId.slice(0, 8)}\uFF0C\u5DF2\u8BB0\u4F4F\u2014\u2014\u540E\u7EED cc_ask \u81EA\u52A8\u63A5\u7EED\uFF1BnewSession=true \u53EF\u91CD\u5F00\uFF09` : "";
18458
+ return { content: `[CC @ ${workDir.split("/").pop()}] ${text2}${tail ? `
18459
+ ${tail}` : ""}`, isError };
18460
+ }
18461
+ var standaloneQueues, MAX_STANDALONE_QUEUE, standaloneStopped, CC_ASK_TIMEOUT_MS, ccAskTimeoutMs;
18002
18462
  var init_cc_ask = __esm({
18003
18463
  "src/tools/cc-ask.ts"() {
18004
18464
  "use strict";
@@ -18009,6 +18469,11 @@ var init_cc_ask = __esm({
18009
18469
  init_handoff();
18010
18470
  init_desktop();
18011
18471
  init_dep_downloader();
18472
+ init_cc_ask_jobs();
18473
+ init_cc_peer();
18474
+ standaloneQueues = /* @__PURE__ */ new Map();
18475
+ MAX_STANDALONE_QUEUE = 6;
18476
+ standaloneStopped = { content: "CC \u4EFB\u52A1\u5DF2\u505C\u6B62\u3002", isError: true };
18012
18477
  CC_ASK_TIMEOUT_MS = 9e5;
18013
18478
  ccAskTimeoutMs = () => {
18014
18479
  const v = Number(process.env.CC_ASK_TIMEOUT_MS);
@@ -18017,13 +18482,15 @@ var init_cc_ask = __esm({
18017
18482
  };
18018
18483
  registry.register({
18019
18484
  name: "cc_ask",
18020
- description: `Ask a running CC terminal (Claude Code) and return its answer here. sessionId selects the exact session UUID; target selects desktop:UUID or channel:chatId. Desktop sessions opened with engine7 cc-desktop receive input in their existing interactive process; busy sessions and unfinished user drafts queue requests. By default discover desktop sessions and Feishu/WeChat hub bindings for workDir. Multiple different sessions require a target; a desktop owning a hub's same UUID is the writer. If the user's current instructions/context clearly identify a discovered target, select it yourself without asking again. If still uncertain, show concise choices with project, desktop/channel and session ID, then ask the user which one; never guess from list order or recency. Selecting a target applies to this call, not a permanent channel rebinding. Without a target/binding keep your own standalone CC session per workDir. newSession=true and resumeLatest=true explicitly use standalone CLI and cannot combine with a target/sessionId. Failed handoff never falls back. Timeout defaults to 900s (CC_ASK_TIMEOUT_MS overrides; 0 disables the timeout entirely, cancellation only via user stop). A submitted desktop turn may continue after timeout/cancellation. For read-only status use cc_progress.`,
18485
+ description: `Send a task to Claude Code. mode=sync (default) waits for the answer; mode=async returns an accepted receipt with jobId once queued. A sync wait timeout (900s by default, CC_ASK_TIMEOUT_MS) returns jobId and the task continues. Use cc_progress({jobId}) to check status or read the answer and cc_stop({jobId}) to explicitly stop that task. Load either tool via ToolSearch if needed. sessionId selects the exact session; target selects desktop:UUID or channel:chatId. Without a selector, discover desktop sessions and channel bindings for workDir. If several differ, choose the session identified by the user's instructions or context, or ask if still ambiguous. With no binding use your own standalone CC session per workDir. newSession=true or resumeLatest=true selects standalone CLI and cannot combine with target/sessionId. Failed handoff never falls back.`,
18021
18486
  schema: {
18022
18487
  type: "object",
18023
18488
  properties: {
18024
18489
  prompt: { type: "string", description: "\u7ED9 CC \u7684\u4EFB\u52A1\u6307\u4EE4\uFF08\u9ED8\u8BA4\u8FDB\u5165\u9879\u76EE\u5DF2\u7ED1\u5B9A\u7684\u98DE\u4E66\uFF0F\u5FAE\u4FE1 CC \u5F53\u524D\u4F1A\u8BDD\uFF09" },
18490
+ mode: { type: "string", enum: ["sync", "async"], description: "sync \u7B49\u7B54\u6848\uFF08\u9ED8\u8BA4\uFF09\uFF1Basync \u7B49\u786E\u8BA4\u5165\u961F\u540E\u8FD4\u56DE jobId\u3002" },
18025
18491
  workDir: { type: "string", description: "CC \u8DD1\u5728\u54EA\u4E2A\u9879\u76EE\u76EE\u5F55\uFF08\u7EDD\u5BF9\u8DEF\u5F84\uFF09\uFF0C\u4F8B\uFF1A/Users/chongzhang/work/engine7-devui" },
18026
- target: { type: "string", description: "\u6307\u5B9A desktop:\u4F1A\u8BDDUUID \u6216 channel:chatId\uFF08\u6B67\u4E49\u7ED3\u679C\u4F1A\u5217\u51FA\u53EF\u9009 target\uFF09" },
18492
+ target: { type: "string", description: "\u6307\u5B9A desktop:\u4F1A\u8BDDUUID\u3001channel:chatId \u6216 remote:\u5DF2\u914D\u7F6E\u7684\u8FDC\u7A0B CC \u522B\u540D" },
18493
+ requestId: { type: "string", description: "\u8FDC\u7A0B\u672A\u786E\u8BA4\u56DE\u6267\u65F6\u91CD\u8BD5\u53EF\u6CBF\u7528\u539F requestId\u3002" },
18027
18494
  sessionId: { type: "string", description: "\u7CBE\u786E\u6307\u5B9A CC \u4F1A\u8BDD UUID\uFF1B\u684C\u9762\u987B\u901A\u8FC7 engine7 cc-desktop \u63A5\u5165\uFF0C\u4E0D\u4F1A\u53E6\u5F00\u8FDB\u7A0B\u5199\u5B83\u7684\u5386\u53F2" },
18028
18495
  newSession: { type: "boolean", description: "true = \u4F7F\u7528\u72EC\u7ACB CLI \u5F3A\u5236\u5F00\u65B0\u4F1A\u8BDD\uFF0C\u4E0D\u8FDB\u5165\u98DE\u4E66\uFF0F\u5FAE\u4FE1\u7ED1\u5B9A\uFF08\u5FD8\u6389\u4E4B\u524D\u72EC\u7ACB cc_ask \u4E0A\u4E0B\u6587\uFF09" },
18029
18496
  resumeLatest: { type: "boolean", description: "true = \u72EC\u7ACB CLI \u63A5\u7EED\u9879\u76EE\u6700\u8FD1\u975E\u6D3B\u8DC3\u4F1A\u8BDD\uFF1B\u9ED8\u8BA4\u4F18\u5148\u8FDB\u5165\u5F53\u524D CC \u7ED1\u5B9A\uFF0C\u65E0\u7ED1\u5B9A\u624D\u63A5\u7EED\u4F60\u81EA\u5DF1\u7684 cc_ask \u4F1A\u8BDD" }
@@ -18034,6 +18501,8 @@ var init_cc_ask = __esm({
18034
18501
  const prompt = typeof args.prompt === "string" ? args.prompt.trim() : "";
18035
18502
  let workDir = typeof args.workDir === "string" ? args.workDir.trim() : "";
18036
18503
  const resumeLatest = args.resumeLatest === true;
18504
+ const mode = args.mode ?? "sync";
18505
+ if (mode !== "sync" && mode !== "async") return { content: "mode \u9700\u8981 sync \u6216 async\u3002", isError: true };
18037
18506
  if (!prompt) return { content: "\u9700\u8981 prompt \u53C2\u6570", isError: true };
18038
18507
  const depth = Number(process.env.CC_ASK_DEPTH ?? 0);
18039
18508
  if (depth >= 1) return { content: `\u9012\u5F52\u4FDD\u62A4\uFF1A\u5F53\u524D\u5BF9\u8BDD\u672C\u8EAB\u662F CC \u9A71\u52A8\u7684\uFF08\u6DF1\u5EA6 ${depth}\uFF09\uFF0C\u4E0D\u518D\u53CD\u5411 cc-ask\u2014\u2014\u8BF7\u76F4\u63A5\u628A\u9700\u6C42\u544A\u8BC9\u5BF9\u65B9\u3002`, isError: true };
@@ -18043,6 +18512,15 @@ var init_cc_ask = __esm({
18043
18512
  if ((targetKey || sessionIdArg) && (args.newSession === true || resumeLatest)) {
18044
18513
  return { content: "target/sessionId \u6307\u5B9A\u5DF2\u6709\u4F1A\u8BDD\uFF0C\u4E0D\u80FD\u540C\u65F6\u4F7F\u7528\u72EC\u7ACB CLI \u7684 newSession/resumeLatest\u3002", isError: true };
18045
18514
  }
18515
+ try {
18516
+ const peer = selectCcPeer(targetKey, !sessionIdArg && args.newSession !== true && !resumeLatest);
18517
+ if (peer) {
18518
+ if (sessionIdArg) return { content: "\u8FDC\u7A0B CC \u4F7F\u7528\u76EE\u6807\u7ED1\u5B9A\u7684\u4F1A\u8BDD\u3002", isError: true };
18519
+ return await askRemoteCc(peer, { ...args, prompt }, ctx, ccAskTimeoutMs(), signal);
18520
+ }
18521
+ } catch (error) {
18522
+ return { content: error.message, isError: true };
18523
+ }
18046
18524
  if (args.newSession !== true && !resumeLatest) {
18047
18525
  try {
18048
18526
  const desktopKey = targetKey.startsWith("desktop:") ? targetKey.slice("desktop:".length) : "";
@@ -18057,51 +18535,40 @@ ${[...desktops, ...targets].map((t) => `${t.key} \u2192 ${t.workDir}`).join("\n"
18057
18535
  }
18058
18536
  if (desktops[0]) {
18059
18537
  const desktop = desktops[0];
18060
- const timeoutMs2 = ccAskTimeoutMs();
18061
- const timeout = new AbortController();
18062
- const timer2 = timeoutMs2 > 0 ? setTimeout(() => timeout.abort(), timeoutMs2) : void 0;
18063
- const combined = signal ? AbortSignal.any([signal, timeout.signal]) : timeout.signal;
18064
18538
  const caller = String(ctx.agentName || registry.config?.name || "agent");
18065
- try {
18066
- console.log(`[cc-ask] desktop target=${desktop.key} pid=${desktop.pid} caller=${String(ctx.sessionId || "").slice(0, 8)}`);
18067
- const result = await askDesktop(desktop, prompt, caller, combined);
18068
- return { content: `[CC @ ${path17.basename(desktop.workDir)}] ${result.text}
18539
+ console.log(`[cc-ask] desktop target=${desktop.key} pid=${desktop.pid} caller=${String(ctx.sessionId || "").slice(0, 8)}`);
18540
+ return await runCcAskJob({
18541
+ ctx,
18542
+ target: desktop,
18543
+ mode,
18544
+ timeoutMs: ccAskTimeoutMs(),
18545
+ signal,
18546
+ stop: (id2) => stopDesktopJob(desktop, id2),
18547
+ run: async (ack, transport) => {
18548
+ const result = await askDesktop(desktop, prompt, caller, transport, ack);
18549
+ return { content: `[CC @ ${path17.basename(desktop.workDir)}] ${result.text}
18069
18550
  \uFF08\u684C\u9762\u4F1A\u8BDD ${result.sessionId}\uFF0C\u5DF2\u5728\u6253\u5F00\u7684\u63A7\u5236\u53F0\u5185\u6267\u884C\uFF09`, isError: result.isError };
18070
- } catch (error) {
18071
- if (combined.aborted) return { content: "\u684C\u9762 CC \u8BF7\u6C42\u7B49\u5F85\u5DF2\u7ED3\u675F\uFF1B\u5C1A\u672A\u6295\u9012\u7684\u6392\u961F\u8BF7\u6C42\u5DF2\u53D6\u6D88\uFF0C\u5DF2\u6295\u9012\u7684\u56DE\u5408\u53EF\u80FD\u4ECD\u5728\u684C\u9762\u6267\u884C\u3002\u8BF7\u67E5\u770B\u63A7\u5236\u53F0\uFF0C\u907F\u514D\u91CD\u590D\u53D1\u9001\u3002", isError: true };
18072
- throw error;
18073
- } finally {
18074
- clearTimeout(timer2);
18075
- }
18551
+ }
18552
+ });
18076
18553
  }
18077
- const target = targets[0];
18078
- if (target) {
18079
- const timeoutMs2 = ccAskTimeoutMs();
18080
- const timeout = new AbortController();
18081
- const timer2 = timeoutMs2 > 0 ? setTimeout(() => timeout.abort(), timeoutMs2) : void 0;
18082
- const combined = signal ? AbortSignal.any([signal, timeout.signal]) : timeout.signal;
18554
+ const target2 = targets[0];
18555
+ if (target2) {
18083
18556
  const caller = String(ctx.agentName || registry.config?.mem7?.agentName || registry.config?.everos?.agentName || "agent");
18084
18557
  const source = `${caller} @${ctx.channel || "unknown"} (${String(ctx.sessionId || "unknown").slice(0, 8)})`;
18085
- console.log(`[cc-ask] handoff target=${target.key} resume=${target.sessionId?.slice(0, 8) ?? "new"} hubPid=${target.endpoint.pid} caller=${String(ctx.sessionId ?? "").slice(0, 8)}`);
18086
- try {
18087
- const result = await askBoundCc(target, prompt, source, combined);
18088
- return { content: `[CC @ ${path17.basename(target.workDir)}] ${result.text}
18089
- \uFF08\u5DF2\u8FDB\u5165 ${target.key} \u7684 CC \u7ED1\u5B9A\u4F1A\u8BDD ${result.sessionId?.slice(0, 8) ?? "new"}\uFF0C\u98DE\u4E66\uFF0F\u5FAE\u4FE1\u540E\u7EED\u5BF9\u8BDD\u5171\u4EAB\u8FD9\u6BB5\u4E0A\u4E0B\u6587\uFF09`, isError: result.isError };
18090
- } catch (error) {
18091
- if (signal?.aborted) {
18092
- let stopped = false;
18093
- try {
18094
- stopped = await stopBoundCc(target);
18095
- } catch {
18096
- stopped = false;
18097
- }
18098
- return { content: stopped ? "CC \u7ED1\u5B9A\u8BF7\u6C42\u5DF2\u53D6\u6D88\uFF0C\u5E76\u5DF2\u901A\u77E5 CC \u505C\u6B62\u5F53\u524D\u4EFB\u52A1\u3002" : "CC \u7ED1\u5B9A\u8BF7\u6C42\u5DF2\u53D6\u6D88\uFF08\u505C\u6B62\u901A\u77E5\u672A\u9001\u8FBE\u2014\u2014\u5F53\u524D\u56DE\u5408\u53EF\u80FD\u4ECD\u5728\u7EE7\u7EED\uFF0C\u53EF\u7528 cc_progress \u67E5\u770B\u8FDB\u5C55\uFF09\u3002", isError: true };
18558
+ console.log(`[cc-ask] handoff target=${target2.key} resume=${target2.sessionId?.slice(0, 8) ?? "new"} hubPid=${target2.endpoint.pid} caller=${String(ctx.sessionId ?? "").slice(0, 8)}`);
18559
+ return await runCcAskJob({
18560
+ ctx,
18561
+ target: target2,
18562
+ mode,
18563
+ timeoutMs: ccAskTimeoutMs(),
18564
+ signal,
18565
+ stop: (id2) => stopBoundCc(target2, id2),
18566
+ run: async (ack, transport) => {
18567
+ const result = await askBoundCc(target2, prompt, source, transport, ack);
18568
+ return { content: `[CC @ ${path17.basename(target2.workDir)}] ${result.text}
18569
+ \uFF08\u5DF2\u8FDB\u5165 ${target2.key} \u7684 CC \u7ED1\u5B9A\u4F1A\u8BDD ${result.sessionId?.slice(0, 8) ?? "new"}\uFF0C\u98DE\u4E66\uFF0F\u5FAE\u4FE1\u540E\u7EED\u5BF9\u8BDD\u5171\u4EAB\u8FD9\u6BB5\u4E0A\u4E0B\u6587\uFF09`, isError: result.isError };
18099
18570
  }
18100
- if (timeout.signal.aborted) return { content: `\u7B49\u5F85\u8D85\u65F6\uFF08>${Math.round(timeoutMs2 / 1e3)}s\uFF09\u5DF2\u5148\u8FD4\u56DE\uFF1BCC \u91CC\u7684\u4EFB\u52A1\u6CA1\u6709\u88AB\u53D6\u6D88\u3001\u4ECD\u5728\u7EE7\u7EED\u8DD1\u5B8C\u2014\u2014\u7A0D\u540E\u7528 cc_progress \u67E5\u770B\u7ED3\u679C\uFF0C\u4E0D\u8981\u91CD\u590D\u53D1\u9001\u3002`, isError: true };
18101
- throw error;
18102
- } finally {
18103
- clearTimeout(timer2);
18104
- }
18571
+ });
18105
18572
  }
18106
18573
  if (targetKey || sessionIdArg) return { content: `\u6CA1\u6709\u627E\u5230\u5F53\u524D\u63A5\u5165\u7684 CC \u76EE\u6807 ${targetKey || sessionIdArg}\u3002\u684C\u9762\u4F1A\u8BDD\u9700\u7528 engine7 cc-desktop --resume <UUID> \u6253\u5F00\u3002`, isError: true };
18107
18574
  if (ccDriverRouter.hub?.bindings.some((b) => !workDir || b.workDir === workDir)) {
@@ -18119,107 +18586,88 @@ ${[...desktops, ...targets].map((t) => `${t.key} \u2192 ${t.workDir}`).join("\n"
18119
18586
  ${dirs.join("\n")}`, isError: true };
18120
18587
  }
18121
18588
  if (!workDir) {
18122
- const recent = listCcProjects().filter((p22) => p22.workDir && existsSync17(p22.workDir));
18123
- if (recent.length === 0) return { content: "\u672C\u673A\u6CA1\u6709 CC \u4F1A\u8BDD\u8BB0\u5F55\uFF0C\u65E0\u6CD5\u63A8\u65AD\u5DE5\u4F5C\u76EE\u5F55\u2014\u2014\u8BF7\u6307\u5B9A workDir", isError: true };
18124
- workDir = recent[0].workDir;
18125
- }
18126
- }
18127
- const stateDir = typeof ctx.stateDir === "string" && ctx.stateDir ? ctx.stateDir : typeof ctx.workspace === "string" ? ctx.workspace : "";
18128
- let store = null;
18129
- if (stateDir) {
18130
- try {
18131
- store = new CcSessionMapStore(stateDir, path17.join("agents", "cc-ask", "session-map.json"));
18132
- } catch {
18133
- store = null;
18134
- }
18135
- }
18136
- const mapKey = `ask:${String(ctx.sessionId ?? ctx.channel ?? "anon")}@${workDir}`;
18137
- let sessionId;
18138
- let resumedFrom = "";
18139
- const forceNew = args.newSession === true;
18140
- if (forceNew) {
18141
- store?.clear(mapKey);
18142
- } else if (resumeLatest) {
18143
- const sessions2 = listProjectSessions(workDir, void 0, 3);
18144
- const candidate = sessions2.find((s) => s.messageCount > 0);
18145
- if (!candidate) return { content: `${workDir} \u4E0B\u6CA1\u6709\u53EF\u63A5\u7EED\u7684 CC \u4F1A\u8BDD\uFF08\u53BB\u6389 resumeLatest \u5F00\u65B0\u4F1A\u8BDD\uFF09`, isError: true };
18146
- if (await checkActive(candidate.file, 300)) {
18147
- return { content: `\u8BE5\u9879\u76EE\u6700\u65B0\u4F1A\u8BDD\u6B63\u88AB\u522B\u5904\u9A71\u52A8\uFF08\u25CFlive\uFF1A\u63A7\u5236\u53F0\u6216\u98DE\u4E66 hub\uFF09\u2014\u2014\u7B49\u5B83\u7A7A\u95F2\u518D\u63A5\u624B\uFF0C\u6216\u53BB\u6389 resumeLatest \u5F00\u65B0\u4F1A\u8BDD\u3002`, isError: true };
18148
- }
18149
- sessionId = candidate.id;
18150
- resumedFrom = "latest";
18151
- } else {
18152
- const mapped = store?.get(mapKey);
18153
- if (mapped?.sessionId) {
18154
- const hit = listProjectSessions(workDir, void 0, 30).find((s) => s.id === mapped.sessionId);
18155
- if (hit) {
18156
- if (await isActiveConfirmed(hit.file, 2e3)) {
18157
- return { content: `\u4F60\u4E0A\u6B21\u7684 CC \u4F1A\u8BDD\uFF08${mapped.sessionId.slice(0, 8)}\uFF09\u6B63\u88AB\u522B\u5904\u9A71\u52A8\uFF08\u25CFlive\uFF1A\u63A7\u5236\u53F0\u6216\u98DE\u4E66 hub\uFF09\u2014\u2014\u7B49\u5B83\u7A7A\u95F2\u518D cc_ask\uFF0C\u6216 newSession=true \u5F00\u65B0\u4F1A\u8BDD\u3002`, isError: true };
18158
- }
18159
- sessionId = mapped.sessionId;
18160
- resumedFrom = "own";
18161
- }
18589
+ const recent = listCcProjects().find((project) => project.workDir && existsSync17(project.workDir))?.workDir;
18590
+ if (!recent) return { content: "\u672C\u673A\u6CA1\u6709 CC \u4F1A\u8BDD\u8BB0\u5F55\uFF0C\u65E0\u6CD5\u63A8\u65AD\u5DE5\u4F5C\u76EE\u5F55\u2014\u2014\u8BF7\u6307\u5B9A workDir", isError: true };
18591
+ workDir = recent;
18162
18592
  }
18163
18593
  }
18164
- if (!sessionId) {
18165
- const sessions2 = listProjectSessions(workDir, void 0, 1);
18166
- const latest = sessions2[0];
18167
- if (latest && await checkActive(latest.file, 300)) {
18168
- return { content: `\u8BE5\u9879\u76EE\u6709\u4F1A\u8BDD\u6B63\u88AB\u522B\u5904\u9A71\u52A8\uFF08\u25CFlive\uFF09\u2014\u2014\u4E3A\u907F\u514D CC \u62FF\u7740\u8FC7\u65F6\u4E0A\u4E0B\u6587\u5E72\u6D3B\uFF0C\u7A0D\u7B49\u5B83\u7A7A\u95F2\uFF0C\u6216\u6307\u5B9A\u5176\u4ED6 workDir\u3002`, isError: true };
18169
- }
18170
- }
18171
- if (sessionId && (nativeSessionOwners(sessionId).length || (await findDesktopTargets(workDir, sessionId)).length)) {
18172
- return { content: "\u8BE5 CC \u4F1A\u8BDD\u4ECD\u7531\u684C\u9762\u8FDB\u7A0B\u6301\u6709\uFF1B\u8BF7\u7528 sessionId \u6295\u9012\u5230 cc-desktop\uFF0C\u4E0D\u80FD\u53E6\u8D77\u72EC\u7ACB CLI \u5199\u5165\u3002", isError: true };
18173
- }
18174
- const timeoutMs = ccAskTimeoutMs();
18175
- const timeoutText = timeoutMs > 0 ? `CC \u8D85\u65F6\uFF08>${Math.round(timeoutMs / 1e3)}s\uFF09\u88AB\u4E2D\u65AD\u2014\u2014\u4E0D\u662F\u88AB\u8C01\u6253\u65AD\uFF0C\u662F\u4EFB\u52A1\u8D85\u51FA cc_ask \u7684\u540C\u6B65\u7B49\u5F85\u4E0A\u9650\u3002\u628A\u4EFB\u52A1\u62C6\u5C0F\u518D\u95EE\uFF0C\u6216\u8D70\u6D88\u606F\u6E20\u9053\u5F02\u6B65\u6D3E\u7ED9 CC \u540E\u7528 cc_progress \u770B\u8FDB\u5C55\u3002` : "CC \u8BF7\u6C42\u5DF2\u53D6\u6D88\uFF08\u65E0\u8D85\u65F6\u4E0A\u9650\u6A21\u5F0F\u4E0B\u7531\u5916\u90E8\u4E2D\u65AD\uFF09\u3002";
18176
- const { query } = await loadOptionalModule("cc-runtime");
18177
- const ac = new AbortController();
18178
- signal?.addEventListener("abort", () => ac.abort(), { once: true });
18179
- const timer = timeoutMs > 0 ? setTimeout(() => ac.abort(), timeoutMs) : void 0;
18180
- let resultText = "";
18181
- let newSessionId;
18182
- let isError = false;
18594
+ let directory2;
18183
18595
  try {
18184
- const stream = query({
18185
- prompt,
18186
- options: {
18187
- abortController: ac,
18188
- cwd: workDir,
18189
- permissionMode: "bypassPermissions",
18190
- ...sessionId ? { resume: sessionId } : {},
18191
- env: { CC_ASK_DEPTH: "1" }
18192
- }
18193
- });
18194
- for await (const msg2 of stream) {
18195
- if (msg2.parent_tool_use_id) continue;
18196
- if (msg2.type === "result") {
18197
- const r = msg2;
18198
- resultText = typeof r.result === "string" ? r.result : "";
18199
- isError = r.is_error === true;
18200
- if (r.session_id) newSessionId = r.session_id;
18201
- }
18202
- }
18203
- } catch (err) {
18204
- clearTimeout(timer);
18205
- if (ac.signal.aborted) return { content: timeoutText, isError: true };
18206
- return { content: `CC \u9A71\u52A8\u5931\u8D25\uFF1A${err?.message ?? err}`, isError: true };
18207
- }
18208
- clearTimeout(timer);
18209
- if (ac.signal.aborted) {
18210
- return { content: timeoutText, isError: true };
18596
+ directory2 = realpathSync12(workDir);
18597
+ if (!statSync7(directory2).isDirectory()) throw new Error("not a directory");
18598
+ } catch {
18599
+ return { content: `CC \u5DE5\u4F5C\u76EE\u5F55\u4E0D\u53EF\u7528\uFF1A${workDir}`, isError: true };
18211
18600
  }
18212
- const text2 = resultText.trim();
18213
- if (!text2) return { content: "CC \u7ED3\u675F\u4F46\u6CA1\u6709\u4EA7\u51FA\u6587\u672C" + (isError ? "\uFF08\u51FA\u9519\uFF09" : ""), isError: true };
18214
- if (newSessionId && store) {
18215
- try {
18216
- store.set(mapKey, newSessionId, workDir);
18217
- } catch {
18601
+ const controller = new AbortController();
18602
+ const target = { key: directory2, workDir, sessionId: null };
18603
+ let queued;
18604
+ return runCcAskJob({
18605
+ ctx,
18606
+ target,
18607
+ mode,
18608
+ timeoutMs: ccAskTimeoutMs(),
18609
+ signal,
18610
+ stop: () => {
18611
+ controller.abort();
18612
+ const queue = standaloneQueues.get(directory2);
18613
+ const index = queue?.indexOf(queued) ?? -1;
18614
+ if (index > 0) queue.splice(index, 1)[0].finish(standaloneStopped);
18615
+ return index >= 0;
18616
+ },
18617
+ run: async (ack) => {
18618
+ const queue = standaloneQueues.get(directory2) ?? [];
18619
+ if (queue.length >= MAX_STANDALONE_QUEUE) throw new Error("CC \u9879\u76EE\u961F\u5217\u5DF2\u6EE1\u3002");
18620
+ const pending = new Promise((finish, reject) => {
18621
+ queued = { finish, run: async () => {
18622
+ try {
18623
+ finish(await runStandalone(args, ctx, prompt, workDir, resumeLatest, controller, (id2) => {
18624
+ target.sessionId = id2;
18625
+ }));
18626
+ } catch (error) {
18627
+ reject(error);
18628
+ }
18629
+ } };
18630
+ queue.push(queued);
18631
+ });
18632
+ ack.onAccepted();
18633
+ if (queue.length === 1) {
18634
+ standaloneQueues.set(directory2, queue);
18635
+ void Promise.resolve().then(() => drainStandalone(directory2, queue));
18636
+ }
18637
+ return pending;
18218
18638
  }
18639
+ });
18640
+ }
18641
+ });
18642
+ registry.register({
18643
+ name: "cc_stop",
18644
+ description: "Explicitly stop one CC task from a cc_ask receipt by jobId. Removes that task if queued or interrupts it if running.",
18645
+ schema: {
18646
+ type: "object",
18647
+ properties: { jobId: { type: "string", description: "Job ID from the cc_ask receipt." } },
18648
+ required: ["jobId"]
18649
+ },
18650
+ handler: async (args, ctx, signal) => await observeRemoteCc("stop", args, ctx, signal) ?? stopCcAskJob(args.jobId, ctx)
18651
+ });
18652
+ registry.register({
18653
+ name: "cc_new",
18654
+ description: "Start a new conversation at the configured remote CC binding. The next CC message starts the new session.",
18655
+ schema: {
18656
+ type: "object",
18657
+ properties: {
18658
+ target: { type: "string", description: "remote:\u5DF2\u914D\u7F6E\u7684 CC \u522B\u540D\u3002\u7701\u7565\u4F7F\u7528\u9ED8\u8BA4\u76EE\u6807\u3002" },
18659
+ requestId: { type: "string", description: "\u672A\u786E\u8BA4\u56DE\u6267\u65F6\u91CD\u8BD5\u53EF\u4EE5\u6CBF\u7528\u539F requestId\u3002" }
18660
+ },
18661
+ required: []
18662
+ },
18663
+ handler: async (args, ctx, signal) => {
18664
+ try {
18665
+ const peer = selectCcPeer(args.target);
18666
+ if (peer) return await newRemoteCc(peer, args, ctx, signal);
18667
+ return { content: "\u672C\u673A\u7ED1\u5B9A\u4F1A\u8BDD\u53EF\u4EE5\u5728\u5BF9\u5E94\u804A\u5929\u8F93\u5165 /cc-new\u3002", isError: true };
18668
+ } catch (error) {
18669
+ return { content: error.message, isError: true };
18219
18670
  }
18220
- const tail = resumedFrom === "own" ? `\uFF08\u63A5\u7EED\u4F60\u4E0A\u6B21\u7684\u4F1A\u8BDD ${newSessionId?.slice(0, 8)}\uFF0C\u4E4B\u524D cc_ask \u5F3A\u8C03\u8FC7\u7684\u8981\u6C42\u90FD\u5728\u4E0A\u4E0B\u6587\u91CC\uFF09` : newSessionId ? `\uFF08${resumedFrom === "latest" ? "\u63A5\u7EED\u9879\u76EE\u6700\u8FD1\u4F1A\u8BDD" : "\u65B0\u4F1A\u8BDD"} ${newSessionId.slice(0, 8)}\uFF0C\u5DF2\u8BB0\u4F4F\u2014\u2014\u540E\u7EED cc_ask \u81EA\u52A8\u63A5\u7EED\uFF1BnewSession=true \u53EF\u91CD\u5F00\uFF09` : "";
18221
- return { content: `[CC @ ${workDir.split("/").pop()}] ${text2}${tail ? `
18222
- ${tail}` : ""}`, isError };
18223
18671
  }
18224
18672
  });
18225
18673
  }
@@ -18256,7 +18704,7 @@ CREATE INDEX idx_calendar_dispatch_scope ON calendar_dispatches(scope_id,event_i
18256
18704
  // src/continuity/sqlite-write-capture.ts
18257
18705
  function installSQLiteWriteCapture(db2, source) {
18258
18706
  if (db2.isTransaction) throw new Error("REPLICATION_TRANSACTION_ALREADY_OPEN");
18259
- const exec3 = db2.exec, prepare = db2.prepare;
18707
+ const exec4 = db2.exec, prepare = db2.prepare;
18260
18708
  let active, failed = false, closed = false, reading = false;
18261
18709
  let direct2;
18262
18710
  const check = () => {
@@ -18267,13 +18715,13 @@ function installSQLiteWriteCapture(db2, source) {
18267
18715
  check();
18268
18716
  const command2 = sql.trim().replace(/;$/, "").trim().toUpperCase();
18269
18717
  if (command2 === "BEGIN IMMEDIATE" || command2 === "BEGIN IMMEDIATE TRANSACTION") {
18270
- exec3.call(db2, sql);
18718
+ exec4.call(db2, sql);
18271
18719
  try {
18272
18720
  active = source.beginCapture();
18273
18721
  failed = false;
18274
18722
  reading = false;
18275
18723
  } catch (error) {
18276
- exec3.call(db2, "ROLLBACK");
18724
+ exec4.call(db2, "ROLLBACK");
18277
18725
  throw error;
18278
18726
  }
18279
18727
  return;
@@ -18282,13 +18730,13 @@ function installSQLiteWriteCapture(db2, source) {
18282
18730
  if (failed) throw new Error("REPLICATION_TRANSACTION_FAILED");
18283
18731
  if (!active) {
18284
18732
  if (!reading) throw new Error("REPLICATION_SQL_FORM_UNSUPPORTED");
18285
- exec3.call(db2, sql);
18733
+ exec4.call(db2, sql);
18286
18734
  reading = false;
18287
18735
  return;
18288
18736
  }
18289
18737
  try {
18290
18738
  source.appendCapture(active);
18291
- exec3.call(db2, sql);
18739
+ exec4.call(db2, sql);
18292
18740
  source.endCapture(active);
18293
18741
  active = void 0;
18294
18742
  } catch (error) {
@@ -18299,7 +18747,7 @@ function installSQLiteWriteCapture(db2, source) {
18299
18747
  }
18300
18748
  if (command2 === "ROLLBACK" || command2 === "ROLLBACK TRANSACTION") {
18301
18749
  try {
18302
- exec3.call(db2, sql);
18750
+ exec4.call(db2, sql);
18303
18751
  } finally {
18304
18752
  if (!db2.isTransaction) reading = false;
18305
18753
  if (active && !db2.isTransaction) {
@@ -18311,12 +18759,12 @@ function installSQLiteWriteCapture(db2, source) {
18311
18759
  return;
18312
18760
  }
18313
18761
  if (command2 === "BEGIN" || command2 === "BEGIN TRANSACTION" || command2 === "BEGIN DEFERRED" || command2 === "BEGIN DEFERRED TRANSACTION") {
18314
- exec3.call(db2, sql);
18762
+ exec4.call(db2, sql);
18315
18763
  reading = true;
18316
18764
  return;
18317
18765
  }
18318
18766
  if (/^(?:SAVEPOINT|RELEASE(?: SAVEPOINT)?|ROLLBACK TO(?: SAVEPOINT)?) [A-Z_][A-Z0-9_]*$/.test(command2) && db2.isTransaction && !failed) {
18319
- exec3.call(db2, sql);
18767
+ exec4.call(db2, sql);
18320
18768
  return;
18321
18769
  }
18322
18770
  throw new Error("REPLICATION_SQL_FORM_UNSUPPORTED");
@@ -18352,13 +18800,13 @@ function installSQLiteWriteCapture(db2, source) {
18352
18800
  close() {
18353
18801
  if (closed) return;
18354
18802
  if (active) {
18355
- if (db2.isTransaction) exec3.call(db2, "ROLLBACK");
18803
+ if (db2.isTransaction) exec4.call(db2, "ROLLBACK");
18356
18804
  source.endCapture(active);
18357
18805
  active = void 0;
18358
18806
  }
18359
18807
  direct2.close();
18360
18808
  db2.prepare = prepare;
18361
- db2.exec = exec3;
18809
+ db2.exec = exec4;
18362
18810
  closed = true;
18363
18811
  }
18364
18812
  };
@@ -18762,14 +19210,14 @@ var init_notification_state = __esm({
18762
19210
 
18763
19211
  // src/travel/chunk-store.ts
18764
19212
  import { gunzipSync as gunzipSync2, gzip as gzip2 } from "node:zlib";
18765
- import { promisify as promisify4 } from "node:util";
19213
+ import { promisify as promisify5 } from "node:util";
18766
19214
  var CHUNK_BYTES2, DATABASE_CHUNK_BYTES, compress2;
18767
19215
  var init_chunk_store = __esm({
18768
19216
  "src/travel/chunk-store.ts"() {
18769
19217
  "use strict";
18770
19218
  CHUNK_BYTES2 = 4 * 1024 * 1024;
18771
19219
  DATABASE_CHUNK_BYTES = 64 * 1024;
18772
- compress2 = promisify4(gzip2);
19220
+ compress2 = promisify5(gzip2);
18773
19221
  }
18774
19222
  });
18775
19223
 
@@ -18870,7 +19318,7 @@ var init_host_turn = __esm({
18870
19318
 
18871
19319
  // src/tools/task-manager.ts
18872
19320
  import { randomBytes as randomBytes2 } from "node:crypto";
18873
- import { spawn } from "node:child_process";
19321
+ import { spawn as spawn2 } from "node:child_process";
18874
19322
  import * as fs15 from "node:fs";
18875
19323
  import * as path19 from "node:path";
18876
19324
  function generateTaskId(type = "local_bash") {
@@ -19123,7 +19571,7 @@ function spawnBackgroundTask(opts) {
19123
19571
  const outputPath = initTaskOutput(taskId);
19124
19572
  const { shell, args: shellArgs } = findShell();
19125
19573
  const outputFd = fs15.openSync(outputPath, "w");
19126
- const child = spawn(shell, [...shellArgs, opts.command], {
19574
+ const child = spawn2(shell, [...shellArgs, opts.command], {
19127
19575
  cwd: opts.cwd,
19128
19576
  env: opts.env || process.env,
19129
19577
  stdio: ["ignore", outputFd, outputFd],
@@ -19187,10 +19635,10 @@ function trackBackgroundTask(opts, child, outputPath, startTime, taskId) {
19187
19635
  });
19188
19636
  }, SIZE_WATCHDOG_INTERVAL_MS);
19189
19637
  sizeWatchdog.unref();
19190
- let finished = false;
19638
+ let finished2 = false;
19191
19639
  const finish = (code, sig) => {
19192
- if (finished) return;
19193
- finished = true;
19640
+ if (finished2) return;
19641
+ finished2 = true;
19194
19642
  opts.queryAbortSignal?.removeEventListener("abort", onAbort);
19195
19643
  clearTimeout(timer);
19196
19644
  if (sizeWatchdog) clearInterval(sizeWatchdog);
@@ -19583,7 +20031,7 @@ __export(BashTool_exports, {
19583
20031
  findShell: () => findShell,
19584
20032
  killChild: () => killChild
19585
20033
  });
19586
- import { spawn as spawn2, execSync } from "node:child_process";
20034
+ import { spawn as spawn3, execSync } from "node:child_process";
19587
20035
  import * as fs16 from "node:fs";
19588
20036
  import * as path20 from "node:path";
19589
20037
  function isWslBash(p) {
@@ -19630,7 +20078,7 @@ function findShell() {
19630
20078
  function killChild(child) {
19631
20079
  if (child.pid) {
19632
20080
  if (process.platform === "win32") {
19633
- spawn2("taskkill", ["/T", "/F", "/PID", String(child.pid)], {
20081
+ spawn3("taskkill", ["/T", "/F", "/PID", String(child.pid)], {
19634
20082
  stdio: "ignore",
19635
20083
  detached: true,
19636
20084
  windowsHide: true
@@ -19734,7 +20182,7 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
19734
20182
  }
19735
20183
  return new Promise((resolve47) => {
19736
20184
  const { shell, args: shellArgs } = findShell();
19737
- const child = spawn2(shell, [...shellArgs, command2], {
20185
+ const child = spawn3(shell, [...shellArgs, command2], {
19738
20186
  cwd,
19739
20187
  env: sanitizeEnv(process.env),
19740
20188
  stdio: ["ignore", outputHandle.fd, outputHandle.fd],
@@ -20599,8 +21047,8 @@ var init_cpu_router_mode_hook = __esm({
20599
21047
  });
20600
21048
 
20601
21049
  // src/hooks/executor.ts
20602
- import { spawn as spawn3 } from "child_process";
20603
- import { randomUUID as randomUUID12 } from "node:crypto";
21050
+ import { spawn as spawn4 } from "child_process";
21051
+ import { randomUUID as randomUUID14 } from "node:crypto";
20604
21052
  import { basename as basename8 } from "node:path";
20605
21053
  function assertHookAuthority(ctx, input) {
20606
21054
  const tool = input?.tool_name;
@@ -20695,7 +21143,7 @@ async function execCommandHook(hook, hookEvent, hookName, jsonInput, signal, hoo
20695
21143
  assertHostTurnCurrent();
20696
21144
  assertHookAuthority(ctx);
20697
21145
  beginHostTurnEffect();
20698
- const child = spawn3(command2, [], {
21146
+ const child = spawn4(command2, [], {
20699
21147
  env: envVars,
20700
21148
  cwd: ctx.cwd || ctx.workspace,
20701
21149
  shell,
@@ -20711,7 +21159,7 @@ async function execCommandHook(hook, hookEvent, hookName, jsonInput, signal, hoo
20711
21159
  if (stopping) return;
20712
21160
  stopping = true;
20713
21161
  if (isWindows && child.pid) {
20714
- const killer = spawn3("taskkill", ["/PID", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
21162
+ const killer = spawn4("taskkill", ["/PID", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
20715
21163
  killer.on("error", () => {
20716
21164
  try {
20717
21165
  child.kill("SIGKILL");
@@ -20784,7 +21232,7 @@ async function execCommandHook(hook, hookEvent, hookName, jsonInput, signal, hoo
20784
21232
  return { stdout, stderr, output, status: exitCode, aborted: timedOut || signal.aborted };
20785
21233
  }
20786
21234
  async function executeOneHook(hook, hookEvent, hookName, hookInput, toolUseID, signal, ctx) {
20787
- const hookId = randomUUID12();
21235
+ const hookId = randomUUID14();
20788
21236
  const startMs = Date.now();
20789
21237
  let callbackSignal;
20790
21238
  assertHostTurnCurrent();
@@ -20978,14 +21426,14 @@ async function executeHooks(event2, hookInput, ctx, signal, matchQuery) {
20978
21426
  if (abortSignal.aborted) {
20979
21427
  return { additionalContexts: [] };
20980
21428
  }
20981
- const toolUseID = randomUUID12();
21429
+ const toolUseID = randomUUID14();
20982
21430
  if (event2 !== "UserPromptSubmit") {
20983
21431
  return aggregateResults(await Promise.all(matchedHooks.map(({ hook }) => executeOneHook(hook, event2, hookName, hookInput, toolUseID, abortSignal, ctx))));
20984
21432
  }
20985
21433
  const batchStart = performance.now();
20986
21434
  let slowestHook;
20987
21435
  let slowestMs = -1;
20988
- let finished = 0;
21436
+ let finished2 = 0;
20989
21437
  let completed = false;
20990
21438
  const timing = (data) => {
20991
21439
  console.log(`[hook:timing] ${JSON.stringify({ event: event2, runId: toolUseID, sessionId: ctx.sessionId, ...data })}`);
@@ -21004,7 +21452,7 @@ async function executeHooks(event2, hookInput, ctx, signal, matchQuery) {
21004
21452
  return result;
21005
21453
  } finally {
21006
21454
  const durationMs = Math.round(performance.now() - start);
21007
- finished++;
21455
+ finished2++;
21008
21456
  if (durationMs > slowestMs) {
21009
21457
  slowestMs = durationMs;
21010
21458
  slowestHook = label;
@@ -21021,7 +21469,7 @@ async function executeHooks(event2, hookInput, ctx, signal, matchQuery) {
21021
21469
  slowestHook,
21022
21470
  slowestMs,
21023
21471
  matched: matchedHooks.length,
21024
- finished,
21472
+ finished: finished2,
21025
21473
  completed,
21026
21474
  aborted: abortSignal.aborted
21027
21475
  });
@@ -21610,7 +22058,7 @@ var init_context_dump = __esm({
21610
22058
  // src/core/steer-mailbox.ts
21611
22059
  import * as fs21 from "node:fs";
21612
22060
  import * as path25 from "node:path";
21613
- import { createHash as createHash34, randomUUID as randomUUID13 } from "node:crypto";
22061
+ import { createHash as createHash34, randomUUID as randomUUID15 } from "node:crypto";
21614
22062
  var MAX_FILE, MAX_PENDING, MAX_PENDING_BYTES, SteerMailbox;
21615
22063
  var init_steer_mailbox = __esm({
21616
22064
  "src/core/steer-mailbox.ts"() {
@@ -21662,7 +22110,7 @@ var init_steer_mailbox = __esm({
21662
22110
  input.channelTarget ?? "",
21663
22111
  input.sender ?? "",
21664
22112
  input.messageId
21665
- ])).digest("hex") : randomUUID13();
22113
+ ])).digest("hex") : randomUUID15();
21666
22114
  const previous = records.find((r) => r.id === id2);
21667
22115
  if (previous) return { accepted: true, duplicate: true, input: previous };
21668
22116
  const record = {
@@ -21734,7 +22182,7 @@ var init_steer_mailbox = __esm({
21734
22182
  }
21735
22183
  if (Buffer.byteLength(data) > MAX_FILE) throw new Error("Steer mailbox full");
21736
22184
  fs21.mkdirSync(path25.dirname(this.path), { recursive: true });
21737
- const temporary = `${this.path}.${randomUUID13()}.tmp`;
22185
+ const temporary = `${this.path}.${randomUUID15()}.tmp`;
21738
22186
  try {
21739
22187
  const fd = fs21.openSync(temporary, "wx", 384);
21740
22188
  try {
@@ -23046,7 +23494,9 @@ var init_tool_loading = __esm({
23046
23494
  ["gmail", ["\u90AE\u7BB1", "\u90AE\u4EF6"]],
23047
23495
  ["device_data", ["\u8BBE\u5907\u8D44\u6599", "\u65E5\u5386", "\u63D0\u9192\u4E8B\u9879", "\u901A\u8BAF\u5F55", "\u8054\u7CFB\u4EBA", "\u5907\u5FD8\u5F55", "\u7167\u7247", "\u5065\u5EB7"]],
23048
23496
  ["cc_ask", ["\u5C0FC", "\u684C\u9762CC", "Claude Code"]],
23049
- ["cc_progress", ["\u5C0FC", "\u684C\u9762CC", "Claude Code"]]
23497
+ ["cc_progress", ["\u5C0FC", "\u684C\u9762CC", "Claude Code"]],
23498
+ ["cc_new", ["\u5C0FC", "\u684C\u9762CC", "Claude Code", "\u65B0\u5EFA CC \u4F1A\u8BDD"]],
23499
+ ["cc_stop", ["\u5C0FC", "\u684C\u9762CC", "Claude Code", "\u505C\u6B62 CC \u4EFB\u52A1"]]
23050
23500
  ]);
23051
23501
  }
23052
23502
  });
@@ -23775,7 +24225,7 @@ var init_context_analyzer = __esm({
23775
24225
 
23776
24226
  // src/core/query.ts
23777
24227
  import { setTimeout as waitForRetry } from "node:timers/promises";
23778
- import { randomUUID as randomUUID14 } from "node:crypto";
24228
+ import { randomUUID as randomUUID16 } from "node:crypto";
23779
24229
  function blockedToolCallsForOverride(calls, override) {
23780
24230
  if (!override) return [];
23781
24231
  const allowed = new Set(override.map((d) => d.function?.name).filter((n) => !!n));
@@ -24008,13 +24458,13 @@ var init_query = __esm({
24008
24458
  this.modelRef = modelRef;
24009
24459
  }
24010
24460
  setProvider(provider) {
24011
- for (const owner of this.backgroundOwners) owner.cancelAll();
24461
+ for (const owner2 of this.backgroundOwners) owner2.cancelAll();
24012
24462
  this.modelGeneration++;
24013
24463
  this.provider = provider;
24014
24464
  }
24015
24465
  /** 热加载:替换 model 字符串(doReloadConfig 切换 primary 后调用) */
24016
24466
  setModel(model) {
24017
- for (const owner of this.backgroundOwners) owner.cancelAll();
24467
+ for (const owner2 of this.backgroundOwners) owner2.cancelAll();
24018
24468
  this.modelGeneration++;
24019
24469
  this.options.model = model;
24020
24470
  }
@@ -24053,7 +24503,7 @@ var init_query = __esm({
24053
24503
  if (!this.steerQueryId) {
24054
24504
  this.stopRequested = false;
24055
24505
  this.cancellationReason = null;
24056
- this.steerQueryId = randomUUID14();
24506
+ this.steerQueryId = randomUUID16();
24057
24507
  this.steerRoute = { channel: context?.channel ?? "console", channelTarget: context?.channelTarget };
24058
24508
  }
24059
24509
  const mailbox = this.steerMailbox;
@@ -24091,7 +24541,7 @@ var init_query = __esm({
24091
24541
  this.compactConfig.systemOverheadTokens = overhead ?? this.compactConfig.systemOverheadTokens;
24092
24542
  }
24093
24543
  const activeSystemStable = perTurnSystemStable || this.resolveOpt(this.options.systemStable) || this.resolveOpt(this.options.systemPrompt);
24094
- for (const m of messages) if ("role" in m && hasMedia(m) && !m.imageInput) m.imageInput = { id: randomUUID14(), observed: hasImage(m) };
24544
+ for (const m of messages) if ("role" in m && hasMedia(m) && !m.imageInput) m.imageInput = { id: randomUUID16(), observed: hasImage(m) };
24095
24545
  let currentMessages = [...messages];
24096
24546
  const stopUserMessages = [];
24097
24547
  const stopToolResults = [];
@@ -24629,13 +25079,13 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
24629
25079
  yield { type: "error", error: `\u4E0A\u4E0B\u6587\u8D85\u51FA\u6A21\u578B\u7A97\u53E3\uFF08\u8F93\u5165 ${overflow.inputTokens} / \u7A97\u53E3 ${overflow.contextLimit}\uFF09\uFF0C\u9700\u8981\u538B\u7F29\u540E\u624D\u80FD\u7EE7\u7EED\u3002` };
24630
25080
  return;
24631
25081
  }
24632
- const delay3 = Math.min(1e3 * Math.pow(2, streamRetries), 16e3);
25082
+ const delay4 = Math.min(1e3 * Math.pow(2, streamRetries), 16e3);
24633
25083
  if (streamRetries < MAX_STREAM_RETRIES && !ac.signal.aborted) {
24634
- console.log(`${this.logPrefix} Turn ${turnCount}: stream retry ${streamRetries + 1}/${MAX_STREAM_RETRIES}, delay=${delay3}ms`);
25084
+ console.log(`${this.logPrefix} Turn ${turnCount}: stream retry ${streamRetries + 1}/${MAX_STREAM_RETRIES}, delay=${delay4}ms`);
24635
25085
  yield { type: "status", text: `\u26A0\uFE0F API error, retrying (${streamRetries + 1}/${MAX_STREAM_RETRIES})...` };
24636
25086
  this.phase = "tools";
24637
25087
  try {
24638
- await waitForRetry(delay3, void 0, { signal: ac.signal });
25088
+ await waitForRetry(delay4, void 0, { signal: ac.signal });
24639
25089
  } catch (error) {
24640
25090
  if (!ac.signal.aborted) throw error;
24641
25091
  }
@@ -24750,7 +25200,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
24750
25200
  if (toolCalls.length === 0) {
24751
25201
  const carryReply = () => {
24752
25202
  if (!this.pendingSteers.some((input) => input.attachment)) return null;
24753
- const replyId = randomUUID14();
25203
+ const replyId = randomUUID16();
24754
25204
  const reply = msg.assistant(textContent);
24755
25205
  if (turnThinking) reply.reasoning_content = turnThinking;
24756
25206
  if (turnThinkingSig) reply.thinking_signature = turnThinkingSig;
@@ -25093,7 +25543,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
25093
25543
  this.activeRequestModel = null;
25094
25544
  this.steerMailbox = new SteerMailbox(stateDir, sessionId);
25095
25545
  this.steerRoute = route;
25096
- this.steerQueryId = randomUUID14();
25546
+ this.steerQueryId = randomUUID16();
25097
25547
  return this.steerQueryId;
25098
25548
  }
25099
25549
  clearSteerDelivery(cancel = false) {
@@ -25140,7 +25590,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
25140
25590
  ...metadata4,
25141
25591
  text: text2,
25142
25592
  queryId: this.steerQueryId,
25143
- id: randomUUID14(),
25593
+ id: randomUUID16(),
25144
25594
  receivedAt: (/* @__PURE__ */ new Date()).toISOString(),
25145
25595
  status: "received"
25146
25596
  } };
@@ -25457,7 +25907,7 @@ var init_builtInAgents = __esm({
25457
25907
  });
25458
25908
 
25459
25909
  // src/tools/AgentTool/forkSubagent.ts
25460
- import { randomUUID as randomUUID15 } from "crypto";
25910
+ import { randomUUID as randomUUID17 } from "crypto";
25461
25911
  function isForkSubagentEnabled() {
25462
25912
  return true;
25463
25913
  }
@@ -25496,7 +25946,7 @@ function buildForkedMessages(directive, parentMessages) {
25496
25946
  type: "tool_result",
25497
25947
  tool_use_id: block.id,
25498
25948
  content: FORK_PLACEHOLDER_RESULT,
25499
- id: `toolr_${randomUUID15().replace(/-/g, "").slice(0, 24)}`
25949
+ id: `toolr_${randomUUID17().replace(/-/g, "").slice(0, 24)}`
25500
25950
  }));
25501
25951
  const toolResultMessage = msg_user(
25502
25952
  buildChildMessage(directive),
@@ -27517,9 +27967,9 @@ async function handleBroadcast(content, summary2, ctx) {
27517
27967
  async function handleShutdownRequest(targetName, reason, ctx) {
27518
27968
  const teamName = getTeamName(ctx);
27519
27969
  const senderName = getAgentName(ctx);
27520
- const requestId = generateRequestId("shutdown", targetName);
27970
+ const requestId2 = generateRequestId("shutdown", targetName);
27521
27971
  const shutdownMessage = createShutdownRequestMessage({
27522
- requestId,
27972
+ requestId: requestId2,
27523
27973
  from: senderName,
27524
27974
  reason
27525
27975
  });
@@ -27535,17 +27985,17 @@ async function handleShutdownRequest(targetName, reason, ctx) {
27535
27985
  return {
27536
27986
  content: JSON.stringify({
27537
27987
  success: true,
27538
- message: `Shutdown request sent to ${targetName}. Request ID: ${requestId}`,
27539
- request_id: requestId,
27988
+ message: `Shutdown request sent to ${targetName}. Request ID: ${requestId2}`,
27989
+ request_id: requestId2,
27540
27990
  target: targetName
27541
27991
  })
27542
27992
  };
27543
27993
  }
27544
- async function handleShutdownApproval(requestId, ctx) {
27994
+ async function handleShutdownApproval(requestId2, ctx) {
27545
27995
  const teamName = getTeamName(ctx);
27546
27996
  const agentName = getAgentName(ctx);
27547
27997
  const approvedMessage = createShutdownApprovedMessage({
27548
- requestId,
27998
+ requestId: requestId2,
27549
27999
  from: agentName
27550
28000
  });
27551
28001
  await writeToMailbox(
@@ -27564,15 +28014,15 @@ async function handleShutdownApproval(requestId, ctx) {
27564
28014
  content: JSON.stringify({
27565
28015
  success: true,
27566
28016
  message: `Shutdown approved. Agent ${agentName} is now exiting.`,
27567
- request_id: requestId
28017
+ request_id: requestId2
27568
28018
  })
27569
28019
  };
27570
28020
  }
27571
- async function handleShutdownRejection(requestId, reason, ctx) {
28021
+ async function handleShutdownRejection(requestId2, reason, ctx) {
27572
28022
  const teamName = getTeamName(ctx);
27573
28023
  const agentName = getAgentName(ctx);
27574
28024
  const rejectedMessage = createShutdownRejectedMessage({
27575
- requestId,
28025
+ requestId: requestId2,
27576
28026
  from: agentName,
27577
28027
  reason
27578
28028
  });
@@ -27589,7 +28039,7 @@ async function handleShutdownRejection(requestId, reason, ctx) {
27589
28039
  content: JSON.stringify({
27590
28040
  success: true,
27591
28041
  message: `Shutdown rejected. Reason: "${reason}". Continuing to work.`,
27592
- request_id: requestId
28042
+ request_id: requestId2
27593
28043
  })
27594
28044
  };
27595
28045
  }
@@ -28451,7 +28901,7 @@ var init_sources = __esm({
28451
28901
  // src/installer/skill-install.ts
28452
28902
  import * as fs28 from "node:fs";
28453
28903
  import * as path32 from "node:path";
28454
- import { exec as exec2 } from "node:child_process";
28904
+ import { exec as exec3 } from "node:child_process";
28455
28905
  function rescanSkills() {
28456
28906
  const state2 = getSkillToolState();
28457
28907
  if (!state2.skillsDirPath) {
@@ -28553,7 +29003,7 @@ function npmInstallDeps(skillDir) {
28553
29003
  }
28554
29004
  if (!hasDeps) return Promise.resolve(true);
28555
29005
  return new Promise((resolve47) => {
28556
- exec2("npm install --omit=dev --no-audit --no-fund --ignore-scripts", {
29006
+ exec3("npm install --omit=dev --no-audit --no-fund --ignore-scripts", {
28557
29007
  cwd: skillDir,
28558
29008
  timeout: 18e4,
28559
29009
  windowsHide: true,
@@ -29853,6 +30303,18 @@ var init_registry2 = __esm({
29853
30303
  effect: "hot",
29854
30304
  internal: true
29855
30305
  },
30306
+ // 1130 Gmail 冷启动:连接即触发 + 每日巡查,新装机默认开。model 为空走 topics.clean.model → extract → mem7 链(免费档自动退回主力模型)
30307
+ { path: "gmailColdstart.enabled", type: "boolean", group: "feature", label: "Gmail \u51B7\u542F\u52A8\uFF08\u8FDE\u63A5\u540E\u81EA\u52A8\u8BFB\u5386\u53F2\u8BA4\u4EBA\uFF09", effect: "hot", internal: true },
30308
+ { path: "gmailColdstart.model", type: "string", group: "model", label: "Gmail \u51B7\u542F\u52A8\u63D0\u70BC\u6A21\u578B\uFF08\u7A7A=\u6CBF\u7528\u8BB0\u5FC6\u63D0\u53D6\u6A21\u578B\uFF0C\u514D\u8D39\u6863\u81EA\u52A8\u9000\u56DE\u4E3B\u529B\uFF09", effect: "hot", internal: true },
30309
+ {
30310
+ path: "gmailColdstart.patrolHour",
30311
+ type: "number",
30312
+ group: "feature",
30313
+ label: "Gmail \u6BCF\u65E5\u5DE1\u67E5\u6574\u70B9\uFF080-23\uFF09",
30314
+ effect: "hot",
30315
+ internal: true,
30316
+ validate: (value2) => Number.isInteger(value2) && Number(value2) >= 0 && Number(value2) <= 23 ? null : "\u5DE1\u67E5\u6574\u70B9\u987B\u4E3A 0-23"
30317
+ },
29856
30318
  {
29857
30319
  path: "mem7.turnReadBudgetMs",
29858
30320
  type: "number",
@@ -31326,12 +31788,12 @@ var init_wx_query = __esm({
31326
31788
  handler: async (args, _context) => {
31327
31789
  const { findShell: findShell2 } = await Promise.resolve().then(() => (init_BashTool(), BashTool_exports));
31328
31790
  const shell = findShell2();
31329
- const { spawn: spawn8 } = await import("node:child_process");
31791
+ const { spawn: spawn9 } = await import("node:child_process");
31330
31792
  const cmd = args.command.trim();
31331
31793
  const timeout = args.timeout || 12e4;
31332
31794
  const fullCmd = `${PYTHON} "${SCRIPT}" ${cmd.replace(/^python3\s+.*wx_query\.py\s*/, "")}`;
31333
31795
  return new Promise((resolve47) => {
31334
- const child = spawn8(shell.shell, [...shell.args, fullCmd], {
31796
+ const child = spawn9(shell.shell, [...shell.args, fullCmd], {
31335
31797
  timeout,
31336
31798
  env: { ...process.env },
31337
31799
  windowsHide: true
@@ -31372,14 +31834,14 @@ var init_wx_query = __esm({
31372
31834
  init_publication_objects();
31373
31835
  init_key_service_store();
31374
31836
  import { DatabaseSync as DatabaseSync42 } from "node:sqlite";
31375
- import { existsSync as existsSync42, readFileSync as readFileSync36, writeFileSync as writeFileSync42, renameSync as renameSync12, realpathSync as realpathSync30, openSync as openSync21, closeSync as closeSync20 } from "node:fs";
31837
+ import { existsSync as existsSync42, readFileSync as readFileSync36, writeFileSync as writeFileSync42, renameSync as renameSync12, realpathSync as realpathSync31, openSync as openSync21, closeSync as closeSync20 } from "node:fs";
31376
31838
  import { join as join73, resolve as resolve46 } from "node:path";
31377
31839
  import { fileURLToPath as fileURLToPath9, pathToFileURL as pathToFileURL2 } from "node:url";
31378
- import { spawn as spawn7 } from "node:child_process";
31840
+ import { spawn as spawn8 } from "node:child_process";
31379
31841
  import { request as request8 } from "node:https";
31380
31842
 
31381
31843
  // src/continuity/pairing-setup.ts
31382
- import { existsSync as existsSync26, mkdirSync as mkdirSync24, readFileSync as readFileSync26, writeFileSync as writeFileSync23, readdirSync as readdirSync11, cpSync, realpathSync as realpathSync13, symlinkSync, lstatSync as lstatSync18 } from "node:fs";
31844
+ import { existsSync as existsSync26, mkdirSync as mkdirSync24, readFileSync as readFileSync26, writeFileSync as writeFileSync23, readdirSync as readdirSync11, cpSync, realpathSync as realpathSync14, symlinkSync, lstatSync as lstatSync18 } from "node:fs";
31383
31845
  import { join as join46 } from "node:path";
31384
31846
  import { homedir as homedir3 } from "node:os";
31385
31847
  import { randomBytes as randomBytes4, createHash as createHash36, X509Certificate } from "node:crypto";
@@ -33019,8 +33481,8 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
33019
33481
  }
33020
33482
  }
33021
33483
  if (!same2(this.db.prepare("SELECT sql FROM sqlite_master WHERE type='table' ORDER BY name").all().map((r) => String(r.sql)).sort(), [...schema2].sort()) || this.db.prepare("PRAGMA quick_check").get()?.quick_check !== "ok" || sender.prepare("SELECT sql FROM sqlite_master WHERE type='table'").get()?.sql !== senderSchema || sender.prepare("PRAGMA quick_check").get()?.quick_check !== "ok") throw new Error("RUNTIME_PUBLICATION_RECOVERY_REQUIRED");
33022
- const binding = this.db.prepare("SELECT profile,layout FROM control WHERE id=1").get(), owner = sender.prepare("SELECT profile,layout FROM sender WHERE id=1").get();
33023
- if (!binding || !owner || !same2(binding, owner) || binding.profile !== JSON.stringify(this.profile) || binding.layout !== this.layoutDigest)
33484
+ const binding = this.db.prepare("SELECT profile,layout FROM control WHERE id=1").get(), owner2 = sender.prepare("SELECT profile,layout FROM sender WHERE id=1").get();
33485
+ if (!binding || !owner2 || !same2(binding, owner2) || binding.profile !== JSON.stringify(this.profile) || binding.layout !== this.layoutDigest)
33024
33486
  throw new Error("RUNTIME_PUBLICATION_PROFILE_MISMATCH");
33025
33487
  this.identities = [incarnation(this.file), incarnation(this.senderFile)];
33026
33488
  const c = this.control(), rows = this.db.prepare("SELECT sequence,digest,parent_digest,state,bytes,object_count,object_cursor FROM publications ORDER BY sequence").all();
@@ -34227,7 +34689,7 @@ var builtInFeatures = [
34227
34689
  id: "cc-driver",
34228
34690
  name: "CC \u7EC8\u7AEF",
34229
34691
  description: "\u9A71\u52A8\u672C\u673A claude CLI\uFF08cc_ask \u4F7F\u5524 / xiaoC_progress\u2192cc_progress \u65C1\u89C2\uFF09\u2014\u2014\u4E0E\u684C\u9762 CC \u540C\u547D\u540D\u7A7A\u95F4",
34230
- requiredTools: ["cc_progress", "cc_ask"],
34692
+ requiredTools: ["cc_progress", "cc_ask", "cc_stop", "cc_new"],
34231
34693
  setup: async () => {
34232
34694
  await Promise.resolve().then(() => (init_cc_progress(), cc_progress_exports));
34233
34695
  await Promise.resolve().then(() => (init_cc_ask(), cc_ask_exports));
@@ -34432,9 +34894,9 @@ var archivePairing = (directory2) => {
34432
34894
  write(join46(directory2, "pairing-environment.json"), { dependenciesSha256: manifest.dependenciesSha256 });
34433
34895
  };
34434
34896
  async function preparePairingMaterial(input) {
34435
- const hostStorage = input.hostStorage ? realpathSync13(input.hostStorage) : join46(homedir3(), ".engine7-travel-test/hosts");
34436
- const engineDir = realpathSync13(input.engineDir), stateDir = realpathSync13(input.stateDir), configPath = realpathSync13(input.configPath);
34437
- const environmentDir = input.environmentDir ? realpathSync13(input.environmentDir) : engineDir;
34897
+ const hostStorage = input.hostStorage ? realpathSync14(input.hostStorage) : join46(homedir3(), ".engine7-travel-test/hosts");
34898
+ const engineDir = realpathSync14(input.engineDir), stateDir = realpathSync14(input.stateDir), configPath = realpathSync14(input.configPath);
34899
+ const environmentDir = input.environmentDir ? realpathSync14(input.environmentDir) : engineDir;
34438
34900
  const pkg = JSON.parse(readFileSync26(join46(environmentDir, "package.json"), "utf8"));
34439
34901
  if (input.environmentDir) {
34440
34902
  const lock = JSON.parse(readFileSync26(join46(environmentDir, "package-lock.json"), "utf8"));
@@ -34444,7 +34906,7 @@ async function preparePairingMaterial(input) {
34444
34906
  const config = JSON.parse(readFileSync26(configPath, "utf8"));
34445
34907
  loadSecretsEnvForConfig(configPath);
34446
34908
  const parsed = loadConfig(configPath);
34447
- if (realpathSync13(parsed.stateDir) !== stateDir) throw new Error("TRAVEL_PAIRING_IDENTITY");
34909
+ if (realpathSync14(parsed.stateDir) !== stateDir) throw new Error("TRAVEL_PAIRING_IDENTITY");
34448
34910
  const companion = JSON.parse(readPrivateFile(join46(stateDir, ".continuity/travel-companion-id.json"), 16384).toString()).companionId;
34449
34911
  const directory2 = join46(homedir3(), ".engine7-travel-test", "tasks", input.taskId);
34450
34912
  mkdirSync24(join46(homedir3(), ".engine7-travel-test", "tasks"), { recursive: true, mode: 448 });
@@ -34477,7 +34939,7 @@ async function preparePairingMaterial(input) {
34477
34939
  const effective = resolveSecrets(config);
34478
34940
  const channels = Object.fromEntries(Object.entries(effective.channels ?? {}).filter(([name]) => name !== "emotion"));
34479
34941
  for (const [name, block] of Object.entries(channels)) if (block.enabled && !["discord", "feishu", "wechat"].includes(name)) throw new Error("TRAVEL_CHANNEL_NOT_CONTROLLED");
34480
- const layout = await describeInitialRuntimeLayout(stateDir, realpathSync13(parsed.workspace), "core");
34942
+ const layout = await describeInitialRuntimeLayout(stateDir, realpathSync14(parsed.workspace), "core");
34481
34943
  preparePrivateDirectory(directory2);
34482
34944
  const identity3 = { tenantId: "self-hosted-" + sha6(homedir3()).slice(0, 20), companionId: companion, seatId: input.taskId };
34483
34945
  const tlsDirectory = join46(directory2, "tls");
@@ -34536,7 +34998,7 @@ async function preparePairingMaterial(input) {
34536
34998
  identity: identity3,
34537
34999
  hostStorage,
34538
35000
  stateDir,
34539
- workspace: realpathSync13(parsed.workspace),
35001
+ workspace: realpathSync14(parsed.workspace),
34540
35002
  configPath,
34541
35003
  consolePort: parsed.api?.port ?? 16992,
34542
35004
  engineDir,
@@ -34632,7 +35094,7 @@ function finalizePairingMaterial(material, binding) {
34632
35094
  }
34633
35095
 
34634
35096
  // src/continuity/initial-baseline-worker.ts
34635
- import { spawn as spawn4 } from "node:child_process";
35097
+ import { spawn as spawn5 } from "node:child_process";
34636
35098
  import { existsSync as existsSync27, writeFileSync as writeFileSync24, unlinkSync as unlinkSync7 } from "node:fs";
34637
35099
  import { join as join47 } from "node:path";
34638
35100
  import { fileURLToPath as fileURLToPath5 } from "node:url";
@@ -34643,7 +35105,7 @@ async function runInitialBaselineWorker(options, onProgress, assertCurrent) {
34643
35105
  writeFileSync24(config, JSON.stringify(options), { mode: 384, flag: "wx", flush: true });
34644
35106
  try {
34645
35107
  await new Promise((done, reject) => {
34646
- const child = spawn4(process.execPath, [...entry.endsWith(".ts") ? ["--import", "tsx"] : [], entry, "--config", config], { stdio: ["ignore", "pipe", "pipe", "ipc"] });
35108
+ const child = spawn5(process.execPath, [...entry.endsWith(".ts") ? ["--import", "tsx"] : [], entry, "--config", config], { stdio: ["ignore", "pipe", "pipe", "ipc"] });
34647
35109
  let failure2, stderr = "";
34648
35110
  child.stderr.on("data", (b) => {
34649
35111
  stderr = (stderr + b).slice(-8192);
@@ -34699,11 +35161,11 @@ function publicPairingError(error) {
34699
35161
  }
34700
35162
 
34701
35163
  // src/continuity/node-main.ts
34702
- import { readFileSync as readFileSync32, lstatSync as lstatSync29, realpathSync as realpathSync27 } from "node:fs";
35164
+ import { readFileSync as readFileSync32, lstatSync as lstatSync29, realpathSync as realpathSync28 } from "node:fs";
34703
35165
  import { DatabaseSync as DatabaseSync37 } from "node:sqlite";
34704
35166
  import { isAbsolute as isAbsolute13, resolve as resolve41 } from "node:path";
34705
35167
  import { fileURLToPath as fileURLToPath7 } from "node:url";
34706
- import { randomUUID as randomUUID22, createHash as createHash50 } from "node:crypto";
35168
+ import { randomUUID as randomUUID24, createHash as createHash50 } from "node:crypto";
34707
35169
 
34708
35170
  // src/continuity/node-agent.ts
34709
35171
  import { DatabaseSync as DatabaseSync36 } from "node:sqlite";
@@ -34734,19 +35196,19 @@ function runtimeEngineConfig(original, stateDir, workspace) {
34734
35196
  }
34735
35197
 
34736
35198
  // src/continuity/node-agent.ts
34737
- import { existsSync as existsSync38, lstatSync as lstatSync28, mkdirSync as mkdirSync31, readFileSync as readFileSync31, realpathSync as realpathSync26, writeFileSync as writeFileSync40 } from "node:fs";
35199
+ import { existsSync as existsSync38, lstatSync as lstatSync28, mkdirSync as mkdirSync31, readFileSync as readFileSync31, realpathSync as realpathSync27, writeFileSync as writeFileSync40 } from "node:fs";
34738
35200
  import { isAbsolute as isAbsolute12, join as join70, resolve as resolve40 } from "node:path";
34739
- import { createHash as createHash48, randomUUID as randomUUID21 } from "node:crypto";
35201
+ import { createHash as createHash48, randomUUID as randomUUID23 } from "node:crypto";
34740
35202
  import { isIP as isIP2 } from "node:net";
34741
35203
 
34742
35204
  // src/continuity/activation.ts
34743
35205
  import { DatabaseSync as DatabaseSync23 } from "node:sqlite";
34744
- import { constants as constants12, existsSync as existsSync32, mkdirSync as mkdirSync25, realpathSync as realpathSync17, unlinkSync as unlinkSync12, writeFileSync as writeFileSync29 } from "node:fs";
35206
+ import { constants as constants12, existsSync as existsSync32, mkdirSync as mkdirSync25, realpathSync as realpathSync18, unlinkSync as unlinkSync12, writeFileSync as writeFileSync29 } from "node:fs";
34745
35207
  import { lstat as lstat4, mkdir as mkdir4, readdir as readdir2 } from "node:fs/promises";
34746
35208
 
34747
35209
  // src/continuity/activation-database-worker.ts
34748
- import { spawn as spawn5 } from "node:child_process";
34749
- import { existsSync as existsSync28, writeFileSync as writeFileSync25, unlinkSync as unlinkSync8, statSync as statSync12 } from "node:fs";
35210
+ import { spawn as spawn6 } from "node:child_process";
35211
+ import { existsSync as existsSync28, writeFileSync as writeFileSync25, unlinkSync as unlinkSync8, statSync as statSync13 } from "node:fs";
34750
35212
  import { join as join49 } from "node:path";
34751
35213
  import { fileURLToPath as fileURLToPath6 } from "node:url";
34752
35214
 
@@ -34802,7 +35264,7 @@ function initializeActivationDatabase(file2, raw) {
34802
35264
  // src/continuity/activation-database-worker.ts
34803
35265
  async function runActivationDatabaseWorker(root, file2, binding, assertCurrent) {
34804
35266
  assertCurrent();
34805
- if (statSync12(file2).size < 16 * 1024 * 1024) {
35267
+ if (statSync13(file2).size < 16 * 1024 * 1024) {
34806
35268
  initializeActivationDatabase(file2, binding);
34807
35269
  assertCurrent();
34808
35270
  return;
@@ -34812,7 +35274,7 @@ async function runActivationDatabaseWorker(root, file2, binding, assertCurrent)
34812
35274
  writeFileSync25(config, JSON.stringify({ root, file: file2, binding }), { mode: 384, flag: "wx", flush: true });
34813
35275
  try {
34814
35276
  await new Promise((done, reject) => {
34815
- const child = spawn5(process.execPath, [...entry.endsWith(".ts") ? ["--import", "tsx"] : [], entry, "--config", config], { stdio: ["ignore", "pipe", "pipe"] });
35277
+ const child = spawn6(process.execPath, [...entry.endsWith(".ts") ? ["--import", "tsx"] : [], entry, "--config", config], { stdio: ["ignore", "pipe", "pipe"] });
34816
35278
  let failure2, stderr = "";
34817
35279
  child.stderr.on("data", (b) => {
34818
35280
  stderr = (stderr + b).slice(-8192);
@@ -34851,7 +35313,7 @@ init_key_service_store();
34851
35313
 
34852
35314
  // src/continuity/generation-integrity.ts
34853
35315
  import { createHash as createHash37 } from "node:crypto";
34854
- import { constants as constants11, closeSync as closeSync17, fstatSync as fstatSync7, lstatSync as lstatSync19, openSync as openSync18, readSync as readSync6, readdirSync as readdirSync12, realpathSync as realpathSync14 } from "node:fs";
35316
+ import { constants as constants11, closeSync as closeSync17, fstatSync as fstatSync7, lstatSync as lstatSync19, openSync as openSync18, readSync as readSync6, readdirSync as readdirSync12, realpathSync as realpathSync15 } from "node:fs";
34855
35317
  import { join as join50, resolve as resolve28 } from "node:path";
34856
35318
  import { open as open5 } from "node:fs/promises";
34857
35319
  var recentSeals = /* @__PURE__ */ new Map();
@@ -34863,7 +35325,7 @@ function rememberSeal(root, integrity, files) {
34863
35325
  var metadata2 = (stat3) => [stat3.dev, stat3.ino, stat3.size, stat3.mode, stat3.mtimeNs, stat3.ctimeNs].join(":");
34864
35326
  function generationFiles(root) {
34865
35327
  const files = [];
34866
- if (realpathSync14(root) !== root) throw new Error("TRAVEL_GENERATION_INTEGRITY");
35328
+ if (realpathSync15(root) !== root) throw new Error("TRAVEL_GENERATION_INTEGRITY");
34867
35329
  const visit = (path37) => {
34868
35330
  if (path37 === ".runtime-publication-receipt.json") return;
34869
35331
  const file2 = join50(root, path37), stat3 = lstatSync19(file2, { bigint: true });
@@ -34944,14 +35406,14 @@ async function verifyRuntimeGenerationIntegrityAsync(directory2, expected) {
34944
35406
  // src/continuity/recovery-deletion-visibility.ts
34945
35407
  init_key_service_store();
34946
35408
  import { DatabaseSync as DatabaseSync22 } from "node:sqlite";
34947
- import { createHash as createHash40, randomUUID as randomUUID17 } from "node:crypto";
34948
- import { existsSync as existsSync31, realpathSync as realpathSync16, renameSync as renameSync11, unlinkSync as unlinkSync11, writeFileSync as writeFileSync28 } from "node:fs";
35409
+ import { createHash as createHash40, randomUUID as randomUUID19 } from "node:crypto";
35410
+ import { existsSync as existsSync31, realpathSync as realpathSync17, renameSync as renameSync11, unlinkSync as unlinkSync11, writeFileSync as writeFileSync28 } from "node:fs";
34949
35411
  import { join as join53, resolve as resolve30 } from "node:path";
34950
35412
 
34951
35413
  // src/continuity/recovery-deletion-overlay.ts
34952
35414
  import { DatabaseSync as DatabaseSync21 } from "node:sqlite";
34953
- import { createHash as createHash39, randomUUID as randomUUID16 } from "node:crypto";
34954
- import { existsSync as existsSync30, realpathSync as realpathSync15, renameSync as renameSync10, unlinkSync as unlinkSync10, writeFileSync as writeFileSync27 } from "node:fs";
35415
+ import { createHash as createHash39, randomUUID as randomUUID18 } from "node:crypto";
35416
+ import { existsSync as existsSync30, realpathSync as realpathSync16, renameSync as renameSync10, unlinkSync as unlinkSync10, writeFileSync as writeFileSync27 } from "node:fs";
34955
35417
  import { dirname as dirname21, join as join52, resolve as resolve29 } from "node:path";
34956
35418
  init_key_service_store();
34957
35419
  init_recovery_deletion_sources();
@@ -35057,7 +35519,7 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
35057
35519
  if (++scanned > 1e6 || bytes > 64 * 1024 * 1024) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
35058
35520
  if (jsonBlocked(parse(payload))) blockedCells.add(String(row.id));
35059
35521
  }
35060
- const jobs = [];
35522
+ const jobs2 = [];
35061
35523
  for (const row of memory.prepare("SELECT * FROM ome_jobs").iterate()) {
35062
35524
  if (++scanned > 1e6) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
35063
35525
  let input = String(row.payload);
@@ -35074,12 +35536,12 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
35074
35536
  if (bytes > 64 * 1024 * 1024) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
35075
35537
  const payload = parse(input), result = row.result_json === null ? void 0 : parse(String(row.result_json));
35076
35538
  const scope = scopeKey(payload?.scope ?? payload?.basis?.scope) ?? (typeof payload?.scopeId === "string" ? payload.scopeId : void 0) ?? (typeof row.scope_id === "string" && !row.scope_id.startsWith("resource:") ? row.scope_id : void 0);
35077
- if (jsonBlocked(payload, scope) || jsonBlocked(result, scope)) jobs.push({ row, input });
35539
+ if (jsonBlocked(payload, scope) || jsonBlocked(result, scope)) jobs2.push({ row, input });
35078
35540
  }
35079
35541
  const removedSources = sources.filter((row) => blocked2(String(row.scope_id), String(row.source_id)));
35080
35542
  if (removedSources.some((row) => row.interpretation_status !== "deleted")) throw new Error("RECOVERY_OVERLAY_SOURCE_PROVENANCE");
35081
35543
  options.transaction(() => {
35082
- for (const { row, input } of jobs) {
35544
+ for (const { row, input } of jobs2) {
35083
35545
  memory.prepare(`UPDATE ome_jobs SET payload='{}',payload_archive=NULL,result_json=NULL,
35084
35546
  retained_input_hash=COALESCE(retained_input_hash,?),retained_input_version=COALESCE(retained_input_version,input_version),
35085
35547
  payload_pruned_at=COALESCE(payload_pruned_at,?),result_pruned_at=COALESCE(result_pruned_at,?),
@@ -35292,7 +35754,7 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
35292
35754
  return {
35293
35755
  format: "engine7-recovery-runtime-copy-cleanup-v6",
35294
35756
  sources: removedSources.length,
35295
- jobs: jobs.length,
35757
+ jobs: jobs2.length,
35296
35758
  sessionEvents,
35297
35759
  intakeRecords,
35298
35760
  debugCaches,
@@ -35310,7 +35772,7 @@ var evidenceRow = (row) => Object.fromEntries(Object.entries(row).map(([key3, va
35310
35772
  var applyRecoveryDeletionRuntimeCopies = (options) => deletionOverlay(options, true);
35311
35773
  async function deletionOverlay(options, runtimeCopies) {
35312
35774
  const manifest = normalizePublication(options.manifest), root = resolve29(options.snapshot), digest7 = publicationDigest(manifest);
35313
- if (root !== options.snapshot || realpathSync15(root) !== root || existsSync30(join52(root, ".travel-active.json"))) throw new Error("RECOVERY_OVERLAY_ISOLATION_REQUIRED");
35775
+ if (root !== options.snapshot || realpathSync16(root) !== root || existsSync30(join52(root, ".travel-active.json"))) throw new Error("RECOVERY_OVERLAY_ISOLATION_REQUIRED");
35314
35776
  const guard = JSON.parse(readPrivateFile(join52(root, ".travel-restored.json"), 1024 * 1024).toString());
35315
35777
  if (guard.activationAllowed !== false) throw new Error("RECOVERY_OVERLAY_ISOLATION_REQUIRED");
35316
35778
  if (!same4(manifest.profile.identity, { tenantId: options.principal.tenantId, companionId: options.principal.companionId, seatId: options.principal.seatId })) throw new Error("RECOVERY_IDENTITY_MISMATCH");
@@ -35516,7 +35978,7 @@ async function deletionOverlay(options, runtimeCopies) {
35516
35978
  remaining: ["runtime copy visibility and queue cleanup", "normal activation"]
35517
35979
  };
35518
35980
  const next = { ...original, originalIntegrity: original.originalIntegrity ?? original.integrity, deletionOverlay: proof, integrity: runtimeGenerationIntegrity(root) };
35519
- const temporary = join52(root, ".runtime-publication-receipt-" + randomUUID16());
35981
+ const temporary = join52(root, ".runtime-publication-receipt-" + randomUUID18());
35520
35982
  try {
35521
35983
  writeFileSync27(temporary, JSON.stringify(next), { mode: 384, flag: "wx", flush: true });
35522
35984
  await check();
@@ -35536,10 +35998,10 @@ async function deletionOverlay(options, runtimeCopies) {
35536
35998
  init_schema_migrations();
35537
35999
  var same5 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
35538
36000
  var sha9 = (value2) => createHash40("sha256").update(value2).digest("hex");
35539
- var format = "engine7-current-h-deletion-visibility-v1";
36001
+ var format2 = "engine7-current-h-deletion-visibility-v1";
35540
36002
  function receipt(options) {
35541
36003
  const root = resolve30(options.snapshot);
35542
- if (root !== options.snapshot || realpathSync16(root) !== root || existsSync31(join53(root, ".travel-active.json")) || JSON.parse(readPrivateFile(join53(root, ".travel-restored.json"), 1024 * 1024).toString()).activationAllowed !== false)
36004
+ if (root !== options.snapshot || realpathSync17(root) !== root || existsSync31(join53(root, ".travel-active.json")) || JSON.parse(readPrivateFile(join53(root, ".travel-restored.json"), 1024 * 1024).toString()).activationAllowed !== false)
35543
36005
  throw new Error("RECOVERY_OVERLAY_ISOLATION_REQUIRED");
35544
36006
  return JSON.parse(readPrivateFile(join53(root, ".runtime-publication-receipt.json"), 4 * 1024 * 1024).toString());
35545
36007
  }
@@ -35591,7 +36053,7 @@ async function completeCurrentHDeletionVisibility(options) {
35591
36053
  validateAuxiliaryState(options);
35592
36054
  verifyRuntimeGenerationIntegrity(options.snapshot, next.integrity);
35593
36055
  const proof = {
35594
- format,
36056
+ format: format2,
35595
36057
  originalDigest: publicationDigest(options.manifest),
35596
36058
  deletionWatermark: floor,
35597
36059
  logDigest: overlay.logDigest,
@@ -35600,7 +36062,7 @@ async function completeCurrentHDeletionVisibility(options) {
35600
36062
  originalIntegrityDigest: sha9(JSON.stringify(next.originalIntegrity)),
35601
36063
  activationAllowed: false
35602
36064
  };
35603
- const file2 = join53(options.snapshot, ".runtime-publication-receipt.json"), temporary = join53(options.snapshot, ".runtime-publication-receipt-" + randomUUID17());
36065
+ const file2 = join53(options.snapshot, ".runtime-publication-receipt.json"), temporary = join53(options.snapshot, ".runtime-publication-receipt-" + randomUUID19());
35604
36066
  try {
35605
36067
  writeFileSync28(temporary, JSON.stringify({ ...next, deletionVisibility: proof }), { mode: 384, flag: "wx", flush: true });
35606
36068
  await check();
@@ -35617,7 +36079,7 @@ async function verifyCurrentHDeletionVisibilityAsync(options) {
35617
36079
  const check = await currentHDeletionCheckAsync(options.manifest, options), floor = await check(), original = receipt(options), proof = original.deletionVisibility;
35618
36080
  const overlay = original.deletionOverlay, digest7 = publicationDigest(options.manifest);
35619
36081
  const logDigest = sha9(JSON.stringify(await options.authority.deletionsSince(options.principal, 0)));
35620
- if (original.format !== "engine7-runtime-publication-restore-v1" || original.activationAllowed !== false || original.receipt?.state !== "PUBLISHED" || original.receipt.digest !== digest7 || original.receipt.sequence !== options.manifest.sequence || original.receipt.deletionWatermark !== options.manifest.deletionWatermark || !same5(original.profile, options.manifest.profile) || !same5(original.databases, options.manifest.databases) || proof?.format !== format || proof.activationAllowed !== false || proof.originalDigest !== digest7 || proof.deletionWatermark !== floor || proof.logDigest !== logDigest || !same5(proof.layout, options.layout) || proof.integrityDigest !== sha9(JSON.stringify(original.integrity)) || !original.originalIntegrity || proof.originalIntegrityDigest !== sha9(JSON.stringify(original.originalIntegrity)) || overlay?.originalDigest !== digest7 || overlay.deletionWatermark !== floor || overlay.logDigest !== logDigest || overlay.activationAllowed !== false || overlay.state !== "QUARANTINED" || overlay.runtimeCopies?.format !== "engine7-recovery-runtime-copy-cleanup-v6")
36082
+ if (original.format !== "engine7-runtime-publication-restore-v1" || original.activationAllowed !== false || original.receipt?.state !== "PUBLISHED" || original.receipt.digest !== digest7 || original.receipt.sequence !== options.manifest.sequence || original.receipt.deletionWatermark !== options.manifest.deletionWatermark || !same5(original.profile, options.manifest.profile) || !same5(original.databases, options.manifest.databases) || proof?.format !== format2 || proof.activationAllowed !== false || proof.originalDigest !== digest7 || proof.deletionWatermark !== floor || proof.logDigest !== logDigest || !same5(proof.layout, options.layout) || proof.integrityDigest !== sha9(JSON.stringify(original.integrity)) || !original.originalIntegrity || proof.originalIntegrityDigest !== sha9(JSON.stringify(original.originalIntegrity)) || overlay?.originalDigest !== digest7 || overlay.deletionWatermark !== floor || overlay.logDigest !== logDigest || overlay.activationAllowed !== false || overlay.state !== "QUARANTINED" || overlay.runtimeCopies?.format !== "engine7-recovery-runtime-copy-cleanup-v6")
35621
36083
  throw new Error("RECOVERY_VISIBILITY_PROOF");
35622
36084
  verifyRuntimeGenerationIntegrity(options.snapshot, original.integrity);
35623
36085
  const sealed = sha9(JSON.stringify(original));
@@ -35747,7 +36209,7 @@ async function activateRuntimeGeneration(options) {
35747
36209
  };
35748
36210
  await checkDeletion();
35749
36211
  if (!await (options.verifyDirectory ?? verifyRuntimeDirectory)(dirname22(destination))) throw new Error("TRAVEL_ACTIVATION_DIRECTORY");
35750
- if (realpathSync17(snapshot) !== snapshot || realpathSync17(dirname22(destination)) !== dirname22(destination) || existsSync32(destination)) throw new Error("TRAVEL_ACTIVATION_NEW_DIRECTORY_REQUIRED");
36212
+ if (realpathSync18(snapshot) !== snapshot || realpathSync18(dirname22(destination)) !== dirname22(destination) || existsSync32(destination)) throw new Error("TRAVEL_ACTIVATION_NEW_DIRECTORY_REQUIRED");
35751
36213
  const proof = JSON.parse(readPrivateFile(join54(snapshot, ".runtime-publication-receipt.json"), 4 * 1024 * 1024).toString());
35752
36214
  if (proof.format !== "engine7-runtime-publication-restore-v1" || !same6(proof.profile, manifest.profile) || proof.receipt?.digest !== digest7 || proof.receipt?.sequence !== manifest.sequence || proof.receipt?.state !== "PUBLISHED" || proof.activationAllowed !== false || !same6(proof.databases, manifest.databases)) throw new Error("TRAVEL_ACTIVATION_RECEIPT");
35753
36215
  await verifyRuntimeGenerationIntegrityAsync(snapshot, proof.integrity);
@@ -35824,9 +36286,9 @@ init_publication_objects();
35824
36286
  init_key_service_store();
35825
36287
  import { fork } from "node:child_process";
35826
36288
  import { DatabaseSync as DatabaseSync24 } from "node:sqlite";
35827
- import { closeSync as closeSync18, lstatSync as lstatSync20, openSync as openSync19, readFileSync as readFileSync29, realpathSync as realpathSync18 } from "node:fs";
36289
+ import { closeSync as closeSync18, lstatSync as lstatSync20, openSync as openSync19, readFileSync as readFileSync29, realpathSync as realpathSync19 } from "node:fs";
35828
36290
  import { isAbsolute as isAbsolute7, join as join55 } from "node:path";
35829
- import { createHash as createHash41, randomUUID as randomUUID18 } from "node:crypto";
36291
+ import { createHash as createHash41, randomUUID as randomUUID20 } from "node:crypto";
35830
36292
 
35831
36293
  // src/continuity/engine-control.ts
35832
36294
  init_runtime_authority();
@@ -35838,7 +36300,7 @@ function travelProcessBinding(stateDir) {
35838
36300
  }
35839
36301
 
35840
36302
  // src/continuity/node-process.ts
35841
- var format2 = "engine7-travel-process-v1";
36303
+ var format3 = "engine7-travel-process-v1";
35842
36304
  var systemEnvironment = /* @__PURE__ */ new Set([
35843
36305
  "PATH",
35844
36306
  "PATHEXT",
@@ -35940,7 +36402,7 @@ var SupervisedRuntimeProcess = class {
35940
36402
  if (retired && (!recovery || continuation?.state !== "SUSPENDED" || continuation.entry_hash !== this.options.entrySha256 || continuation.authority_boot_id !== permit.authorityBootId)) throw new Error("TRAVEL_PROCESS_GENERATION_RETIRED");
35941
36403
  if (recovery && !retired) throw new Error("TRAVEL_PROCESS_GENERATION_RETIRED");
35942
36404
  const info = lstatSync20(this.options.entry);
35943
- if (!info.isFile() || info.isSymbolicLink() || info.size > 64 * 1024 * 1024 || realpathSync18(this.options.entry) !== this.options.entry || createHash41("sha256").update(readFileSync29(this.options.entry)).digest("hex") !== this.options.entrySha256) throw new Error("TRAVEL_PROCESS_BUILD");
36405
+ if (!info.isFile() || info.isSymbolicLink() || info.size > 64 * 1024 * 1024 || realpathSync19(this.options.entry) !== this.options.entry || createHash41("sha256").update(readFileSync29(this.options.entry)).digest("hex") !== this.options.entrySha256) throw new Error("TRAVEL_PROCESS_BUILD");
35944
36406
  let environment;
35945
36407
  try {
35946
36408
  environment = supervisedRuntimeEnvironment(JSON.parse(readPrivateFile(this.options.configFile, 1024 * 1024).toString()), process.env, this.options.environmentNames);
@@ -35952,7 +36414,7 @@ var SupervisedRuntimeProcess = class {
35952
36414
  this.expectedAuthorityBootId = permit.authorityBootId;
35953
36415
  this.expected = binding;
35954
36416
  this.plannedExit = false;
35955
- const log = join55(this.options.directory, "engine-" + randomUUID18() + ".log"), fd = openSync19(log, "wx", 384);
36417
+ const log = join55(this.options.directory, "engine-" + randomUUID20() + ".log"), fd = openSync19(log, "wx", 384);
35956
36418
  let child;
35957
36419
  try {
35958
36420
  child = fork(this.options.entry, [this.options.configFile], {
@@ -35977,7 +36439,7 @@ var SupervisedRuntimeProcess = class {
35977
36439
  child.once("error", fail2);
35978
36440
  child.once("exit", fail2);
35979
36441
  child.on("message", (message) => {
35980
- if (message?.format !== format2 || JSON.stringify(message.binding) !== JSON.stringify(binding)) return;
36442
+ if (message?.format !== format3 || JSON.stringify(message.binding) !== JSON.stringify(binding)) return;
35981
36443
  if (message.type === "ready") {
35982
36444
  clearTimeout(timer);
35983
36445
  resolve47();
@@ -36018,14 +36480,14 @@ var SupervisedRuntimeProcess = class {
36018
36480
  }
36019
36481
  request(action, fields3 = {}) {
36020
36482
  if (!this.child?.connected) return Promise.reject(new Error("TRAVEL_PROCESS_EXITED"));
36021
- const nonce = randomUUID18(), child = this.child;
36483
+ const nonce = randomUUID20(), child = this.child;
36022
36484
  return new Promise((resolve47, reject) => {
36023
36485
  const timer = setTimeout(() => {
36024
36486
  this.pending.delete(nonce);
36025
36487
  reject(new Error("TRAVEL_PROCESS_TIMEOUT"));
36026
36488
  }, action === "status" ? Math.min(this.timeout, 5e3) : this.timeout);
36027
36489
  this.pending.set(nonce, { resolve: resolve47, reject, timer });
36028
- child.send?.({ format: format2, type: "request", nonce, binding: this.expected, action, ...fields3 }, (error) => {
36490
+ child.send?.({ format: format3, type: "request", nonce, binding: this.expected, action, ...fields3 }, (error) => {
36029
36491
  if (error) {
36030
36492
  clearTimeout(timer);
36031
36493
  this.pending.delete(nonce);
@@ -36129,7 +36591,7 @@ import { join as join57, resolve as resolve33 } from "node:path";
36129
36591
 
36130
36592
  // src/continuity/publication-files.ts
36131
36593
  import { DatabaseSync as DatabaseSync25 } from "node:sqlite";
36132
- import { lstatSync as lstatSync21, readdirSync as readdirSync13, realpathSync as realpathSync19, mkdirSync as mkdirSync26, writeFileSync as writeFileSync30, chmodSync as chmodSync7, openSync as openSync20, closeSync as closeSync19, fsyncSync as fsyncSync11 } from "node:fs";
36594
+ import { lstatSync as lstatSync21, readdirSync as readdirSync13, realpathSync as realpathSync20, mkdirSync as mkdirSync26, writeFileSync as writeFileSync30, chmodSync as chmodSync7, openSync as openSync20, closeSync as closeSync19, fsyncSync as fsyncSync11 } from "node:fs";
36133
36595
  import { join as join56, resolve as resolve32, dirname as dirname23 } from "node:path";
36134
36596
  async function restorePublication(options) {
36135
36597
  const { receiver } = options, status = await receiver.status(false);
@@ -36137,7 +36599,7 @@ async function restorePublication(options) {
36137
36599
  const manifest = await receiver.manifest(status.published.sequence);
36138
36600
  if (JSON.stringify(Object.keys(options.databases).sort()) !== JSON.stringify(manifest.profile.databaseIds)) throw new Error("PUBLICATION_INCOMPLETE_DATABASES");
36139
36601
  const destination = resolve32(options.destination);
36140
- if (realpathSync19(dirname23(destination)) !== dirname23(destination)) throw new Error("SYMLINK_REFUSED");
36602
+ if (realpathSync20(dirname23(destination)) !== dirname23(destination)) throw new Error("SYMLINK_REFUSED");
36141
36603
  if (isWithin(receiver.objects.directory, destination) || isWithin(destination, receiver.objects.directory)) throw new Error("PUBLICATION_OVERLAPPING_PATHS");
36142
36604
  try {
36143
36605
  mkdirSync26(destination, { mode: 448 });
@@ -36280,7 +36742,7 @@ import { join as join59 } from "node:path";
36280
36742
  init_key_service_store();
36281
36743
  init_publication_objects();
36282
36744
  import { DatabaseSync as DatabaseSync27 } from "node:sqlite";
36283
- import { existsSync as existsSync33, lstatSync as lstatSync22, realpathSync as realpathSync20 } from "node:fs";
36745
+ import { existsSync as existsSync33, lstatSync as lstatSync22, realpathSync as realpathSync21 } from "node:fs";
36284
36746
  import { createHash as createHash42 } from "node:crypto";
36285
36747
  import { isAbsolute as isAbsolute8, join as join58, resolve as resolve34 } from "node:path";
36286
36748
  init_sqlite_replication();
@@ -36292,7 +36754,7 @@ async function openRuntimeGenerationSource(options) {
36292
36754
  for (const path37 of [options.stateDir, options.dataDirectory]) if (!isAbsolute8(path37) || resolve34(path37) !== path37) throw new Error("TRAVEL_SOURCE_PATH");
36293
36755
  const stateDir = options.stateDir, dataDirectory = options.dataDirectory;
36294
36756
  assertPrivateDirectory(stateDir);
36295
- if (realpathSync20(stateDir) !== stateDir || realpathSync20(join58(dataDirectory, "..")) !== resolve34(dataDirectory, "..") || isWithin(stateDir, dataDirectory) || isWithin(dataDirectory, stateDir) || isWithin(stateDir, options.objects.directory)) throw new Error("TRAVEL_SOURCE_PATH");
36757
+ if (realpathSync21(stateDir) !== stateDir || realpathSync21(join58(dataDirectory, "..")) !== resolve34(dataDirectory, "..") || isWithin(stateDir, dataDirectory) || isWithin(dataDirectory, stateDir) || isWithin(stateDir, options.objects.directory)) throw new Error("TRAVEL_SOURCE_PATH");
36296
36758
  if (options.mode !== "LIVE" && options.mode !== "SEALED") throw new Error("TRAVEL_SOURCE_MODE");
36297
36759
  if (existsSync33(join58(stateDir, ".travel-restored.json"))) throw new Error("TRAVEL_ACTIVATION_REQUIRED");
36298
36760
  const receipt2 = JSON.parse(readPrivateFile(join58(stateDir, ".travel-active.json"), 4 * 1024 * 1024).toString());
@@ -36313,7 +36775,7 @@ async function openRuntimeGenerationSource(options) {
36313
36775
  }
36314
36776
  const workspace = join58(stateDir, layout.trees[workspaceTree.id]);
36315
36777
  assertPrivateDirectory(workspace);
36316
- if (workspace === stateDir || !isWithin(stateDir, workspace) || realpathSync20(workspace) !== workspace) throw new Error("TRAVEL_SOURCE_LAYOUT");
36778
+ if (workspace === stateDir || !isWithin(stateDir, workspace) || realpathSync21(workspace) !== workspace) throw new Error("TRAVEL_SOURCE_LAYOUT");
36317
36779
  const handles = {}, databases = {}, writableDatabases = {};
36318
36780
  const releases2 = [], sessionDirectories = [], sessionTrees = [];
36319
36781
  const registeredRoots = /* @__PURE__ */ new Set();
@@ -36339,7 +36801,7 @@ async function openRuntimeGenerationSource(options) {
36339
36801
  const path37 = layout.databases[id2];
36340
36802
  validatePublicationPath(path37);
36341
36803
  const file2 = join58(stateDir, path37), place = sqliteStoreLocation(file2), info = lstatSync22(file2);
36342
- if (!place || !isWithin(stateDir, place.stateDir) || !info.isFile() || info.isSymbolicLink() || realpathSync20(file2) !== file2 || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid())) throw new Error("TRAVEL_SOURCE_LAYOUT");
36804
+ if (!place || !isWithin(stateDir, place.stateDir) || !info.isFile() || info.isSymbolicLink() || realpathSync21(file2) !== file2 || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid())) throw new Error("TRAVEL_SOURCE_LAYOUT");
36343
36805
  const db2 = new DatabaseSync27(file2, { readOnly: options.mode === "SEALED", allowExtension: options.mode === "LIVE" && place.component === "legacy-memory" });
36344
36806
  handles[id2] = db2;
36345
36807
  const schema5 = readSchemaVersion(db2), registration = readSQLiteStoreRegistration(place), actual = readSQLiteReplicationSource(db2);
@@ -36559,11 +37021,11 @@ function startTravelHeartbeatReporting(options) {
36559
37021
  preparePrivateDirectory(options.directory);
36560
37022
  const ownerFile = join60(options.directory, "heartbeat-owner.sqlite");
36561
37023
  preparePrivateDatabase(ownerFile);
36562
- const owner = new DatabaseSync28(ownerFile);
37024
+ const owner2 = new DatabaseSync28(ownerFile);
36563
37025
  try {
36564
- owner.exec("CREATE TABLE IF NOT EXISTS owner(id INTEGER PRIMARY KEY);BEGIN IMMEDIATE");
37026
+ owner2.exec("CREATE TABLE IF NOT EXISTS owner(id INTEGER PRIMARY KEY);BEGIN IMMEDIATE");
36565
37027
  } catch {
36566
- owner.close();
37028
+ owner2.close();
36567
37029
  throw new Error("TRAVEL_REPORTING_BUSY");
36568
37030
  }
36569
37031
  let db2;
@@ -36575,7 +37037,7 @@ function startTravelHeartbeatReporting(options) {
36575
37037
  if (db2.prepare("PRAGMA quick_check").get()?.quick_check !== "ok") throw new Error("TRAVEL_REPORTING_RECOVERY_REQUIRED");
36576
37038
  db2.prepare("INSERT OR IGNORE INTO sequences VALUES(?,?,0)").run(options.nodeId, options.bootId);
36577
37039
  } catch (error) {
36578
- owner.close();
37040
+ owner2.close();
36579
37041
  throw error;
36580
37042
  }
36581
37043
  let stopped = false, registered = false, active, stopping, timer, lastError = null, deadline = clock2();
@@ -36686,7 +37148,7 @@ function startTravelHeartbeatReporting(options) {
36686
37148
  await active;
36687
37149
  } finally {
36688
37150
  db2.close();
36689
- owner.close();
37151
+ owner2.close();
36690
37152
  }
36691
37153
  })();
36692
37154
  return stopping;
@@ -36699,7 +37161,7 @@ init_key_service_store();
36699
37161
 
36700
37162
  // src/continuity/recovery-archive-restore.ts
36701
37163
  import { DatabaseSync as DatabaseSync29 } from "node:sqlite";
36702
- import { mkdirSync as mkdirSync28, writeFileSync as writeFileSync32, realpathSync as realpathSync21 } from "node:fs";
37164
+ import { mkdirSync as mkdirSync28, writeFileSync as writeFileSync32, realpathSync as realpathSync22 } from "node:fs";
36703
37165
  import { dirname as dirname24, join as join61, resolve as resolve35 } from "node:path";
36704
37166
  init_sqlite_replication();
36705
37167
  async function restoreRecoveryArchive(options) {
@@ -36717,7 +37179,7 @@ async function restoreOriginal(options, original, currentHCheck) {
36717
37179
  const verify4 = async () => currentHCheck ? currentHCheck() : await checkRecoveryDeletionAsync(manifest, options.deletionWatermark, floor);
36718
37180
  floor = await verify4();
36719
37181
  const destination = resolve35(options.destination);
36720
- if (realpathSync21(dirname24(destination)) !== dirname24(destination)) throw new Error("SYMLINK_REFUSED");
37182
+ if (realpathSync22(dirname24(destination)) !== dirname24(destination)) throw new Error("SYMLINK_REFUSED");
36721
37183
  for (const root of [objects.directory, options.archive.directory]) if (isWithin(root, destination) || isWithin(destination, root)) throw new Error("RECOVERY_OVERLAPPING_PATHS");
36722
37184
  try {
36723
37185
  mkdirSync28(destination, { mode: 448 });
@@ -36795,7 +37257,7 @@ import { DatabaseSync as DatabaseSync30 } from "node:sqlite";
36795
37257
  import { existsSync as existsSync34, lstatSync as lstatSync23, writeFileSync as writeFileSync33 } from "node:fs";
36796
37258
  import { join as join62 } from "node:path";
36797
37259
  var zero = "0".repeat(64);
36798
- var format3 = "engine7-runtime-checkpoint-control-v1";
37260
+ var format4 = "engine7-runtime-checkpoint-control-v1";
36799
37261
  var hash7 = (value2) => typeof value2 === "string" && /^[a-f0-9]{64}$/.test(value2);
36800
37262
  var natural3 = (value2) => typeof value2 === "number" && Number.isSafeInteger(value2) && value2 >= 0;
36801
37263
  var incarnation3 = (file2) => {
@@ -36812,9 +37274,9 @@ var RuntimeCheckpointControl = class {
36812
37274
  this.files = ["checkpoints.json", "checkpoint-owner.sqlite", "checkpoints.sqlite"].map((file2) => join62(options.directory, file2));
36813
37275
  const presence = this.files.map(existsSync34), fresh = presence.every((value2) => !value2);
36814
37276
  if (fresh && options.initialize !== true || !fresh && !presence.every(Boolean)) throw new Error("TRAVEL_CHECKPOINT_RECOVERY_REQUIRED");
36815
- if (fresh) writeFileSync33(this.files[0], JSON.stringify({ format: format3, binding: this.binding }), { mode: 384, flag: "wx", flush: true });
37277
+ if (fresh) writeFileSync33(this.files[0], JSON.stringify({ format: format4, binding: this.binding }), { mode: 384, flag: "wx", flush: true });
36816
37278
  const marker = JSON.parse(readPrivateFile(this.files[0], 65536).toString());
36817
- if (marker.format !== format3 || marker.binding !== this.binding || Object.keys(marker).length !== 2) throw new Error("TRAVEL_CHECKPOINT_IDENTITY");
37279
+ if (marker.format !== format4 || marker.binding !== this.binding || Object.keys(marker).length !== 2) throw new Error("TRAVEL_CHECKPOINT_IDENTITY");
36818
37280
  preparePrivateDatabase(this.files[1]);
36819
37281
  this.owner = new DatabaseSync30(this.files[1]);
36820
37282
  try {
@@ -37788,13 +38250,13 @@ async function transferRecoveryArchive(options) {
37788
38250
  init_publication_objects();
37789
38251
  init_key_service_store();
37790
38252
  import { DatabaseSync as DatabaseSync32 } from "node:sqlite";
37791
- import { existsSync as existsSync36, lstatSync as lstatSync25, realpathSync as realpathSync23, writeFileSync as writeFileSync35 } from "node:fs";
38253
+ import { existsSync as existsSync36, lstatSync as lstatSync25, realpathSync as realpathSync24, writeFileSync as writeFileSync35 } from "node:fs";
37792
38254
  import { isAbsolute as isAbsolute10, join as join64, resolve as resolve37 } from "node:path";
37793
- import { randomUUID as randomUUID19 } from "node:crypto";
38255
+ import { randomUUID as randomUUID21 } from "node:crypto";
37794
38256
 
37795
38257
  // src/continuity/runtime-replica-seed.ts
37796
38258
  import { DatabaseSync as DatabaseSync31 } from "node:sqlite";
37797
- import { existsSync as existsSync35, writeFileSync as writeFileSync34, realpathSync as realpathSync22, lstatSync as lstatSync24 } from "node:fs";
38259
+ import { existsSync as existsSync35, writeFileSync as writeFileSync34, realpathSync as realpathSync23, lstatSync as lstatSync24 } from "node:fs";
37798
38260
  import { dirname as dirname25, isAbsolute as isAbsolute9, join as join63, resolve as resolve36 } from "node:path";
37799
38261
  init_publication_objects();
37800
38262
  init_sqlite_replication();
@@ -37804,14 +38266,14 @@ function acquireReplicaOwner(directory2, initialize2 = false) {
37804
38266
  const file2 = join63(directory2, "replica-owner.sqlite");
37805
38267
  if (!initialize2 && !existsSync35(file2)) throw new Error("TRAVEL_REPLICA_RECOVERY_REQUIRED");
37806
38268
  preparePrivateDatabase(file2);
37807
- const owner = new DatabaseSync31(file2);
38269
+ const owner2 = new DatabaseSync31(file2);
37808
38270
  try {
37809
- if (initialize2) owner.exec("CREATE TABLE owner(id INTEGER PRIMARY KEY)");
37810
- if (owner.prepare("PRAGMA quick_check").get()?.quick_check !== "ok" || !owner.prepare("SELECT 1 FROM sqlite_master WHERE name='owner' AND type='table'").get()) throw new Error("TRAVEL_REPLICA_RECOVERY_REQUIRED");
37811
- owner.exec("PRAGMA busy_timeout=0;BEGIN IMMEDIATE");
37812
- return owner;
38271
+ if (initialize2) owner2.exec("CREATE TABLE owner(id INTEGER PRIMARY KEY)");
38272
+ if (owner2.prepare("PRAGMA quick_check").get()?.quick_check !== "ok" || !owner2.prepare("SELECT 1 FROM sqlite_master WHERE name='owner' AND type='table'").get()) throw new Error("TRAVEL_REPLICA_RECOVERY_REQUIRED");
38273
+ owner2.exec("PRAGMA busy_timeout=0;BEGIN IMMEDIATE");
38274
+ return owner2;
37813
38275
  } catch (error) {
37814
- owner.close();
38276
+ owner2.close();
37815
38277
  if (error.code === "ERR_SQLITE_ERROR" && /locked|busy/i.test(error.message)) throw new Error("TRAVEL_REPLICA_BUSY");
37816
38278
  throw error;
37817
38279
  }
@@ -37832,14 +38294,14 @@ async function seedRuntimeReplica(options) {
37832
38294
  if (status.buildManifestId !== manifest.profile.buildManifestId) throw new Error("TRAVEL_REPLICA_BUILD");
37833
38295
  };
37834
38296
  await check();
37835
- for (const path37 of [options.destination, options.dataDirectory]) if (!isAbsolute9(path37) || resolve36(path37) !== path37 || realpathSync22(dirname25(path37)) !== dirname25(path37)) throw new Error("TRAVEL_REPLICA_PATH");
38297
+ for (const path37 of [options.destination, options.dataDirectory]) if (!isAbsolute9(path37) || resolve36(path37) !== path37 || realpathSync23(dirname25(path37)) !== dirname25(path37)) throw new Error("TRAVEL_REPLICA_PATH");
37836
38298
  if (existsSync35(destination) || existsSync35(dataDirectory) || isWithin(destination, dataDirectory) || isWithin(dataDirectory, destination)) throw new Error("TRAVEL_REPLICA_NEW_DIRECTORY_REQUIRED");
37837
38299
  for (const path37 of [destination, dataDirectory]) for (const root of [options.objects.directory, options.archive.directory, options.archive.objects.directory]) if (isWithin(root, path37) || isWithin(path37, root)) throw new Error("TRAVEL_REPLICA_PATH");
37838
38300
  if (!await (options.verifyDirectory ?? verifyRuntimeDirectory)(dirname25(destination))) throw new Error("TRAVEL_REPLICA_DIRECTORY");
37839
38301
  await check();
37840
38302
  preparePrivateDirectory(dataDirectory);
37841
38303
  const databases = {}, replicas = {};
37842
- let receiver, owner, closed = false;
38304
+ let receiver, owner2, closed = false;
37843
38305
  const close = () => {
37844
38306
  if (closed) return;
37845
38307
  closed = true;
@@ -37847,11 +38309,11 @@ async function seedRuntimeReplica(options) {
37847
38309
  receiver?.close();
37848
38310
  for (const db2 of Object.values(databases)) db2.close();
37849
38311
  } finally {
37850
- owner?.close();
38312
+ owner2?.close();
37851
38313
  }
37852
38314
  };
37853
38315
  try {
37854
- owner = acquireReplicaOwner(dataDirectory, true);
38316
+ owner2 = acquireReplicaOwner(dataDirectory, true);
37855
38317
  await restoreRecoveryArchive({ archive: options.archive, id: options.id, destination, deletionWatermark: options.deletionWatermark, verifyDatabases: false });
37856
38318
  const refs2 = /* @__PURE__ */ new Map();
37857
38319
  for (const content of [...manifest.trees.flatMap((tree) => tree.files.map((file2) => file2.content)), ...entry.databases.map((db2) => db2.content)]) for (const ref of content.chunks) refs2.set(ref.sha256, ref);
@@ -37908,7 +38370,7 @@ async function openSeededRuntimeReplica(options) {
37908
38370
  for (const path37 of [options.destination, options.dataDirectory]) {
37909
38371
  if (!isAbsolute9(path37) || resolve36(path37) !== path37) throw new Error("TRAVEL_REPLICA_PATH");
37910
38372
  assertPrivateDirectory(path37);
37911
- if (realpathSync22(path37) !== path37) throw new Error("TRAVEL_REPLICA_PATH");
38373
+ if (realpathSync23(path37) !== path37) throw new Error("TRAVEL_REPLICA_PATH");
37912
38374
  }
37913
38375
  if (isWithin(options.destination, options.dataDirectory) || isWithin(options.dataDirectory, options.destination)) throw new Error("TRAVEL_REPLICA_PATH");
37914
38376
  for (const path37 of [options.destination, options.dataDirectory]) for (const root of [options.objects.directory, options.archive.directory, options.archive.objects.directory]) if (isWithin(root, path37) || isWithin(path37, root)) throw new Error("TRAVEL_REPLICA_PATH");
@@ -37924,7 +38386,7 @@ async function openSeededRuntimeReplica(options) {
37924
38386
  };
37925
38387
  floor();
37926
38388
  if (!await (options.verifyDirectory ?? verifyRuntimeDirectory)(dirname25(options.destination))) throw new Error("TRAVEL_REPLICA_DIRECTORY");
37927
- const owner = acquireReplicaOwner(options.dataDirectory), databases = {}, replicas = {};
38389
+ const owner2 = acquireReplicaOwner(options.dataDirectory), databases = {}, replicas = {};
37928
38390
  let receiver, closed = false;
37929
38391
  const close = () => {
37930
38392
  if (closed) return;
@@ -37933,7 +38395,7 @@ async function openSeededRuntimeReplica(options) {
37933
38395
  receiver?.close();
37934
38396
  for (const db2 of Object.values(databases)) db2.close();
37935
38397
  } finally {
37936
- owner.close();
38398
+ owner2.close();
37937
38399
  }
37938
38400
  };
37939
38401
  try {
@@ -37949,7 +38411,7 @@ async function openSeededRuntimeReplica(options) {
37949
38411
  const file2 = join63(options.destination, "databases", d.databaseId + ".sqlite");
37950
38412
  if (!existsSync35(file2)) throw new Error("TRAVEL_REPLICA_RECOVERY_REQUIRED");
37951
38413
  const stat3 = lstatSync24(file2);
37952
- if (!stat3.isFile() || stat3.isSymbolicLink() || realpathSync22(file2) !== file2 || process.platform !== "win32" && (stat3.uid !== process.getuid() || stat3.mode & 63)) throw new Error("TRAVEL_REPLICA_PATH");
38414
+ if (!stat3.isFile() || stat3.isSymbolicLink() || realpathSync23(file2) !== file2 || process.platform !== "win32" && (stat3.uid !== process.getuid() || stat3.mode & 63)) throw new Error("TRAVEL_REPLICA_PATH");
37953
38415
  const probe = new DatabaseSync31(file2, { readOnly: true }), binding = normalizeBinding({ ...profile.identity, databaseId: d.databaseId, baselineId: profile.baselineId, epoch: profile.epoch });
37954
38416
  let component, version;
37955
38417
  try {
@@ -37994,7 +38456,7 @@ var RuntimeReplicaRepository = class _RuntimeReplicaRepository {
37994
38456
  this.options = options;
37995
38457
  if (!validId2(options.nodeId) || !isAbsolute10(options.directory) || resolve37(options.directory) !== options.directory || !isAbsolute10(options.generationsDirectory) || resolve37(options.generationsDirectory) !== options.generationsDirectory || isWithin(options.directory, options.generationsDirectory) || isWithin(options.generationsDirectory, options.directory)) throw new Error("TRAVEL_REPLICA_PATH");
37996
38458
  assertPrivateDirectory(options.generationsDirectory);
37997
- if (realpathSync23(options.generationsDirectory) !== options.generationsDirectory) throw new Error("TRAVEL_REPLICA_PATH");
38459
+ if (realpathSync24(options.generationsDirectory) !== options.generationsDirectory) throw new Error("TRAVEL_REPLICA_PATH");
37998
38460
  preparePrivateDirectory(options.directory);
37999
38461
  this.files = ["replicas.json", "replicas-owner.sqlite", "replicas.sqlite"].map((name) => join64(options.directory, name));
38000
38462
  const presence = this.files.map(existsSync36), fresh = presence.every((value2) => !value2);
@@ -38127,7 +38589,7 @@ var RuntimeReplicaRepository = class _RuntimeReplicaRepository {
38127
38589
  }
38128
38590
  if (row && row.state !== "PREPARING") throw new Error("TRAVEL_REPLICA_RECOVERY_REQUIRED");
38129
38591
  preparePrivateDirectory(join64(this.options.directory, "receivers"));
38130
- const attempt = randomUUID19(), destination = join64(this.options.generationsDirectory, "replica-" + attempt), dataDirectory = join64(this.options.directory, "receivers", "replica-" + attempt);
38592
+ const attempt = randomUUID21(), destination = join64(this.options.generationsDirectory, "replica-" + attempt), dataDirectory = join64(this.options.directory, "receivers", "replica-" + attempt);
38131
38593
  this.db.exec("BEGIN IMMEDIATE");
38132
38594
  try {
38133
38595
  if (row) this.db.prepare("UPDATE attempts SET state='FAILED' WHERE id=? AND state='PREPARING'").run(row.attempt_id);
@@ -38409,7 +38871,7 @@ async function createTravelNodeDataServer(options) {
38409
38871
  init_store();
38410
38872
  init_schema_migrations();
38411
38873
  import { DatabaseSync as DatabaseSync35 } from "node:sqlite";
38412
- import { lstatSync as lstatSync27, realpathSync as realpathSync25 } from "node:fs";
38874
+ import { lstatSync as lstatSync27, realpathSync as realpathSync26 } from "node:fs";
38413
38875
  import { isAbsolute as isAbsolute11, join as join68, resolve as resolve39 } from "node:path";
38414
38876
 
38415
38877
  // src/continuity/recovery-admission.ts
@@ -38821,8 +39283,8 @@ function nativeReferences(db2, table, row, common, branch, scopeProof, originalB
38821
39283
  const entity = db2.prepare("SELECT kind FROM entities WHERE scope_id=? AND entity_id=? AND state='active'").get(scope, payload.entityId);
38822
39284
  if (!entity) return false;
38823
39285
  if (payload.provenance === "host_identity") {
38824
- const owner = db2.prepare("SELECT app_id FROM memory_scopes WHERE scope_id=?").get(scope);
38825
- if (entity.kind !== "agent" || !["assistant-actor", "scope-agent"].includes(text2("namespace") ?? "") || text2("namespace") === "scope-agent" && text2("external_id") !== owner?.app_id) return false;
39286
+ const owner2 = db2.prepare("SELECT app_id FROM memory_scopes WHERE scope_id=?").get(scope);
39287
+ if (entity.kind !== "agent" || !["assistant-actor", "scope-agent"].includes(text2("namespace") ?? "") || text2("namespace") === "scope-agent" && text2("external_id") !== owner2?.app_id) return false;
38826
39288
  } else {
38827
39289
  const source = db2.prepare("SELECT * FROM memory_sources WHERE scope_id=? AND source_id=? AND interpretation_status<>'deleted'").get(scope, payload.sourceId);
38828
39290
  if (!source || db2.prepare("SELECT 1 FROM memory_sources WHERE scope_id=? AND origin_key=? AND source_version>?").get(scope, source.origin_key, source.source_version)) return false;
@@ -38855,8 +39317,8 @@ function nativeReferences(db2, table, row, common, branch, scopeProof, originalB
38855
39317
  if (table === "memory_artifact_generations") {
38856
39318
  try {
38857
39319
  const result = JSON.parse(text2("result_json") ?? "");
38858
- const owner = db2.prepare("SELECT owner_id,app_id,project_id FROM memory_scopes WHERE scope_id=?").get(scope);
38859
- if (!owner || !same10(result.basis?.scope, { ownerId: owner.owner_id, appId: owner.app_id, projectId: owner.project_id })) return false;
39320
+ const owner2 = db2.prepare("SELECT owner_id,app_id,project_id FROM memory_scopes WHERE scope_id=?").get(scope);
39321
+ if (!owner2 || !same10(result.basis?.scope, { ownerId: owner2.owner_id, appId: owner2.app_id, projectId: owner2.project_id })) return false;
38860
39322
  refs2 = result.basis.dependencies;
38861
39323
  } catch {
38862
39324
  return false;
@@ -39058,9 +39520,9 @@ function projectNative(db2, branch, table, original, baseline, current2, archive
39058
39520
  map("artifact_job", JSON.stringify([decode(row.kind), decode(row.artifact_id), Number(decode(row.version))]), original.version, () => BigInt(generation.job_id));
39059
39521
  }
39060
39522
  const kind = String(decode(row.kind)), id2 = String(decode(row.artifact_id)), version = Number(decode(row.version));
39061
- const owner = db2.prepare("SELECT owner_id,app_id,project_id FROM memory_scopes WHERE scope_id=?").get(scope);
39523
+ const owner2 = db2.prepare("SELECT owner_id,app_id,project_id FROM memory_scopes WHERE scope_id=?").get(scope);
39062
39524
  const refs2 = JSON.parse(String(decode(row.dependencies_json)));
39063
- recordArtifactBasis(db2, { ownerId: String(owner.owner_id), appId: String(owner.app_id), projectId: String(owner.project_id) }, kind, id2, version, refs2);
39525
+ recordArtifactBasis(db2, { ownerId: String(owner2.owner_id), appId: String(owner2.app_id), projectId: String(owner2.project_id) }, kind, id2, version, refs2);
39064
39526
  row.history_id = history("artifact.publication", JSON.stringify([kind, id2, version, String(decode(row.medium))]), { kind, id: id2, version, medium: decode(row.medium), digest: decode(row.digest) });
39065
39527
  }
39066
39528
  return row;
@@ -39710,8 +40172,8 @@ async function admitRecoveryArchives(options) {
39710
40172
  }
39711
40173
 
39712
40174
  // src/continuity/recovery-artifact-projection.ts
39713
- import { createHash as createHash46, randomUUID as randomUUID20 } from "node:crypto";
39714
- import { existsSync as existsSync37, linkSync, lstatSync as lstatSync26, mkdirSync as mkdirSync29, readFileSync as readFileSync30, realpathSync as realpathSync24, unlinkSync as unlinkSync13, writeFileSync as writeFileSync38 } from "node:fs";
40175
+ import { createHash as createHash46, randomUUID as randomUUID22 } from "node:crypto";
40176
+ import { existsSync as existsSync37, linkSync, lstatSync as lstatSync26, mkdirSync as mkdirSync29, readFileSync as readFileSync30, realpathSync as realpathSync25, unlinkSync as unlinkSync13, writeFileSync as writeFileSync38 } from "node:fs";
39715
40177
  import { dirname as dirname26, join as join67, resolve as resolve38 } from "node:path";
39716
40178
  import { createRequire as createRequire9 } from "node:module";
39717
40179
  init_runtime_authority();
@@ -39719,7 +40181,7 @@ init_dependencies();
39719
40181
  var sha10 = (bytes) => createHash46("sha256").update(bytes).digest("hex");
39720
40182
  var require5 = createRequire9(import.meta.url);
39721
40183
  function privateParents(root, path37) {
39722
- if (realpathSync24(root) !== root) throw new Error("RECOVERY_PROJECTION_UNSAFE_PATH");
40184
+ if (realpathSync25(root) !== root) throw new Error("RECOVERY_PROJECTION_UNSAFE_PATH");
39723
40185
  const visit = (directory2) => {
39724
40186
  if (!isWithin(root, directory2)) throw new Error("RECOVERY_PROJECTION_UNSAFE_PATH");
39725
40187
  if (directory2 !== root) visit(dirname26(directory2));
@@ -39758,11 +40220,11 @@ async function projectRecoveryArtifacts(options) {
39758
40220
  const verifyArtifact = (scopeId2, kind, id2, version) => {
39759
40221
  active();
39760
40222
  if (!memory) throw new Error("RECOVERY_ARTIFACT_DEPENDENCY_PENDING");
39761
- const owner = memory.prepare("SELECT owner_id,app_id,project_id FROM memory_scopes WHERE scope_id=?").get(scopeId2);
39762
- if (!owner) throw new Error("RECOVERY_ARTIFACT_DEPENDENCY_PENDING");
40223
+ const owner2 = memory.prepare("SELECT owner_id,app_id,project_id FROM memory_scopes WHERE scope_id=?").get(scopeId2);
40224
+ if (!owner2) throw new Error("RECOVERY_ARTIFACT_DEPENDENCY_PENDING");
39763
40225
  const dependencies2 = new MemoryDependencies(memory, (operation) => operation(), (operation) => operation());
39764
40226
  try {
39765
- dependencies2.assertCurrent({ ownerId: String(owner.owner_id), appId: String(owner.app_id), projectId: String(owner.project_id) }, kind, id2, version);
40227
+ dependencies2.assertCurrent({ ownerId: String(owner2.owner_id), appId: String(owner2.app_id), projectId: String(owner2.project_id) }, kind, id2, version);
39766
40228
  } catch {
39767
40229
  throw new Error("RECOVERY_ARTIFACT_DEPENDENCY_PENDING");
39768
40230
  }
@@ -39832,7 +40294,7 @@ async function projectRecoveryArtifacts(options) {
39832
40294
  commit();
39833
40295
  continue;
39834
40296
  }
39835
- const temporary = join67(dirname26(path37), ".recovery-" + randomUUID20()), original = Buffer.from(body);
40297
+ const temporary = join67(dirname26(path37), ".recovery-" + randomUUID22()), original = Buffer.from(body);
39836
40298
  writeFileSync38(temporary, original, { mode: local.mode, flag: "wx", flush: true });
39837
40299
  let created = false;
39838
40300
  try {
@@ -39954,7 +40416,7 @@ function policies(version) {
39954
40416
  async function admitNormalRecoveryArchives(options) {
39955
40417
  if (options.policyUpgrade !== void 0 && options.policyUpgrade !== "normal-v1") throw new Error("RECOVERY_INVALID_RESOLUTION");
39956
40418
  const stateDir = options.stateDir;
39957
- if (!isAbsolute11(stateDir) || resolve39(stateDir) !== stateDir || realpathSync25(stateDir) !== stateDir || typeof options.withSafeBoundary !== "function") throw new Error("RECOVERY_CURRENT_LAYOUT");
40419
+ if (!isAbsolute11(stateDir) || resolve39(stateDir) !== stateDir || realpathSync26(stateDir) !== stateDir || typeof options.withSafeBoundary !== "function") throw new Error("RECOVERY_CURRENT_LAYOUT");
39958
40420
  assertPrivateDirectory(stateDir);
39959
40421
  const runtime = runtimeAuthorityFor(stateDir);
39960
40422
  if (!runtime) throw new Error("RECOVERY_AUTHORITY_BARRIER");
@@ -39973,7 +40435,7 @@ async function admitNormalRecoveryArchives(options) {
39973
40435
  for (const id2 of profile.databaseIds) {
39974
40436
  validatePublicationPath(layout.databases[id2]);
39975
40437
  const file2 = join68(stateDir, layout.databases[id2]), place = sqliteStoreLocation(file2), stat3 = lstatSync27(file2);
39976
- if (!place || !stat3.isFile() || stat3.isSymbolicLink() || realpathSync25(file2) !== file2 || process.platform !== "win32" && (stat3.uid !== process.getuid() || stat3.mode & 63)) throw new Error("RECOVERY_CURRENT_LAYOUT");
40438
+ if (!place || !stat3.isFile() || stat3.isSymbolicLink() || realpathSync26(file2) !== file2 || process.platform !== "win32" && (stat3.uid !== process.getuid() || stat3.mode & 63)) throw new Error("RECOVERY_CURRENT_LAYOUT");
39977
40439
  if (place.component === "mem7") {
39978
40440
  if (id2 !== "memory" || memory || place.stateDir !== stateDir) throw new Error("RECOVERY_CURRENT_LAYOUT");
39979
40441
  memory = new Mem7Store(stateDir);
@@ -40136,7 +40598,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
40136
40598
  for (const path37 of [options.directory, options.generationsDirectory, options.build.entry, options.dataBuild.entry]) if (!isAbsolute12(path37) || resolve40(path37) !== path37) throw new Error("TRAVEL_NODE_PATH");
40137
40599
  if (options.dataIntervalMs !== void 0 && (!Number.isSafeInteger(options.dataIntervalMs) || options.dataIntervalMs < 250 || options.dataIntervalMs > 6e4)) throw new Error("TRAVEL_DATA_CONFIG");
40138
40600
  assertPrivateDirectory(options.generationsDirectory);
40139
- if (realpathSync26(options.generationsDirectory) !== options.generationsDirectory || isWithin(options.directory, options.generationsDirectory) || isWithin(options.generationsDirectory, options.directory)) throw new Error("TRAVEL_NODE_PATH");
40601
+ if (realpathSync27(options.generationsDirectory) !== options.generationsDirectory || isWithin(options.directory, options.generationsDirectory) || isWithin(options.generationsDirectory, options.directory)) throw new Error("TRAVEL_NODE_PATH");
40140
40602
  if (!Array.isArray(options.allowedTools) || options.allowedTools.length > 1024 || options.allowedTools.some((tool) => !/^\w[\w.:-]{0,127}$/.test(tool))) throw new Error("TRAVEL_NODE_CAPABILITIES");
40141
40603
  validateTravelChannelConfiguration(options.engineConfig.channels);
40142
40604
  this.checkBuild();
@@ -40279,7 +40741,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
40279
40741
  checkBuild() {
40280
40742
  for (const b of [this.options.build, this.options.dataBuild]) {
40281
40743
  const info = lstatSync28(b.entry);
40282
- if (!/^[a-f0-9]{64}$/.test(b.sha256) || !info.isFile() || info.isSymbolicLink() || info.size > 64 * 1024 * 1024 || realpathSync26(b.entry) !== b.entry || hash10(readFileSync31(b.entry)) !== b.sha256) throw new Error("TRAVEL_NODE_BUILD");
40744
+ if (!/^[a-f0-9]{64}$/.test(b.sha256) || !info.isFile() || info.isSymbolicLink() || info.size > 64 * 1024 * 1024 || realpathSync27(b.entry) !== b.entry || hash10(readFileSync31(b.entry)) !== b.sha256) throw new Error("TRAVEL_NODE_BUILD");
40283
40745
  }
40284
40746
  }
40285
40747
  assertKey() {
@@ -40465,7 +40927,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
40465
40927
  const directory2 = join70(this.options.directory, "data", "objects"), file2 = join70(directory2, "catalog.sqlite");
40466
40928
  assertPrivateDirectory(directory2);
40467
40929
  assertPrivateDirectory(join70(directory2, "chunks"));
40468
- if (realpathSync26(directory2) !== directory2 || !existsSync38(file2)) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
40930
+ if (realpathSync27(directory2) !== directory2 || !existsSync38(file2)) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
40469
40931
  const stat3 = lstatSync28(file2, { bigint: true });
40470
40932
  if (!stat3.isFile() || stat3.isSymbolicLink()) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
40471
40933
  const db2 = new DatabaseSync36(file2, { readOnly: true });
@@ -40678,14 +41140,14 @@ var TravelNodeAgent = class _TravelNodeAgent {
40678
41140
  const prior = this.db.prepare("SELECT snapshot FROM preparations WHERE digest=?").get(digest7);
40679
41141
  if (prior) {
40680
41142
  const snapshot2 = String(prior.snapshot);
40681
- if (!isWithin(this.options.generationsDirectory, snapshot2) || realpathSync26(snapshot2) !== snapshot2) throw new Error("TRAVEL_NODE_PATH");
41143
+ if (!isWithin(this.options.generationsDirectory, snapshot2) || realpathSync27(snapshot2) !== snapshot2) throw new Error("TRAVEL_NODE_PATH");
40682
41144
  const receipt2 = JSON.parse(readPrivateFile(join70(snapshot2, ".runtime-publication-receipt.json"), 4 * 1024 * 1024).toString());
40683
41145
  if (receipt2.receipt?.digest !== digest7) throw new Error("TRAVEL_NODE_CHECKPOINT");
40684
41146
  await verifyRuntimeGenerationIntegrityAsync(snapshot2, receipt2.integrity);
40685
41147
  validateRuntimeActivationSnapshot(snapshot2, manifest, locations);
40686
41148
  return { snapshot: snapshot2, manifest };
40687
41149
  }
40688
- const snapshot = join70(this.options.generationsDirectory, "snapshot-" + randomUUID21());
41150
+ const snapshot = join70(this.options.generationsDirectory, "snapshot-" + randomUUID23());
40689
41151
  await restoreRuntimePublication({ receiver, databases, destination: snapshot, sequence: manifest.sequence });
40690
41152
  validateRuntimeActivationSnapshot(snapshot, manifest, locations);
40691
41153
  this.db.prepare("INSERT INTO preparations VALUES(?,?)").run(digest7, snapshot);
@@ -40710,7 +41172,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
40710
41172
  const prior = this.db.prepare("SELECT * FROM common_preparations WHERE digest=?").get(digest7);
40711
41173
  if (prior) {
40712
41174
  const snapshot2 = String(prior.snapshot);
40713
- if (prior.archive_digest !== entry.receipt.digest || !isWithin(this.options.generationsDirectory, snapshot2) || realpathSync26(snapshot2) !== snapshot2) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
41175
+ if (prior.archive_digest !== entry.receipt.digest || !isWithin(this.options.generationsDirectory, snapshot2) || realpathSync27(snapshot2) !== snapshot2) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
40714
41176
  const proof = JSON.parse(readPrivateFile(join70(snapshot2, ".runtime-publication-receipt.json"), 4 * 1024 * 1024).toString());
40715
41177
  if (proof.recoveryArchive?.id !== entry.id || proof.recoveryArchive?.digest !== entry.receipt.digest || !same12(proof.receipt, entry.publication) || !same12(proof.profile, manifest.profile)) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
40716
41178
  await verifyRuntimeGenerationIntegrityAsync(snapshot2, proof.integrity);
@@ -40718,7 +41180,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
40718
41180
  await check();
40719
41181
  return { snapshot: snapshot2, manifest };
40720
41182
  }
40721
- const snapshot = join70(this.options.generationsDirectory, "snapshot-" + randomUUID21());
41183
+ const snapshot = join70(this.options.generationsDirectory, "snapshot-" + randomUUID23());
40722
41184
  await restoreRecoveryArchive({ archive: this.archive, id: entry.id, destination: snapshot, deletionWatermark: check, verifyDatabases: false });
40723
41185
  validateRuntimeActivationSnapshot(snapshot, manifest, locations);
40724
41186
  await check();
@@ -40749,14 +41211,14 @@ var TravelNodeAgent = class _TravelNodeAgent {
40749
41211
  const prior = this.db.prepare("SELECT * FROM common_preparations WHERE digest=?").get(digest7);
40750
41212
  if (prior) {
40751
41213
  const snapshot2 = String(prior.snapshot);
40752
- if (!isWithin(this.options.generationsDirectory, snapshot2) || realpathSync26(snapshot2) !== snapshot2 || prior.archive_digest !== entry.receipt.digest) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
41214
+ if (!isWithin(this.options.generationsDirectory, snapshot2) || realpathSync27(snapshot2) !== snapshot2 || prior.archive_digest !== entry.receipt.digest) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
40753
41215
  const proof2 = JSON.parse(readPrivateFile(join70(snapshot2, ".runtime-publication-receipt.json"), 4 * 1024 * 1024).toString());
40754
41216
  if (proof2.deletionVisibility?.deletionWatermark === this.keyWatermark) {
40755
41217
  const deletionWatermark = await (await verifyCurrentHDeletionVisibilityAsync({ snapshot: snapshot2, manifest, layout: this.options.layout, gateway: this.options.gateway, ...control2 }))();
40756
41218
  return { snapshot: snapshot2, manifest, deletionWatermark };
40757
41219
  }
40758
41220
  }
40759
- const snapshot = join70(this.options.generationsDirectory, "snapshot-" + randomUUID21());
41221
+ const snapshot = join70(this.options.generationsDirectory, "snapshot-" + randomUUID23());
40760
41222
  await restoreCurrentHForDeletion({ archive: this.archive, id: id2, destination: snapshot, ...control2 });
40761
41223
  writeFileSync40(join70(snapshot, ".runtime-publication-receipt.json"), JSON.stringify({
40762
41224
  format: "engine7-runtime-publication-restore-v1",
@@ -41148,7 +41610,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
41148
41610
  });
41149
41611
  }
41150
41612
  assertActive();
41151
- const destination = join70(this.options.generationsDirectory, "runtime-" + randomUUID21()), baselineId = "node-" + randomUUID21();
41613
+ const destination = join70(this.options.generationsDirectory, "runtime-" + randomUUID23()), baselineId = "node-" + randomUUID23();
41152
41614
  this.db.prepare("INSERT INTO generations VALUES(?,?,?,?,?)").run(binding, destination, digest7, "{}", "ACTIVATING");
41153
41615
  try {
41154
41616
  const activation = await activateRuntimeGeneration({
@@ -41402,12 +41864,12 @@ var TravelNodeAgent = class _TravelNodeAgent {
41402
41864
  this.db.prepare("INSERT INTO recovery_jobs VALUES(?,?,?,?,?,?,?,'PREPARED',NULL)").run(binding, receipt2.digest, common.id, local.id, remote.id, JSON.stringify(manifests), this.keyWatermark);
41403
41865
  }
41404
41866
  }
41405
- const jobs = this.db.prepare("SELECT * FROM recovery_jobs WHERE binding=? ORDER BY local_digest").all(binding);
41406
- if (jobs.some((job) => job.deletion_watermark !== this.keyWatermark)) throw new Error("RECOVERY_DELETION_BARRIER");
41407
- if (jobs.some((job) => job.state !== "DONE")) {
41867
+ const jobs2 = this.db.prepare("SELECT * FROM recovery_jobs WHERE binding=? ORDER BY local_digest").all(binding);
41868
+ if (jobs2.some((job) => job.deletion_watermark !== this.keyWatermark)) throw new Error("RECOVERY_DELETION_BARRIER");
41869
+ if (jobs2.some((job) => job.state !== "DONE")) {
41408
41870
  trace("normal-admission");
41409
41871
  await this.withNormalRecoveryBoundary(async () => {
41410
- for (const job of jobs) {
41872
+ for (const job of jobs2) {
41411
41873
  if (job.state === "DONE") continue;
41412
41874
  await check();
41413
41875
  const result = await admitNormalRecoveryArchives({
@@ -42742,7 +43204,7 @@ async function startTravelNodeService(input) {
42742
43204
  if (!nodeSupervisorRecord(input) || !nodeSupervisorRecord(input.principal) || !nodeSupervisorRecord(input.peer) || !nodeSupervisorRecord(input.control) || !nodeSupervisorRecord(input.management) || !nodeSupervisorRecord(input.data) || Object.hasOwn(input, "authorityDir")) throw new Error("TRAVEL_NODE_CONFIG");
42743
43205
  const config = input;
42744
43206
  assertPrivateDirectory(path34(config.generationsDirectory));
42745
- const bootId2 = config.bootId ?? randomUUID22();
43207
+ const bootId2 = config.bootId ?? randomUUID24();
42746
43208
  if (!nodeSupervisorId(bootId2)) throw new Error("TRAVEL_NODE_IDENTITY");
42747
43209
  const serverTls = tls(config.tls), clientTls = tls(config.clientTls ?? config.tls);
42748
43210
  const clients = [];
@@ -42842,7 +43304,7 @@ async function startTravelNodeService(input) {
42842
43304
  if (JSON.stringify(Object.keys(config.initialReplica.databases).sort()) !== JSON.stringify(profile.databaseIds)) throw new Error("TRAVEL_NODE_REPLICA_NOT_READY");
42843
43305
  for (const id2 of profile.databaseIds) {
42844
43306
  const file2 = path34(config.initialReplica.databases[id2]), stat3 = lstatSync29(file2);
42845
- if (!stat3.isFile() || stat3.isSymbolicLink() || realpathSync27(file2) !== file2 || process.platform !== "win32" && (stat3.uid !== process.getuid() || stat3.mode & 63)) throw new Error("TRAVEL_NODE_PATH");
43307
+ if (!stat3.isFile() || stat3.isSymbolicLink() || realpathSync28(file2) !== file2 || process.platform !== "win32" && (stat3.uid !== process.getuid() || stat3.mode & 63)) throw new Error("TRAVEL_NODE_PATH");
42846
43308
  const db2 = new DatabaseSync37(file2, { allowExtension: id2 === "legacy" });
42847
43309
  replicaHandles.push(db2);
42848
43310
  databases[id2] = db2;
@@ -43132,12 +43594,12 @@ async function waitForPidGone(pid, timeoutMs = 5e3) {
43132
43594
  import { readFileSync as readFileSync35, existsSync as existsSync41 } from "node:fs";
43133
43595
  import { isAbsolute as isAbsolute17, resolve as resolve45 } from "node:path";
43134
43596
  import { fileURLToPath as fileURLToPath8 } from "node:url";
43135
- import { execFile as execFile4 } from "node:child_process";
43136
- import { promisify as promisify5 } from "node:util";
43597
+ import { execFile as execFile6 } from "node:child_process";
43598
+ import { promisify as promisify6 } from "node:util";
43137
43599
  import { createHash as createHash55 } from "node:crypto";
43138
43600
 
43139
43601
  // src/continuity/user-seat-resource.ts
43140
- import { spawn as spawn6 } from "node:child_process";
43602
+ import { spawn as spawn7 } from "node:child_process";
43141
43603
  import { createHash as createHash51 } from "node:crypto";
43142
43604
  import { isAbsolute as isAbsolute14, resolve as resolve42 } from "node:path";
43143
43605
  var UserSeatResource = class {
@@ -43153,7 +43615,7 @@ var UserSeatResource = class {
43153
43615
  identity;
43154
43616
  call(action, input) {
43155
43617
  return new Promise((done, reject) => {
43156
- const child = spawn6("/usr/bin/sudo", ["-n", "/usr/sbin/runuser", "-u", this.config.runAs.user, "--", this.config.runAs.node, this.config.runAs.entry, action, "--config", this.config.runAs.configFile], { stdio: ["pipe", "pipe", "pipe"] });
43618
+ const child = spawn7("/usr/bin/sudo", ["-n", "/usr/sbin/runuser", "-u", this.config.runAs.user, "--", this.config.runAs.node, this.config.runAs.entry, action, "--config", this.config.runAs.configFile], { stdio: ["pipe", "pipe", "pipe"] });
43157
43619
  const chunks = [];
43158
43620
  let bytes = 0, stderr = "";
43159
43621
  const timer = setTimeout(() => child.kill("SIGKILL"), 12e4);
@@ -43201,7 +43663,7 @@ init_key_service_store();
43201
43663
  import { DatabaseSync as DatabaseSync39 } from "node:sqlite";
43202
43664
  import { createHash as createHash52 } from "node:crypto";
43203
43665
  import { existsSync as existsSync39 } from "node:fs";
43204
- import { accessSync, constants as constants14, lstatSync as lstatSync30, readdirSync as readdirSync15, readFileSync as readFileSync33, readlinkSync, realpathSync as realpathSync28, rmSync as rmSync7 } from "node:fs";
43666
+ import { accessSync, constants as constants14, lstatSync as lstatSync30, readdirSync as readdirSync15, readFileSync as readFileSync33, readlinkSync, realpathSync as realpathSync29, rmSync as rmSync7 } from "node:fs";
43205
43667
  import { dirname as dirname27, isAbsolute as isAbsolute15, join as join71, resolve as resolve43, relative as relative15 } from "node:path";
43206
43668
  var identity = (value2) => JSON.stringify([value2.tenantId, value2.companionId, value2.seatId]);
43207
43669
  var sha11 = (value2) => createHash52("sha256").update(value2).digest("hex");
@@ -43216,7 +43678,7 @@ var LocalSeatResource = class {
43216
43678
  check() {
43217
43679
  if (!existsSync39(this.path)) return false;
43218
43680
  const stat3 = lstatSync30(this.path);
43219
- if (!stat3.isDirectory() || stat3.isSymbolicLink() || realpathSync28(this.path) !== this.path || process.platform !== "win32" && stat3.uid !== process.getuid()) throw new Error("TRAVEL_RETIREMENT_PATH");
43681
+ if (!stat3.isDirectory() || stat3.isSymbolicLink() || realpathSync29(this.path) !== this.path || process.platform !== "win32" && stat3.uid !== process.getuid()) throw new Error("TRAVEL_RETIREMENT_PATH");
43220
43682
  if (identity(JSON.parse(readPrivateFile(join71(this.path, ".travel-seat-resource.json"), 65536).toString())) !== identity(this.identity)) throw new Error("TRAVEL_RETIREMENT_IDENTITY");
43221
43683
  return true;
43222
43684
  }
@@ -43369,7 +43831,7 @@ var TravelRetirement = class {
43369
43831
 
43370
43832
  // src/continuity/local-exit.ts
43371
43833
  init_runtime_lock();
43372
- import { cpSync as cpSync2, existsSync as existsSync40, mkdirSync as mkdirSync32, readFileSync as readFileSync34, readdirSync as readdirSync16, realpathSync as realpathSync29, rmSync as rmSync8, writeFileSync as writeFileSync41 } from "node:fs";
43834
+ import { cpSync as cpSync2, existsSync as existsSync40, mkdirSync as mkdirSync32, readFileSync as readFileSync34, readdirSync as readdirSync16, realpathSync as realpathSync30, rmSync as rmSync8, writeFileSync as writeFileSync41 } from "node:fs";
43373
43835
  import { DatabaseSync as DatabaseSync41 } from "node:sqlite";
43374
43836
  import { isAbsolute as isAbsolute16, join as join72, dirname as dirname29, resolve as resolve44 } from "node:path";
43375
43837
  import { createHash as createHash54, verify as verify3 } from "node:crypto";
@@ -43476,14 +43938,14 @@ function detachReplication(directory2) {
43476
43938
  }
43477
43939
  async function createOrdinaryLocalRecovery(options) {
43478
43940
  const source = resolve44(options.stateDir), destination = resolve44(options.destination);
43479
- if (!isAbsolute16(options.destination) || source !== options.stateDir || destination !== options.destination || realpathSync29(source) !== source || destination === source || destination.startsWith(source + "/") || source.startsWith(destination + "/") || realpathSync29(dirname29(destination)) !== dirname29(destination)) throw new Error("TRAVEL_EXIT_PATH");
43941
+ if (!isAbsolute16(options.destination) || source !== options.stateDir || destination !== options.destination || realpathSync30(source) !== source || destination === source || destination.startsWith(source + "/") || source.startsWith(destination + "/") || realpathSync30(dirname29(destination)) !== dirname29(destination)) throw new Error("TRAVEL_EXIT_PATH");
43480
43942
  const activation = JSON.parse(readFileSync34(join72(source, ".travel-active.json"), "utf8")), permit = activation.permit, { signature: signature2, ...signed } = permit;
43481
43943
  if (activation.format !== "engine7-runtime-activation-v1" || identity2(activation.identity) !== identity2(options.identity) || identity2(permit) !== identity2(options.identity) || permit.nodeId !== options.localNodeId || activation.nodeId !== options.localNodeId || !verify3(null, Buffer.from(JSON.stringify(signed)), options.publicKey, Buffer.from(signature2, "base64")) || identity2(options.dedupeReceipt.identity) !== identity2(options.identity) || options.dedupeReceipt.checkpointDigest !== options.checkpointDigest || options.dedupeReceipt.deletionWatermark !== permit.deletionWatermark) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
43482
43944
  return withCheckpointLock(source, async () => {
43483
43945
  if (!options.authority || !options.principal || options.authority.publicKey !== options.publicKey) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
43484
43946
  const proof = await verifyStoppedLocalExitProof({ ...options, stateDir: source });
43485
43947
  if (existsSync40(destination)) {
43486
- if (realpathSync29(destination) !== destination) throw new Error("TRAVEL_EXIT_PATH");
43948
+ if (realpathSync30(destination) !== destination) throw new Error("TRAVEL_EXIT_PATH");
43487
43949
  let receipt2;
43488
43950
  try {
43489
43951
  receipt2 = JSON.parse(readPrivateFile(join72(destination, ".continuity/travel-exit-receipt.json"), 65536).toString());
@@ -43531,7 +43993,7 @@ async function createOrdinaryLocalRecovery(options) {
43531
43993
  // src/continuity/retirement-main.ts
43532
43994
  init_key_service_store();
43533
43995
  init_key_service_store();
43534
- var command = promisify5(execFile4);
43996
+ var command = promisify6(execFile6);
43535
43997
  var sha14 = (value2) => createHash55("sha256").update(value2).digest("hex");
43536
43998
  var path36 = (value2) => {
43537
43999
  if (typeof value2 !== "string" || !isAbsolute17(value2) || resolve45(value2) !== value2) throw new Error("TRAVEL_RETIREMENT_PATH");
@@ -43606,7 +44068,7 @@ if (process.argv[1] && /[\\/](retirement-main\.ts|travel-retire\.mjs)$/.test(fil
43606
44068
  }
43607
44069
 
43608
44070
  // src/continuity/pairing-host.ts
43609
- import { randomUUID as randomUUID23 } from "node:crypto";
44071
+ import { randomUUID as randomUUID25 } from "node:crypto";
43610
44072
  async function startInitialPairingRuntime(node, authority, digest7, assertInitial) {
43611
44073
  const started = performance.now(), trace = (phase) => {
43612
44074
  if (process.env.ENGINE7_TRAVEL_TRACE === "1") process.stderr.write("[travel-initial-runtime] " + JSON.stringify({ phase, elapsedMs: Math.round(performance.now() - started) }) + "\n");
@@ -43625,7 +44087,7 @@ async function startInitialPairingRuntime(node, authority, digest7, assertInitia
43625
44087
  }
43626
44088
  function readManagedPairingHostConfig(stateDir, binding) {
43627
44089
  const config = JSON.parse(readPrivateFile(binding.hostConfig, 65536).toString());
43628
- if (binding.version !== 1 || realpathSync30(config.stateDir) !== realpathSync30(stateDir) || JSON.stringify(binding.identity) !== JSON.stringify(config.identity)) throw new Error("TRAVEL_PAIRING_IDENTITY");
44090
+ if (binding.version !== 1 || realpathSync31(config.stateDir) !== realpathSync31(stateDir) || JSON.stringify(binding.identity) !== JSON.stringify(config.identity)) throw new Error("TRAVEL_PAIRING_IDENTITY");
43629
44091
  return config;
43630
44092
  }
43631
44093
  async function pauseInitialPairingIngress(state2, ingress, pair) {
@@ -43666,7 +44128,7 @@ function initialPairingSnapshot(options) {
43666
44128
  };
43667
44129
  }
43668
44130
  var write2 = (file2, value2) => writeFileSync42(file2, JSON.stringify(value2), { mode: 384, flush: true });
43669
- var delay2 = (ms) => new Promise((done) => setTimeout(done, ms));
44131
+ var delay3 = (ms) => new Promise((done) => setTimeout(done, ms));
43670
44132
  function rpc(url, tls2, token, body, timeout = 6e5) {
43671
44133
  return new Promise((done, reject) => {
43672
44134
  const req = request8(url, { method: "POST", ...tls2, minVersion: "TLSv1.3", headers: { Authorization: "Bearer " + token, "Content-Type": "application/json" } }, (res) => {
@@ -43692,7 +44154,7 @@ function rpc(url, tls2, token, body, timeout = 6e5) {
43692
44154
  req.end(JSON.stringify(body));
43693
44155
  });
43694
44156
  }
43695
- function startPairingRelays(material, spawnRelay = spawn7) {
44157
+ function startPairingRelays(material, spawnRelay = spawn8) {
43696
44158
  const directory2 = material.directory, ports = material.ports;
43697
44159
  let stopped = false;
43698
44160
  const lanes = [{ name: "control", forward: ["authority", "gateway", "key", "pairing", "cloudManagement", "console", "cloudApi"], reverse: ["localManagement"] }, { name: "data", forward: ["cloudData"], reverse: ["localData"] }];
@@ -43732,11 +44194,11 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
43732
44194
  if (JSON.stringify(binding.identity) !== JSON.stringify(material.identity)) throw new Error("TRAVEL_PAIRING_IDENTITY");
43733
44195
  const ownerFile = join73(directory2, "host-owner.sqlite");
43734
44196
  preparePrivateDatabase(ownerFile);
43735
- const owner = new DatabaseSync42(ownerFile);
44197
+ const owner2 = new DatabaseSync42(ownerFile);
43736
44198
  try {
43737
- owner.exec("CREATE TABLE IF NOT EXISTS owner(id INTEGER PRIMARY KEY);BEGIN IMMEDIATE");
44199
+ owner2.exec("CREATE TABLE IF NOT EXISTS owner(id INTEGER PRIMARY KEY);BEGIN IMMEDIATE");
43738
44200
  } catch {
43739
- owner.close();
44201
+ owner2.close();
43740
44202
  throw new Error("TRAVEL_PAIRING_BUSY");
43741
44203
  }
43742
44204
  const lifecycleFile = join73(directory2, "lifecycle.json");
@@ -43799,7 +44261,7 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
43799
44261
  if (!stoppedOrdinary || stopped || sourcePid() !== null) return;
43800
44262
  const log = openSync21(join73(directory2, "ordinary-resumed.log"), "a", 384);
43801
44263
  try {
43802
- const child = spawn7(process.execPath, [join73(material.engineDir, "dist/main.mjs"), "--engine-config", material.configPath], { cwd: material.stateDir, detached: true, stdio: ["ignore", log, log] });
44264
+ const child = spawn8(process.execPath, [join73(material.engineDir, "dist/main.mjs"), "--engine-config", material.configPath], { cwd: material.stateDir, detached: true, stdio: ["ignore", log, log] });
43803
44265
  await new Promise((done, reject) => {
43804
44266
  child.once("spawn", done);
43805
44267
  child.once("error", reject);
@@ -43827,7 +44289,7 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
43827
44289
  break;
43828
44290
  } catch (error) {
43829
44291
  if (attempt >= 30 || !["busy", "not_ready", "service_unavailable"].includes(error.message)) throw error;
43830
- await delay2(1e3);
44292
+ await delay3(1e3);
43831
44293
  }
43832
44294
  }
43833
44295
  lifecycle.state = "MANAGED";
@@ -43861,13 +44323,13 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
43861
44323
  save();
43862
44324
  const baselineDir = join73(directory2, "first-baseline");
43863
44325
  if (lifecycle.recapture && existsSync42(join73(baselineDir, "ready.json"))) {
43864
- renameSync12(baselineDir, join73(directory2, "unused-baseline-" + randomUUID23()));
44326
+ renameSync12(baselineDir, join73(directory2, "unused-baseline-" + randomUUID25()));
43865
44327
  delete lifecycle.recapture;
43866
44328
  save();
43867
44329
  }
43868
44330
  let baseline;
43869
44331
  if (!existsSync42(join73(baselineDir, "ready.json"))) {
43870
- if (existsSync42(baselineDir)) renameSync12(baselineDir, join73(directory2, "failed-baseline-" + randomUUID23()));
44332
+ if (existsSync42(baselineDir)) renameSync12(baselineDir, join73(directory2, "failed-baseline-" + randomUUID25()));
43871
44333
  const key3 = readPrivateFile(join73(directory2, "data.key"), 32);
43872
44334
  let lastProgressSave = 0, lastPhase = "";
43873
44335
  try {
@@ -43910,7 +44372,7 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
43910
44372
  if (current2.activeNodeId !== null) {
43911
44373
  for (let attempt = 0; !(await authority.status()).expired; attempt++) {
43912
44374
  if (attempt >= 120) throw new Error("TRAVEL_INITIAL_SOURCE_RUNNING");
43913
- await delay2(500);
44375
+ await delay3(500);
43914
44376
  }
43915
44377
  }
43916
44378
  await startInitialPairingRuntime(localService.node, { acquire: (ready) => {
@@ -43937,8 +44399,8 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
43937
44399
  save();
43938
44400
  process.stderr.write(JSON.stringify({ state: lifecycle.state, ...failure2, stack: error instanceof Error ? error.stack?.split("\n").slice(1, 7) : [] }) + "\n");
43939
44401
  };
43940
- const startInitial = (requestId) => {
43941
- if (requestId !== lifecycle.requestId) throw new Error("invalid_request");
44402
+ const startInitial = (requestId2) => {
44403
+ if (requestId2 !== lifecycle.requestId) throw new Error("invalid_request");
43942
44404
  if (!pendingInitial) return;
43943
44405
  pendingInitial = false;
43944
44406
  initial ??= initialize2().catch(recordInitialFailure).finally(() => {
@@ -43981,14 +44443,14 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
43981
44443
  lifecycle.automatic = action === "auto_on";
43982
44444
  save();
43983
44445
  } else if (action === "to_cloud" || action === "sync") {
43984
- const target = action === "sync" ? "local" : "cloud", requestId = action === "sync" ? lifecycle.requestId ?? randomUUID23() : payload?.requestId;
43985
- if (!requestId || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(requestId)) throw new Error("invalid_request");
43986
- if (lifecycle.requestId && (lifecycle.requestId !== requestId || (lifecycle.target ?? "cloud") !== target)) throw new Error("busy");
44446
+ const target = action === "sync" ? "local" : "cloud", requestId2 = action === "sync" ? lifecycle.requestId ?? randomUUID25() : payload?.requestId;
44447
+ if (!requestId2 || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(requestId2)) throw new Error("invalid_request");
44448
+ if (lifecycle.requestId && (lifecycle.requestId !== requestId2 || (lifecycle.target ?? "cloud") !== target)) throw new Error("busy");
43987
44449
  if (!lifecycle.requestId) {
43988
44450
  lifecycle.state = "STARTING";
43989
44451
  lifecycle.startedAt = Date.now();
43990
44452
  }
43991
- lifecycle.requestId = requestId;
44453
+ lifecycle.requestId = requestId2;
43992
44454
  lifecycle.target = target;
43993
44455
  delete lifecycle.error;
43994
44456
  save();
@@ -44007,7 +44469,7 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
44007
44469
  break;
44008
44470
  } catch (error) {
44009
44471
  if (attempt >= 20) throw error;
44010
- await delay2(500);
44472
+ await delay3(500);
44011
44473
  }
44012
44474
  }
44013
44475
  if (lifecycle.state === "PAIRED") await pauseInitialPairingIngress(lifecycle.state, gatewayIngress, pair);
@@ -44015,7 +44477,7 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
44015
44477
  for (let attempt = 0; ; attempt++) {
44016
44478
  if ((await cloudClient.observe()).connected) break;
44017
44479
  if (attempt >= 30) throw new Error("TRAVEL_PAIRING_HEALTH");
44018
- await delay2(500);
44480
+ await delay3(500);
44019
44481
  }
44020
44482
  hostServer = createTravelConsoleServer({ manager: { execute }, identity: material.identity, token: consoleToken, startInitial, cert: readFileSync36(join73(directory2, "tls/local-server.pem")), key: readPrivateFile(join73(directory2, "tls/local-server.key"), 65536) });
44021
44483
  await new Promise((done, reject) => {
@@ -44052,7 +44514,7 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
44052
44514
  localClient.close();
44053
44515
  cloudClient.close();
44054
44516
  authority.close();
44055
- owner.close();
44517
+ owner2.close();
44056
44518
  tls2.key.fill(0);
44057
44519
  }
44058
44520
  };
@@ -44067,7 +44529,7 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
44067
44529
  localClient.close();
44068
44530
  cloudClient.close();
44069
44531
  authority.close();
44070
- owner.close();
44532
+ owner2.close();
44071
44533
  tls2.key.fill(0);
44072
44534
  }
44073
44535
  throw error;