engine7 7.1.149 → 7.1.150

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.
@@ -5334,7 +5334,7 @@ var init_recovery_deletion = __esm({
5334
5334
  add(table, row) {
5335
5335
  this.affected = void 0;
5336
5336
  const { owners, parents } = this.links(table, row);
5337
- for (const parent of parents) for (const owner of owners) this.edge(parent, owner);
5337
+ for (const parent of parents) for (const owner2 of owners) this.edge(parent, owner2);
5338
5338
  if (table === "memory_artifact_publications") {
5339
5339
  const medium = text(row, "medium"), path37 = text(row, "path"), physicalId = text(row, "physical_id"), kind = text(row, "kind");
5340
5340
  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 +8112,8 @@ function attachmentToMessage(attachment) {
8112
8112
  ${attachment.notifications.join("\n\n")}`
8113
8113
  )
8114
8114
  };
8115
+ case "coldstart_hint":
8116
+ return { role: "user", content: wrapInSystemReminder(attachment.text) };
8115
8117
  case "teammate_messages": {
8116
8118
  const lines = attachment.messages.map(
8117
8119
  (m) => m.summary ? `[From: ${m.from}] ${m.summary}
@@ -12002,11 +12004,11 @@ ${e.outcome}
12002
12004
  const out = [];
12003
12005
  const usersDir = join16(this.root, "users");
12004
12006
  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");
12007
+ for (const owner2 of readdirSync2(usersDir, { withFileTypes: true })) {
12008
+ if (!owner2.isDirectory()) continue;
12009
+ if (scope && owner2.name !== scope.ownerId) continue;
12010
+ if (!scope && this.tombstones.anyForOwner(owner2.name)) continue;
12011
+ const dir = join16(usersDir, owner2.name, ".foresights");
12010
12012
  if (!existsSync6(dir)) continue;
12011
12013
  for (const f of readdirSync2(dir)) {
12012
12014
  if (!/^foresight-\d{4}-\d{2}-\d{2}\.md$/.test(f)) continue;
@@ -12030,7 +12032,7 @@ ${e.outcome}
12030
12032
  if (!end || !start || !text2) continue;
12031
12033
  if (end < today) continue;
12032
12034
  out.push({
12033
- ownerId: owner.name,
12035
+ ownerId: owner2.name,
12034
12036
  ...scope ? { entryId, version: this.dependencies.version(scope, "foresight", entryId) } : {},
12035
12037
  startDate: start,
12036
12038
  endDate: end,
@@ -13608,10 +13610,10 @@ function projectReadSnapshots(messages, context, options = {}) {
13608
13610
  const returned = new Set(messages.flatMap((m) => "role" in m && m.role === "tool" && m.tool_call_id ? [m.tool_call_id] : []));
13609
13611
  const protectedImage = unobservedImageIndex(messages);
13610
13612
  let turnStart = 0;
13611
- let finished = false;
13613
+ let finished2 = false;
13612
13614
  let unresolved = false;
13613
13615
  const finishTurn = (end) => {
13614
- if ((finished || options.includeLastTurn) && !unresolved) completed.fill(1, turnStart, end);
13616
+ if ((finished2 || options.includeLastTurn) && !unresolved) completed.fill(1, turnStart, end);
13615
13617
  };
13616
13618
  for (let i = 0; i < messages.length; i++) {
13617
13619
  const message = messages[i];
@@ -13619,9 +13621,9 @@ function projectReadSnapshots(messages, context, options = {}) {
13619
13621
  if (message.role === "user") {
13620
13622
  finishTurn(i);
13621
13623
  turnStart = i;
13622
- finished = false;
13624
+ finished2 = false;
13623
13625
  unresolved = false;
13624
- } else if (message.role === "assistant" && !message.tool_calls?.length && message.content) finished = true;
13626
+ } else if (message.role === "assistant" && !message.tool_calls?.length && message.content) finished2 = true;
13625
13627
  if (message.tool_calls?.some((call) => !returned.has(call.id))) unresolved = true;
13626
13628
  }
13627
13629
  finishTurn(messages.length);
@@ -14811,6 +14813,251 @@ ${filenames.join("\n")}${truncatedNote}`
14811
14813
  }
14812
14814
  });
14813
14815
 
14816
+ // src/tools/cc-ask-jobs.ts
14817
+ import { randomUUID as randomUUID12 } from "node:crypto";
14818
+ async function runCcAskJob(options) {
14819
+ const { ctx, target, mode, timeoutMs, signal, run, stop } = options;
14820
+ if (signal?.aborted) return { content: "CC \u8BF7\u6C42\u5DF2\u53D6\u6D88\uFF0C\u5C1A\u672A\u6295\u9012\u3002", isError: true };
14821
+ const jobId = randomUUID12();
14822
+ const job = { owner: owner(ctx), target, status: "accepted", stop: () => stop(jobId) };
14823
+ const transport = new AbortController();
14824
+ 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);
14825
+ let accept;
14826
+ let rejectAcceptance;
14827
+ const accepted = new Promise((resolve47, reject) => {
14828
+ accept = resolve47;
14829
+ rejectAcceptance = reject;
14830
+ });
14831
+ const onAccepted = () => {
14832
+ clearTimeout(timer);
14833
+ jobs.set(jobId, job);
14834
+ accept();
14835
+ };
14836
+ const result = Promise.resolve().then(() => run({ jobId, onAccepted }, transport.signal)).catch((error) => {
14837
+ rejectAcceptance(error);
14838
+ return { content: `CC \u6295\u9012\u6216\u7ED3\u679C\u8BFB\u53D6\u5931\u8D25\uFF1A${describeError(error)}`, isError: true };
14839
+ }).then((output) => {
14840
+ clearTimeout(timer);
14841
+ if (!jobs.has(jobId)) rejectAcceptance(new Error(output.isError ? output.content : "CC \u672A\u786E\u8BA4\u4EFB\u52A1\u5165\u961F\u3002"));
14842
+ else {
14843
+ job.status = output.isError ? job.status === "stopping" ? "stopped" : "failed" : "completed";
14844
+ job.result = output;
14845
+ job.stop = void 0;
14846
+ finished.add(jobId);
14847
+ if (finished.size > MAX_FINISHED) {
14848
+ const oldest = finished.values().next().value;
14849
+ jobs.delete(oldest);
14850
+ finished.delete(oldest);
14851
+ }
14852
+ }
14853
+ return output;
14854
+ });
14855
+ try {
14856
+ await accepted;
14857
+ } catch (error) {
14858
+ return { content: describeError(error), isError: true };
14859
+ }
14860
+ const receipt2 = (status) => ({
14861
+ content: JSON.stringify({ jobId, status, target: target.key, workDir: target.workDir, sessionId: target.sessionId }),
14862
+ isError: false
14863
+ });
14864
+ if (mode === "async") return receipt2("accepted");
14865
+ const waitSignals = [signal, ctx.yieldSignal].filter((item) => !!item);
14866
+ let endWait;
14867
+ const waiting = new Promise((resolve47) => {
14868
+ endWait = resolve47;
14869
+ });
14870
+ const cancelWait = () => {
14871
+ if (signal?.aborted && signal.reason !== "interrupt") {
14872
+ endWait(requestStop(jobId, job));
14873
+ } else {
14874
+ endWait(receipt2("waiting_yielded"));
14875
+ }
14876
+ };
14877
+ if (waitSignals.some((item) => item.aborted)) cancelWait();
14878
+ else for (const item of waitSignals) item.addEventListener("abort", cancelWait, { once: true });
14879
+ const waitTimer = timeoutMs > 0 ? setTimeout(() => endWait(receipt2("waiting_timed_out")), timeoutMs) : void 0;
14880
+ try {
14881
+ return await Promise.race([result, waiting]);
14882
+ } finally {
14883
+ clearTimeout(waitTimer);
14884
+ for (const item of waitSignals) item.removeEventListener("abort", cancelWait);
14885
+ }
14886
+ }
14887
+ function jobFor(id2, ctx) {
14888
+ const job = typeof id2 === "string" ? jobs.get(id2) : void 0;
14889
+ return job?.owner === owner(ctx) ? job : void 0;
14890
+ }
14891
+ function ccAskJobProgress(id2, ctx, readSession) {
14892
+ const job = jobFor(id2, ctx);
14893
+ if (!job) return { content: "\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u627E\u5230\u8FD9\u4E2A CC \u4EFB\u52A1\u3002", isError: true };
14894
+ const sessionRecent = job.stop ? readSession(job.target) : void 0;
14895
+ return { content: JSON.stringify({
14896
+ jobId: id2,
14897
+ target: job.target.key,
14898
+ workDir: job.target.workDir,
14899
+ sessionId: job.target.sessionId,
14900
+ status: job.status,
14901
+ sessionRecent,
14902
+ result: job.result?.content
14903
+ }) };
14904
+ }
14905
+ async function requestStop(id2, job) {
14906
+ if (!job.stop || job.status === "stopping") return { content: JSON.stringify({ jobId: id2, status: job.status }) };
14907
+ job.status = "stopping";
14908
+ try {
14909
+ if (await job.stop()) return { content: JSON.stringify({ jobId: id2, status: "stop_requested" }), isError: false };
14910
+ if (job.status === "stopping") job.status = "accepted";
14911
+ if (!job.stop) return { content: JSON.stringify({ jobId: id2, status: job.status }) };
14912
+ return { content: `CC \u672A\u786E\u8BA4\u505C\u6B62\u4EFB\u52A1 ${id2}\uFF0C\u53EF\u7528 cc_progress({jobId}) \u67E5\u770B\u3002`, isError: true };
14913
+ } catch (error) {
14914
+ if (job.status === "stopping") job.status = "accepted";
14915
+ return { content: `\u505C\u6B62 CC \u5931\u8D25\uFF1A${describeError(error)}`, isError: true };
14916
+ }
14917
+ }
14918
+ async function stopCcAskJob(id2, ctx) {
14919
+ const job = jobFor(id2, ctx);
14920
+ return job ? requestStop(String(id2), job) : { content: "\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u627E\u5230\u8FD9\u4E2A CC \u4EFB\u52A1\u3002", isError: true };
14921
+ }
14922
+ var jobs, finished, MAX_FINISHED, ACCEPT_TIMEOUT_MS, owner, describeError;
14923
+ var init_cc_ask_jobs = __esm({
14924
+ "src/tools/cc-ask-jobs.ts"() {
14925
+ "use strict";
14926
+ jobs = /* @__PURE__ */ new Map();
14927
+ finished = /* @__PURE__ */ new Set();
14928
+ MAX_FINISHED = 100;
14929
+ ACCEPT_TIMEOUT_MS = 1e4;
14930
+ owner = (ctx) => JSON.stringify([ctx.stateDir || ctx.workspace, ctx.sessionId || ctx.channel]);
14931
+ describeError = (error) => error instanceof Error ? error.message : String(error);
14932
+ }
14933
+ });
14934
+
14935
+ // src/cc-driver/peer-tunnel.ts
14936
+ import { execFile as execFile3, spawn } from "node:child_process";
14937
+ import { promisify as promisify3 } from "node:util";
14938
+ var exec2, validSshHost;
14939
+ var init_peer_tunnel = __esm({
14940
+ "src/cc-driver/peer-tunnel.ts"() {
14941
+ "use strict";
14942
+ exec2 = promisify3(execFile3);
14943
+ validSshHost = (name) => typeof name === "string" && /^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,62}$/.test(name);
14944
+ }
14945
+ });
14946
+
14947
+ // src/tools/cc-peer.ts
14948
+ import { execFile as execFile4 } from "node:child_process";
14949
+ import { randomUUID as randomUUID13 } from "node:crypto";
14950
+ import { setTimeout as delay2 } from "node:timers/promises";
14951
+ function resolvePeer(alias) {
14952
+ const targets = peerConfig()?.targets;
14953
+ if (!validAlias(alias) || !targets || !Object.hasOwn(targets, alias) || !validSshHost(targets[alias])) {
14954
+ throw new Error(`\u8FDC\u7A0B CC \u76EE\u6807\u672A\u914D\u7F6E\uFF1A${alias}`);
14955
+ }
14956
+ return { alias, host: targets[alias] };
14957
+ }
14958
+ function selectCcPeer(target, useDefault = true) {
14959
+ if (typeof target === "string" && target.startsWith("remote:")) return resolvePeer(target.slice(7));
14960
+ const configured = peerConfig()?.default;
14961
+ if (!target && useDefault && configured) return resolvePeer(configured);
14962
+ return void 0;
14963
+ }
14964
+ function parsePeerJob(id2) {
14965
+ if (typeof id2 !== "string" || !id2.startsWith("remote:")) return void 0;
14966
+ const [alias, jobId, extra] = id2.slice(7).split(":");
14967
+ if (extra !== void 0 || !jobId) throw new Error("\u8FDC\u7A0B CC \u4EFB\u52A1 ID \u65E0\u6548");
14968
+ return { peer: resolvePeer(alias), jobId };
14969
+ }
14970
+ function callPeer(peer, ctx, input, signal) {
14971
+ return new Promise((resolve47, reject) => {
14972
+ const child = execFile4("/usr/bin/ssh", [
14973
+ "-T",
14974
+ "-o",
14975
+ "BatchMode=yes",
14976
+ "-o",
14977
+ "ConnectTimeout=4",
14978
+ "-o",
14979
+ "StrictHostKeyChecking=yes",
14980
+ "-o",
14981
+ "ClearAllForwardings=yes",
14982
+ peer.host,
14983
+ "cc-peer"
14984
+ ], { timeout: 8e3, maxBuffer: 160 * 1024, signal }, (error, stdout) => {
14985
+ if (error) {
14986
+ reject(new Error("\u8FDC\u7A0B CC \u94FE\u8DEF\u4E0D\u53EF\u7528\u6216\u672A\u786E\u8BA4\u56DE\u6267"));
14987
+ return;
14988
+ }
14989
+ try {
14990
+ const reply = JSON.parse(stdout);
14991
+ if (!reply || typeof reply !== "object") throw new Error("\u8FDC\u7A0B CC \u56DE\u6267\u683C\u5F0F\u65E0\u6548");
14992
+ if (reply.error) throw new Error(reply.error);
14993
+ resolve47(reply);
14994
+ } catch (cause) {
14995
+ reject(cause);
14996
+ }
14997
+ });
14998
+ child.stdin?.on("error", () => {
14999
+ });
15000
+ child.stdin?.end(JSON.stringify({ ...input, conversation: String(ctx.sessionId ?? ctx.channel ?? "default") }));
15001
+ });
15002
+ }
15003
+ async function askRemoteCc(peer, args, ctx, timeoutMs, signal) {
15004
+ const id2 = requestId(args.requestId);
15005
+ let receipt2;
15006
+ try {
15007
+ receipt2 = await callPeer(peer, ctx, { op: "submit", prompt: args.prompt, workDir: args.workDir, requestId: id2 }, signal);
15008
+ } catch (error) {
15009
+ 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 };
15010
+ }
15011
+ if (args.mode === "async" || !receipt2.jobId || !["accepted", "running", "stopping"].includes(receipt2.status ?? "")) return format(peer, receipt2);
15012
+ const deadline = timeoutMs > 0 ? AbortSignal.timeout(Math.min(Math.ceil(timeoutMs), 2147483647)) : void 0;
15013
+ const wait = AbortSignal.any([deadline, signal, ctx.yieldSignal].filter((item) => !!item));
15014
+ try {
15015
+ while (true) {
15016
+ await delay2(2e3, void 0, { signal: wait });
15017
+ const update = await callPeer(peer, ctx, { op: "progress", jobId: receipt2.jobId, includeTranscript: false }, wait);
15018
+ if (update.status === "completed") return { content: update.result || "" };
15019
+ if (!["accepted", "running", "stopping"].includes(update.status ?? "")) return format(peer, update);
15020
+ }
15021
+ } catch {
15022
+ return format(peer, { ...receipt2, status: deadline?.aborted ? "waiting_timed_out" : wait.aborted ? "waiting_yielded" : "waiting_disconnected" });
15023
+ }
15024
+ }
15025
+ async function observeRemoteCc(op, args, ctx, signal) {
15026
+ try {
15027
+ const job = parsePeerJob(args.jobId);
15028
+ if (job) return format(job.peer, await callPeer(job.peer, ctx, { op, jobId: job.jobId }, signal));
15029
+ if (op !== "progress" || args.jobId !== void 0) return void 0;
15030
+ const peer = selectCcPeer(args.target, !args.workDir && args.view !== "sessions");
15031
+ return peer ? format(peer, await callPeer(peer, ctx, { op }, signal)) : void 0;
15032
+ } catch (error) {
15033
+ return asError(error);
15034
+ }
15035
+ }
15036
+ async function newRemoteCc(peer, args, ctx, signal) {
15037
+ const id2 = requestId(args.requestId);
15038
+ try {
15039
+ return format(peer, await callPeer(peer, ctx, { op: "new", requestId: id2, workDir: args.workDir }, signal));
15040
+ } catch (error) {
15041
+ return { content: `${error.message}\u3002\u672C\u6B21 requestId ${id2}\uFF0C\u9700\u8981\u91CD\u8BD5\u65F6\u6CBF\u7528\u8BE5 ID\u3002`, isError: true };
15042
+ }
15043
+ }
15044
+ var validAlias, peerConfig, asError, format, requestId;
15045
+ var init_cc_peer = __esm({
15046
+ "src/tools/cc-peer.ts"() {
15047
+ "use strict";
15048
+ init_live();
15049
+ init_peer_tunnel();
15050
+ validAlias = (s) => /^[a-z0-9_-]{1,32}$/.test(s);
15051
+ peerConfig = () => liveConfig.get("channels.ccDriver.remoteTargets");
15052
+ asError = (error) => ({ content: error.message, isError: true });
15053
+ format = (peer, reply) => ({
15054
+ content: JSON.stringify({ ...reply, target: `remote:${peer.alias}`, ...reply.jobId ? { jobId: `remote:${peer.alias}:${reply.jobId}` } : {} }),
15055
+ isError: ["failed", "rejected", "stopped", "unknown"].includes(reply.status ?? "")
15056
+ });
15057
+ requestId = (arg) => typeof arg === "string" ? arg : `${Date.now()}:${randomUUID13()}`;
15058
+ }
15059
+ });
15060
+
14814
15061
  // src/cc-driver/project-sessions.ts
14815
15062
  import fs8 from "node:fs";
14816
15063
  import os from "node:os";
@@ -15077,15 +15324,63 @@ var init_project_sessions = __esm({
15077
15324
  }
15078
15325
  });
15079
15326
 
15327
+ // src/cc-driver/progress-transcript.ts
15328
+ function extractBlocks(content) {
15329
+ if (typeof content === "string") return [{ type: "text", text: content }];
15330
+ if (Array.isArray(content)) return content;
15331
+ return [];
15332
+ }
15333
+ function snippet(text2, max = 220) {
15334
+ const t = text2.replace(/\s+/g, " ").trim();
15335
+ return t.length > max ? t.slice(0, max) + "\u2026" : t;
15336
+ }
15337
+ function summarizeTranscript(file2) {
15338
+ const lines = tailSessionLines(file2, 65536);
15339
+ const recent = [];
15340
+ let lastTs = "";
15341
+ for (let i = lines.length - 1; i >= 0 && recent.length < 8; i--) {
15342
+ let entry;
15343
+ try {
15344
+ entry = JSON.parse(lines[i]);
15345
+ } catch {
15346
+ continue;
15347
+ }
15348
+ if (entry.type !== "user" && entry.type !== "assistant") continue;
15349
+ if (!lastTs && entry.timestamp) lastTs = entry.timestamp;
15350
+ const blocks = extractBlocks(entry.message?.content);
15351
+ for (const b of blocks) {
15352
+ if (entry.type === "user" && b.type === "text" && b.text && !b.text.includes("tool_result")) {
15353
+ recent.push(`\u{1F464} ${snippet(b.text)}`);
15354
+ } else if (entry.type === "assistant" && b.type === "text" && b.text) {
15355
+ recent.push(`\u{1F916} ${snippet(b.text)}`);
15356
+ } else if (entry.type === "assistant" && b.type === "tool_use" && b.name) {
15357
+ recent.push(`\u{1F527} ${b.name}`);
15358
+ }
15359
+ }
15360
+ }
15361
+ recent.reverse();
15362
+ return { recent, lastTs };
15363
+ }
15364
+ var init_progress_transcript = __esm({
15365
+ "src/cc-driver/progress-transcript.ts"() {
15366
+ "use strict";
15367
+ init_project_sessions();
15368
+ }
15369
+ });
15370
+
15080
15371
  // src/cc-driver/long-http.ts
15081
15372
  import { request } from "node:http";
15082
- function longPostJson(url, body, headers = {}, signal) {
15373
+ function longPostJson(url, body, headers = {}, signal, acknowledgment) {
15083
15374
  const data = Buffer.from(JSON.stringify(body));
15084
15375
  return new Promise((resolve47, reject) => {
15085
15376
  const req = request(url, { method: "POST", headers: { ...headers, "Content-Length": String(data.byteLength) } }, (res) => {
15377
+ if (acknowledgment && res.statusCode === 200 && res.headers[CC_JOB_HEADER] === acknowledgment.jobId) acknowledgment.onAccepted();
15086
15378
  const chunks = [];
15087
15379
  res.on("data", (chunk) => chunks.push(chunk));
15088
- res.on("error", reject);
15380
+ res.on("error", (err) => {
15381
+ cleanup();
15382
+ reject(err);
15383
+ });
15089
15384
  res.on("end", () => {
15090
15385
  cleanup();
15091
15386
  const text2 = Buffer.concat(chunks).toString("utf8");
@@ -15117,9 +15412,11 @@ function longPostJson(url, body, headers = {}, signal) {
15117
15412
  req.end(data);
15118
15413
  });
15119
15414
  }
15415
+ var CC_JOB_HEADER;
15120
15416
  var init_long_http = __esm({
15121
15417
  "src/cc-driver/long-http.ts"() {
15122
15418
  "use strict";
15419
+ CC_JOB_HEADER = "x-engine7-cc-job-id";
15123
15420
  }
15124
15421
  });
15125
15422
 
@@ -15173,19 +15470,31 @@ async function findDesktopTargets(workDir, sessionId) {
15173
15470
  }
15174
15471
  return targets;
15175
15472
  }
15176
- async function askDesktop(target, prompt, source, signal) {
15473
+ async function askDesktop(target, prompt, source, signal, acknowledgment) {
15474
+ const endpoint2 = acknowledgment ? "submit" : "ask";
15177
15475
  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 },
15476
+ `http://127.0.0.1:${target.port}/${endpoint2}`,
15477
+ { prompt, source, jobId: acknowledgment?.jobId, sessionId: target.sessionId, instance: target.instance, workDir: target.workDir },
15180
15478
  { authorization: `Bearer ${target.token}` },
15181
- signal
15479
+ signal,
15480
+ acknowledgment
15182
15481
  );
15183
- if (status !== 200) throw failure(result?.error || `Desktop CC HTTP ${status}`, status);
15482
+ if (status !== 200 || result?.error) throw failure(result?.error || `Desktop CC HTTP ${status}`, status);
15184
15483
  if (result.sessionId !== target.sessionId || typeof result.text !== "string" || typeof result.isError !== "boolean") {
15185
15484
  throw failure("Desktop CC returned an invalid result");
15186
15485
  }
15187
15486
  return result;
15188
15487
  }
15488
+ async function stopDesktopJob(target, jobId) {
15489
+ const { status, json } = await longPostJson(
15490
+ `http://127.0.0.1:${target.port}/stop`,
15491
+ { jobId, sessionId: target.sessionId, instance: target.instance, workDir: target.workDir },
15492
+ { authorization: `Bearer ${target.token}` },
15493
+ AbortSignal.timeout(5e3)
15494
+ );
15495
+ if (status !== 200) throw failure(json?.error || `Desktop CC HTTP ${status}`, status);
15496
+ return json?.stopped === true;
15497
+ }
15189
15498
  var registryDir, canonical3, failure, alive;
15190
15499
  var init_desktop = __esm({
15191
15500
  "src/cc-driver/desktop.ts"() {
@@ -15286,8 +15595,8 @@ var init_session_activity = __esm({
15286
15595
  import fs10 from "node:fs";
15287
15596
  import os3 from "node:os";
15288
15597
  import path12 from "node:path";
15289
- import { execFile as execFile3 } from "node:child_process";
15290
- import { promisify as promisify3 } from "node:util";
15598
+ import { execFile as execFile5 } from "node:child_process";
15599
+ import { promisify as promisify4 } from "node:util";
15291
15600
  async function listOpenCcSessions(workDir) {
15292
15601
  const configDir = process.env.CLAUDE_CONFIG_DIR || path12.join(os3.homedir(), ".claude");
15293
15602
  const dir = path12.join(configDir, "sessions");
@@ -15357,7 +15666,7 @@ var init_open_sessions = __esm({
15357
15666
  init_desktop();
15358
15667
  init_project_sessions();
15359
15668
  init_session_activity();
15360
- execFileAsync = promisify3(execFile3);
15669
+ execFileAsync = promisify4(execFile5);
15361
15670
  uuid = /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i;
15362
15671
  canonical4 = (dir) => {
15363
15672
  try {
@@ -16927,6 +17236,7 @@ var init_driver = __esm({
16927
17236
  revision = 0;
16928
17237
  idleWaiters = [];
16929
17238
  abort = null;
17239
+ activeJob;
16930
17240
  /** 当前流式 chunk 的 steer 口(仅用户消息路径开;外部 ask/桌面路径为 null) */
16931
17241
  feeder = null;
16932
17242
  sessionId = null;
@@ -16971,13 +17281,17 @@ var init_driver = __esm({
16971
17281
  void this.drain();
16972
17282
  }
16973
17283
  /** 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 };
17284
+ async ask(prompt, source, expectedSessionId, signal) {
17285
+ return this.submit(prompt, source, expectedSessionId, signal);
17286
+ }
17287
+ submit(prompt, source, expectedSessionId, signal, id2, onSession) {
17288
+ if (this.closed) throw requestError("CC binding is stopping", 503);
17289
+ if (!prompt.trim()) throw requestError("prompt is required", 400);
17290
+ if (signal?.aborted) throw requestError("CC request cancelled", 499);
17291
+ if (this.sessionId !== expectedSessionId) throw requestError("CC session changed; select the current binding again");
17292
+ if (id2 && (this.activeJob?.id === id2 || this.queue.some((job2) => job2.id === id2))) throw requestError("CC job already exists");
17293
+ if (this.queue.length >= MAX_QUEUE) throw requestError("CC queue is full", 429);
17294
+ const job = { id: id2, prompt: prompt.trim(), source, expectedSessionId, expectedRevision: id2 ? this.revision : void 0, signal, onSession };
16981
17295
  const cancel = () => {
16982
17296
  const index = this.queue.indexOf(job);
16983
17297
  if (index >= 0) {
@@ -16992,7 +17306,16 @@ var init_driver = __esm({
16992
17306
  signal?.addEventListener("abort", cancel, { once: true });
16993
17307
  void this.drain();
16994
17308
  });
16995
- return pending.finally(() => signal?.removeEventListener("abort", cancel));
17309
+ return signal ? pending.finally(() => signal.removeEventListener("abort", cancel)) : pending;
17310
+ }
17311
+ stopJob(id2) {
17312
+ const index = this.queue.findIndex((job) => job.id === id2);
17313
+ if (index >= 0) {
17314
+ this.queue.splice(index, 1)[0].reject?.(requestError("CC request cancelled (stop)", 499));
17315
+ return true;
17316
+ }
17317
+ if (this.activeJob?.id === id2) return this.activeJob.stop?.() ?? false;
17318
+ return false;
16996
17319
  }
16997
17320
  /** Reload/stop must not leave the old hub executing queued work. */
16998
17321
  shutdown() {
@@ -17018,6 +17341,9 @@ var init_driver = __esm({
17018
17341
  stop() {
17019
17342
  this.abort?.abort();
17020
17343
  }
17344
+ get queued() {
17345
+ return this.queue.length;
17346
+ }
17021
17347
  get busy() {
17022
17348
  return this.draining;
17023
17349
  }
@@ -17031,15 +17357,17 @@ var init_driver = __esm({
17031
17357
  await this.predecessor;
17032
17358
  while (!this.closed && this.queue.length > 0) {
17033
17359
  const job = this.queue.shift();
17360
+ this.activeJob = job;
17034
17361
  try {
17035
17362
  if (job.signal?.aborted) throw requestError("CC request cancelled", 499);
17036
- if (job.expectedSessionId !== void 0 && job.expectedSessionId !== this.sessionId) {
17363
+ const changed = job.expectedRevision !== void 0 ? job.expectedRevision !== this.revision : job.expectedSessionId !== void 0 && job.expectedSessionId !== this.sessionId;
17364
+ if (changed) {
17037
17365
  throw requestError("CC session changed while this request was queued");
17038
17366
  }
17039
17367
  if (job.source) {
17040
17368
  const prompt = `[cc_ask from ${job.source.replace(/[\r\n]/g, " ").slice(0, 160)}]
17041
17369
  ${job.prompt}`;
17042
- const result = await this.runTurn(prompt, job.signal, true);
17370
+ const result = await this.runTurn(prompt, job.signal, true, job);
17043
17371
  job.resolve?.(result);
17044
17372
  } else {
17045
17373
  await this.runStreaming(job);
@@ -17048,6 +17376,8 @@ ${job.prompt}`;
17048
17376
  job.reject?.(err);
17049
17377
  console.error(`[cc-driver] turn \u5931\u8D25 key=${this.key}: ${err?.stack || err}`);
17050
17378
  await this.sendText(`[cc-driver] \u8FD9\u6B21\u4EFB\u52A1\u5931\u8D25\uFF1A${err?.message || String(err)}`);
17379
+ } finally {
17380
+ this.activeJob = void 0;
17051
17381
  }
17052
17382
  }
17053
17383
  } finally {
@@ -17055,12 +17385,24 @@ ${job.prompt}`;
17055
17385
  for (const resolve47 of this.idleWaiters.splice(0)) resolve47();
17056
17386
  }
17057
17387
  }
17058
- async runTurn(prompt, signal, external = false) {
17388
+ async runTurn(prompt, signal, external = false, job) {
17059
17389
  const ac = new AbortController();
17060
17390
  this.abort = ac;
17391
+ if (job?.id) job.stop = () => {
17392
+ ac.abort();
17393
+ return true;
17394
+ };
17061
17395
  const resumedFrom = this.sessionId;
17062
17396
  const revision = this.revision;
17063
17397
  let turnSessionId = resumedFrom;
17398
+ const observeSession = (id2) => {
17399
+ try {
17400
+ job?.onSession?.(id2);
17401
+ } catch (error) {
17402
+ console.error("[cc-driver] task session update failed:", error.message);
17403
+ }
17404
+ };
17405
+ observeSession(turnSessionId);
17064
17406
  const cancel = () => ac.abort();
17065
17407
  signal?.addEventListener("abort", cancel, { once: true });
17066
17408
  if (signal?.aborted) ac.abort();
@@ -17084,13 +17426,31 @@ ${job.prompt}`;
17084
17426
  const acc = this.makeStreamAccumulator();
17085
17427
  try {
17086
17428
  const desktops = resumedFrom ? await findDesktopTargets(this.workDir, resumedFrom) : [];
17429
+ ac.signal.throwIfAborted();
17087
17430
  if (desktops.length > 1) throw new Error("Multiple desktop writers claim this CC session; close the duplicate");
17088
17431
  if (desktops[0]) {
17089
- const result2 = await askDesktop(desktops[0], prompt, this.key, ac.signal);
17432
+ const desktop = desktops[0];
17433
+ let result2;
17434
+ if (job?.id) {
17435
+ const jobId = job.id;
17436
+ let acknowledge;
17437
+ const accepted = new Promise((resolve47) => {
17438
+ acknowledge = resolve47;
17439
+ });
17440
+ job.stop = async () => await accepted && stopDesktopJob(desktop, jobId);
17441
+ try {
17442
+ result2 = await askDesktop(desktop, prompt, this.key, ac.signal, { jobId, onAccepted: () => acknowledge(true) });
17443
+ } finally {
17444
+ acknowledge(false);
17445
+ }
17446
+ } else {
17447
+ result2 = await askDesktop(desktop, prompt, this.key, ac.signal);
17448
+ }
17090
17449
  finalText = result2.text;
17091
17450
  isError = result2.isError;
17092
17451
  gotResult = true;
17093
17452
  turnSessionId = result2.sessionId;
17453
+ observeSession(turnSessionId);
17094
17454
  if (this.revision === revision) this.sessionId = result2.sessionId;
17095
17455
  } else {
17096
17456
  if (resumedFrom && nativeSessionOwners(resumedFrom).length) {
@@ -17103,6 +17463,7 @@ ${job.prompt}`;
17103
17463
  const mb = total ? `\u7EA6 ${Math.round(total / 1024 / 1024)}M` : "\u7EA6 350M";
17104
17464
  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
17465
  });
17466
+ ac.signal.throwIfAborted();
17106
17467
  const stream = query({
17107
17468
  prompt,
17108
17469
  options: {
@@ -17145,6 +17506,7 @@ ${job.prompt}`;
17145
17506
  const r = msg2;
17146
17507
  if (r.session_id) {
17147
17508
  turnSessionId = r.session_id;
17509
+ observeSession(turnSessionId);
17148
17510
  if (this.revision === revision) this.sessionId = r.session_id;
17149
17511
  }
17150
17512
  isError = r.is_error === true;
@@ -17155,6 +17517,7 @@ ${job.prompt}`;
17155
17517
  const sid = msg2.session_id;
17156
17518
  if (sid) {
17157
17519
  turnSessionId = sid;
17520
+ observeSession(turnSessionId);
17158
17521
  if (this.revision === revision) this.sessionId = sid;
17159
17522
  }
17160
17523
  } else {
@@ -17164,6 +17527,7 @@ ${job.prompt}`;
17164
17527
  }
17165
17528
  if (turnSessionId && gotResult && this.revision === revision) this.map.switchTo(this.key, turnSessionId, this.workDir);
17166
17529
  } finally {
17530
+ if (job) job.stop = void 0;
17167
17531
  this.abort = null;
17168
17532
  signal?.removeEventListener("abort", cancel);
17169
17533
  }
@@ -17589,29 +17953,32 @@ async function findBoundCcTargets(workDir, key3) {
17589
17953
  }));
17590
17954
  return lists.flat();
17591
17955
  }
17592
- async function askBoundCc(target, prompt, source, signal) {
17956
+ async function askBoundCc(target, prompt, source, signal, acknowledgment) {
17957
+ const endpoint2 = acknowledgment ? "submit" : "ask";
17593
17958
  const { status, json: result } = await longPostJson(
17594
- `http://127.0.0.1:${target.endpoint.port}/api/cc-driver/ask`,
17959
+ `http://127.0.0.1:${target.endpoint.port}/api/cc-driver/${endpoint2}`,
17595
17960
  {
17596
17961
  key: target.key,
17597
17962
  workDir: target.workDir,
17598
17963
  prompt,
17599
17964
  source,
17965
+ jobId: acknowledgment?.jobId,
17600
17966
  expectedSessionId: target.sessionId,
17601
17967
  expectedPid: target.endpoint.pid,
17602
17968
  expectedStateDir: target.endpoint.stateDir
17603
17969
  },
17604
17970
  { "x-engine-console": "1" },
17605
- signal
17971
+ signal,
17972
+ acknowledgment
17606
17973
  );
17607
- if (status !== 200) throw new Error(result?.error || `CC hub handoff failed (HTTP ${status})`);
17974
+ if (status !== 200 || result?.error) throw new Error(result?.error || `CC hub handoff failed (HTTP ${status})`);
17608
17975
  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
17976
  return result;
17610
17977
  }
17611
- async function stopBoundCc(target) {
17978
+ async function stopBoundCc(target, jobId) {
17612
17979
  const { status, json } = await longPostJson(
17613
17980
  `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 },
17981
+ { key: target.key, workDir: target.workDir, jobId, expectedPid: target.endpoint.pid, expectedStateDir: target.endpoint.stateDir },
17615
17982
  { "x-engine-console": "1" },
17616
17983
  AbortSignal.timeout(5e3)
17617
17984
  );
@@ -17720,9 +18087,9 @@ __export(router_exports, {
17720
18087
  import { existsSync as existsSync16 } from "node:fs";
17721
18088
  function autoBindHit(inbound) {
17722
18089
  if (inbound.channel !== "feishu" || inbound.channelType !== "dm") return null;
17723
- const owner = liveConfig.get("channels.feishu.ownerOpenId");
18090
+ const owner2 = liveConfig.get("channels.feishu.ownerOpenId");
17724
18091
  const workDir = liveConfig.get("channels.ccDriver.autoBind.workDir");
17725
- if (!owner || !workDir || inbound.from !== owner) return null;
18092
+ if (!owner2 || !workDir || inbound.from !== owner2) return null;
17726
18093
  const cur = liveConfig.get("channels.ccDriver");
17727
18094
  if (cur?.enabled === false) return null;
17728
18095
  if ((cur?.bindings ?? []).length > 0) return null;
@@ -17841,11 +18208,6 @@ var init_router = __esm({
17841
18208
  // src/tools/cc-progress.ts
17842
18209
  var cc_progress_exports = {};
17843
18210
  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
18211
  function fmtTime(ts) {
17850
18212
  if (!ts) return "?";
17851
18213
  const d = new Date(ts);
@@ -17855,33 +18217,44 @@ function fmtTime(ts) {
17855
18217
  if (diff < 3600) return `${Math.floor(diff / 60)}\u5206\u949F\u524D`;
17856
18218
  return d.toLocaleString("zh-CN", { hour12: false });
17857
18219
  }
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
18220
  var init_cc_progress = __esm({
17863
18221
  "src/tools/cc-progress.ts"() {
17864
18222
  "use strict";
17865
18223
  init_registry();
18224
+ init_cc_ask_jobs();
18225
+ init_cc_peer();
17866
18226
  init_project_sessions();
18227
+ init_progress_transcript();
17867
18228
  init_open_sessions();
17868
18229
  registry.register({
17869
18230
  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.`,
18231
+ 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
18232
  schema: {
17872
18233
  type: "object",
17873
18234
  properties: {
17874
18235
  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" }
18236
+ 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" },
18237
+ target: { type: "string", description: "remote:\u5DF2\u914D\u7F6E\u7684 CC \u522B\u540D\uFF0C\u7528\u4E8E\u67E5\u8FDC\u7A0B\u7ED1\u5B9A\u72B6\u6001\u3002" },
18238
+ 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
18239
  },
17877
18240
  required: []
17878
18241
  },
17879
- handler: async (args, ctx) => {
18242
+ handler: async (args, ctx, signal) => {
18243
+ const remote = await observeRemoteCc("progress", args, ctx, signal);
18244
+ if (remote) return remote;
18245
+ if (args.jobId !== void 0) return ccAskJobProgress(args.jobId, ctx, ({ workDir: workDir2, sessionId }) => {
18246
+ if (!sessionId || !/^[a-zA-Z0-9_-]+$/.test(sessionId)) return void 0;
18247
+ try {
18248
+ return summarizeTranscript(path16.join(projectDirFor(workDir2), `${sessionId}.jsonl`)).recent;
18249
+ } catch {
18250
+ return void 0;
18251
+ }
18252
+ });
17880
18253
  let workDir = typeof args.workDir === "string" && args.workDir.trim() ? args.workDir.trim() : "";
17881
18254
  if (args.view !== void 0 && !["sessions", "progress"].includes(args.view)) return { content: "view \u9700\u8981 sessions \u6216 progress\u3002", isError: true };
17882
18255
  if (args.view === "sessions" || !args.view && !workDir) {
17883
18256
  const { sessions: sessions3, warning } = await listOpenCcSessions(workDir || void 0);
17884
- const lines2 = sessions3.map((s, i) => {
18257
+ const lines = sessions3.map((s, i) => {
17885
18258
  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
18259
  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
18260
  return `${i + 1}. ${s.sessionId}
@@ -17894,7 +18267,7 @@ var init_cc_progress = __esm({
17894
18267
  return { content: [
17895
18268
  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
18269
  warning,
17897
- ...lines2,
18270
+ ...lines,
17898
18271
  "\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
18272
  ].filter(Boolean).join("\n") };
17900
18273
  }
@@ -17915,30 +18288,7 @@ ${dirs.join("\n")}`, isError: true };
17915
18288
  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
18289
  }
17917
18290
  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();
18291
+ const { recent, lastTs } = summarizeTranscript(latest.file);
17942
18292
  const idleMs = Date.now() - latest.modifiedAt;
17943
18293
  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
18294
  const out = [
@@ -17960,8 +18310,15 @@ var cc_ask_exports = {};
17960
18310
  __export(cc_ask_exports, {
17961
18311
  ccAskOnce: () => ccAskOnce
17962
18312
  });
17963
- import { existsSync as existsSync17 } from "node:fs";
18313
+ import { existsSync as existsSync17, realpathSync as realpathSync12, statSync as statSync7 } from "node:fs";
17964
18314
  import path17 from "node:path";
18315
+ async function drainStandalone(directory2, queue) {
18316
+ while (queue.length) {
18317
+ await queue[0].run();
18318
+ queue.shift();
18319
+ }
18320
+ standaloneQueues.delete(directory2);
18321
+ }
17965
18322
  async function ccAskOnce(prompt, workDir, timeoutMs = ccAskTimeoutMs()) {
17966
18323
  const { query } = await loadOptionalModule("cc-runtime");
17967
18324
  const ac = new AbortController();
@@ -17998,7 +18355,104 @@ async function ccAskOnce(prompt, workDir, timeoutMs = ccAskTimeoutMs()) {
17998
18355
  if (!resultText.trim()) return { ok: false, text: "CC \u7ED3\u675F\u4F46\u6CA1\u6709\u4EA7\u51FA\u6587\u672C" + (isError ? "\uFF08\u51FA\u9519\uFF09" : ""), sessionId };
17999
18356
  return { ok: !isError, text: resultText, sessionId };
18000
18357
  }
18001
- var CC_ASK_TIMEOUT_MS, ccAskTimeoutMs;
18358
+ async function runStandalone(args, ctx, prompt, workDir, resumeLatest, ac, onSession) {
18359
+ if (ac.signal.aborted) return standaloneStopped;
18360
+ const stateDir = typeof ctx.stateDir === "string" && ctx.stateDir ? ctx.stateDir : typeof ctx.workspace === "string" ? ctx.workspace : "";
18361
+ let store = null;
18362
+ if (stateDir) {
18363
+ try {
18364
+ store = new CcSessionMapStore(stateDir, path17.join("agents", "cc-ask", "session-map.json"));
18365
+ } catch {
18366
+ store = null;
18367
+ }
18368
+ }
18369
+ const mapKey = `ask:${String(ctx.sessionId ?? ctx.channel ?? "anon")}@${workDir}`;
18370
+ let sessionId;
18371
+ let resumedFrom = "";
18372
+ const forceNew = args.newSession === true;
18373
+ if (forceNew) {
18374
+ store?.clear(mapKey);
18375
+ } else if (resumeLatest) {
18376
+ const sessions2 = listProjectSessions(workDir, void 0, 3);
18377
+ const candidate = sessions2.find((s) => s.messageCount > 0);
18378
+ 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 };
18379
+ if (await checkActive(candidate.file, 300)) {
18380
+ 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 };
18381
+ }
18382
+ sessionId = candidate.id;
18383
+ resumedFrom = "latest";
18384
+ } else {
18385
+ const mapped = store?.get(mapKey);
18386
+ if (mapped?.sessionId) {
18387
+ const hit = listProjectSessions(workDir, void 0, 30).find((s) => s.id === mapped.sessionId);
18388
+ if (hit) {
18389
+ if (await isActiveConfirmed(hit.file, 2e3)) {
18390
+ 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 };
18391
+ }
18392
+ sessionId = mapped.sessionId;
18393
+ resumedFrom = "own";
18394
+ }
18395
+ }
18396
+ }
18397
+ if (!sessionId) {
18398
+ const sessions2 = listProjectSessions(workDir, void 0, 1);
18399
+ const latest = sessions2[0];
18400
+ if (latest && await checkActive(latest.file, 300)) {
18401
+ 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 };
18402
+ }
18403
+ }
18404
+ if (sessionId && (nativeSessionOwners(sessionId).length || (await findDesktopTargets(workDir, sessionId)).length)) {
18405
+ 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 };
18406
+ }
18407
+ if (ac.signal.aborted) return standaloneStopped;
18408
+ if (sessionId) onSession(sessionId);
18409
+ const { query } = await loadOptionalModule("cc-runtime");
18410
+ if (ac.signal.aborted) return standaloneStopped;
18411
+ let resultText = "";
18412
+ let newSessionId;
18413
+ let isError = false;
18414
+ try {
18415
+ const stream = query({
18416
+ prompt,
18417
+ options: {
18418
+ abortController: ac,
18419
+ cwd: workDir,
18420
+ permissionMode: "bypassPermissions",
18421
+ ...sessionId ? { resume: sessionId } : {},
18422
+ env: { CC_ASK_DEPTH: "1" }
18423
+ }
18424
+ });
18425
+ for await (const msg2 of stream) {
18426
+ if (msg2.parent_tool_use_id) continue;
18427
+ if (msg2.type === "system" && msg2.subtype === "init" && typeof msg2.session_id === "string") onSession(msg2.session_id);
18428
+ if (msg2.type === "result") {
18429
+ const r = msg2;
18430
+ resultText = typeof r.result === "string" ? r.result : "";
18431
+ isError = r.is_error === true;
18432
+ if (r.session_id) {
18433
+ newSessionId = r.session_id;
18434
+ onSession(r.session_id);
18435
+ }
18436
+ }
18437
+ }
18438
+ } catch (err) {
18439
+ if (ac.signal.aborted) return standaloneStopped;
18440
+ return { content: `CC \u9A71\u52A8\u5931\u8D25\uFF1A${err?.message ?? err}`, isError: true };
18441
+ }
18442
+ if (ac.signal.aborted) return standaloneStopped;
18443
+ const text2 = resultText.trim();
18444
+ if (!text2) return { content: "CC \u7ED3\u675F\u4F46\u6CA1\u6709\u4EA7\u51FA\u6587\u672C" + (isError ? "\uFF08\u51FA\u9519\uFF09" : ""), isError: true };
18445
+ if (newSessionId && store) {
18446
+ try {
18447
+ store.set(mapKey, newSessionId, workDir);
18448
+ } catch {
18449
+ }
18450
+ }
18451
+ 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` : "";
18452
+ return { content: `[CC @ ${workDir.split("/").pop()}] ${text2}${tail ? `
18453
+ ${tail}` : ""}`, isError };
18454
+ }
18455
+ var standaloneQueues, MAX_STANDALONE_QUEUE, standaloneStopped, CC_ASK_TIMEOUT_MS, ccAskTimeoutMs;
18002
18456
  var init_cc_ask = __esm({
18003
18457
  "src/tools/cc-ask.ts"() {
18004
18458
  "use strict";
@@ -18009,6 +18463,11 @@ var init_cc_ask = __esm({
18009
18463
  init_handoff();
18010
18464
  init_desktop();
18011
18465
  init_dep_downloader();
18466
+ init_cc_ask_jobs();
18467
+ init_cc_peer();
18468
+ standaloneQueues = /* @__PURE__ */ new Map();
18469
+ MAX_STANDALONE_QUEUE = 6;
18470
+ standaloneStopped = { content: "CC \u4EFB\u52A1\u5DF2\u505C\u6B62\u3002", isError: true };
18012
18471
  CC_ASK_TIMEOUT_MS = 9e5;
18013
18472
  ccAskTimeoutMs = () => {
18014
18473
  const v = Number(process.env.CC_ASK_TIMEOUT_MS);
@@ -18017,13 +18476,15 @@ var init_cc_ask = __esm({
18017
18476
  };
18018
18477
  registry.register({
18019
18478
  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.`,
18479
+ 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
18480
  schema: {
18022
18481
  type: "object",
18023
18482
  properties: {
18024
18483
  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" },
18484
+ 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
18485
  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" },
18486
+ target: { type: "string", description: "\u6307\u5B9A desktop:\u4F1A\u8BDDUUID\u3001channel:chatId \u6216 remote:\u5DF2\u914D\u7F6E\u7684\u8FDC\u7A0B CC \u522B\u540D" },
18487
+ requestId: { type: "string", description: "\u8FDC\u7A0B\u672A\u786E\u8BA4\u56DE\u6267\u65F6\u91CD\u8BD5\u53EF\u6CBF\u7528\u539F requestId\u3002" },
18027
18488
  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
18489
  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
18490
  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 +18495,8 @@ var init_cc_ask = __esm({
18034
18495
  const prompt = typeof args.prompt === "string" ? args.prompt.trim() : "";
18035
18496
  let workDir = typeof args.workDir === "string" ? args.workDir.trim() : "";
18036
18497
  const resumeLatest = args.resumeLatest === true;
18498
+ const mode = args.mode ?? "sync";
18499
+ if (mode !== "sync" && mode !== "async") return { content: "mode \u9700\u8981 sync \u6216 async\u3002", isError: true };
18037
18500
  if (!prompt) return { content: "\u9700\u8981 prompt \u53C2\u6570", isError: true };
18038
18501
  const depth = Number(process.env.CC_ASK_DEPTH ?? 0);
18039
18502
  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 +18506,15 @@ var init_cc_ask = __esm({
18043
18506
  if ((targetKey || sessionIdArg) && (args.newSession === true || resumeLatest)) {
18044
18507
  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
18508
  }
18509
+ try {
18510
+ const peer = selectCcPeer(targetKey, !sessionIdArg && args.newSession !== true && !resumeLatest);
18511
+ if (peer) {
18512
+ if (sessionIdArg) return { content: "\u8FDC\u7A0B CC \u4F7F\u7528\u76EE\u6807\u7ED1\u5B9A\u7684\u4F1A\u8BDD\u3002", isError: true };
18513
+ return await askRemoteCc(peer, { ...args, prompt }, ctx, ccAskTimeoutMs(), signal);
18514
+ }
18515
+ } catch (error) {
18516
+ return { content: error.message, isError: true };
18517
+ }
18046
18518
  if (args.newSession !== true && !resumeLatest) {
18047
18519
  try {
18048
18520
  const desktopKey = targetKey.startsWith("desktop:") ? targetKey.slice("desktop:".length) : "";
@@ -18057,51 +18529,40 @@ ${[...desktops, ...targets].map((t) => `${t.key} \u2192 ${t.workDir}`).join("\n"
18057
18529
  }
18058
18530
  if (desktops[0]) {
18059
18531
  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
18532
  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}
18533
+ console.log(`[cc-ask] desktop target=${desktop.key} pid=${desktop.pid} caller=${String(ctx.sessionId || "").slice(0, 8)}`);
18534
+ return await runCcAskJob({
18535
+ ctx,
18536
+ target: desktop,
18537
+ mode,
18538
+ timeoutMs: ccAskTimeoutMs(),
18539
+ signal,
18540
+ stop: (id2) => stopDesktopJob(desktop, id2),
18541
+ run: async (ack, transport) => {
18542
+ const result = await askDesktop(desktop, prompt, caller, transport, ack);
18543
+ return { content: `[CC @ ${path17.basename(desktop.workDir)}] ${result.text}
18069
18544
  \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
- }
18545
+ }
18546
+ });
18076
18547
  }
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;
18548
+ const target2 = targets[0];
18549
+ if (target2) {
18083
18550
  const caller = String(ctx.agentName || registry.config?.mem7?.agentName || registry.config?.everos?.agentName || "agent");
18084
18551
  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 };
18552
+ 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)}`);
18553
+ return await runCcAskJob({
18554
+ ctx,
18555
+ target: target2,
18556
+ mode,
18557
+ timeoutMs: ccAskTimeoutMs(),
18558
+ signal,
18559
+ stop: (id2) => stopBoundCc(target2, id2),
18560
+ run: async (ack, transport) => {
18561
+ const result = await askBoundCc(target2, prompt, source, transport, ack);
18562
+ return { content: `[CC @ ${path17.basename(target2.workDir)}] ${result.text}
18563
+ \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
18564
  }
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
- }
18565
+ });
18105
18566
  }
18106
18567
  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
18568
  if (ccDriverRouter.hub?.bindings.some((b) => !workDir || b.workDir === workDir)) {
@@ -18119,107 +18580,88 @@ ${[...desktops, ...targets].map((t) => `${t.key} \u2192 ${t.workDir}`).join("\n"
18119
18580
  ${dirs.join("\n")}`, isError: true };
18120
18581
  }
18121
18582
  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
- }
18583
+ const recent = listCcProjects().find((project) => project.workDir && existsSync17(project.workDir))?.workDir;
18584
+ 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 };
18585
+ workDir = recent;
18162
18586
  }
18163
18587
  }
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;
18588
+ let directory2;
18183
18589
  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 };
18590
+ directory2 = realpathSync12(workDir);
18591
+ if (!statSync7(directory2).isDirectory()) throw new Error("not a directory");
18592
+ } catch {
18593
+ return { content: `CC \u5DE5\u4F5C\u76EE\u5F55\u4E0D\u53EF\u7528\uFF1A${workDir}`, isError: true };
18211
18594
  }
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 {
18595
+ const controller = new AbortController();
18596
+ const target = { key: directory2, workDir, sessionId: null };
18597
+ let queued;
18598
+ return runCcAskJob({
18599
+ ctx,
18600
+ target,
18601
+ mode,
18602
+ timeoutMs: ccAskTimeoutMs(),
18603
+ signal,
18604
+ stop: () => {
18605
+ controller.abort();
18606
+ const queue = standaloneQueues.get(directory2);
18607
+ const index = queue?.indexOf(queued) ?? -1;
18608
+ if (index > 0) queue.splice(index, 1)[0].finish(standaloneStopped);
18609
+ return index >= 0;
18610
+ },
18611
+ run: async (ack) => {
18612
+ const queue = standaloneQueues.get(directory2) ?? [];
18613
+ if (queue.length >= MAX_STANDALONE_QUEUE) throw new Error("CC \u9879\u76EE\u961F\u5217\u5DF2\u6EE1\u3002");
18614
+ const pending = new Promise((finish, reject) => {
18615
+ queued = { finish, run: async () => {
18616
+ try {
18617
+ finish(await runStandalone(args, ctx, prompt, workDir, resumeLatest, controller, (id2) => {
18618
+ target.sessionId = id2;
18619
+ }));
18620
+ } catch (error) {
18621
+ reject(error);
18622
+ }
18623
+ } };
18624
+ queue.push(queued);
18625
+ });
18626
+ ack.onAccepted();
18627
+ if (queue.length === 1) {
18628
+ standaloneQueues.set(directory2, queue);
18629
+ void Promise.resolve().then(() => drainStandalone(directory2, queue));
18630
+ }
18631
+ return pending;
18218
18632
  }
18633
+ });
18634
+ }
18635
+ });
18636
+ registry.register({
18637
+ name: "cc_stop",
18638
+ description: "Explicitly stop one CC task from a cc_ask receipt by jobId. Removes that task if queued or interrupts it if running.",
18639
+ schema: {
18640
+ type: "object",
18641
+ properties: { jobId: { type: "string", description: "Job ID from the cc_ask receipt." } },
18642
+ required: ["jobId"]
18643
+ },
18644
+ handler: async (args, ctx, signal) => await observeRemoteCc("stop", args, ctx, signal) ?? stopCcAskJob(args.jobId, ctx)
18645
+ });
18646
+ registry.register({
18647
+ name: "cc_new",
18648
+ description: "Start a new conversation at the configured remote CC binding. The next CC message starts the new session.",
18649
+ schema: {
18650
+ type: "object",
18651
+ properties: {
18652
+ target: { type: "string", description: "remote:\u5DF2\u914D\u7F6E\u7684 CC \u522B\u540D\u3002\u7701\u7565\u4F7F\u7528\u9ED8\u8BA4\u76EE\u6807\u3002" },
18653
+ requestId: { type: "string", description: "\u672A\u786E\u8BA4\u56DE\u6267\u65F6\u91CD\u8BD5\u53EF\u4EE5\u6CBF\u7528\u539F requestId\u3002" }
18654
+ },
18655
+ required: []
18656
+ },
18657
+ handler: async (args, ctx, signal) => {
18658
+ try {
18659
+ const peer = selectCcPeer(args.target);
18660
+ if (peer) return await newRemoteCc(peer, args, ctx, signal);
18661
+ return { content: "\u672C\u673A\u7ED1\u5B9A\u4F1A\u8BDD\u53EF\u4EE5\u5728\u5BF9\u5E94\u804A\u5929\u8F93\u5165 /cc-new\u3002", isError: true };
18662
+ } catch (error) {
18663
+ return { content: error.message, isError: true };
18219
18664
  }
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
18665
  }
18224
18666
  });
18225
18667
  }
@@ -18256,7 +18698,7 @@ CREATE INDEX idx_calendar_dispatch_scope ON calendar_dispatches(scope_id,event_i
18256
18698
  // src/continuity/sqlite-write-capture.ts
18257
18699
  function installSQLiteWriteCapture(db2, source) {
18258
18700
  if (db2.isTransaction) throw new Error("REPLICATION_TRANSACTION_ALREADY_OPEN");
18259
- const exec3 = db2.exec, prepare = db2.prepare;
18701
+ const exec4 = db2.exec, prepare = db2.prepare;
18260
18702
  let active, failed = false, closed = false, reading = false;
18261
18703
  let direct2;
18262
18704
  const check = () => {
@@ -18267,13 +18709,13 @@ function installSQLiteWriteCapture(db2, source) {
18267
18709
  check();
18268
18710
  const command2 = sql.trim().replace(/;$/, "").trim().toUpperCase();
18269
18711
  if (command2 === "BEGIN IMMEDIATE" || command2 === "BEGIN IMMEDIATE TRANSACTION") {
18270
- exec3.call(db2, sql);
18712
+ exec4.call(db2, sql);
18271
18713
  try {
18272
18714
  active = source.beginCapture();
18273
18715
  failed = false;
18274
18716
  reading = false;
18275
18717
  } catch (error) {
18276
- exec3.call(db2, "ROLLBACK");
18718
+ exec4.call(db2, "ROLLBACK");
18277
18719
  throw error;
18278
18720
  }
18279
18721
  return;
@@ -18282,13 +18724,13 @@ function installSQLiteWriteCapture(db2, source) {
18282
18724
  if (failed) throw new Error("REPLICATION_TRANSACTION_FAILED");
18283
18725
  if (!active) {
18284
18726
  if (!reading) throw new Error("REPLICATION_SQL_FORM_UNSUPPORTED");
18285
- exec3.call(db2, sql);
18727
+ exec4.call(db2, sql);
18286
18728
  reading = false;
18287
18729
  return;
18288
18730
  }
18289
18731
  try {
18290
18732
  source.appendCapture(active);
18291
- exec3.call(db2, sql);
18733
+ exec4.call(db2, sql);
18292
18734
  source.endCapture(active);
18293
18735
  active = void 0;
18294
18736
  } catch (error) {
@@ -18299,7 +18741,7 @@ function installSQLiteWriteCapture(db2, source) {
18299
18741
  }
18300
18742
  if (command2 === "ROLLBACK" || command2 === "ROLLBACK TRANSACTION") {
18301
18743
  try {
18302
- exec3.call(db2, sql);
18744
+ exec4.call(db2, sql);
18303
18745
  } finally {
18304
18746
  if (!db2.isTransaction) reading = false;
18305
18747
  if (active && !db2.isTransaction) {
@@ -18311,12 +18753,12 @@ function installSQLiteWriteCapture(db2, source) {
18311
18753
  return;
18312
18754
  }
18313
18755
  if (command2 === "BEGIN" || command2 === "BEGIN TRANSACTION" || command2 === "BEGIN DEFERRED" || command2 === "BEGIN DEFERRED TRANSACTION") {
18314
- exec3.call(db2, sql);
18756
+ exec4.call(db2, sql);
18315
18757
  reading = true;
18316
18758
  return;
18317
18759
  }
18318
18760
  if (/^(?:SAVEPOINT|RELEASE(?: SAVEPOINT)?|ROLLBACK TO(?: SAVEPOINT)?) [A-Z_][A-Z0-9_]*$/.test(command2) && db2.isTransaction && !failed) {
18319
- exec3.call(db2, sql);
18761
+ exec4.call(db2, sql);
18320
18762
  return;
18321
18763
  }
18322
18764
  throw new Error("REPLICATION_SQL_FORM_UNSUPPORTED");
@@ -18352,13 +18794,13 @@ function installSQLiteWriteCapture(db2, source) {
18352
18794
  close() {
18353
18795
  if (closed) return;
18354
18796
  if (active) {
18355
- if (db2.isTransaction) exec3.call(db2, "ROLLBACK");
18797
+ if (db2.isTransaction) exec4.call(db2, "ROLLBACK");
18356
18798
  source.endCapture(active);
18357
18799
  active = void 0;
18358
18800
  }
18359
18801
  direct2.close();
18360
18802
  db2.prepare = prepare;
18361
- db2.exec = exec3;
18803
+ db2.exec = exec4;
18362
18804
  closed = true;
18363
18805
  }
18364
18806
  };
@@ -18762,14 +19204,14 @@ var init_notification_state = __esm({
18762
19204
 
18763
19205
  // src/travel/chunk-store.ts
18764
19206
  import { gunzipSync as gunzipSync2, gzip as gzip2 } from "node:zlib";
18765
- import { promisify as promisify4 } from "node:util";
19207
+ import { promisify as promisify5 } from "node:util";
18766
19208
  var CHUNK_BYTES2, DATABASE_CHUNK_BYTES, compress2;
18767
19209
  var init_chunk_store = __esm({
18768
19210
  "src/travel/chunk-store.ts"() {
18769
19211
  "use strict";
18770
19212
  CHUNK_BYTES2 = 4 * 1024 * 1024;
18771
19213
  DATABASE_CHUNK_BYTES = 64 * 1024;
18772
- compress2 = promisify4(gzip2);
19214
+ compress2 = promisify5(gzip2);
18773
19215
  }
18774
19216
  });
18775
19217
 
@@ -18870,7 +19312,7 @@ var init_host_turn = __esm({
18870
19312
 
18871
19313
  // src/tools/task-manager.ts
18872
19314
  import { randomBytes as randomBytes2 } from "node:crypto";
18873
- import { spawn } from "node:child_process";
19315
+ import { spawn as spawn2 } from "node:child_process";
18874
19316
  import * as fs15 from "node:fs";
18875
19317
  import * as path19 from "node:path";
18876
19318
  function generateTaskId(type = "local_bash") {
@@ -19123,7 +19565,7 @@ function spawnBackgroundTask(opts) {
19123
19565
  const outputPath = initTaskOutput(taskId);
19124
19566
  const { shell, args: shellArgs } = findShell();
19125
19567
  const outputFd = fs15.openSync(outputPath, "w");
19126
- const child = spawn(shell, [...shellArgs, opts.command], {
19568
+ const child = spawn2(shell, [...shellArgs, opts.command], {
19127
19569
  cwd: opts.cwd,
19128
19570
  env: opts.env || process.env,
19129
19571
  stdio: ["ignore", outputFd, outputFd],
@@ -19187,10 +19629,10 @@ function trackBackgroundTask(opts, child, outputPath, startTime, taskId) {
19187
19629
  });
19188
19630
  }, SIZE_WATCHDOG_INTERVAL_MS);
19189
19631
  sizeWatchdog.unref();
19190
- let finished = false;
19632
+ let finished2 = false;
19191
19633
  const finish = (code, sig) => {
19192
- if (finished) return;
19193
- finished = true;
19634
+ if (finished2) return;
19635
+ finished2 = true;
19194
19636
  opts.queryAbortSignal?.removeEventListener("abort", onAbort);
19195
19637
  clearTimeout(timer);
19196
19638
  if (sizeWatchdog) clearInterval(sizeWatchdog);
@@ -19583,7 +20025,7 @@ __export(BashTool_exports, {
19583
20025
  findShell: () => findShell,
19584
20026
  killChild: () => killChild
19585
20027
  });
19586
- import { spawn as spawn2, execSync } from "node:child_process";
20028
+ import { spawn as spawn3, execSync } from "node:child_process";
19587
20029
  import * as fs16 from "node:fs";
19588
20030
  import * as path20 from "node:path";
19589
20031
  function isWslBash(p) {
@@ -19630,7 +20072,7 @@ function findShell() {
19630
20072
  function killChild(child) {
19631
20073
  if (child.pid) {
19632
20074
  if (process.platform === "win32") {
19633
- spawn2("taskkill", ["/T", "/F", "/PID", String(child.pid)], {
20075
+ spawn3("taskkill", ["/T", "/F", "/PID", String(child.pid)], {
19634
20076
  stdio: "ignore",
19635
20077
  detached: true,
19636
20078
  windowsHide: true
@@ -19734,7 +20176,7 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
19734
20176
  }
19735
20177
  return new Promise((resolve47) => {
19736
20178
  const { shell, args: shellArgs } = findShell();
19737
- const child = spawn2(shell, [...shellArgs, command2], {
20179
+ const child = spawn3(shell, [...shellArgs, command2], {
19738
20180
  cwd,
19739
20181
  env: sanitizeEnv(process.env),
19740
20182
  stdio: ["ignore", outputHandle.fd, outputHandle.fd],
@@ -20599,8 +21041,8 @@ var init_cpu_router_mode_hook = __esm({
20599
21041
  });
20600
21042
 
20601
21043
  // src/hooks/executor.ts
20602
- import { spawn as spawn3 } from "child_process";
20603
- import { randomUUID as randomUUID12 } from "node:crypto";
21044
+ import { spawn as spawn4 } from "child_process";
21045
+ import { randomUUID as randomUUID14 } from "node:crypto";
20604
21046
  import { basename as basename8 } from "node:path";
20605
21047
  function assertHookAuthority(ctx, input) {
20606
21048
  const tool = input?.tool_name;
@@ -20695,7 +21137,7 @@ async function execCommandHook(hook, hookEvent, hookName, jsonInput, signal, hoo
20695
21137
  assertHostTurnCurrent();
20696
21138
  assertHookAuthority(ctx);
20697
21139
  beginHostTurnEffect();
20698
- const child = spawn3(command2, [], {
21140
+ const child = spawn4(command2, [], {
20699
21141
  env: envVars,
20700
21142
  cwd: ctx.cwd || ctx.workspace,
20701
21143
  shell,
@@ -20711,7 +21153,7 @@ async function execCommandHook(hook, hookEvent, hookName, jsonInput, signal, hoo
20711
21153
  if (stopping) return;
20712
21154
  stopping = true;
20713
21155
  if (isWindows && child.pid) {
20714
- const killer = spawn3("taskkill", ["/PID", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
21156
+ const killer = spawn4("taskkill", ["/PID", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
20715
21157
  killer.on("error", () => {
20716
21158
  try {
20717
21159
  child.kill("SIGKILL");
@@ -20784,7 +21226,7 @@ async function execCommandHook(hook, hookEvent, hookName, jsonInput, signal, hoo
20784
21226
  return { stdout, stderr, output, status: exitCode, aborted: timedOut || signal.aborted };
20785
21227
  }
20786
21228
  async function executeOneHook(hook, hookEvent, hookName, hookInput, toolUseID, signal, ctx) {
20787
- const hookId = randomUUID12();
21229
+ const hookId = randomUUID14();
20788
21230
  const startMs = Date.now();
20789
21231
  let callbackSignal;
20790
21232
  assertHostTurnCurrent();
@@ -20978,14 +21420,14 @@ async function executeHooks(event2, hookInput, ctx, signal, matchQuery) {
20978
21420
  if (abortSignal.aborted) {
20979
21421
  return { additionalContexts: [] };
20980
21422
  }
20981
- const toolUseID = randomUUID12();
21423
+ const toolUseID = randomUUID14();
20982
21424
  if (event2 !== "UserPromptSubmit") {
20983
21425
  return aggregateResults(await Promise.all(matchedHooks.map(({ hook }) => executeOneHook(hook, event2, hookName, hookInput, toolUseID, abortSignal, ctx))));
20984
21426
  }
20985
21427
  const batchStart = performance.now();
20986
21428
  let slowestHook;
20987
21429
  let slowestMs = -1;
20988
- let finished = 0;
21430
+ let finished2 = 0;
20989
21431
  let completed = false;
20990
21432
  const timing = (data) => {
20991
21433
  console.log(`[hook:timing] ${JSON.stringify({ event: event2, runId: toolUseID, sessionId: ctx.sessionId, ...data })}`);
@@ -21004,7 +21446,7 @@ async function executeHooks(event2, hookInput, ctx, signal, matchQuery) {
21004
21446
  return result;
21005
21447
  } finally {
21006
21448
  const durationMs = Math.round(performance.now() - start);
21007
- finished++;
21449
+ finished2++;
21008
21450
  if (durationMs > slowestMs) {
21009
21451
  slowestMs = durationMs;
21010
21452
  slowestHook = label;
@@ -21021,7 +21463,7 @@ async function executeHooks(event2, hookInput, ctx, signal, matchQuery) {
21021
21463
  slowestHook,
21022
21464
  slowestMs,
21023
21465
  matched: matchedHooks.length,
21024
- finished,
21466
+ finished: finished2,
21025
21467
  completed,
21026
21468
  aborted: abortSignal.aborted
21027
21469
  });
@@ -21610,7 +22052,7 @@ var init_context_dump = __esm({
21610
22052
  // src/core/steer-mailbox.ts
21611
22053
  import * as fs21 from "node:fs";
21612
22054
  import * as path25 from "node:path";
21613
- import { createHash as createHash34, randomUUID as randomUUID13 } from "node:crypto";
22055
+ import { createHash as createHash34, randomUUID as randomUUID15 } from "node:crypto";
21614
22056
  var MAX_FILE, MAX_PENDING, MAX_PENDING_BYTES, SteerMailbox;
21615
22057
  var init_steer_mailbox = __esm({
21616
22058
  "src/core/steer-mailbox.ts"() {
@@ -21662,7 +22104,7 @@ var init_steer_mailbox = __esm({
21662
22104
  input.channelTarget ?? "",
21663
22105
  input.sender ?? "",
21664
22106
  input.messageId
21665
- ])).digest("hex") : randomUUID13();
22107
+ ])).digest("hex") : randomUUID15();
21666
22108
  const previous = records.find((r) => r.id === id2);
21667
22109
  if (previous) return { accepted: true, duplicate: true, input: previous };
21668
22110
  const record = {
@@ -21734,7 +22176,7 @@ var init_steer_mailbox = __esm({
21734
22176
  }
21735
22177
  if (Buffer.byteLength(data) > MAX_FILE) throw new Error("Steer mailbox full");
21736
22178
  fs21.mkdirSync(path25.dirname(this.path), { recursive: true });
21737
- const temporary = `${this.path}.${randomUUID13()}.tmp`;
22179
+ const temporary = `${this.path}.${randomUUID15()}.tmp`;
21738
22180
  try {
21739
22181
  const fd = fs21.openSync(temporary, "wx", 384);
21740
22182
  try {
@@ -23046,7 +23488,9 @@ var init_tool_loading = __esm({
23046
23488
  ["gmail", ["\u90AE\u7BB1", "\u90AE\u4EF6"]],
23047
23489
  ["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
23490
  ["cc_ask", ["\u5C0FC", "\u684C\u9762CC", "Claude Code"]],
23049
- ["cc_progress", ["\u5C0FC", "\u684C\u9762CC", "Claude Code"]]
23491
+ ["cc_progress", ["\u5C0FC", "\u684C\u9762CC", "Claude Code"]],
23492
+ ["cc_new", ["\u5C0FC", "\u684C\u9762CC", "Claude Code", "\u65B0\u5EFA CC \u4F1A\u8BDD"]],
23493
+ ["cc_stop", ["\u5C0FC", "\u684C\u9762CC", "Claude Code", "\u505C\u6B62 CC \u4EFB\u52A1"]]
23050
23494
  ]);
23051
23495
  }
23052
23496
  });
@@ -23775,7 +24219,7 @@ var init_context_analyzer = __esm({
23775
24219
 
23776
24220
  // src/core/query.ts
23777
24221
  import { setTimeout as waitForRetry } from "node:timers/promises";
23778
- import { randomUUID as randomUUID14 } from "node:crypto";
24222
+ import { randomUUID as randomUUID16 } from "node:crypto";
23779
24223
  function blockedToolCallsForOverride(calls, override) {
23780
24224
  if (!override) return [];
23781
24225
  const allowed = new Set(override.map((d) => d.function?.name).filter((n) => !!n));
@@ -24008,13 +24452,13 @@ var init_query = __esm({
24008
24452
  this.modelRef = modelRef;
24009
24453
  }
24010
24454
  setProvider(provider) {
24011
- for (const owner of this.backgroundOwners) owner.cancelAll();
24455
+ for (const owner2 of this.backgroundOwners) owner2.cancelAll();
24012
24456
  this.modelGeneration++;
24013
24457
  this.provider = provider;
24014
24458
  }
24015
24459
  /** 热加载:替换 model 字符串(doReloadConfig 切换 primary 后调用) */
24016
24460
  setModel(model) {
24017
- for (const owner of this.backgroundOwners) owner.cancelAll();
24461
+ for (const owner2 of this.backgroundOwners) owner2.cancelAll();
24018
24462
  this.modelGeneration++;
24019
24463
  this.options.model = model;
24020
24464
  }
@@ -24053,7 +24497,7 @@ var init_query = __esm({
24053
24497
  if (!this.steerQueryId) {
24054
24498
  this.stopRequested = false;
24055
24499
  this.cancellationReason = null;
24056
- this.steerQueryId = randomUUID14();
24500
+ this.steerQueryId = randomUUID16();
24057
24501
  this.steerRoute = { channel: context?.channel ?? "console", channelTarget: context?.channelTarget };
24058
24502
  }
24059
24503
  const mailbox = this.steerMailbox;
@@ -24091,7 +24535,7 @@ var init_query = __esm({
24091
24535
  this.compactConfig.systemOverheadTokens = overhead ?? this.compactConfig.systemOverheadTokens;
24092
24536
  }
24093
24537
  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) };
24538
+ for (const m of messages) if ("role" in m && hasMedia(m) && !m.imageInput) m.imageInput = { id: randomUUID16(), observed: hasImage(m) };
24095
24539
  let currentMessages = [...messages];
24096
24540
  const stopUserMessages = [];
24097
24541
  const stopToolResults = [];
@@ -24629,13 +25073,13 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
24629
25073
  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
25074
  return;
24631
25075
  }
24632
- const delay3 = Math.min(1e3 * Math.pow(2, streamRetries), 16e3);
25076
+ const delay4 = Math.min(1e3 * Math.pow(2, streamRetries), 16e3);
24633
25077
  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`);
25078
+ console.log(`${this.logPrefix} Turn ${turnCount}: stream retry ${streamRetries + 1}/${MAX_STREAM_RETRIES}, delay=${delay4}ms`);
24635
25079
  yield { type: "status", text: `\u26A0\uFE0F API error, retrying (${streamRetries + 1}/${MAX_STREAM_RETRIES})...` };
24636
25080
  this.phase = "tools";
24637
25081
  try {
24638
- await waitForRetry(delay3, void 0, { signal: ac.signal });
25082
+ await waitForRetry(delay4, void 0, { signal: ac.signal });
24639
25083
  } catch (error) {
24640
25084
  if (!ac.signal.aborted) throw error;
24641
25085
  }
@@ -24750,7 +25194,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
24750
25194
  if (toolCalls.length === 0) {
24751
25195
  const carryReply = () => {
24752
25196
  if (!this.pendingSteers.some((input) => input.attachment)) return null;
24753
- const replyId = randomUUID14();
25197
+ const replyId = randomUUID16();
24754
25198
  const reply = msg.assistant(textContent);
24755
25199
  if (turnThinking) reply.reasoning_content = turnThinking;
24756
25200
  if (turnThinkingSig) reply.thinking_signature = turnThinkingSig;
@@ -25093,7 +25537,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
25093
25537
  this.activeRequestModel = null;
25094
25538
  this.steerMailbox = new SteerMailbox(stateDir, sessionId);
25095
25539
  this.steerRoute = route;
25096
- this.steerQueryId = randomUUID14();
25540
+ this.steerQueryId = randomUUID16();
25097
25541
  return this.steerQueryId;
25098
25542
  }
25099
25543
  clearSteerDelivery(cancel = false) {
@@ -25140,7 +25584,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
25140
25584
  ...metadata4,
25141
25585
  text: text2,
25142
25586
  queryId: this.steerQueryId,
25143
- id: randomUUID14(),
25587
+ id: randomUUID16(),
25144
25588
  receivedAt: (/* @__PURE__ */ new Date()).toISOString(),
25145
25589
  status: "received"
25146
25590
  } };
@@ -25457,7 +25901,7 @@ var init_builtInAgents = __esm({
25457
25901
  });
25458
25902
 
25459
25903
  // src/tools/AgentTool/forkSubagent.ts
25460
- import { randomUUID as randomUUID15 } from "crypto";
25904
+ import { randomUUID as randomUUID17 } from "crypto";
25461
25905
  function isForkSubagentEnabled() {
25462
25906
  return true;
25463
25907
  }
@@ -25496,7 +25940,7 @@ function buildForkedMessages(directive, parentMessages) {
25496
25940
  type: "tool_result",
25497
25941
  tool_use_id: block.id,
25498
25942
  content: FORK_PLACEHOLDER_RESULT,
25499
- id: `toolr_${randomUUID15().replace(/-/g, "").slice(0, 24)}`
25943
+ id: `toolr_${randomUUID17().replace(/-/g, "").slice(0, 24)}`
25500
25944
  }));
25501
25945
  const toolResultMessage = msg_user(
25502
25946
  buildChildMessage(directive),
@@ -27517,9 +27961,9 @@ async function handleBroadcast(content, summary2, ctx) {
27517
27961
  async function handleShutdownRequest(targetName, reason, ctx) {
27518
27962
  const teamName = getTeamName(ctx);
27519
27963
  const senderName = getAgentName(ctx);
27520
- const requestId = generateRequestId("shutdown", targetName);
27964
+ const requestId2 = generateRequestId("shutdown", targetName);
27521
27965
  const shutdownMessage = createShutdownRequestMessage({
27522
- requestId,
27966
+ requestId: requestId2,
27523
27967
  from: senderName,
27524
27968
  reason
27525
27969
  });
@@ -27535,17 +27979,17 @@ async function handleShutdownRequest(targetName, reason, ctx) {
27535
27979
  return {
27536
27980
  content: JSON.stringify({
27537
27981
  success: true,
27538
- message: `Shutdown request sent to ${targetName}. Request ID: ${requestId}`,
27539
- request_id: requestId,
27982
+ message: `Shutdown request sent to ${targetName}. Request ID: ${requestId2}`,
27983
+ request_id: requestId2,
27540
27984
  target: targetName
27541
27985
  })
27542
27986
  };
27543
27987
  }
27544
- async function handleShutdownApproval(requestId, ctx) {
27988
+ async function handleShutdownApproval(requestId2, ctx) {
27545
27989
  const teamName = getTeamName(ctx);
27546
27990
  const agentName = getAgentName(ctx);
27547
27991
  const approvedMessage = createShutdownApprovedMessage({
27548
- requestId,
27992
+ requestId: requestId2,
27549
27993
  from: agentName
27550
27994
  });
27551
27995
  await writeToMailbox(
@@ -27564,15 +28008,15 @@ async function handleShutdownApproval(requestId, ctx) {
27564
28008
  content: JSON.stringify({
27565
28009
  success: true,
27566
28010
  message: `Shutdown approved. Agent ${agentName} is now exiting.`,
27567
- request_id: requestId
28011
+ request_id: requestId2
27568
28012
  })
27569
28013
  };
27570
28014
  }
27571
- async function handleShutdownRejection(requestId, reason, ctx) {
28015
+ async function handleShutdownRejection(requestId2, reason, ctx) {
27572
28016
  const teamName = getTeamName(ctx);
27573
28017
  const agentName = getAgentName(ctx);
27574
28018
  const rejectedMessage = createShutdownRejectedMessage({
27575
- requestId,
28019
+ requestId: requestId2,
27576
28020
  from: agentName,
27577
28021
  reason
27578
28022
  });
@@ -27589,7 +28033,7 @@ async function handleShutdownRejection(requestId, reason, ctx) {
27589
28033
  content: JSON.stringify({
27590
28034
  success: true,
27591
28035
  message: `Shutdown rejected. Reason: "${reason}". Continuing to work.`,
27592
- request_id: requestId
28036
+ request_id: requestId2
27593
28037
  })
27594
28038
  };
27595
28039
  }
@@ -28451,7 +28895,7 @@ var init_sources = __esm({
28451
28895
  // src/installer/skill-install.ts
28452
28896
  import * as fs28 from "node:fs";
28453
28897
  import * as path32 from "node:path";
28454
- import { exec as exec2 } from "node:child_process";
28898
+ import { exec as exec3 } from "node:child_process";
28455
28899
  function rescanSkills() {
28456
28900
  const state2 = getSkillToolState();
28457
28901
  if (!state2.skillsDirPath) {
@@ -28553,7 +28997,7 @@ function npmInstallDeps(skillDir) {
28553
28997
  }
28554
28998
  if (!hasDeps) return Promise.resolve(true);
28555
28999
  return new Promise((resolve47) => {
28556
- exec2("npm install --omit=dev --no-audit --no-fund --ignore-scripts", {
29000
+ exec3("npm install --omit=dev --no-audit --no-fund --ignore-scripts", {
28557
29001
  cwd: skillDir,
28558
29002
  timeout: 18e4,
28559
29003
  windowsHide: true,
@@ -29853,6 +30297,18 @@ var init_registry2 = __esm({
29853
30297
  effect: "hot",
29854
30298
  internal: true
29855
30299
  },
30300
+ // 1130 Gmail 冷启动:连接即触发 + 每日巡查,新装机默认开。model 为空走 topics.clean.model → extract → mem7 链(免费档自动退回主力模型)
30301
+ { 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 },
30302
+ { 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 },
30303
+ {
30304
+ path: "gmailColdstart.patrolHour",
30305
+ type: "number",
30306
+ group: "feature",
30307
+ label: "Gmail \u6BCF\u65E5\u5DE1\u67E5\u6574\u70B9\uFF080-23\uFF09",
30308
+ effect: "hot",
30309
+ internal: true,
30310
+ validate: (value2) => Number.isInteger(value2) && Number(value2) >= 0 && Number(value2) <= 23 ? null : "\u5DE1\u67E5\u6574\u70B9\u987B\u4E3A 0-23"
30311
+ },
29856
30312
  {
29857
30313
  path: "mem7.turnReadBudgetMs",
29858
30314
  type: "number",
@@ -31326,12 +31782,12 @@ var init_wx_query = __esm({
31326
31782
  handler: async (args, _context) => {
31327
31783
  const { findShell: findShell2 } = await Promise.resolve().then(() => (init_BashTool(), BashTool_exports));
31328
31784
  const shell = findShell2();
31329
- const { spawn: spawn8 } = await import("node:child_process");
31785
+ const { spawn: spawn9 } = await import("node:child_process");
31330
31786
  const cmd = args.command.trim();
31331
31787
  const timeout = args.timeout || 12e4;
31332
31788
  const fullCmd = `${PYTHON} "${SCRIPT}" ${cmd.replace(/^python3\s+.*wx_query\.py\s*/, "")}`;
31333
31789
  return new Promise((resolve47) => {
31334
- const child = spawn8(shell.shell, [...shell.args, fullCmd], {
31790
+ const child = spawn9(shell.shell, [...shell.args, fullCmd], {
31335
31791
  timeout,
31336
31792
  env: { ...process.env },
31337
31793
  windowsHide: true
@@ -31372,14 +31828,14 @@ var init_wx_query = __esm({
31372
31828
  init_publication_objects();
31373
31829
  init_key_service_store();
31374
31830
  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";
31831
+ 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
31832
  import { join as join73, resolve as resolve46 } from "node:path";
31377
31833
  import { fileURLToPath as fileURLToPath9, pathToFileURL as pathToFileURL2 } from "node:url";
31378
- import { spawn as spawn7 } from "node:child_process";
31834
+ import { spawn as spawn8 } from "node:child_process";
31379
31835
  import { request as request8 } from "node:https";
31380
31836
 
31381
31837
  // 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";
31838
+ 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
31839
  import { join as join46 } from "node:path";
31384
31840
  import { homedir as homedir3 } from "node:os";
31385
31841
  import { randomBytes as randomBytes4, createHash as createHash36, X509Certificate } from "node:crypto";
@@ -33019,8 +33475,8 @@ var RuntimePublicationSource = class _RuntimePublicationSource {
33019
33475
  }
33020
33476
  }
33021
33477
  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)
33478
+ 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();
33479
+ if (!binding || !owner2 || !same2(binding, owner2) || binding.profile !== JSON.stringify(this.profile) || binding.layout !== this.layoutDigest)
33024
33480
  throw new Error("RUNTIME_PUBLICATION_PROFILE_MISMATCH");
33025
33481
  this.identities = [incarnation(this.file), incarnation(this.senderFile)];
33026
33482
  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 +34683,7 @@ var builtInFeatures = [
34227
34683
  id: "cc-driver",
34228
34684
  name: "CC \u7EC8\u7AEF",
34229
34685
  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"],
34686
+ requiredTools: ["cc_progress", "cc_ask", "cc_stop", "cc_new"],
34231
34687
  setup: async () => {
34232
34688
  await Promise.resolve().then(() => (init_cc_progress(), cc_progress_exports));
34233
34689
  await Promise.resolve().then(() => (init_cc_ask(), cc_ask_exports));
@@ -34432,9 +34888,9 @@ var archivePairing = (directory2) => {
34432
34888
  write(join46(directory2, "pairing-environment.json"), { dependenciesSha256: manifest.dependenciesSha256 });
34433
34889
  };
34434
34890
  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;
34891
+ const hostStorage = input.hostStorage ? realpathSync14(input.hostStorage) : join46(homedir3(), ".engine7-travel-test/hosts");
34892
+ const engineDir = realpathSync14(input.engineDir), stateDir = realpathSync14(input.stateDir), configPath = realpathSync14(input.configPath);
34893
+ const environmentDir = input.environmentDir ? realpathSync14(input.environmentDir) : engineDir;
34438
34894
  const pkg = JSON.parse(readFileSync26(join46(environmentDir, "package.json"), "utf8"));
34439
34895
  if (input.environmentDir) {
34440
34896
  const lock = JSON.parse(readFileSync26(join46(environmentDir, "package-lock.json"), "utf8"));
@@ -34444,7 +34900,7 @@ async function preparePairingMaterial(input) {
34444
34900
  const config = JSON.parse(readFileSync26(configPath, "utf8"));
34445
34901
  loadSecretsEnvForConfig(configPath);
34446
34902
  const parsed = loadConfig(configPath);
34447
- if (realpathSync13(parsed.stateDir) !== stateDir) throw new Error("TRAVEL_PAIRING_IDENTITY");
34903
+ if (realpathSync14(parsed.stateDir) !== stateDir) throw new Error("TRAVEL_PAIRING_IDENTITY");
34448
34904
  const companion = JSON.parse(readPrivateFile(join46(stateDir, ".continuity/travel-companion-id.json"), 16384).toString()).companionId;
34449
34905
  const directory2 = join46(homedir3(), ".engine7-travel-test", "tasks", input.taskId);
34450
34906
  mkdirSync24(join46(homedir3(), ".engine7-travel-test", "tasks"), { recursive: true, mode: 448 });
@@ -34477,7 +34933,7 @@ async function preparePairingMaterial(input) {
34477
34933
  const effective = resolveSecrets(config);
34478
34934
  const channels = Object.fromEntries(Object.entries(effective.channels ?? {}).filter(([name]) => name !== "emotion"));
34479
34935
  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");
34936
+ const layout = await describeInitialRuntimeLayout(stateDir, realpathSync14(parsed.workspace), "core");
34481
34937
  preparePrivateDirectory(directory2);
34482
34938
  const identity3 = { tenantId: "self-hosted-" + sha6(homedir3()).slice(0, 20), companionId: companion, seatId: input.taskId };
34483
34939
  const tlsDirectory = join46(directory2, "tls");
@@ -34536,7 +34992,7 @@ async function preparePairingMaterial(input) {
34536
34992
  identity: identity3,
34537
34993
  hostStorage,
34538
34994
  stateDir,
34539
- workspace: realpathSync13(parsed.workspace),
34995
+ workspace: realpathSync14(parsed.workspace),
34540
34996
  configPath,
34541
34997
  consolePort: parsed.api?.port ?? 16992,
34542
34998
  engineDir,
@@ -34632,7 +35088,7 @@ function finalizePairingMaterial(material, binding) {
34632
35088
  }
34633
35089
 
34634
35090
  // src/continuity/initial-baseline-worker.ts
34635
- import { spawn as spawn4 } from "node:child_process";
35091
+ import { spawn as spawn5 } from "node:child_process";
34636
35092
  import { existsSync as existsSync27, writeFileSync as writeFileSync24, unlinkSync as unlinkSync7 } from "node:fs";
34637
35093
  import { join as join47 } from "node:path";
34638
35094
  import { fileURLToPath as fileURLToPath5 } from "node:url";
@@ -34643,7 +35099,7 @@ async function runInitialBaselineWorker(options, onProgress, assertCurrent) {
34643
35099
  writeFileSync24(config, JSON.stringify(options), { mode: 384, flag: "wx", flush: true });
34644
35100
  try {
34645
35101
  await new Promise((done, reject) => {
34646
- const child = spawn4(process.execPath, [...entry.endsWith(".ts") ? ["--import", "tsx"] : [], entry, "--config", config], { stdio: ["ignore", "pipe", "pipe", "ipc"] });
35102
+ const child = spawn5(process.execPath, [...entry.endsWith(".ts") ? ["--import", "tsx"] : [], entry, "--config", config], { stdio: ["ignore", "pipe", "pipe", "ipc"] });
34647
35103
  let failure2, stderr = "";
34648
35104
  child.stderr.on("data", (b) => {
34649
35105
  stderr = (stderr + b).slice(-8192);
@@ -34699,11 +35155,11 @@ function publicPairingError(error) {
34699
35155
  }
34700
35156
 
34701
35157
  // src/continuity/node-main.ts
34702
- import { readFileSync as readFileSync32, lstatSync as lstatSync29, realpathSync as realpathSync27 } from "node:fs";
35158
+ import { readFileSync as readFileSync32, lstatSync as lstatSync29, realpathSync as realpathSync28 } from "node:fs";
34703
35159
  import { DatabaseSync as DatabaseSync37 } from "node:sqlite";
34704
35160
  import { isAbsolute as isAbsolute13, resolve as resolve41 } from "node:path";
34705
35161
  import { fileURLToPath as fileURLToPath7 } from "node:url";
34706
- import { randomUUID as randomUUID22, createHash as createHash50 } from "node:crypto";
35162
+ import { randomUUID as randomUUID24, createHash as createHash50 } from "node:crypto";
34707
35163
 
34708
35164
  // src/continuity/node-agent.ts
34709
35165
  import { DatabaseSync as DatabaseSync36 } from "node:sqlite";
@@ -34734,19 +35190,19 @@ function runtimeEngineConfig(original, stateDir, workspace) {
34734
35190
  }
34735
35191
 
34736
35192
  // 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";
35193
+ import { existsSync as existsSync38, lstatSync as lstatSync28, mkdirSync as mkdirSync31, readFileSync as readFileSync31, realpathSync as realpathSync27, writeFileSync as writeFileSync40 } from "node:fs";
34738
35194
  import { isAbsolute as isAbsolute12, join as join70, resolve as resolve40 } from "node:path";
34739
- import { createHash as createHash48, randomUUID as randomUUID21 } from "node:crypto";
35195
+ import { createHash as createHash48, randomUUID as randomUUID23 } from "node:crypto";
34740
35196
  import { isIP as isIP2 } from "node:net";
34741
35197
 
34742
35198
  // src/continuity/activation.ts
34743
35199
  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";
35200
+ import { constants as constants12, existsSync as existsSync32, mkdirSync as mkdirSync25, realpathSync as realpathSync18, unlinkSync as unlinkSync12, writeFileSync as writeFileSync29 } from "node:fs";
34745
35201
  import { lstat as lstat4, mkdir as mkdir4, readdir as readdir2 } from "node:fs/promises";
34746
35202
 
34747
35203
  // 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";
35204
+ import { spawn as spawn6 } from "node:child_process";
35205
+ import { existsSync as existsSync28, writeFileSync as writeFileSync25, unlinkSync as unlinkSync8, statSync as statSync13 } from "node:fs";
34750
35206
  import { join as join49 } from "node:path";
34751
35207
  import { fileURLToPath as fileURLToPath6 } from "node:url";
34752
35208
 
@@ -34802,7 +35258,7 @@ function initializeActivationDatabase(file2, raw) {
34802
35258
  // src/continuity/activation-database-worker.ts
34803
35259
  async function runActivationDatabaseWorker(root, file2, binding, assertCurrent) {
34804
35260
  assertCurrent();
34805
- if (statSync12(file2).size < 16 * 1024 * 1024) {
35261
+ if (statSync13(file2).size < 16 * 1024 * 1024) {
34806
35262
  initializeActivationDatabase(file2, binding);
34807
35263
  assertCurrent();
34808
35264
  return;
@@ -34812,7 +35268,7 @@ async function runActivationDatabaseWorker(root, file2, binding, assertCurrent)
34812
35268
  writeFileSync25(config, JSON.stringify({ root, file: file2, binding }), { mode: 384, flag: "wx", flush: true });
34813
35269
  try {
34814
35270
  await new Promise((done, reject) => {
34815
- const child = spawn5(process.execPath, [...entry.endsWith(".ts") ? ["--import", "tsx"] : [], entry, "--config", config], { stdio: ["ignore", "pipe", "pipe"] });
35271
+ const child = spawn6(process.execPath, [...entry.endsWith(".ts") ? ["--import", "tsx"] : [], entry, "--config", config], { stdio: ["ignore", "pipe", "pipe"] });
34816
35272
  let failure2, stderr = "";
34817
35273
  child.stderr.on("data", (b) => {
34818
35274
  stderr = (stderr + b).slice(-8192);
@@ -34851,7 +35307,7 @@ init_key_service_store();
34851
35307
 
34852
35308
  // src/continuity/generation-integrity.ts
34853
35309
  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";
35310
+ 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
35311
  import { join as join50, resolve as resolve28 } from "node:path";
34856
35312
  import { open as open5 } from "node:fs/promises";
34857
35313
  var recentSeals = /* @__PURE__ */ new Map();
@@ -34863,7 +35319,7 @@ function rememberSeal(root, integrity, files) {
34863
35319
  var metadata2 = (stat3) => [stat3.dev, stat3.ino, stat3.size, stat3.mode, stat3.mtimeNs, stat3.ctimeNs].join(":");
34864
35320
  function generationFiles(root) {
34865
35321
  const files = [];
34866
- if (realpathSync14(root) !== root) throw new Error("TRAVEL_GENERATION_INTEGRITY");
35322
+ if (realpathSync15(root) !== root) throw new Error("TRAVEL_GENERATION_INTEGRITY");
34867
35323
  const visit = (path37) => {
34868
35324
  if (path37 === ".runtime-publication-receipt.json") return;
34869
35325
  const file2 = join50(root, path37), stat3 = lstatSync19(file2, { bigint: true });
@@ -34944,14 +35400,14 @@ async function verifyRuntimeGenerationIntegrityAsync(directory2, expected) {
34944
35400
  // src/continuity/recovery-deletion-visibility.ts
34945
35401
  init_key_service_store();
34946
35402
  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";
35403
+ import { createHash as createHash40, randomUUID as randomUUID19 } from "node:crypto";
35404
+ import { existsSync as existsSync31, realpathSync as realpathSync17, renameSync as renameSync11, unlinkSync as unlinkSync11, writeFileSync as writeFileSync28 } from "node:fs";
34949
35405
  import { join as join53, resolve as resolve30 } from "node:path";
34950
35406
 
34951
35407
  // src/continuity/recovery-deletion-overlay.ts
34952
35408
  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";
35409
+ import { createHash as createHash39, randomUUID as randomUUID18 } from "node:crypto";
35410
+ import { existsSync as existsSync30, realpathSync as realpathSync16, renameSync as renameSync10, unlinkSync as unlinkSync10, writeFileSync as writeFileSync27 } from "node:fs";
34955
35411
  import { dirname as dirname21, join as join52, resolve as resolve29 } from "node:path";
34956
35412
  init_key_service_store();
34957
35413
  init_recovery_deletion_sources();
@@ -35057,7 +35513,7 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
35057
35513
  if (++scanned > 1e6 || bytes > 64 * 1024 * 1024) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
35058
35514
  if (jsonBlocked(parse(payload))) blockedCells.add(String(row.id));
35059
35515
  }
35060
- const jobs = [];
35516
+ const jobs2 = [];
35061
35517
  for (const row of memory.prepare("SELECT * FROM ome_jobs").iterate()) {
35062
35518
  if (++scanned > 1e6) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
35063
35519
  let input = String(row.payload);
@@ -35074,12 +35530,12 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
35074
35530
  if (bytes > 64 * 1024 * 1024) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
35075
35531
  const payload = parse(input), result = row.result_json === null ? void 0 : parse(String(row.result_json));
35076
35532
  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 });
35533
+ if (jsonBlocked(payload, scope) || jsonBlocked(result, scope)) jobs2.push({ row, input });
35078
35534
  }
35079
35535
  const removedSources = sources.filter((row) => blocked2(String(row.scope_id), String(row.source_id)));
35080
35536
  if (removedSources.some((row) => row.interpretation_status !== "deleted")) throw new Error("RECOVERY_OVERLAY_SOURCE_PROVENANCE");
35081
35537
  options.transaction(() => {
35082
- for (const { row, input } of jobs) {
35538
+ for (const { row, input } of jobs2) {
35083
35539
  memory.prepare(`UPDATE ome_jobs SET payload='{}',payload_archive=NULL,result_json=NULL,
35084
35540
  retained_input_hash=COALESCE(retained_input_hash,?),retained_input_version=COALESCE(retained_input_version,input_version),
35085
35541
  payload_pruned_at=COALESCE(payload_pruned_at,?),result_pruned_at=COALESCE(result_pruned_at,?),
@@ -35292,7 +35748,7 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
35292
35748
  return {
35293
35749
  format: "engine7-recovery-runtime-copy-cleanup-v6",
35294
35750
  sources: removedSources.length,
35295
- jobs: jobs.length,
35751
+ jobs: jobs2.length,
35296
35752
  sessionEvents,
35297
35753
  intakeRecords,
35298
35754
  debugCaches,
@@ -35310,7 +35766,7 @@ var evidenceRow = (row) => Object.fromEntries(Object.entries(row).map(([key3, va
35310
35766
  var applyRecoveryDeletionRuntimeCopies = (options) => deletionOverlay(options, true);
35311
35767
  async function deletionOverlay(options, runtimeCopies) {
35312
35768
  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");
35769
+ if (root !== options.snapshot || realpathSync16(root) !== root || existsSync30(join52(root, ".travel-active.json"))) throw new Error("RECOVERY_OVERLAY_ISOLATION_REQUIRED");
35314
35770
  const guard = JSON.parse(readPrivateFile(join52(root, ".travel-restored.json"), 1024 * 1024).toString());
35315
35771
  if (guard.activationAllowed !== false) throw new Error("RECOVERY_OVERLAY_ISOLATION_REQUIRED");
35316
35772
  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 +35972,7 @@ async function deletionOverlay(options, runtimeCopies) {
35516
35972
  remaining: ["runtime copy visibility and queue cleanup", "normal activation"]
35517
35973
  };
35518
35974
  const next = { ...original, originalIntegrity: original.originalIntegrity ?? original.integrity, deletionOverlay: proof, integrity: runtimeGenerationIntegrity(root) };
35519
- const temporary = join52(root, ".runtime-publication-receipt-" + randomUUID16());
35975
+ const temporary = join52(root, ".runtime-publication-receipt-" + randomUUID18());
35520
35976
  try {
35521
35977
  writeFileSync27(temporary, JSON.stringify(next), { mode: 384, flag: "wx", flush: true });
35522
35978
  await check();
@@ -35536,10 +35992,10 @@ async function deletionOverlay(options, runtimeCopies) {
35536
35992
  init_schema_migrations();
35537
35993
  var same5 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
35538
35994
  var sha9 = (value2) => createHash40("sha256").update(value2).digest("hex");
35539
- var format = "engine7-current-h-deletion-visibility-v1";
35995
+ var format2 = "engine7-current-h-deletion-visibility-v1";
35540
35996
  function receipt(options) {
35541
35997
  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)
35998
+ 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
35999
  throw new Error("RECOVERY_OVERLAY_ISOLATION_REQUIRED");
35544
36000
  return JSON.parse(readPrivateFile(join53(root, ".runtime-publication-receipt.json"), 4 * 1024 * 1024).toString());
35545
36001
  }
@@ -35591,7 +36047,7 @@ async function completeCurrentHDeletionVisibility(options) {
35591
36047
  validateAuxiliaryState(options);
35592
36048
  verifyRuntimeGenerationIntegrity(options.snapshot, next.integrity);
35593
36049
  const proof = {
35594
- format,
36050
+ format: format2,
35595
36051
  originalDigest: publicationDigest(options.manifest),
35596
36052
  deletionWatermark: floor,
35597
36053
  logDigest: overlay.logDigest,
@@ -35600,7 +36056,7 @@ async function completeCurrentHDeletionVisibility(options) {
35600
36056
  originalIntegrityDigest: sha9(JSON.stringify(next.originalIntegrity)),
35601
36057
  activationAllowed: false
35602
36058
  };
35603
- const file2 = join53(options.snapshot, ".runtime-publication-receipt.json"), temporary = join53(options.snapshot, ".runtime-publication-receipt-" + randomUUID17());
36059
+ const file2 = join53(options.snapshot, ".runtime-publication-receipt.json"), temporary = join53(options.snapshot, ".runtime-publication-receipt-" + randomUUID19());
35604
36060
  try {
35605
36061
  writeFileSync28(temporary, JSON.stringify({ ...next, deletionVisibility: proof }), { mode: 384, flag: "wx", flush: true });
35606
36062
  await check();
@@ -35617,7 +36073,7 @@ async function verifyCurrentHDeletionVisibilityAsync(options) {
35617
36073
  const check = await currentHDeletionCheckAsync(options.manifest, options), floor = await check(), original = receipt(options), proof = original.deletionVisibility;
35618
36074
  const overlay = original.deletionOverlay, digest7 = publicationDigest(options.manifest);
35619
36075
  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")
36076
+ 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
36077
  throw new Error("RECOVERY_VISIBILITY_PROOF");
35622
36078
  verifyRuntimeGenerationIntegrity(options.snapshot, original.integrity);
35623
36079
  const sealed = sha9(JSON.stringify(original));
@@ -35747,7 +36203,7 @@ async function activateRuntimeGeneration(options) {
35747
36203
  };
35748
36204
  await checkDeletion();
35749
36205
  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");
36206
+ if (realpathSync18(snapshot) !== snapshot || realpathSync18(dirname22(destination)) !== dirname22(destination) || existsSync32(destination)) throw new Error("TRAVEL_ACTIVATION_NEW_DIRECTORY_REQUIRED");
35751
36207
  const proof = JSON.parse(readPrivateFile(join54(snapshot, ".runtime-publication-receipt.json"), 4 * 1024 * 1024).toString());
35752
36208
  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
36209
  await verifyRuntimeGenerationIntegrityAsync(snapshot, proof.integrity);
@@ -35824,9 +36280,9 @@ init_publication_objects();
35824
36280
  init_key_service_store();
35825
36281
  import { fork } from "node:child_process";
35826
36282
  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";
36283
+ import { closeSync as closeSync18, lstatSync as lstatSync20, openSync as openSync19, readFileSync as readFileSync29, realpathSync as realpathSync19 } from "node:fs";
35828
36284
  import { isAbsolute as isAbsolute7, join as join55 } from "node:path";
35829
- import { createHash as createHash41, randomUUID as randomUUID18 } from "node:crypto";
36285
+ import { createHash as createHash41, randomUUID as randomUUID20 } from "node:crypto";
35830
36286
 
35831
36287
  // src/continuity/engine-control.ts
35832
36288
  init_runtime_authority();
@@ -35838,7 +36294,7 @@ function travelProcessBinding(stateDir) {
35838
36294
  }
35839
36295
 
35840
36296
  // src/continuity/node-process.ts
35841
- var format2 = "engine7-travel-process-v1";
36297
+ var format3 = "engine7-travel-process-v1";
35842
36298
  var systemEnvironment = /* @__PURE__ */ new Set([
35843
36299
  "PATH",
35844
36300
  "PATHEXT",
@@ -35940,7 +36396,7 @@ var SupervisedRuntimeProcess = class {
35940
36396
  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
36397
  if (recovery && !retired) throw new Error("TRAVEL_PROCESS_GENERATION_RETIRED");
35942
36398
  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");
36399
+ 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
36400
  let environment;
35945
36401
  try {
35946
36402
  environment = supervisedRuntimeEnvironment(JSON.parse(readPrivateFile(this.options.configFile, 1024 * 1024).toString()), process.env, this.options.environmentNames);
@@ -35952,7 +36408,7 @@ var SupervisedRuntimeProcess = class {
35952
36408
  this.expectedAuthorityBootId = permit.authorityBootId;
35953
36409
  this.expected = binding;
35954
36410
  this.plannedExit = false;
35955
- const log = join55(this.options.directory, "engine-" + randomUUID18() + ".log"), fd = openSync19(log, "wx", 384);
36411
+ const log = join55(this.options.directory, "engine-" + randomUUID20() + ".log"), fd = openSync19(log, "wx", 384);
35956
36412
  let child;
35957
36413
  try {
35958
36414
  child = fork(this.options.entry, [this.options.configFile], {
@@ -35977,7 +36433,7 @@ var SupervisedRuntimeProcess = class {
35977
36433
  child.once("error", fail2);
35978
36434
  child.once("exit", fail2);
35979
36435
  child.on("message", (message) => {
35980
- if (message?.format !== format2 || JSON.stringify(message.binding) !== JSON.stringify(binding)) return;
36436
+ if (message?.format !== format3 || JSON.stringify(message.binding) !== JSON.stringify(binding)) return;
35981
36437
  if (message.type === "ready") {
35982
36438
  clearTimeout(timer);
35983
36439
  resolve47();
@@ -36018,14 +36474,14 @@ var SupervisedRuntimeProcess = class {
36018
36474
  }
36019
36475
  request(action, fields3 = {}) {
36020
36476
  if (!this.child?.connected) return Promise.reject(new Error("TRAVEL_PROCESS_EXITED"));
36021
- const nonce = randomUUID18(), child = this.child;
36477
+ const nonce = randomUUID20(), child = this.child;
36022
36478
  return new Promise((resolve47, reject) => {
36023
36479
  const timer = setTimeout(() => {
36024
36480
  this.pending.delete(nonce);
36025
36481
  reject(new Error("TRAVEL_PROCESS_TIMEOUT"));
36026
36482
  }, action === "status" ? Math.min(this.timeout, 5e3) : this.timeout);
36027
36483
  this.pending.set(nonce, { resolve: resolve47, reject, timer });
36028
- child.send?.({ format: format2, type: "request", nonce, binding: this.expected, action, ...fields3 }, (error) => {
36484
+ child.send?.({ format: format3, type: "request", nonce, binding: this.expected, action, ...fields3 }, (error) => {
36029
36485
  if (error) {
36030
36486
  clearTimeout(timer);
36031
36487
  this.pending.delete(nonce);
@@ -36129,7 +36585,7 @@ import { join as join57, resolve as resolve33 } from "node:path";
36129
36585
 
36130
36586
  // src/continuity/publication-files.ts
36131
36587
  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";
36588
+ 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
36589
  import { join as join56, resolve as resolve32, dirname as dirname23 } from "node:path";
36134
36590
  async function restorePublication(options) {
36135
36591
  const { receiver } = options, status = await receiver.status(false);
@@ -36137,7 +36593,7 @@ async function restorePublication(options) {
36137
36593
  const manifest = await receiver.manifest(status.published.sequence);
36138
36594
  if (JSON.stringify(Object.keys(options.databases).sort()) !== JSON.stringify(manifest.profile.databaseIds)) throw new Error("PUBLICATION_INCOMPLETE_DATABASES");
36139
36595
  const destination = resolve32(options.destination);
36140
- if (realpathSync19(dirname23(destination)) !== dirname23(destination)) throw new Error("SYMLINK_REFUSED");
36596
+ if (realpathSync20(dirname23(destination)) !== dirname23(destination)) throw new Error("SYMLINK_REFUSED");
36141
36597
  if (isWithin(receiver.objects.directory, destination) || isWithin(destination, receiver.objects.directory)) throw new Error("PUBLICATION_OVERLAPPING_PATHS");
36142
36598
  try {
36143
36599
  mkdirSync26(destination, { mode: 448 });
@@ -36280,7 +36736,7 @@ import { join as join59 } from "node:path";
36280
36736
  init_key_service_store();
36281
36737
  init_publication_objects();
36282
36738
  import { DatabaseSync as DatabaseSync27 } from "node:sqlite";
36283
- import { existsSync as existsSync33, lstatSync as lstatSync22, realpathSync as realpathSync20 } from "node:fs";
36739
+ import { existsSync as existsSync33, lstatSync as lstatSync22, realpathSync as realpathSync21 } from "node:fs";
36284
36740
  import { createHash as createHash42 } from "node:crypto";
36285
36741
  import { isAbsolute as isAbsolute8, join as join58, resolve as resolve34 } from "node:path";
36286
36742
  init_sqlite_replication();
@@ -36292,7 +36748,7 @@ async function openRuntimeGenerationSource(options) {
36292
36748
  for (const path37 of [options.stateDir, options.dataDirectory]) if (!isAbsolute8(path37) || resolve34(path37) !== path37) throw new Error("TRAVEL_SOURCE_PATH");
36293
36749
  const stateDir = options.stateDir, dataDirectory = options.dataDirectory;
36294
36750
  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");
36751
+ 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
36752
  if (options.mode !== "LIVE" && options.mode !== "SEALED") throw new Error("TRAVEL_SOURCE_MODE");
36297
36753
  if (existsSync33(join58(stateDir, ".travel-restored.json"))) throw new Error("TRAVEL_ACTIVATION_REQUIRED");
36298
36754
  const receipt2 = JSON.parse(readPrivateFile(join58(stateDir, ".travel-active.json"), 4 * 1024 * 1024).toString());
@@ -36313,7 +36769,7 @@ async function openRuntimeGenerationSource(options) {
36313
36769
  }
36314
36770
  const workspace = join58(stateDir, layout.trees[workspaceTree.id]);
36315
36771
  assertPrivateDirectory(workspace);
36316
- if (workspace === stateDir || !isWithin(stateDir, workspace) || realpathSync20(workspace) !== workspace) throw new Error("TRAVEL_SOURCE_LAYOUT");
36772
+ if (workspace === stateDir || !isWithin(stateDir, workspace) || realpathSync21(workspace) !== workspace) throw new Error("TRAVEL_SOURCE_LAYOUT");
36317
36773
  const handles = {}, databases = {}, writableDatabases = {};
36318
36774
  const releases2 = [], sessionDirectories = [], sessionTrees = [];
36319
36775
  const registeredRoots = /* @__PURE__ */ new Set();
@@ -36339,7 +36795,7 @@ async function openRuntimeGenerationSource(options) {
36339
36795
  const path37 = layout.databases[id2];
36340
36796
  validatePublicationPath(path37);
36341
36797
  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");
36798
+ 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
36799
  const db2 = new DatabaseSync27(file2, { readOnly: options.mode === "SEALED", allowExtension: options.mode === "LIVE" && place.component === "legacy-memory" });
36344
36800
  handles[id2] = db2;
36345
36801
  const schema5 = readSchemaVersion(db2), registration = readSQLiteStoreRegistration(place), actual = readSQLiteReplicationSource(db2);
@@ -36559,11 +37015,11 @@ function startTravelHeartbeatReporting(options) {
36559
37015
  preparePrivateDirectory(options.directory);
36560
37016
  const ownerFile = join60(options.directory, "heartbeat-owner.sqlite");
36561
37017
  preparePrivateDatabase(ownerFile);
36562
- const owner = new DatabaseSync28(ownerFile);
37018
+ const owner2 = new DatabaseSync28(ownerFile);
36563
37019
  try {
36564
- owner.exec("CREATE TABLE IF NOT EXISTS owner(id INTEGER PRIMARY KEY);BEGIN IMMEDIATE");
37020
+ owner2.exec("CREATE TABLE IF NOT EXISTS owner(id INTEGER PRIMARY KEY);BEGIN IMMEDIATE");
36565
37021
  } catch {
36566
- owner.close();
37022
+ owner2.close();
36567
37023
  throw new Error("TRAVEL_REPORTING_BUSY");
36568
37024
  }
36569
37025
  let db2;
@@ -36575,7 +37031,7 @@ function startTravelHeartbeatReporting(options) {
36575
37031
  if (db2.prepare("PRAGMA quick_check").get()?.quick_check !== "ok") throw new Error("TRAVEL_REPORTING_RECOVERY_REQUIRED");
36576
37032
  db2.prepare("INSERT OR IGNORE INTO sequences VALUES(?,?,0)").run(options.nodeId, options.bootId);
36577
37033
  } catch (error) {
36578
- owner.close();
37034
+ owner2.close();
36579
37035
  throw error;
36580
37036
  }
36581
37037
  let stopped = false, registered = false, active, stopping, timer, lastError = null, deadline = clock2();
@@ -36686,7 +37142,7 @@ function startTravelHeartbeatReporting(options) {
36686
37142
  await active;
36687
37143
  } finally {
36688
37144
  db2.close();
36689
- owner.close();
37145
+ owner2.close();
36690
37146
  }
36691
37147
  })();
36692
37148
  return stopping;
@@ -36699,7 +37155,7 @@ init_key_service_store();
36699
37155
 
36700
37156
  // src/continuity/recovery-archive-restore.ts
36701
37157
  import { DatabaseSync as DatabaseSync29 } from "node:sqlite";
36702
- import { mkdirSync as mkdirSync28, writeFileSync as writeFileSync32, realpathSync as realpathSync21 } from "node:fs";
37158
+ import { mkdirSync as mkdirSync28, writeFileSync as writeFileSync32, realpathSync as realpathSync22 } from "node:fs";
36703
37159
  import { dirname as dirname24, join as join61, resolve as resolve35 } from "node:path";
36704
37160
  init_sqlite_replication();
36705
37161
  async function restoreRecoveryArchive(options) {
@@ -36717,7 +37173,7 @@ async function restoreOriginal(options, original, currentHCheck) {
36717
37173
  const verify4 = async () => currentHCheck ? currentHCheck() : await checkRecoveryDeletionAsync(manifest, options.deletionWatermark, floor);
36718
37174
  floor = await verify4();
36719
37175
  const destination = resolve35(options.destination);
36720
- if (realpathSync21(dirname24(destination)) !== dirname24(destination)) throw new Error("SYMLINK_REFUSED");
37176
+ if (realpathSync22(dirname24(destination)) !== dirname24(destination)) throw new Error("SYMLINK_REFUSED");
36721
37177
  for (const root of [objects.directory, options.archive.directory]) if (isWithin(root, destination) || isWithin(destination, root)) throw new Error("RECOVERY_OVERLAPPING_PATHS");
36722
37178
  try {
36723
37179
  mkdirSync28(destination, { mode: 448 });
@@ -36795,7 +37251,7 @@ import { DatabaseSync as DatabaseSync30 } from "node:sqlite";
36795
37251
  import { existsSync as existsSync34, lstatSync as lstatSync23, writeFileSync as writeFileSync33 } from "node:fs";
36796
37252
  import { join as join62 } from "node:path";
36797
37253
  var zero = "0".repeat(64);
36798
- var format3 = "engine7-runtime-checkpoint-control-v1";
37254
+ var format4 = "engine7-runtime-checkpoint-control-v1";
36799
37255
  var hash7 = (value2) => typeof value2 === "string" && /^[a-f0-9]{64}$/.test(value2);
36800
37256
  var natural3 = (value2) => typeof value2 === "number" && Number.isSafeInteger(value2) && value2 >= 0;
36801
37257
  var incarnation3 = (file2) => {
@@ -36812,9 +37268,9 @@ var RuntimeCheckpointControl = class {
36812
37268
  this.files = ["checkpoints.json", "checkpoint-owner.sqlite", "checkpoints.sqlite"].map((file2) => join62(options.directory, file2));
36813
37269
  const presence = this.files.map(existsSync34), fresh = presence.every((value2) => !value2);
36814
37270
  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 });
37271
+ if (fresh) writeFileSync33(this.files[0], JSON.stringify({ format: format4, binding: this.binding }), { mode: 384, flag: "wx", flush: true });
36816
37272
  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");
37273
+ if (marker.format !== format4 || marker.binding !== this.binding || Object.keys(marker).length !== 2) throw new Error("TRAVEL_CHECKPOINT_IDENTITY");
36818
37274
  preparePrivateDatabase(this.files[1]);
36819
37275
  this.owner = new DatabaseSync30(this.files[1]);
36820
37276
  try {
@@ -37788,13 +38244,13 @@ async function transferRecoveryArchive(options) {
37788
38244
  init_publication_objects();
37789
38245
  init_key_service_store();
37790
38246
  import { DatabaseSync as DatabaseSync32 } from "node:sqlite";
37791
- import { existsSync as existsSync36, lstatSync as lstatSync25, realpathSync as realpathSync23, writeFileSync as writeFileSync35 } from "node:fs";
38247
+ import { existsSync as existsSync36, lstatSync as lstatSync25, realpathSync as realpathSync24, writeFileSync as writeFileSync35 } from "node:fs";
37792
38248
  import { isAbsolute as isAbsolute10, join as join64, resolve as resolve37 } from "node:path";
37793
- import { randomUUID as randomUUID19 } from "node:crypto";
38249
+ import { randomUUID as randomUUID21 } from "node:crypto";
37794
38250
 
37795
38251
  // src/continuity/runtime-replica-seed.ts
37796
38252
  import { DatabaseSync as DatabaseSync31 } from "node:sqlite";
37797
- import { existsSync as existsSync35, writeFileSync as writeFileSync34, realpathSync as realpathSync22, lstatSync as lstatSync24 } from "node:fs";
38253
+ import { existsSync as existsSync35, writeFileSync as writeFileSync34, realpathSync as realpathSync23, lstatSync as lstatSync24 } from "node:fs";
37798
38254
  import { dirname as dirname25, isAbsolute as isAbsolute9, join as join63, resolve as resolve36 } from "node:path";
37799
38255
  init_publication_objects();
37800
38256
  init_sqlite_replication();
@@ -37804,14 +38260,14 @@ function acquireReplicaOwner(directory2, initialize2 = false) {
37804
38260
  const file2 = join63(directory2, "replica-owner.sqlite");
37805
38261
  if (!initialize2 && !existsSync35(file2)) throw new Error("TRAVEL_REPLICA_RECOVERY_REQUIRED");
37806
38262
  preparePrivateDatabase(file2);
37807
- const owner = new DatabaseSync31(file2);
38263
+ const owner2 = new DatabaseSync31(file2);
37808
38264
  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;
38265
+ if (initialize2) owner2.exec("CREATE TABLE owner(id INTEGER PRIMARY KEY)");
38266
+ 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");
38267
+ owner2.exec("PRAGMA busy_timeout=0;BEGIN IMMEDIATE");
38268
+ return owner2;
37813
38269
  } catch (error) {
37814
- owner.close();
38270
+ owner2.close();
37815
38271
  if (error.code === "ERR_SQLITE_ERROR" && /locked|busy/i.test(error.message)) throw new Error("TRAVEL_REPLICA_BUSY");
37816
38272
  throw error;
37817
38273
  }
@@ -37832,14 +38288,14 @@ async function seedRuntimeReplica(options) {
37832
38288
  if (status.buildManifestId !== manifest.profile.buildManifestId) throw new Error("TRAVEL_REPLICA_BUILD");
37833
38289
  };
37834
38290
  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");
38291
+ 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
38292
  if (existsSync35(destination) || existsSync35(dataDirectory) || isWithin(destination, dataDirectory) || isWithin(dataDirectory, destination)) throw new Error("TRAVEL_REPLICA_NEW_DIRECTORY_REQUIRED");
37837
38293
  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
38294
  if (!await (options.verifyDirectory ?? verifyRuntimeDirectory)(dirname25(destination))) throw new Error("TRAVEL_REPLICA_DIRECTORY");
37839
38295
  await check();
37840
38296
  preparePrivateDirectory(dataDirectory);
37841
38297
  const databases = {}, replicas = {};
37842
- let receiver, owner, closed = false;
38298
+ let receiver, owner2, closed = false;
37843
38299
  const close = () => {
37844
38300
  if (closed) return;
37845
38301
  closed = true;
@@ -37847,11 +38303,11 @@ async function seedRuntimeReplica(options) {
37847
38303
  receiver?.close();
37848
38304
  for (const db2 of Object.values(databases)) db2.close();
37849
38305
  } finally {
37850
- owner?.close();
38306
+ owner2?.close();
37851
38307
  }
37852
38308
  };
37853
38309
  try {
37854
- owner = acquireReplicaOwner(dataDirectory, true);
38310
+ owner2 = acquireReplicaOwner(dataDirectory, true);
37855
38311
  await restoreRecoveryArchive({ archive: options.archive, id: options.id, destination, deletionWatermark: options.deletionWatermark, verifyDatabases: false });
37856
38312
  const refs2 = /* @__PURE__ */ new Map();
37857
38313
  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 +38364,7 @@ async function openSeededRuntimeReplica(options) {
37908
38364
  for (const path37 of [options.destination, options.dataDirectory]) {
37909
38365
  if (!isAbsolute9(path37) || resolve36(path37) !== path37) throw new Error("TRAVEL_REPLICA_PATH");
37910
38366
  assertPrivateDirectory(path37);
37911
- if (realpathSync22(path37) !== path37) throw new Error("TRAVEL_REPLICA_PATH");
38367
+ if (realpathSync23(path37) !== path37) throw new Error("TRAVEL_REPLICA_PATH");
37912
38368
  }
37913
38369
  if (isWithin(options.destination, options.dataDirectory) || isWithin(options.dataDirectory, options.destination)) throw new Error("TRAVEL_REPLICA_PATH");
37914
38370
  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 +38380,7 @@ async function openSeededRuntimeReplica(options) {
37924
38380
  };
37925
38381
  floor();
37926
38382
  if (!await (options.verifyDirectory ?? verifyRuntimeDirectory)(dirname25(options.destination))) throw new Error("TRAVEL_REPLICA_DIRECTORY");
37927
- const owner = acquireReplicaOwner(options.dataDirectory), databases = {}, replicas = {};
38383
+ const owner2 = acquireReplicaOwner(options.dataDirectory), databases = {}, replicas = {};
37928
38384
  let receiver, closed = false;
37929
38385
  const close = () => {
37930
38386
  if (closed) return;
@@ -37933,7 +38389,7 @@ async function openSeededRuntimeReplica(options) {
37933
38389
  receiver?.close();
37934
38390
  for (const db2 of Object.values(databases)) db2.close();
37935
38391
  } finally {
37936
- owner.close();
38392
+ owner2.close();
37937
38393
  }
37938
38394
  };
37939
38395
  try {
@@ -37949,7 +38405,7 @@ async function openSeededRuntimeReplica(options) {
37949
38405
  const file2 = join63(options.destination, "databases", d.databaseId + ".sqlite");
37950
38406
  if (!existsSync35(file2)) throw new Error("TRAVEL_REPLICA_RECOVERY_REQUIRED");
37951
38407
  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");
38408
+ 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
38409
  const probe = new DatabaseSync31(file2, { readOnly: true }), binding = normalizeBinding({ ...profile.identity, databaseId: d.databaseId, baselineId: profile.baselineId, epoch: profile.epoch });
37954
38410
  let component, version;
37955
38411
  try {
@@ -37994,7 +38450,7 @@ var RuntimeReplicaRepository = class _RuntimeReplicaRepository {
37994
38450
  this.options = options;
37995
38451
  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
38452
  assertPrivateDirectory(options.generationsDirectory);
37997
- if (realpathSync23(options.generationsDirectory) !== options.generationsDirectory) throw new Error("TRAVEL_REPLICA_PATH");
38453
+ if (realpathSync24(options.generationsDirectory) !== options.generationsDirectory) throw new Error("TRAVEL_REPLICA_PATH");
37998
38454
  preparePrivateDirectory(options.directory);
37999
38455
  this.files = ["replicas.json", "replicas-owner.sqlite", "replicas.sqlite"].map((name) => join64(options.directory, name));
38000
38456
  const presence = this.files.map(existsSync36), fresh = presence.every((value2) => !value2);
@@ -38127,7 +38583,7 @@ var RuntimeReplicaRepository = class _RuntimeReplicaRepository {
38127
38583
  }
38128
38584
  if (row && row.state !== "PREPARING") throw new Error("TRAVEL_REPLICA_RECOVERY_REQUIRED");
38129
38585
  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);
38586
+ const attempt = randomUUID21(), destination = join64(this.options.generationsDirectory, "replica-" + attempt), dataDirectory = join64(this.options.directory, "receivers", "replica-" + attempt);
38131
38587
  this.db.exec("BEGIN IMMEDIATE");
38132
38588
  try {
38133
38589
  if (row) this.db.prepare("UPDATE attempts SET state='FAILED' WHERE id=? AND state='PREPARING'").run(row.attempt_id);
@@ -38409,7 +38865,7 @@ async function createTravelNodeDataServer(options) {
38409
38865
  init_store();
38410
38866
  init_schema_migrations();
38411
38867
  import { DatabaseSync as DatabaseSync35 } from "node:sqlite";
38412
- import { lstatSync as lstatSync27, realpathSync as realpathSync25 } from "node:fs";
38868
+ import { lstatSync as lstatSync27, realpathSync as realpathSync26 } from "node:fs";
38413
38869
  import { isAbsolute as isAbsolute11, join as join68, resolve as resolve39 } from "node:path";
38414
38870
 
38415
38871
  // src/continuity/recovery-admission.ts
@@ -38821,8 +39277,8 @@ function nativeReferences(db2, table, row, common, branch, scopeProof, originalB
38821
39277
  const entity = db2.prepare("SELECT kind FROM entities WHERE scope_id=? AND entity_id=? AND state='active'").get(scope, payload.entityId);
38822
39278
  if (!entity) return false;
38823
39279
  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;
39280
+ const owner2 = db2.prepare("SELECT app_id FROM memory_scopes WHERE scope_id=?").get(scope);
39281
+ if (entity.kind !== "agent" || !["assistant-actor", "scope-agent"].includes(text2("namespace") ?? "") || text2("namespace") === "scope-agent" && text2("external_id") !== owner2?.app_id) return false;
38826
39282
  } else {
38827
39283
  const source = db2.prepare("SELECT * FROM memory_sources WHERE scope_id=? AND source_id=? AND interpretation_status<>'deleted'").get(scope, payload.sourceId);
38828
39284
  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 +39311,8 @@ function nativeReferences(db2, table, row, common, branch, scopeProof, originalB
38855
39311
  if (table === "memory_artifact_generations") {
38856
39312
  try {
38857
39313
  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;
39314
+ const owner2 = db2.prepare("SELECT owner_id,app_id,project_id FROM memory_scopes WHERE scope_id=?").get(scope);
39315
+ if (!owner2 || !same10(result.basis?.scope, { ownerId: owner2.owner_id, appId: owner2.app_id, projectId: owner2.project_id })) return false;
38860
39316
  refs2 = result.basis.dependencies;
38861
39317
  } catch {
38862
39318
  return false;
@@ -39058,9 +39514,9 @@ function projectNative(db2, branch, table, original, baseline, current2, archive
39058
39514
  map("artifact_job", JSON.stringify([decode(row.kind), decode(row.artifact_id), Number(decode(row.version))]), original.version, () => BigInt(generation.job_id));
39059
39515
  }
39060
39516
  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);
39517
+ const owner2 = db2.prepare("SELECT owner_id,app_id,project_id FROM memory_scopes WHERE scope_id=?").get(scope);
39062
39518
  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);
39519
+ recordArtifactBasis(db2, { ownerId: String(owner2.owner_id), appId: String(owner2.app_id), projectId: String(owner2.project_id) }, kind, id2, version, refs2);
39064
39520
  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
39521
  }
39066
39522
  return row;
@@ -39710,8 +40166,8 @@ async function admitRecoveryArchives(options) {
39710
40166
  }
39711
40167
 
39712
40168
  // 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";
40169
+ import { createHash as createHash46, randomUUID as randomUUID22 } from "node:crypto";
40170
+ 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
40171
  import { dirname as dirname26, join as join67, resolve as resolve38 } from "node:path";
39716
40172
  import { createRequire as createRequire9 } from "node:module";
39717
40173
  init_runtime_authority();
@@ -39719,7 +40175,7 @@ init_dependencies();
39719
40175
  var sha10 = (bytes) => createHash46("sha256").update(bytes).digest("hex");
39720
40176
  var require5 = createRequire9(import.meta.url);
39721
40177
  function privateParents(root, path37) {
39722
- if (realpathSync24(root) !== root) throw new Error("RECOVERY_PROJECTION_UNSAFE_PATH");
40178
+ if (realpathSync25(root) !== root) throw new Error("RECOVERY_PROJECTION_UNSAFE_PATH");
39723
40179
  const visit = (directory2) => {
39724
40180
  if (!isWithin(root, directory2)) throw new Error("RECOVERY_PROJECTION_UNSAFE_PATH");
39725
40181
  if (directory2 !== root) visit(dirname26(directory2));
@@ -39758,11 +40214,11 @@ async function projectRecoveryArtifacts(options) {
39758
40214
  const verifyArtifact = (scopeId2, kind, id2, version) => {
39759
40215
  active();
39760
40216
  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");
40217
+ const owner2 = memory.prepare("SELECT owner_id,app_id,project_id FROM memory_scopes WHERE scope_id=?").get(scopeId2);
40218
+ if (!owner2) throw new Error("RECOVERY_ARTIFACT_DEPENDENCY_PENDING");
39763
40219
  const dependencies2 = new MemoryDependencies(memory, (operation) => operation(), (operation) => operation());
39764
40220
  try {
39765
- dependencies2.assertCurrent({ ownerId: String(owner.owner_id), appId: String(owner.app_id), projectId: String(owner.project_id) }, kind, id2, version);
40221
+ dependencies2.assertCurrent({ ownerId: String(owner2.owner_id), appId: String(owner2.app_id), projectId: String(owner2.project_id) }, kind, id2, version);
39766
40222
  } catch {
39767
40223
  throw new Error("RECOVERY_ARTIFACT_DEPENDENCY_PENDING");
39768
40224
  }
@@ -39832,7 +40288,7 @@ async function projectRecoveryArtifacts(options) {
39832
40288
  commit();
39833
40289
  continue;
39834
40290
  }
39835
- const temporary = join67(dirname26(path37), ".recovery-" + randomUUID20()), original = Buffer.from(body);
40291
+ const temporary = join67(dirname26(path37), ".recovery-" + randomUUID22()), original = Buffer.from(body);
39836
40292
  writeFileSync38(temporary, original, { mode: local.mode, flag: "wx", flush: true });
39837
40293
  let created = false;
39838
40294
  try {
@@ -39954,7 +40410,7 @@ function policies(version) {
39954
40410
  async function admitNormalRecoveryArchives(options) {
39955
40411
  if (options.policyUpgrade !== void 0 && options.policyUpgrade !== "normal-v1") throw new Error("RECOVERY_INVALID_RESOLUTION");
39956
40412
  const stateDir = options.stateDir;
39957
- if (!isAbsolute11(stateDir) || resolve39(stateDir) !== stateDir || realpathSync25(stateDir) !== stateDir || typeof options.withSafeBoundary !== "function") throw new Error("RECOVERY_CURRENT_LAYOUT");
40413
+ if (!isAbsolute11(stateDir) || resolve39(stateDir) !== stateDir || realpathSync26(stateDir) !== stateDir || typeof options.withSafeBoundary !== "function") throw new Error("RECOVERY_CURRENT_LAYOUT");
39958
40414
  assertPrivateDirectory(stateDir);
39959
40415
  const runtime = runtimeAuthorityFor(stateDir);
39960
40416
  if (!runtime) throw new Error("RECOVERY_AUTHORITY_BARRIER");
@@ -39973,7 +40429,7 @@ async function admitNormalRecoveryArchives(options) {
39973
40429
  for (const id2 of profile.databaseIds) {
39974
40430
  validatePublicationPath(layout.databases[id2]);
39975
40431
  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");
40432
+ 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
40433
  if (place.component === "mem7") {
39978
40434
  if (id2 !== "memory" || memory || place.stateDir !== stateDir) throw new Error("RECOVERY_CURRENT_LAYOUT");
39979
40435
  memory = new Mem7Store(stateDir);
@@ -40136,7 +40592,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
40136
40592
  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
40593
  if (options.dataIntervalMs !== void 0 && (!Number.isSafeInteger(options.dataIntervalMs) || options.dataIntervalMs < 250 || options.dataIntervalMs > 6e4)) throw new Error("TRAVEL_DATA_CONFIG");
40138
40594
  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");
40595
+ if (realpathSync27(options.generationsDirectory) !== options.generationsDirectory || isWithin(options.directory, options.generationsDirectory) || isWithin(options.generationsDirectory, options.directory)) throw new Error("TRAVEL_NODE_PATH");
40140
40596
  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
40597
  validateTravelChannelConfiguration(options.engineConfig.channels);
40142
40598
  this.checkBuild();
@@ -40279,7 +40735,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
40279
40735
  checkBuild() {
40280
40736
  for (const b of [this.options.build, this.options.dataBuild]) {
40281
40737
  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");
40738
+ 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
40739
  }
40284
40740
  }
40285
40741
  assertKey() {
@@ -40465,7 +40921,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
40465
40921
  const directory2 = join70(this.options.directory, "data", "objects"), file2 = join70(directory2, "catalog.sqlite");
40466
40922
  assertPrivateDirectory(directory2);
40467
40923
  assertPrivateDirectory(join70(directory2, "chunks"));
40468
- if (realpathSync26(directory2) !== directory2 || !existsSync38(file2)) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
40924
+ if (realpathSync27(directory2) !== directory2 || !existsSync38(file2)) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
40469
40925
  const stat3 = lstatSync28(file2, { bigint: true });
40470
40926
  if (!stat3.isFile() || stat3.isSymbolicLink()) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
40471
40927
  const db2 = new DatabaseSync36(file2, { readOnly: true });
@@ -40678,14 +41134,14 @@ var TravelNodeAgent = class _TravelNodeAgent {
40678
41134
  const prior = this.db.prepare("SELECT snapshot FROM preparations WHERE digest=?").get(digest7);
40679
41135
  if (prior) {
40680
41136
  const snapshot2 = String(prior.snapshot);
40681
- if (!isWithin(this.options.generationsDirectory, snapshot2) || realpathSync26(snapshot2) !== snapshot2) throw new Error("TRAVEL_NODE_PATH");
41137
+ if (!isWithin(this.options.generationsDirectory, snapshot2) || realpathSync27(snapshot2) !== snapshot2) throw new Error("TRAVEL_NODE_PATH");
40682
41138
  const receipt2 = JSON.parse(readPrivateFile(join70(snapshot2, ".runtime-publication-receipt.json"), 4 * 1024 * 1024).toString());
40683
41139
  if (receipt2.receipt?.digest !== digest7) throw new Error("TRAVEL_NODE_CHECKPOINT");
40684
41140
  await verifyRuntimeGenerationIntegrityAsync(snapshot2, receipt2.integrity);
40685
41141
  validateRuntimeActivationSnapshot(snapshot2, manifest, locations);
40686
41142
  return { snapshot: snapshot2, manifest };
40687
41143
  }
40688
- const snapshot = join70(this.options.generationsDirectory, "snapshot-" + randomUUID21());
41144
+ const snapshot = join70(this.options.generationsDirectory, "snapshot-" + randomUUID23());
40689
41145
  await restoreRuntimePublication({ receiver, databases, destination: snapshot, sequence: manifest.sequence });
40690
41146
  validateRuntimeActivationSnapshot(snapshot, manifest, locations);
40691
41147
  this.db.prepare("INSERT INTO preparations VALUES(?,?)").run(digest7, snapshot);
@@ -40710,7 +41166,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
40710
41166
  const prior = this.db.prepare("SELECT * FROM common_preparations WHERE digest=?").get(digest7);
40711
41167
  if (prior) {
40712
41168
  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");
41169
+ if (prior.archive_digest !== entry.receipt.digest || !isWithin(this.options.generationsDirectory, snapshot2) || realpathSync27(snapshot2) !== snapshot2) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
40714
41170
  const proof = JSON.parse(readPrivateFile(join70(snapshot2, ".runtime-publication-receipt.json"), 4 * 1024 * 1024).toString());
40715
41171
  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
41172
  await verifyRuntimeGenerationIntegrityAsync(snapshot2, proof.integrity);
@@ -40718,7 +41174,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
40718
41174
  await check();
40719
41175
  return { snapshot: snapshot2, manifest };
40720
41176
  }
40721
- const snapshot = join70(this.options.generationsDirectory, "snapshot-" + randomUUID21());
41177
+ const snapshot = join70(this.options.generationsDirectory, "snapshot-" + randomUUID23());
40722
41178
  await restoreRecoveryArchive({ archive: this.archive, id: entry.id, destination: snapshot, deletionWatermark: check, verifyDatabases: false });
40723
41179
  validateRuntimeActivationSnapshot(snapshot, manifest, locations);
40724
41180
  await check();
@@ -40749,14 +41205,14 @@ var TravelNodeAgent = class _TravelNodeAgent {
40749
41205
  const prior = this.db.prepare("SELECT * FROM common_preparations WHERE digest=?").get(digest7);
40750
41206
  if (prior) {
40751
41207
  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");
41208
+ if (!isWithin(this.options.generationsDirectory, snapshot2) || realpathSync27(snapshot2) !== snapshot2 || prior.archive_digest !== entry.receipt.digest) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
40753
41209
  const proof2 = JSON.parse(readPrivateFile(join70(snapshot2, ".runtime-publication-receipt.json"), 4 * 1024 * 1024).toString());
40754
41210
  if (proof2.deletionVisibility?.deletionWatermark === this.keyWatermark) {
40755
41211
  const deletionWatermark = await (await verifyCurrentHDeletionVisibilityAsync({ snapshot: snapshot2, manifest, layout: this.options.layout, gateway: this.options.gateway, ...control2 }))();
40756
41212
  return { snapshot: snapshot2, manifest, deletionWatermark };
40757
41213
  }
40758
41214
  }
40759
- const snapshot = join70(this.options.generationsDirectory, "snapshot-" + randomUUID21());
41215
+ const snapshot = join70(this.options.generationsDirectory, "snapshot-" + randomUUID23());
40760
41216
  await restoreCurrentHForDeletion({ archive: this.archive, id: id2, destination: snapshot, ...control2 });
40761
41217
  writeFileSync40(join70(snapshot, ".runtime-publication-receipt.json"), JSON.stringify({
40762
41218
  format: "engine7-runtime-publication-restore-v1",
@@ -41148,7 +41604,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
41148
41604
  });
41149
41605
  }
41150
41606
  assertActive();
41151
- const destination = join70(this.options.generationsDirectory, "runtime-" + randomUUID21()), baselineId = "node-" + randomUUID21();
41607
+ const destination = join70(this.options.generationsDirectory, "runtime-" + randomUUID23()), baselineId = "node-" + randomUUID23();
41152
41608
  this.db.prepare("INSERT INTO generations VALUES(?,?,?,?,?)").run(binding, destination, digest7, "{}", "ACTIVATING");
41153
41609
  try {
41154
41610
  const activation = await activateRuntimeGeneration({
@@ -41402,12 +41858,12 @@ var TravelNodeAgent = class _TravelNodeAgent {
41402
41858
  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
41859
  }
41404
41860
  }
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")) {
41861
+ const jobs2 = this.db.prepare("SELECT * FROM recovery_jobs WHERE binding=? ORDER BY local_digest").all(binding);
41862
+ if (jobs2.some((job) => job.deletion_watermark !== this.keyWatermark)) throw new Error("RECOVERY_DELETION_BARRIER");
41863
+ if (jobs2.some((job) => job.state !== "DONE")) {
41408
41864
  trace("normal-admission");
41409
41865
  await this.withNormalRecoveryBoundary(async () => {
41410
- for (const job of jobs) {
41866
+ for (const job of jobs2) {
41411
41867
  if (job.state === "DONE") continue;
41412
41868
  await check();
41413
41869
  const result = await admitNormalRecoveryArchives({
@@ -42742,7 +43198,7 @@ async function startTravelNodeService(input) {
42742
43198
  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
43199
  const config = input;
42744
43200
  assertPrivateDirectory(path34(config.generationsDirectory));
42745
- const bootId2 = config.bootId ?? randomUUID22();
43201
+ const bootId2 = config.bootId ?? randomUUID24();
42746
43202
  if (!nodeSupervisorId(bootId2)) throw new Error("TRAVEL_NODE_IDENTITY");
42747
43203
  const serverTls = tls(config.tls), clientTls = tls(config.clientTls ?? config.tls);
42748
43204
  const clients = [];
@@ -42842,7 +43298,7 @@ async function startTravelNodeService(input) {
42842
43298
  if (JSON.stringify(Object.keys(config.initialReplica.databases).sort()) !== JSON.stringify(profile.databaseIds)) throw new Error("TRAVEL_NODE_REPLICA_NOT_READY");
42843
43299
  for (const id2 of profile.databaseIds) {
42844
43300
  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");
43301
+ 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
43302
  const db2 = new DatabaseSync37(file2, { allowExtension: id2 === "legacy" });
42847
43303
  replicaHandles.push(db2);
42848
43304
  databases[id2] = db2;
@@ -43132,12 +43588,12 @@ async function waitForPidGone(pid, timeoutMs = 5e3) {
43132
43588
  import { readFileSync as readFileSync35, existsSync as existsSync41 } from "node:fs";
43133
43589
  import { isAbsolute as isAbsolute17, resolve as resolve45 } from "node:path";
43134
43590
  import { fileURLToPath as fileURLToPath8 } from "node:url";
43135
- import { execFile as execFile4 } from "node:child_process";
43136
- import { promisify as promisify5 } from "node:util";
43591
+ import { execFile as execFile6 } from "node:child_process";
43592
+ import { promisify as promisify6 } from "node:util";
43137
43593
  import { createHash as createHash55 } from "node:crypto";
43138
43594
 
43139
43595
  // src/continuity/user-seat-resource.ts
43140
- import { spawn as spawn6 } from "node:child_process";
43596
+ import { spawn as spawn7 } from "node:child_process";
43141
43597
  import { createHash as createHash51 } from "node:crypto";
43142
43598
  import { isAbsolute as isAbsolute14, resolve as resolve42 } from "node:path";
43143
43599
  var UserSeatResource = class {
@@ -43153,7 +43609,7 @@ var UserSeatResource = class {
43153
43609
  identity;
43154
43610
  call(action, input) {
43155
43611
  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"] });
43612
+ 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
43613
  const chunks = [];
43158
43614
  let bytes = 0, stderr = "";
43159
43615
  const timer = setTimeout(() => child.kill("SIGKILL"), 12e4);
@@ -43201,7 +43657,7 @@ init_key_service_store();
43201
43657
  import { DatabaseSync as DatabaseSync39 } from "node:sqlite";
43202
43658
  import { createHash as createHash52 } from "node:crypto";
43203
43659
  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";
43660
+ 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
43661
  import { dirname as dirname27, isAbsolute as isAbsolute15, join as join71, resolve as resolve43, relative as relative15 } from "node:path";
43206
43662
  var identity = (value2) => JSON.stringify([value2.tenantId, value2.companionId, value2.seatId]);
43207
43663
  var sha11 = (value2) => createHash52("sha256").update(value2).digest("hex");
@@ -43216,7 +43672,7 @@ var LocalSeatResource = class {
43216
43672
  check() {
43217
43673
  if (!existsSync39(this.path)) return false;
43218
43674
  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");
43675
+ if (!stat3.isDirectory() || stat3.isSymbolicLink() || realpathSync29(this.path) !== this.path || process.platform !== "win32" && stat3.uid !== process.getuid()) throw new Error("TRAVEL_RETIREMENT_PATH");
43220
43676
  if (identity(JSON.parse(readPrivateFile(join71(this.path, ".travel-seat-resource.json"), 65536).toString())) !== identity(this.identity)) throw new Error("TRAVEL_RETIREMENT_IDENTITY");
43221
43677
  return true;
43222
43678
  }
@@ -43369,7 +43825,7 @@ var TravelRetirement = class {
43369
43825
 
43370
43826
  // src/continuity/local-exit.ts
43371
43827
  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";
43828
+ 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
43829
  import { DatabaseSync as DatabaseSync41 } from "node:sqlite";
43374
43830
  import { isAbsolute as isAbsolute16, join as join72, dirname as dirname29, resolve as resolve44 } from "node:path";
43375
43831
  import { createHash as createHash54, verify as verify3 } from "node:crypto";
@@ -43476,14 +43932,14 @@ function detachReplication(directory2) {
43476
43932
  }
43477
43933
  async function createOrdinaryLocalRecovery(options) {
43478
43934
  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");
43935
+ 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
43936
  const activation = JSON.parse(readFileSync34(join72(source, ".travel-active.json"), "utf8")), permit = activation.permit, { signature: signature2, ...signed } = permit;
43481
43937
  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
43938
  return withCheckpointLock(source, async () => {
43483
43939
  if (!options.authority || !options.principal || options.authority.publicKey !== options.publicKey) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
43484
43940
  const proof = await verifyStoppedLocalExitProof({ ...options, stateDir: source });
43485
43941
  if (existsSync40(destination)) {
43486
- if (realpathSync29(destination) !== destination) throw new Error("TRAVEL_EXIT_PATH");
43942
+ if (realpathSync30(destination) !== destination) throw new Error("TRAVEL_EXIT_PATH");
43487
43943
  let receipt2;
43488
43944
  try {
43489
43945
  receipt2 = JSON.parse(readPrivateFile(join72(destination, ".continuity/travel-exit-receipt.json"), 65536).toString());
@@ -43531,7 +43987,7 @@ async function createOrdinaryLocalRecovery(options) {
43531
43987
  // src/continuity/retirement-main.ts
43532
43988
  init_key_service_store();
43533
43989
  init_key_service_store();
43534
- var command = promisify5(execFile4);
43990
+ var command = promisify6(execFile6);
43535
43991
  var sha14 = (value2) => createHash55("sha256").update(value2).digest("hex");
43536
43992
  var path36 = (value2) => {
43537
43993
  if (typeof value2 !== "string" || !isAbsolute17(value2) || resolve45(value2) !== value2) throw new Error("TRAVEL_RETIREMENT_PATH");
@@ -43606,7 +44062,7 @@ if (process.argv[1] && /[\\/](retirement-main\.ts|travel-retire\.mjs)$/.test(fil
43606
44062
  }
43607
44063
 
43608
44064
  // src/continuity/pairing-host.ts
43609
- import { randomUUID as randomUUID23 } from "node:crypto";
44065
+ import { randomUUID as randomUUID25 } from "node:crypto";
43610
44066
  async function startInitialPairingRuntime(node, authority, digest7, assertInitial) {
43611
44067
  const started = performance.now(), trace = (phase) => {
43612
44068
  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 +44081,7 @@ async function startInitialPairingRuntime(node, authority, digest7, assertInitia
43625
44081
  }
43626
44082
  function readManagedPairingHostConfig(stateDir, binding) {
43627
44083
  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");
44084
+ if (binding.version !== 1 || realpathSync31(config.stateDir) !== realpathSync31(stateDir) || JSON.stringify(binding.identity) !== JSON.stringify(config.identity)) throw new Error("TRAVEL_PAIRING_IDENTITY");
43629
44085
  return config;
43630
44086
  }
43631
44087
  async function pauseInitialPairingIngress(state2, ingress, pair) {
@@ -43666,7 +44122,7 @@ function initialPairingSnapshot(options) {
43666
44122
  };
43667
44123
  }
43668
44124
  var write2 = (file2, value2) => writeFileSync42(file2, JSON.stringify(value2), { mode: 384, flush: true });
43669
- var delay2 = (ms) => new Promise((done) => setTimeout(done, ms));
44125
+ var delay3 = (ms) => new Promise((done) => setTimeout(done, ms));
43670
44126
  function rpc(url, tls2, token, body, timeout = 6e5) {
43671
44127
  return new Promise((done, reject) => {
43672
44128
  const req = request8(url, { method: "POST", ...tls2, minVersion: "TLSv1.3", headers: { Authorization: "Bearer " + token, "Content-Type": "application/json" } }, (res) => {
@@ -43692,7 +44148,7 @@ function rpc(url, tls2, token, body, timeout = 6e5) {
43692
44148
  req.end(JSON.stringify(body));
43693
44149
  });
43694
44150
  }
43695
- function startPairingRelays(material, spawnRelay = spawn7) {
44151
+ function startPairingRelays(material, spawnRelay = spawn8) {
43696
44152
  const directory2 = material.directory, ports = material.ports;
43697
44153
  let stopped = false;
43698
44154
  const lanes = [{ name: "control", forward: ["authority", "gateway", "key", "pairing", "cloudManagement", "console", "cloudApi"], reverse: ["localManagement"] }, { name: "data", forward: ["cloudData"], reverse: ["localData"] }];
@@ -43732,11 +44188,11 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
43732
44188
  if (JSON.stringify(binding.identity) !== JSON.stringify(material.identity)) throw new Error("TRAVEL_PAIRING_IDENTITY");
43733
44189
  const ownerFile = join73(directory2, "host-owner.sqlite");
43734
44190
  preparePrivateDatabase(ownerFile);
43735
- const owner = new DatabaseSync42(ownerFile);
44191
+ const owner2 = new DatabaseSync42(ownerFile);
43736
44192
  try {
43737
- owner.exec("CREATE TABLE IF NOT EXISTS owner(id INTEGER PRIMARY KEY);BEGIN IMMEDIATE");
44193
+ owner2.exec("CREATE TABLE IF NOT EXISTS owner(id INTEGER PRIMARY KEY);BEGIN IMMEDIATE");
43738
44194
  } catch {
43739
- owner.close();
44195
+ owner2.close();
43740
44196
  throw new Error("TRAVEL_PAIRING_BUSY");
43741
44197
  }
43742
44198
  const lifecycleFile = join73(directory2, "lifecycle.json");
@@ -43799,7 +44255,7 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
43799
44255
  if (!stoppedOrdinary || stopped || sourcePid() !== null) return;
43800
44256
  const log = openSync21(join73(directory2, "ordinary-resumed.log"), "a", 384);
43801
44257
  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] });
44258
+ 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
44259
  await new Promise((done, reject) => {
43804
44260
  child.once("spawn", done);
43805
44261
  child.once("error", reject);
@@ -43827,7 +44283,7 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
43827
44283
  break;
43828
44284
  } catch (error) {
43829
44285
  if (attempt >= 30 || !["busy", "not_ready", "service_unavailable"].includes(error.message)) throw error;
43830
- await delay2(1e3);
44286
+ await delay3(1e3);
43831
44287
  }
43832
44288
  }
43833
44289
  lifecycle.state = "MANAGED";
@@ -43861,13 +44317,13 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
43861
44317
  save();
43862
44318
  const baselineDir = join73(directory2, "first-baseline");
43863
44319
  if (lifecycle.recapture && existsSync42(join73(baselineDir, "ready.json"))) {
43864
- renameSync12(baselineDir, join73(directory2, "unused-baseline-" + randomUUID23()));
44320
+ renameSync12(baselineDir, join73(directory2, "unused-baseline-" + randomUUID25()));
43865
44321
  delete lifecycle.recapture;
43866
44322
  save();
43867
44323
  }
43868
44324
  let baseline;
43869
44325
  if (!existsSync42(join73(baselineDir, "ready.json"))) {
43870
- if (existsSync42(baselineDir)) renameSync12(baselineDir, join73(directory2, "failed-baseline-" + randomUUID23()));
44326
+ if (existsSync42(baselineDir)) renameSync12(baselineDir, join73(directory2, "failed-baseline-" + randomUUID25()));
43871
44327
  const key3 = readPrivateFile(join73(directory2, "data.key"), 32);
43872
44328
  let lastProgressSave = 0, lastPhase = "";
43873
44329
  try {
@@ -43910,7 +44366,7 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
43910
44366
  if (current2.activeNodeId !== null) {
43911
44367
  for (let attempt = 0; !(await authority.status()).expired; attempt++) {
43912
44368
  if (attempt >= 120) throw new Error("TRAVEL_INITIAL_SOURCE_RUNNING");
43913
- await delay2(500);
44369
+ await delay3(500);
43914
44370
  }
43915
44371
  }
43916
44372
  await startInitialPairingRuntime(localService.node, { acquire: (ready) => {
@@ -43937,8 +44393,8 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
43937
44393
  save();
43938
44394
  process.stderr.write(JSON.stringify({ state: lifecycle.state, ...failure2, stack: error instanceof Error ? error.stack?.split("\n").slice(1, 7) : [] }) + "\n");
43939
44395
  };
43940
- const startInitial = (requestId) => {
43941
- if (requestId !== lifecycle.requestId) throw new Error("invalid_request");
44396
+ const startInitial = (requestId2) => {
44397
+ if (requestId2 !== lifecycle.requestId) throw new Error("invalid_request");
43942
44398
  if (!pendingInitial) return;
43943
44399
  pendingInitial = false;
43944
44400
  initial ??= initialize2().catch(recordInitialFailure).finally(() => {
@@ -43981,14 +44437,14 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
43981
44437
  lifecycle.automatic = action === "auto_on";
43982
44438
  save();
43983
44439
  } 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");
44440
+ const target = action === "sync" ? "local" : "cloud", requestId2 = action === "sync" ? lifecycle.requestId ?? randomUUID25() : payload?.requestId;
44441
+ if (!requestId2 || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(requestId2)) throw new Error("invalid_request");
44442
+ if (lifecycle.requestId && (lifecycle.requestId !== requestId2 || (lifecycle.target ?? "cloud") !== target)) throw new Error("busy");
43987
44443
  if (!lifecycle.requestId) {
43988
44444
  lifecycle.state = "STARTING";
43989
44445
  lifecycle.startedAt = Date.now();
43990
44446
  }
43991
- lifecycle.requestId = requestId;
44447
+ lifecycle.requestId = requestId2;
43992
44448
  lifecycle.target = target;
43993
44449
  delete lifecycle.error;
43994
44450
  save();
@@ -44007,7 +44463,7 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
44007
44463
  break;
44008
44464
  } catch (error) {
44009
44465
  if (attempt >= 20) throw error;
44010
- await delay2(500);
44466
+ await delay3(500);
44011
44467
  }
44012
44468
  }
44013
44469
  if (lifecycle.state === "PAIRED") await pauseInitialPairingIngress(lifecycle.state, gatewayIngress, pair);
@@ -44015,7 +44471,7 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
44015
44471
  for (let attempt = 0; ; attempt++) {
44016
44472
  if ((await cloudClient.observe()).connected) break;
44017
44473
  if (attempt >= 30) throw new Error("TRAVEL_PAIRING_HEALTH");
44018
- await delay2(500);
44474
+ await delay3(500);
44019
44475
  }
44020
44476
  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
44477
  await new Promise((done, reject) => {
@@ -44052,7 +44508,7 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
44052
44508
  localClient.close();
44053
44509
  cloudClient.close();
44054
44510
  authority.close();
44055
- owner.close();
44511
+ owner2.close();
44056
44512
  tls2.key.fill(0);
44057
44513
  }
44058
44514
  };
@@ -44067,7 +44523,7 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
44067
44523
  localClient.close();
44068
44524
  cloudClient.close();
44069
44525
  authority.close();
44070
- owner.close();
44526
+ owner2.close();
44071
44527
  tls2.key.fill(0);
44072
44528
  }
44073
44529
  throw error;