engine7 7.1.151 → 7.1.152

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.
@@ -3706,8 +3706,9 @@ function invalidateDerivedDependencies(db2, event2) {
3706
3706
  }
3707
3707
  return invalidateChildren(db2, event2.scopeId, pending, event2.kind);
3708
3708
  }
3709
- function invalidateScopeDependencies(db2, scope, parent, reason) {
3710
- const children = db2.prepare("SELECT child_kind,child_id FROM memory_dependencies WHERE scope_id=? AND parent_kind='scope' AND parent_id=?").all(scope, parent);
3709
+ function invalidateScopeDependencies(db2, scope, parent, reason, options = {}) {
3710
+ let children = db2.prepare("SELECT child_kind,child_id FROM memory_dependencies WHERE scope_id=? AND parent_kind='scope' AND parent_id=?").all(scope, parent);
3711
+ if (options.skipKinds?.size) children = children.filter((child) => !options.skipKinds.has(child.child_kind));
3711
3712
  invalidateChildren(db2, scope, children, reason);
3712
3713
  }
3713
3714
  function invalidateChildren(db2, scope, pending, reason) {
@@ -3727,7 +3728,7 @@ function invalidateChildren(db2, scope, pending, reason) {
3727
3728
  }
3728
3729
  const state2 = child.deleted ? "deleted" : "needs_revalidation";
3729
3730
  db2.prepare(`UPDATE memory_derivations SET state=?,reason=?,updated_at=?
3730
- WHERE scope_id=? AND child_kind=? AND child_id=? AND state IN ('current','needs_revalidation','invalid') AND state<>?`).run(state2, reason, (/* @__PURE__ */ new Date()).toISOString(), scope, child.child_kind, child.child_id, state2);
3731
+ WHERE scope_id=? AND child_kind=? AND child_id=? AND state IN ('current','needs_revalidation') AND state<>?`).run(state2, reason, (/* @__PURE__ */ new Date()).toISOString(), scope, child.child_kind, child.child_id, state2);
3731
3732
  result.push(child.child_id);
3732
3733
  pending.push(...db2.prepare("SELECT child_kind,child_id,role FROM memory_dependencies WHERE scope_id=? AND parent_kind='artifact' AND parent_id=?").all(scope, child.child_id).map((row) => ({ ...row, deleted: child.deleted && row.role === "supports" })));
3733
3734
  }
@@ -4406,7 +4407,7 @@ import { createHash as createHash10 } from "node:crypto";
4406
4407
  function projectedSourceIdFromScopeId(id2, originKey, sourceVersion) {
4407
4408
  return "src_" + digest2([id2, originKey, sourceVersion]);
4408
4409
  }
4409
- var SOURCE_SCHEMA, SOURCE_ALIAS_SCHEMA, digest2, SourceStore;
4410
+ var RECEIVED_INVALIDATION_SKIP, SOURCE_SCHEMA, SOURCE_ALIAS_SCHEMA, digest2, SourceStore;
4410
4411
  var init_source_store = __esm({
4411
4412
  "src/mem7/core/source-store.ts"() {
4412
4413
  "use strict";
@@ -4418,6 +4419,7 @@ var init_source_store = __esm({
4418
4419
  init_watermarks();
4419
4420
  init_interpretation_impact();
4420
4421
  init_conversation_text();
4422
+ RECEIVED_INVALIDATION_SKIP = /* @__PURE__ */ new Set(["foresight"]);
4421
4423
  SOURCE_SCHEMA = `
4422
4424
  CREATE TABLE memory_scopes (
4423
4425
  scope_id TEXT PRIMARY KEY, owner_id TEXT NOT NULL, app_id TEXT NOT NULL, project_id TEXT NOT NULL,
@@ -4599,8 +4601,8 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
4599
4601
  if (this.db.prepare("SELECT 1 FROM memory_sources WHERE scope_id=? AND origin_key=? AND interpretation_status='deleted'").get(id2, input.originKey)) throw new Error("DELETED_EVIDENCE");
4600
4602
  if (version !== Number(latest.version ?? 0) + 1) throw new Error("SOURCE_VERSION_CONFLICT: edits must follow the previous version");
4601
4603
  this.db.prepare("UPDATE memory_scopes SET source_seq=source_seq+1,context_revision=context_revision+1 WHERE scope_id=?").run(id2);
4602
- invalidateScopeDependencies(this.db, id2, "sources", "source.received");
4603
- invalidateScopeDependencies(this.db, id2, "context", "source.received");
4604
+ invalidateScopeDependencies(this.db, id2, "sources", "source.received", { skipKinds: RECEIVED_INVALIDATION_SKIP });
4605
+ invalidateScopeDependencies(this.db, id2, "context", "source.received", { skipKinds: RECEIVED_INVALIDATION_SKIP });
4604
4606
  const seq = Number(this.db.prepare("SELECT source_seq FROM memory_scopes WHERE scope_id=?").get(id2).source_seq);
4605
4607
  const sourceId = projectedSourceIdFromScopeId(id2, input.originKey, version);
4606
4608
  const receiptId = "rcpt_" + digest2([id2, sourceId]);
@@ -7964,6 +7966,13 @@ function tokenize(text2) {
7964
7966
  function tokenizeToField(text2) {
7965
7967
  return tokenize(text2).join(" ");
7966
7968
  }
7969
+ function cjkBigrams(text2) {
7970
+ const out = [];
7971
+ for (const seg of String(text2 ?? "").match(/[\u4e00-\u9fff]{2,}/g) ?? []) {
7972
+ for (let i = 0; i + 1 < seg.length; i++) out.push(seg.slice(i, i + 2));
7973
+ }
7974
+ return out;
7975
+ }
7967
7976
  var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba;
7968
7977
  var init_tokenizer = __esm({
7969
7978
  "src/mem7/core/tokenizer.ts"() {
@@ -10456,7 +10465,7 @@ function contentHash(text2) {
10456
10465
  function mem7Root(stateDir) {
10457
10466
  return join16(stateDir, "mem7");
10458
10467
  }
10459
- var STALE_ARTIFACT_FORCE_MS, SCHEMA, AGENT_SCHEMA, Mem7Store;
10468
+ var STALE_ARTIFACT_FORCE_MS, STARVATION_GRACE_MS, SCHEMA, AGENT_SCHEMA, Mem7Store;
10460
10469
  var init_store = __esm({
10461
10470
  "src/mem7/core/store.ts"() {
10462
10471
  "use strict";
@@ -10494,6 +10503,7 @@ var init_store = __esm({
10494
10503
  init_job_retention();
10495
10504
  init_retire_graph_audits();
10496
10505
  STALE_ARTIFACT_FORCE_MS = 2 * 36e5;
10506
+ STARVATION_GRACE_MS = 36e5;
10497
10507
  SCHEMA = `
10498
10508
  CREATE TABLE IF NOT EXISTS memcells (
10499
10509
  id TEXT PRIMARY KEY,
@@ -11584,7 +11594,7 @@ ${e.outcome}
11584
11594
  return this.transaction(() => {
11585
11595
  const kindFilter = options.kinds ? ` AND kind IN (${options.kinds.map(() => "?").join(",")})` : "";
11586
11596
  const scopeFilter = options.scopeId !== void 0 ? " AND scope_id=?" : "";
11587
- const rows = this.db.prepare(`SELECT * FROM ome_jobs j INDEXED BY ${options.scopeId !== void 0 && options.kinds?.length === 1 ? "idx_jobs_scope_priority" : "idx_jobs_runnable_priority"}
11597
+ const base = `SELECT * FROM ome_jobs j INDEXED BY ${options.scopeId !== void 0 && options.kinds?.length === 1 ? "idx_jobs_scope_priority" : "idx_jobs_runnable_priority"}
11588
11598
  WHERE status IN ('pending','running') AND NOT EXISTS (SELECT 1 FROM memory_job_holds h WHERE h.job_id=j.id AND h.released_at IS NULL)
11589
11599
  AND ((status='pending' AND next_run_at<=?)
11590
11600
  OR (status='running' AND COALESCE(lease_until,0)<=?))${kindFilter}${scopeFilter}
@@ -11604,40 +11614,48 @@ ${e.outcome}
11604
11614
  -- Cognition rebuilds its read set at claim time; delayed old work must not fence fresh judgments.
11605
11615
  AND (kind IN ('social.interpret','source.interpret','relationship.cognition') OR scope_id NOT LIKE 'resource:%' OR NOT EXISTS (SELECT 1 FROM ome_jobs prior
11606
11616
  WHERE prior.scope_id=j.scope_id AND prior.id<j.id AND prior.status IN ('pending','running')
11607
- AND NOT EXISTS (SELECT 1 FROM memory_job_holds h WHERE h.job_id=prior.id AND h.released_at IS NULL)) OR scope_id IS NULL)
11608
- -- Retrying an old deferred job must not reserve the next stage budget.
11609
- -- Boundary/resource predecessor predicates above still enforce ordering.
11610
- ORDER BY priority,next_run_at,id LIMIT ?`).all(now2, now2, ...options.kinds ?? [], ...options.scopeId !== void 0 ? [options.scopeId] : [], now2, limit);
11611
- const claimedScopes = /* @__PURE__ */ new Set();
11612
- return rows.flatMap((row) => {
11613
- if (!this.jobProvenance.prepareForClaim(row.id, now2)) return [];
11614
- const updated = this.db.prepare("SELECT * FROM ome_jobs WHERE id=?").get(row.id);
11615
- if (updated.scope_id !== row.scope_id && updated.scope_id) {
11616
- const conflict = this.db.prepare(`SELECT 1 FROM ome_jobs j WHERE j.scope_id=? AND j.id<>?
11617
- AND (j.status='running' AND j.lease_until>? OR ? LIKE 'resource:%' AND j.id<? AND j.status IN ('pending','running')
11618
- AND NOT EXISTS (SELECT 1 FROM memory_job_holds h WHERE h.job_id=j.id AND h.released_at IS NULL))`).get(updated.scope_id, updated.id, now2, updated.scope_id, updated.id);
11619
- if (conflict) return [];
11620
- }
11621
- return [updated];
11622
- }).filter((row) => {
11623
- if (!row.scope_id) return true;
11624
- if (claimedScopes.has(row.scope_id)) return false;
11625
- claimedScopes.add(row.scope_id);
11626
- return true;
11627
- }).map((row) => {
11628
- const leaseToken = randomUUID10();
11629
- this.db.prepare("UPDATE ome_jobs SET status='running',lease_token=?,lease_until=? WHERE id=?").run(leaseToken, now2 + leaseMs, row.id);
11630
- return {
11631
- id: row.id,
11632
- kind: row.kind,
11633
- payload: JSON.parse(row.payload),
11634
- attempts: row.attempts,
11635
- leaseToken,
11636
- inputVersion: row.input_version,
11637
- scopeId: row.scope_id ?? void 0,
11638
- result: row.result_json === null ? void 0 : JSON.parse(row.result_json)
11639
- };
11640
- });
11617
+ AND NOT EXISTS (SELECT 1 FROM memory_job_holds h WHERE h.job_id=prior.id AND h.released_at IS NULL)) OR scope_id IS NULL)`;
11618
+ const select = (starved2) => {
11619
+ const sql = `${base}${starved2 ? " AND status='pending' AND next_run_at<=?" : ""}
11620
+ ORDER BY priority,next_run_at,id LIMIT ?`;
11621
+ const args = starved2 ? [now2, now2, ...options.kinds ?? [], ...options.scopeId !== void 0 ? [options.scopeId] : [], now2, now2 - STARVATION_GRACE_MS, limit] : [now2, now2, ...options.kinds ?? [], ...options.scopeId !== void 0 ? [options.scopeId] : [], now2, limit];
11622
+ return this.db.prepare(sql).all(...args);
11623
+ };
11624
+ const claim = (rows) => {
11625
+ const claimedScopes = /* @__PURE__ */ new Set();
11626
+ return rows.flatMap((row) => {
11627
+ if (!this.jobProvenance.prepareForClaim(row.id, now2)) return [];
11628
+ const updated = this.db.prepare("SELECT * FROM ome_jobs WHERE id=?").get(row.id);
11629
+ if (updated.scope_id !== row.scope_id && updated.scope_id) {
11630
+ const conflict = this.db.prepare(`SELECT 1 FROM ome_jobs j WHERE j.scope_id=? AND j.id<>?
11631
+ AND (j.status='running' AND j.lease_until>? OR ? LIKE 'resource:%' AND j.id<? AND j.status IN ('pending','running')
11632
+ AND NOT EXISTS (SELECT 1 FROM memory_job_holds h WHERE h.job_id=j.id AND h.released_at IS NULL))`).get(updated.scope_id, updated.id, now2, updated.scope_id, updated.id);
11633
+ if (conflict) return [];
11634
+ }
11635
+ return [updated];
11636
+ }).filter((row) => {
11637
+ if (!row.scope_id) return true;
11638
+ if (claimedScopes.has(row.scope_id)) return false;
11639
+ claimedScopes.add(row.scope_id);
11640
+ return true;
11641
+ }).map((row) => {
11642
+ const leaseToken = randomUUID10();
11643
+ this.db.prepare("UPDATE ome_jobs SET status='running',lease_token=?,lease_until=? WHERE id=?").run(leaseToken, now2 + leaseMs, row.id);
11644
+ return {
11645
+ id: row.id,
11646
+ kind: row.kind,
11647
+ payload: JSON.parse(row.payload),
11648
+ attempts: row.attempts,
11649
+ leaseToken,
11650
+ inputVersion: row.input_version,
11651
+ scopeId: row.scope_id ?? void 0,
11652
+ result: row.result_json === null ? void 0 : JSON.parse(row.result_json)
11653
+ };
11654
+ });
11655
+ };
11656
+ if (options.staleOnly) return claim(select(true));
11657
+ const starved = claim(select(true));
11658
+ return starved.length ? starved : claim(select(false));
11641
11659
  });
11642
11660
  }
11643
11661
  /** Compatibility entry point: only expired leases can be recovered. */
@@ -12200,6 +12218,12 @@ function loadArrow() {
12200
12218
  }
12201
12219
  return arrowPromise;
12202
12220
  }
12221
+ function shortCjkQueryBigrams(text2) {
12222
+ const chars = (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
12223
+ if (!chars || chars > 6) return null;
12224
+ const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
12225
+ return grams.length ? grams : null;
12226
+ }
12203
12227
  function buildSchemas(arrow) {
12204
12228
  const vecField = () => new arrow.Field("vector", new arrow.FixedSizeList(VECTOR_DIM, new arrow.Field("item", new arrow.Float32(), true)), true);
12205
12229
  const commonFields = () => [
@@ -12296,7 +12320,7 @@ function textColumnOf(kind) {
12296
12320
  return "fact";
12297
12321
  }
12298
12322
  }
12299
- var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
12323
+ var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, BM25_TEXT_FIELDS, sqlLiteral, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
12300
12324
  var init_vector_store = __esm({
12301
12325
  "src/mem7/core/vector-store.ts"() {
12302
12326
  "use strict";
@@ -12327,6 +12351,14 @@ var init_vector_store = __esm({
12327
12351
  agent_case: ["task_intent_tokens", "approach_tokens"],
12328
12352
  agent_skill: ["description_tokens", "content_tokens"]
12329
12353
  };
12354
+ BM25_TEXT_FIELDS = {
12355
+ foresight: ["foresight", "evidence"],
12356
+ episode: ["episode"],
12357
+ atomic_fact: ["fact"],
12358
+ agent_case: ["task_intent", "approach"],
12359
+ agent_skill: ["description", "content"]
12360
+ };
12361
+ sqlLiteral = (value2) => value2.replace(/'/g, "''");
12330
12362
  RRF_K = 60;
12331
12363
  warnedFts = /* @__PURE__ */ new Set();
12332
12364
  warnedVecIdx = /* @__PURE__ */ new Set();
@@ -12924,6 +12956,28 @@ var init_vector_store = __esm({
12924
12956
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
12925
12957
  }
12926
12958
  }
12959
+ const grams = shortCjkQueryBigrams(queryText);
12960
+ if (grams) {
12961
+ try {
12962
+ const textCols = BM25_TEXT_FIELDS[kind];
12963
+ const expr = textCols.map((col) => `(${grams.map((g) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" OR ");
12964
+ const where2 = compileFilter(opts.filter);
12965
+ const extra = await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(topK * 3).toArray();
12966
+ const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
12967
+ for (const r of extra) {
12968
+ const rid = String(r.id ?? "");
12969
+ if (!rid) continue;
12970
+ const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
12971
+ const matched = grams.filter((gram) => text2.includes(gram)).length;
12972
+ if (!matched) continue;
12973
+ const score = maxScore + matched / grams.length;
12974
+ const cur = best.get(rid);
12975
+ if (cur) cur._score = Math.max(Number(cur._score ?? 0), score);
12976
+ else best.set(rid, { ...r, _score: score });
12977
+ }
12978
+ } catch {
12979
+ }
12980
+ }
12927
12981
  return this.visibleRows(kind, [...best.values()]).filter((r) => Number(r._score ?? 0) > 0).sort((a, b) => Number(b._score ?? 0) - Number(a._score ?? 0)).slice(0, topK).map((r) => ({ ...this.toHit(kind, r), distance: 0, score: Number(r._score ?? 0) }));
12928
12982
  } catch (err) {
12929
12983
  const msg2 = String(err?.message ?? err);
@@ -21265,8 +21319,10 @@ async function executeOneHook(hook, hookEvent, hookName, hookInput, toolUseID, s
21265
21319
  hookEvent,
21266
21320
  durationMs: durationMs2
21267
21321
  });
21322
+ const output = syncOutput.hookSpecificOutput;
21268
21323
  return {
21269
21324
  ...processed,
21325
+ ...hook.id === "skill-gate-prompt" && output?.hookEventName === "UserPromptSubmit" && output.selectSkill === true ? { selectSkill: true } : {},
21270
21326
  outcome: processed.blockingError ? "blocking" : "success",
21271
21327
  hook
21272
21328
  };
@@ -21368,6 +21424,7 @@ function aggregateResults(results) {
21368
21424
  if (result.permissionBehavior) {
21369
21425
  aggregated.permissionBehavior = result.permissionBehavior;
21370
21426
  }
21427
+ if (result.selectSkill) aggregated.selectSkill = true;
21371
21428
  if (result.additionalContext) {
21372
21429
  aggregated.additionalContexts.push(result.additionalContext);
21373
21430
  }
@@ -23596,6 +23653,412 @@ var init_store2 = __esm({
23596
23653
  }
23597
23654
  });
23598
23655
 
23656
+ // src/skills/recent-user-texts.ts
23657
+ var init_recent_user_texts = __esm({
23658
+ "src/skills/recent-user-texts.ts"() {
23659
+ "use strict";
23660
+ init_strip_injected();
23661
+ }
23662
+ });
23663
+
23664
+ // src/core/query-skill-selection.ts
23665
+ async function selectSkillCall(provider, params, allowedNames, recordUsage) {
23666
+ const timeout = AbortSignal.timeout(5e3);
23667
+ const signal = AbortSignal.any([params.signal, timeout]);
23668
+ const chunks = [];
23669
+ let calledSkill = false;
23670
+ let skillName = "";
23671
+ let requestComplete = false;
23672
+ let otherCut = false;
23673
+ try {
23674
+ for await (const chunk of provider.streamChat({
23675
+ ...params,
23676
+ signal,
23677
+ httpRetry: { maxRetries: 0 }
23678
+ })) {
23679
+ signal.throwIfAborted();
23680
+ if (chunk.type === "error") return { outcome: "upstream-error" };
23681
+ if (chunk.type === "tool_call") {
23682
+ if (calledSkill || !chunk.tool_call?.id || chunk.tool_call.function?.name !== SKILL_TOOL_NAME) return { outcome: "invalid" };
23683
+ let args;
23684
+ try {
23685
+ args = JSON.parse(chunk.tool_call.function.arguments);
23686
+ } catch {
23687
+ return { outcome: "invalid" };
23688
+ }
23689
+ if (typeof args?.skill !== "string" || !allowedNames.has(args.skill.trim().replace(/^\//, ""))) return { outcome: "invalid" };
23690
+ calledSkill = true;
23691
+ skillName = args.skill.trim().replace(/^\//, "");
23692
+ chunks.push(chunk);
23693
+ }
23694
+ if (chunk.type === "done") {
23695
+ if (chunk.usage) recordUsage(chunk.usage);
23696
+ requestComplete ||= chunk.requestComplete === true;
23697
+ otherCut ||= ["incomplete", "content_filter"].includes(chunk.stopReason ?? "");
23698
+ }
23699
+ }
23700
+ } catch (error) {
23701
+ params.signal.throwIfAborted();
23702
+ if (error instanceof Error && /^TRAVEL_/.test(error.message)) throw error;
23703
+ return { outcome: timeout.aborted ? "timeout" : "upstream-error" };
23704
+ }
23705
+ params.signal.throwIfAborted();
23706
+ if (timeout.aborted) return { outcome: "timeout" };
23707
+ if (!requestComplete || otherCut) return { outcome: "incomplete" };
23708
+ return calledSkill ? { outcome: "selected", skill: skillName, chunks } : { outcome: "no-skill" };
23709
+ }
23710
+ var SKILL_SELECTION_PROMPT, SKILL_SELECTION_MAX_TOKENS;
23711
+ var init_query_skill_selection = __esm({
23712
+ "src/core/query-skill-selection.ts"() {
23713
+ "use strict";
23714
+ init_constants4();
23715
+ init_types();
23716
+ init_recent_user_texts();
23717
+ SKILL_SELECTION_PROMPT = "\u6309 currentTask \u7684\u76EE\u6807\u548C\u6240\u5904\u9636\u6BB5\uFF0C\u5224\u65AD\u54EA\u9879\u5DF2\u5B89\u88C5\u6280\u80FD\u80FD\u5207\u5B9E\u5E2E\u52A9\u5B8C\u6210\u8FD9\u8F6E\u4EFB\u52A1\uFF0C\u6D41\u7A0B\u7C7B\u6280\u80FD\u7EA6\u675F\u505A\u6CD5\uFF0C\u6587\u6863\u3001\u8868\u683C\u3001\u53D1\u5E03\u7B49\u9886\u57DF\u7C7B\u6280\u80FD\u63D0\u4F9B\u4E13\u95E8\u80FD\u529B\u3002recentDialogue \u53EA\u7528\u4E8E\u7406\u89E3\u6307\u4EE3\u3002\u4E0B\u9762\u662F\u5DF2\u5B89\u88C5\u6280\u80FD\u7684\u540D\u79F0\u548C\u7528\u9014\u3002\u4F60\u53EA\u8D1F\u8D23\u6311\u9009\u6280\u80FD\uFF0C\u4E0D\u8D1F\u8D23\u56DE\u7B54\u4EFB\u52A1\u672C\u8EAB\uFF1A\u6B63\u5F0F\u56DE\u7B54\u7531\u540E\u7EED\u9636\u6BB5\u5B8C\u6210\uFF0C\u8FD9\u91CC\u4E0D\u8981\u5199\u4EFB\u4F55\u56DE\u7B54\u3002\u9002\u7528\u65F6\u76F4\u63A5\u8C03\u7528\u4E00\u9879\u6700\u5408\u9002\u7684 Skill\uFF0C\u4E0D\u8981\u8F93\u51FA\u4EFB\u4F55\u8BF4\u660E\u6587\u5B57\u3002\u7528\u666E\u901A\u5DE5\u5177\u6216\u53EA\u8BFB\u64CD\u4F5C\u4E5F\u53EF\u4EE5\u9075\u5FAA\u6D41\u7A0B\u3002\u5982\u679C\u5BF9\u65B9\u660E\u786E\u8981\u6C42\u8DF3\u8FC7\u3001\u5F53\u524D\u4EFB\u52A1\u6CA1\u6709\u9002\u7528\u7684\u6280\u80FD\uFF0C\u6216\u7F3A\u5C11\u9009\u51C6\u6240\u9700\u7684\u4FE1\u606F\uFF0C\u4E0D\u8C03\u7528\u4EFB\u4F55\u5DE5\u5177\uFF0C\u4E5F\u4E0D\u5199\u4EFB\u4F55\u5B57\uFF0C\u7ACB\u5373\u7ED3\u675F\u3002\u6B63\u5E38\u5DE5\u4F5C\u9636\u6BB5\u4F1A\u63D0\u4F9B\u5B8C\u6574\u5BF9\u8BDD\u548C\u9879\u76EE\u5DE5\u5177\u3002";
23718
+ SKILL_SELECTION_MAX_TOKENS = 64;
23719
+ }
23720
+ });
23721
+
23722
+ // src/skills/scanner.ts
23723
+ import * as path27 from "node:path";
23724
+ import * as fs23 from "node:fs";
23725
+ function scanSkills(skillsDir) {
23726
+ if (!fs23.existsSync(skillsDir)) {
23727
+ console.log(`[skills] Directory not found: ${skillsDir}`);
23728
+ return [];
23729
+ }
23730
+ const skills = [];
23731
+ const scanDir = (dir, depth, seen) => {
23732
+ const entries = fs23.readdirSync(dir, { withFileTypes: true });
23733
+ for (const entry of entries) {
23734
+ if (entry.name.startsWith(".") || entry.name === "_archive") continue;
23735
+ const full = path27.join(dir, entry.name);
23736
+ let isDir = entry.isDirectory();
23737
+ let isFile = entry.isFile();
23738
+ if (entry.isSymbolicLink()) {
23739
+ try {
23740
+ const st = fs23.statSync(full);
23741
+ isDir = st.isDirectory();
23742
+ isFile = st.isFile();
23743
+ } catch {
23744
+ console.warn(`[skills] Broken symlink, skipped: ${full}`);
23745
+ continue;
23746
+ }
23747
+ }
23748
+ if (isDir && depth < 3) {
23749
+ let real;
23750
+ try {
23751
+ real = fs23.realpathSync(full);
23752
+ } catch {
23753
+ continue;
23754
+ }
23755
+ if (seen.has(real)) continue;
23756
+ seen.add(real);
23757
+ scanDir(full, depth + 1, seen);
23758
+ continue;
23759
+ }
23760
+ if (!isFile || entry.name !== "SKILL.md") continue;
23761
+ try {
23762
+ const content = fs23.readFileSync(full, "utf-8");
23763
+ const frontmatter = parseFrontmatter(content);
23764
+ if (!frontmatter.name) {
23765
+ console.warn(`[skills] Skipping ${full}: missing 'name' in frontmatter`);
23766
+ continue;
23767
+ }
23768
+ const rel = path27.relative(skillsDir, full).split(path27.sep).join("/");
23769
+ skills.push({
23770
+ name: frontmatter.name,
23771
+ description: frontmatter.description || "",
23772
+ location: `skills/${rel}`,
23773
+ ...frontmatter
23774
+ });
23775
+ } catch (err) {
23776
+ console.warn(`[skills] Error parsing ${full}: ${err.message}`);
23777
+ }
23778
+ }
23779
+ };
23780
+ scanDir(skillsDir, 0, /* @__PURE__ */ new Set([fs23.realpathSync(skillsDir)]));
23781
+ console.log(`[skills] Scanned ${skills.length} skills from ${skillsDir}`);
23782
+ return skills;
23783
+ }
23784
+ function parseFrontmatter(content) {
23785
+ const result = {};
23786
+ const match = content.match(/^---\s*\n([\s\S]*?)\n---/);
23787
+ if (!match) return result;
23788
+ const lines = match[1].split("\n");
23789
+ let i = 0;
23790
+ while (i < lines.length) {
23791
+ const line = lines[i];
23792
+ const colonIdx = line.indexOf(":");
23793
+ if (colonIdx === -1) {
23794
+ i++;
23795
+ continue;
23796
+ }
23797
+ const key3 = line.slice(0, colonIdx).trim();
23798
+ let value2 = line.slice(colonIdx + 1).trim();
23799
+ if (value2.startsWith('"') && value2.endsWith('"') || value2.startsWith("'") && value2.endsWith("'")) {
23800
+ value2 = value2.slice(1, -1);
23801
+ result[key3] = value2;
23802
+ i++;
23803
+ continue;
23804
+ } else if (value2 === "|" || value2 === ">") {
23805
+ const blockLines = [];
23806
+ i++;
23807
+ while (i < lines.length && lines[i].startsWith(" ")) {
23808
+ blockLines.push(lines[i].slice(2));
23809
+ i++;
23810
+ }
23811
+ result[key3] = blockLines.join("\n").trim();
23812
+ continue;
23813
+ } else if (value2.startsWith("[") && value2.endsWith("]")) {
23814
+ result[key3] = value2.slice(1, -1).split(",").map((s) => s.trim());
23815
+ i++;
23816
+ continue;
23817
+ } else if (value2.includes(" ") && !value2.startsWith('"')) {
23818
+ result[key3] = value2;
23819
+ } else {
23820
+ result[key3] = value2;
23821
+ }
23822
+ i++;
23823
+ }
23824
+ return result;
23825
+ }
23826
+ var init_scanner = __esm({
23827
+ "src/skills/scanner.ts"() {
23828
+ "use strict";
23829
+ }
23830
+ });
23831
+
23832
+ // src/tools/SkillTool/SkillTool.ts
23833
+ import { createHash as createHash36 } from "node:crypto";
23834
+ import * as fs24 from "node:fs";
23835
+ import * as path28 from "node:path";
23836
+ function getSkillSelectionCatalog() {
23837
+ return selectionCatalog;
23838
+ }
23839
+ function getCharBudget(contextWindowTokens) {
23840
+ if (contextWindowTokens) {
23841
+ return Math.floor(contextWindowTokens * CHARS_PER_TOKEN * SKILL_BUDGET_CONTEXT_PERCENT);
23842
+ }
23843
+ return DEFAULT_CHAR_BUDGET;
23844
+ }
23845
+ function stringWidth(str) {
23846
+ return str.length;
23847
+ }
23848
+ function truncate(str, maxLen) {
23849
+ if (str.length <= maxLen) return str;
23850
+ return str.slice(0, maxLen - 1) + "\u2026";
23851
+ }
23852
+ function getCommandDescription(skill) {
23853
+ return (skill.description || "").length > MAX_LISTING_DESC_CHARS ? (skill.description || "").slice(0, MAX_LISTING_DESC_CHARS - 1) + "\u2026" : skill.description || "";
23854
+ }
23855
+ function formatSkillsListing(skills, contextWindowTokens) {
23856
+ if (skills.length === 0) return "";
23857
+ const budget = getCharBudget(contextWindowTokens);
23858
+ const fullEntries = skills.map((s) => ({
23859
+ skill: s,
23860
+ full: `- ${s.name}: ${getCommandDescription(s)}`
23861
+ }));
23862
+ const fullTotal = fullEntries.reduce((sum, e) => sum + stringWidth(e.full), 0) + (fullEntries.length - 1);
23863
+ if (fullTotal <= budget) {
23864
+ return fullEntries.map((e) => e.full).join("\n");
23865
+ }
23866
+ const nameOverhead = skills.reduce((sum, s) => sum + stringWidth(s.name) + 4, 0) + (skills.length - 1);
23867
+ const availableForDescs = budget - nameOverhead;
23868
+ const maxDescLen = Math.floor(availableForDescs / skills.length);
23869
+ if (maxDescLen < MIN_DESC_LENGTH) {
23870
+ return skills.map((s) => `- ${s.name}`).join("\n");
23871
+ }
23872
+ return skills.map((s) => {
23873
+ const description = getCommandDescription(s);
23874
+ return `- ${s.name}: ${truncate(description, maxDescLen)}`;
23875
+ }).join("\n");
23876
+ }
23877
+ function buildSkillToolPrompt() {
23878
+ return `Execute a skill within the main conversation
23879
+
23880
+ Skills provide specialized capabilities and domain knowledge.
23881
+
23882
+ When users reference a "slash command" or "/<something>" (e.g., "/commit", "/review-pr"), they are referring to a skill. Use this tool to invoke it.
23883
+
23884
+ How to invoke:
23885
+ - Use this tool with the skill name and optional arguments
23886
+ - Examples:
23887
+ - \`skill: "pdf"\` - invoke the pdf skill
23888
+ - \`skill: "commit", args: "-m 'Fix bug'"\` - invoke with arguments
23889
+ - \`skill: "review-pr", args: "123"\` - invoke with arguments
23890
+ - \`skill: "ms-office-suite:pdf"\` - invoke using fully qualified name
23891
+
23892
+ Important:
23893
+ - Available skills are listed in system-reminder messages in the conversation
23894
+ - Do not invoke a skill that is already running
23895
+ - Do not use this tool for built-in CLI commands (like /help, /clear, etc.)
23896
+ - If you see a <${COMMAND_NAME_TAG}> tag in the current conversation turn, the skill has ALREADY been loaded - follow the instructions directly instead of calling this tool again
23897
+ `;
23898
+ }
23899
+ function loadSkillContent(skillsDir, skill) {
23900
+ const skillMdPath = skill.location ? path28.join(skillsDir, skill.location.slice("skills/".length)) : path28.join(skillsDir, skill.name, "SKILL.md");
23901
+ if (!fs24.existsSync(skillMdPath)) return null;
23902
+ const content = fs24.readFileSync(skillMdPath, "utf-8");
23903
+ const dependencies2 = parseFrontmatter(content)["requires-tools"];
23904
+ const requiredTools = [...new Set((Array.isArray(dependencies2) ? dependencies2 : typeof dependencies2 === "string" ? dependencies2.split(/[\s,]+/) : []).filter((n) => typeof n === "string").map((n) => n.trim().replace(/^(['"])(.*)\1$/, "$2")).filter(Boolean))];
23905
+ const bodyMatch = content.match(/^---\s*\n[\s\S]*?\n---\s*\n([\s\S]*)/);
23906
+ const body = bodyMatch ? bodyMatch[1] : content;
23907
+ const skillDir = path28.dirname(skillMdPath);
23908
+ const normalizedDir = process.platform === "win32" ? skillDir.replace(/\\/g, "/") : skillDir;
23909
+ let finalContent = `Base directory for this skill: ${normalizedDir}
23910
+
23911
+ ${body}`;
23912
+ finalContent = finalContent.replace(/\$\{CLAUDE_SKILL_DIR\}/g, normalizedDir);
23913
+ finalContent = finalContent.replace(/\$\{CLAUDE_SESSION_ID\}/g, getSessionId());
23914
+ return { content: finalContent, requiredTools };
23915
+ }
23916
+ function getSessionId() {
23917
+ return String(process.pid);
23918
+ }
23919
+ function skillFingerprint(skill, body) {
23920
+ return createHash36("sha256").update(skill.location ?? skill.name).update("\0").update(body).digest("hex").slice(0, 16);
23921
+ }
23922
+ function findLoadedSkill(history, skill, fingerprint2, resolve47) {
23923
+ if (!history) return void 0;
23924
+ for (let i = history.length - 1; i >= 0; i--) {
23925
+ const message = history[i];
23926
+ if (!("role" in message) || message.role !== "tool" || message.is_error || typeof message.content !== "string") continue;
23927
+ let call;
23928
+ for (let j = i - 1; j >= 0 && !call; j--) {
23929
+ const previous = history[j];
23930
+ if ("role" in previous && previous.role === "assistant") call = (previous.tool_calls ?? []).find((c) => c.id === message.tool_call_id && c.function.name === SKILL_TOOL_NAME);
23931
+ }
23932
+ if (!call) continue;
23933
+ let args = {};
23934
+ try {
23935
+ args = JSON.parse(call.function.arguments);
23936
+ } catch {
23937
+ continue;
23938
+ }
23939
+ if (typeof args?.skill !== "string" || resolve47(args.skill.trim().replace(/^\//, "")) !== skill) continue;
23940
+ if (!message.content.includes(SKILL_FINGERPRINT_PREFIX + fingerprint2 + "]")) return void 0;
23941
+ return estimateMessageTokens(history.slice(i + 1)) <= SKILL_RELOAD_DISTANCE_TOKENS ? call.id : void 0;
23942
+ }
23943
+ return void 0;
23944
+ }
23945
+ function findLoadedSkillCall(history, skillName) {
23946
+ const resolve47 = resolveSkillFn;
23947
+ if (!history || !resolve47) return void 0;
23948
+ const skill = resolve47(skillName.trim().replace(/^\//, ""));
23949
+ if (!skill) return void 0;
23950
+ const content = loadSkillContent(skillsDirPath, skill);
23951
+ if (!content) return void 0;
23952
+ return findLoadedSkill(history, skill, skillFingerprint(skill, content.content), resolve47);
23953
+ }
23954
+ function registerSkillTool(skillsDir, skills, contextWindowTokens) {
23955
+ skillsDirPath = skillsDir;
23956
+ cachedSkills = skills;
23957
+ cachedContextWindowTokens = contextWindowTokens;
23958
+ const groupedSkills = /* @__PURE__ */ new Map();
23959
+ for (const skill of skills) {
23960
+ const parts = skill.location?.split("/");
23961
+ if (!parts || parts[0] !== "skills" || parts.length < 4 || skill.name.includes(":")) continue;
23962
+ const qualifiedName = `${parts[1]}:${skill.name}`;
23963
+ if (!groupedSkills.has(qualifiedName)) groupedSkills.set(qualifiedName, skill);
23964
+ }
23965
+ const resolveSkill = (name) => skills.find((s) => s.name === name) ?? groupedSkills.get(name);
23966
+ resolveSkillFn = resolveSkill;
23967
+ const entries = [];
23968
+ const allowedNames = /* @__PURE__ */ new Set();
23969
+ for (const skill of skills) {
23970
+ const shortName = skill.name;
23971
+ const parts = skill.location?.split("/");
23972
+ const qualifiedName = !shortName.includes(":") && parts && parts[0] === "skills" && parts.length >= 4 ? `${parts[1]}:${shortName}` : shortName;
23973
+ const names2 = [.../* @__PURE__ */ new Set([shortName, qualifiedName])].filter((candidate) => resolveSkill(candidate) === skill);
23974
+ if (names2.length === 0) continue;
23975
+ for (const name of names2) allowedNames.add(name);
23976
+ entries.push({ name: names2[0], description: getCommandDescription(skill) });
23977
+ }
23978
+ selectionCatalog = { entries, allowedNames };
23979
+ const descriptionText = buildSkillToolPrompt();
23980
+ cachedListing = formatSkillsListing(cachedSkills, contextWindowTokens);
23981
+ registry.register({
23982
+ name: SKILL_TOOL_NAME,
23983
+ description: descriptionText,
23984
+ schema: {
23985
+ type: "object",
23986
+ properties: {
23987
+ skill: { type: "string", description: 'The skill name. E.g., "commit", "review-pr", or "pdf"' },
23988
+ args: { type: "string", description: "Optional arguments for the skill" }
23989
+ },
23990
+ required: ["skill"]
23991
+ },
23992
+ // 对齐 CC SkillTool.call()
23993
+ handler: async (args, ctx) => {
23994
+ const skillName = (args.skill || "").trim();
23995
+ const skillArgs = args.args || "";
23996
+ if (!skillName) {
23997
+ return { content: "Invalid skill: empty name", isError: true };
23998
+ }
23999
+ const normalizedName = skillName.startsWith("/") ? skillName.substring(1) : skillName;
24000
+ const skill = resolveSkill(normalizedName);
24001
+ if (!skill) {
24002
+ const available = skills.map((s) => s.name).join(", ");
24003
+ return { content: `Unknown skill: ${normalizedName}. Available: ${available}`, isError: true };
24004
+ }
24005
+ const content = loadSkillContent(skillsDir, skill);
24006
+ if (!content) {
24007
+ return { content: `Skill file not found: ${normalizedName}`, isError: true };
24008
+ }
24009
+ const fingerprint2 = skillFingerprint(skill, content.content);
24010
+ const loadedEarlier = findLoadedSkill(ctx.toolResultHistory, skill, fingerprint2, resolveSkill);
24011
+ if (loadedEarlier) {
24012
+ return { content: `[\u6280\u80FD\u5DF2\u52A0\u8F7D\uFF1A${skill.name} \u6B63\u6587\u672A\u53D8\uFF0C\u89C1\u5DE5\u5177\u7ED3\u679C ${loadedEarlier}\uFF1B\u4E0D\u91CD\u590D\u6CE8\u5165\u3002]` };
24013
+ }
24014
+ let dependencyContent = "";
24015
+ if (content.requiredTools.length) {
24016
+ const loaded = loadToolSchemas(content.requiredTools, ctx);
24017
+ if (loaded.isError) return loaded;
24018
+ dependencyContent = `
24019
+ <${SKILL_DEPENDENCIES_TAG}>
24020
+ ${content.requiredTools.join("\n")}
24021
+ </${SKILL_DEPENDENCIES_TAG}>
24022
+ ${loaded.content}
24023
+ `;
24024
+ }
24025
+ const argLine = skillArgs ? `
24026
+
24027
+ User arguments: ${skillArgs}` : "";
24028
+ return { content: `Skill "${skill.name}" loaded. ${SKILL_FINGERPRINT_PREFIX}${fingerprint2}]${dependencyContent}
24029
+
24030
+ ${content.content}${argLine}` };
24031
+ },
24032
+ // 对齐 CC SkillTool properties
24033
+ isConcurrencySafe: () => false,
24034
+ isDestructive: () => false,
24035
+ isReadOnly: () => true
24036
+ });
24037
+ console.log(`[skills] SkillTool registered with ${cachedSkills.length} skills (budget: ${getCharBudget(contextWindowTokens)} chars)`);
24038
+ }
24039
+ function getSkillToolState() {
24040
+ return { skillsDirPath, contextWindowTokens: cachedContextWindowTokens, skillNames: cachedSkills.map((s) => s.name) };
24041
+ }
24042
+ var COMMAND_NAME_TAG, MIN_DESC_LENGTH, skillsDirPath, cachedSkills, selectionCatalog, cachedListing, cachedContextWindowTokens, resolveSkillFn, SKILL_FINGERPRINT_PREFIX, SKILL_RELOAD_DISTANCE_TOKENS;
24043
+ var init_SkillTool = __esm({
24044
+ "src/tools/SkillTool/SkillTool.ts"() {
24045
+ "use strict";
24046
+ init_registry();
24047
+ init_scanner();
24048
+ init_tool_loading();
24049
+ init_tokenEstimate();
24050
+ init_constants4();
24051
+ COMMAND_NAME_TAG = "command-name";
24052
+ MIN_DESC_LENGTH = 20;
24053
+ skillsDirPath = "";
24054
+ cachedSkills = [];
24055
+ selectionCatalog = { entries: [], allowedNames: /* @__PURE__ */ new Set() };
24056
+ cachedListing = "";
24057
+ SKILL_FINGERPRINT_PREFIX = "[fingerprint ";
24058
+ SKILL_RELOAD_DISTANCE_TOKENS = 16e3;
24059
+ }
24060
+ });
24061
+
23599
24062
  // src/memory/memdir/memoryTypes.ts
23600
24063
  var MEMORY_TYPES, TYPES_SECTION_INDIVIDUAL, WHAT_NOT_TO_SAVE_SECTION, MEMORY_DRIFT_CAVEAT, WHEN_TO_ACCESS_SECTION, TRUSTING_RECALL_SECTION, MEMORY_FRONTMATTER_EXAMPLE;
23601
24064
  var init_memoryTypes = __esm({
@@ -23760,8 +24223,8 @@ __export(memdir_exports, {
23760
24223
  loadMemoryPrompt: () => loadMemoryPrompt,
23761
24224
  truncateEntrypointContent: () => truncateEntrypointContent
23762
24225
  });
23763
- import { readFileSync as readFileSync19 } from "node:fs";
23764
- import { join as join36 } from "node:path";
24226
+ import { readFileSync as readFileSync21 } from "node:fs";
24227
+ import { join as join38 } from "node:path";
23765
24228
  function truncateEntrypointContent(raw) {
23766
24229
  const trimmed = raw.trim();
23767
24230
  const contentLines = trimmed.split("\n");
@@ -23854,11 +24317,11 @@ function buildMemoryLines(displayName, memoryDir, extraGuidelines, skipIndex = f
23854
24317
  }
23855
24318
  function buildMemoryPrompt(params) {
23856
24319
  const { displayName, memoryDir, extraGuidelines } = params;
23857
- const entrypoint = join36(memoryDir, ENTRYPOINT_NAME);
24320
+ const entrypoint = join38(memoryDir, ENTRYPOINT_NAME);
23858
24321
  let entrypointContent = params.entrypointContent ?? "";
23859
24322
  if (params.entrypointContent === void 0) {
23860
24323
  try {
23861
- entrypointContent = readFileSync19(entrypoint, "utf-8");
24324
+ entrypointContent = readFileSync21(entrypoint, "utf-8");
23862
24325
  } catch {
23863
24326
  }
23864
24327
  }
@@ -23904,8 +24367,8 @@ __export(context_analyzer_exports, {
23904
24367
  formatContextReport: () => formatContextReport,
23905
24368
  scanMemoryFiles: () => scanMemoryFiles
23906
24369
  });
23907
- import * as fs23 from "node:fs";
23908
- import * as path27 from "node:path";
24370
+ import * as fs25 from "node:fs";
24371
+ import * as path29 from "node:path";
23909
24372
  function estimateMessageTokens2(m) {
23910
24373
  let tokens = 0;
23911
24374
  if (typeof m.content === "string") {
@@ -24015,9 +24478,9 @@ function breakdownMessages(messages) {
24015
24478
  }
24016
24479
  async function scanMemoryFiles(workspace) {
24017
24480
  const files = [];
24018
- const soul = readFileIfExists(path27.join(workspace, "SOUL.md"));
24481
+ const soul = readFileIfExists(path29.join(workspace, "SOUL.md"));
24019
24482
  if (soul) files.push({ path: "SOUL.md", tokens: roughTokenCountEstimation(soul), stable: true });
24020
- const agents = readFileIfExists(path27.join(workspace, "AGENTS.md"));
24483
+ const agents = readFileIfExists(path29.join(workspace, "AGENTS.md"));
24021
24484
  if (agents) files.push({ path: "AGENTS.md", tokens: roughTokenCountEstimation(agents), stable: true });
24022
24485
  try {
24023
24486
  const { buildMemoryPrompt: buildMemoryPrompt2 } = await Promise.resolve().then(() => (init_memdir(), memdir_exports));
@@ -24033,7 +24496,7 @@ async function scanMemoryFiles(workspace) {
24033
24496
  }
24034
24497
  function readFileIfExists(filePath) {
24035
24498
  try {
24036
- if (fs23.existsSync(filePath)) return fs23.readFileSync(filePath, "utf-8");
24499
+ if (fs25.existsSync(filePath)) return fs25.readFileSync(filePath, "utf-8");
24037
24500
  } catch {
24038
24501
  }
24039
24502
  return null;
@@ -24304,6 +24767,8 @@ var init_query = __esm({
24304
24767
  init_task_manager();
24305
24768
  init_skill_gate();
24306
24769
  init_skill_gate();
24770
+ init_query_skill_selection();
24771
+ init_SkillTool();
24307
24772
  QueryEngine = class _QueryEngine {
24308
24773
  constructor(provider, options) {
24309
24774
  this.provider = provider;
@@ -24657,6 +25122,7 @@ var init_query = __esm({
24657
25122
  turnCount++;
24658
25123
  const steers = this.pendingSteers.splice(0);
24659
25124
  let steerConsumedThisTurn = false;
25125
+ let userSteerConsumedThisTurn = false;
24660
25126
  if (steers.length > 0) {
24661
25127
  for (const input of steers) {
24662
25128
  if (this.steerHistoryIds.has(input.id)) {
@@ -24688,6 +25154,7 @@ var init_query = __esm({
24688
25154
  if (collectStopEvidence) stopUserMessages.push(input.originalText ?? input.text);
24689
25155
  this.steerHistoryIds.add(input.id);
24690
25156
  steerConsumedThisTurn = true;
25157
+ userSteerConsumedThisTurn = true;
24691
25158
  yield {
24692
25159
  type: "user_input",
24693
25160
  message: steerMsg,
@@ -24943,7 +25410,53 @@ var init_query = __esm({
24943
25410
  let turnAborted = false;
24944
25411
  try {
24945
25412
  wholeQueryAbort.signal.throwIfAborted();
24946
- const view = normalizeMessagesForAPI(currentMessages).map((m) => {
25413
+ const beforeRequest = () => {
25414
+ wholeQueryAbort.signal.throwIfAborted();
25415
+ ac.signal.throwIfAborted();
25416
+ };
25417
+ const startRequest = () => {
25418
+ this.phase = "streaming";
25419
+ assertRuntimeAuthority(void 0, "INPUT");
25420
+ if (perTurnOptions?.onRequestStarted) {
25421
+ const start = perTurnOptions.onRequestStarted;
25422
+ setImmediate(() => {
25423
+ if (!wholeQueryAbort.signal.aborted) start();
25424
+ });
25425
+ }
25426
+ };
25427
+ let selected;
25428
+ const selectionInput = perTurnOptions?.skillSelectionInput;
25429
+ const skill = turnCount === 1 && maxTurns >= 2 && !userSteerConsumedThisTurn && !hasPendingUserInput() && selectionInput ? allToolDefs.find((tool) => tool.function.name === SKILL_TOOL_NAME) : void 0;
25430
+ const catalog = skill ? getSkillSelectionCatalog() : void 0;
25431
+ if (skill && selectionInput && catalog?.entries.length) {
25432
+ const input = normalizeMessagesForAPI([selectionInput]);
25433
+ const started = performance.now();
25434
+ startRequest();
25435
+ const selection = await selectSkillCall(queryProvider, {
25436
+ preferFastFallback,
25437
+ model: queryModel,
25438
+ messages: input,
25439
+ tools: [skill],
25440
+ systemStable: SKILL_SELECTION_PROMPT + "\n\n" + JSON.stringify(catalog.entries),
25441
+ maxTokens: SKILL_SELECTION_MAX_TOKENS,
25442
+ signal: ac.signal,
25443
+ beforeRequest: () => {
25444
+ assertHostTurnCurrent();
25445
+ beforeRequest();
25446
+ },
25447
+ disableThinking: true
25448
+ }, catalog.allowedNames, recordUsage);
25449
+ assertHostTurnCurrent();
25450
+ beforeRequest();
25451
+ console.log(`${this.logPrefix} [skill-selection] ${selection.outcome} ms=${Math.round(performance.now() - started)}`);
25452
+ if (hasPendingUserInput()) continue;
25453
+ if (selection.outcome === "selected") {
25454
+ if (findLoadedSkillCall(currentMessages, selection.skill)) {
25455
+ console.log(`${this.logPrefix} [skill-selection] already-loaded ${selection.skill}`);
25456
+ } else selected = selection.chunks;
25457
+ }
25458
+ }
25459
+ const view = (selected ? [] : normalizeMessagesForAPI(currentMessages)).map((m) => {
24947
25460
  if (!Array.isArray(m.content) || !m.imageInput?.observed || !queryModelRef) return m;
24948
25461
  const blocks = m.content.filter((b) => {
24949
25462
  if (b.type === "image" || b.type === "image_ref") return !!queryInputs?.includes("image");
@@ -24978,7 +25491,7 @@ ${hint}` : [...current2.content, { type: "text", text: hint }] };
24978
25491
  const fullSystemDynamic = deferredHint && perTurnSystemDynamic ? `${deferredHint}
24979
25492
 
24980
25493
  ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
24981
- if ((!this.options.agentLabel || this.options.agentLabel === "main") && isContextDumpEnabled()) {
25494
+ if (!selected && (!this.options.agentLabel || this.options.agentLabel === "main") && isContextDumpEnabled()) {
24982
25495
  try {
24983
25496
  const ws = process.env.ENGINE7_WORKSPACE;
24984
25497
  if (ws) {
@@ -24994,15 +25507,8 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
24994
25507
  } catch {
24995
25508
  }
24996
25509
  }
24997
- this.phase = "streaming";
24998
- assertRuntimeAuthority(void 0, "INPUT");
24999
- if (perTurnOptions?.onRequestStarted) {
25000
- const start = perTurnOptions.onRequestStarted;
25001
- setImmediate(() => {
25002
- if (!wholeQueryAbort.signal.aborted) start();
25003
- });
25004
- }
25005
- for await (const chunk of queryProvider.streamChat({
25510
+ if (!selected) startRequest();
25511
+ for await (const chunk of selected ?? queryProvider.streamChat({
25006
25512
  preferFastFallback,
25007
25513
  model: queryModel,
25008
25514
  messages: apiMessages,
@@ -25015,10 +25521,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
25015
25521
  maxTokens: this.resolveRequestMaxTokens(apiMessages, maxTokensOverride),
25016
25522
  temperature: this.options.temperature,
25017
25523
  signal: ac.signal,
25018
- beforeRequest: () => {
25019
- wholeQueryAbort.signal.throwIfAborted();
25020
- ac.signal.throwIfAborted();
25021
- },
25524
+ beforeRequest,
25022
25525
  disableThinking: this.options.disableThinking || !!perTurnEmotion
25023
25526
  // 情感模式关 thinking(对齐 deskBuddy)
25024
25527
  })) {
@@ -25379,6 +25882,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
25379
25882
  if (vcDelivery) await vcDelivery;
25380
25883
  }
25381
25884
  const { messages: toolResults, summaries } = toolRes;
25885
+ if (selected) console.log(`${this.logPrefix} [skill-selection] ${summaries.length === 1 && !summaries[0].isError ? "loaded" : "load-failed"}`);
25382
25886
  if (collectStopEvidence) stopToolResults.push(...summaries);
25383
25887
  for (const s of summaries) {
25384
25888
  try {
@@ -26446,30 +26950,30 @@ __export(teamHelpers_exports, {
26446
26950
  writeTeamFile: () => writeTeamFile,
26447
26951
  writeTeamFileAsync: () => writeTeamFileAsync
26448
26952
  });
26449
- import { mkdirSync as mkdirSync21, readFileSync as readFileSync21, writeFileSync as writeFileSync21 } from "node:fs";
26953
+ import { mkdirSync as mkdirSync21, readFileSync as readFileSync23, writeFileSync as writeFileSync21 } from "node:fs";
26450
26954
  import { mkdir as mkdir2, readFile, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
26451
- import { join as join38 } from "node:path";
26955
+ import { join as join40 } from "node:path";
26452
26956
  function initTeamDirs(stateDir) {
26453
26957
  _stateDir = stateDir;
26454
26958
  }
26455
26959
  function getTeamsDir() {
26456
- return join38(_stateDir, "teams");
26960
+ return join40(_stateDir, "teams");
26457
26961
  }
26458
26962
  function getTasksDir() {
26459
- return join38(_stateDir, "tasks");
26963
+ return join40(_stateDir, "tasks");
26460
26964
  }
26461
26965
  function sanitizeName(name) {
26462
26966
  return name.replace(/[^a-zA-Z0-9_-]/g, "-").toLowerCase();
26463
26967
  }
26464
26968
  function getTeamDir(teamName) {
26465
- return join38(getTeamsDir(), sanitizeName(teamName));
26969
+ return join40(getTeamsDir(), sanitizeName(teamName));
26466
26970
  }
26467
26971
  function getTeamFilePath(teamName) {
26468
- return join38(getTeamDir(teamName), "config.json");
26972
+ return join40(getTeamDir(teamName), "config.json");
26469
26973
  }
26470
26974
  function readTeamFile(teamName) {
26471
26975
  try {
26472
- const content = readFileSync21(getTeamFilePath(teamName), "utf-8");
26976
+ const content = readFileSync23(getTeamFilePath(teamName), "utf-8");
26473
26977
  return JSON.parse(content);
26474
26978
  } catch (e) {
26475
26979
  if (e?.code === "ENOENT") return null;
@@ -26570,7 +27074,7 @@ async function cleanupTeamDirectories(teamName) {
26570
27074
  } catch (error) {
26571
27075
  console.warn(`[teamHelpers] Failed to clean up team directory ${teamDir}: ${error.message}`);
26572
27076
  }
26573
- const tasksDir = join38(getTasksDir(), sanitizedName);
27077
+ const tasksDir = join40(getTasksDir(), sanitizedName);
26574
27078
  try {
26575
27079
  await rm2(tasksDir, { recursive: true, force: true });
26576
27080
  console.log(`[teamHelpers] Cleaned up tasks directory: ${tasksDir}`);
@@ -26579,7 +27083,7 @@ async function cleanupTeamDirectories(teamName) {
26579
27083
  }
26580
27084
  }
26581
27085
  function ensureTasksDir(taskListId) {
26582
- const dir = join38(getTasksDir(), taskListId);
27086
+ const dir = join40(getTasksDir(), taskListId);
26583
27087
  mkdirSync21(dir, { recursive: true });
26584
27088
  }
26585
27089
  function setLeaderTeamName(name) {
@@ -26760,9 +27264,9 @@ The user interacts primarily with the team lead. Your work is coordinated throug
26760
27264
 
26761
27265
  // src/swarm/teammateMailbox.ts
26762
27266
  import { mkdir as mkdir3, readFile as readFile2, writeFile as writeFile4 } from "node:fs/promises";
26763
- import { join as join39 } from "node:path";
27267
+ import { join as join41 } from "node:path";
26764
27268
  function getTeamsDir2() {
26765
- return join39(process.env.ENGINE_STATE_DIR || ".", "teams");
27269
+ return join41(process.env.ENGINE_STATE_DIR || ".", "teams");
26766
27270
  }
26767
27271
  function sanitizePathComponent(s) {
26768
27272
  return s.replace(/[^a-zA-Z0-9_-]/g, "-");
@@ -26771,12 +27275,12 @@ function getInboxPath(agentName, teamName) {
26771
27275
  const team = teamName || "default";
26772
27276
  const safeTeam = sanitizePathComponent(team);
26773
27277
  const safeAgentName = sanitizePathComponent(agentName);
26774
- return join39(getTeamsDir2(), safeTeam, "inboxes", `${safeAgentName}.json`);
27278
+ return join41(getTeamsDir2(), safeTeam, "inboxes", `${safeAgentName}.json`);
26775
27279
  }
26776
27280
  async function ensureInboxDir(teamName) {
26777
27281
  const team = teamName || "default";
26778
27282
  const safeTeam = sanitizePathComponent(team);
26779
- const inboxDir = join39(getTeamsDir2(), safeTeam, "inboxes");
27283
+ const inboxDir = join41(getTeamsDir2(), safeTeam, "inboxes");
26780
27284
  await mkdir3(inboxDir, { recursive: true });
26781
27285
  }
26782
27286
  async function sleep2(ms) {
@@ -28476,284 +28980,6 @@ var init_web_fetch = __esm({
28476
28980
  }
28477
28981
  });
28478
28982
 
28479
- // src/skills/scanner.ts
28480
- import * as path28 from "node:path";
28481
- import * as fs24 from "node:fs";
28482
- function scanSkills(skillsDir) {
28483
- if (!fs24.existsSync(skillsDir)) {
28484
- console.log(`[skills] Directory not found: ${skillsDir}`);
28485
- return [];
28486
- }
28487
- const skills = [];
28488
- const scanDir = (dir, depth, seen) => {
28489
- const entries = fs24.readdirSync(dir, { withFileTypes: true });
28490
- for (const entry of entries) {
28491
- if (entry.name.startsWith(".") || entry.name === "_archive") continue;
28492
- const full = path28.join(dir, entry.name);
28493
- let isDir = entry.isDirectory();
28494
- let isFile = entry.isFile();
28495
- if (entry.isSymbolicLink()) {
28496
- try {
28497
- const st = fs24.statSync(full);
28498
- isDir = st.isDirectory();
28499
- isFile = st.isFile();
28500
- } catch {
28501
- console.warn(`[skills] Broken symlink, skipped: ${full}`);
28502
- continue;
28503
- }
28504
- }
28505
- if (isDir && depth < 3) {
28506
- let real;
28507
- try {
28508
- real = fs24.realpathSync(full);
28509
- } catch {
28510
- continue;
28511
- }
28512
- if (seen.has(real)) continue;
28513
- seen.add(real);
28514
- scanDir(full, depth + 1, seen);
28515
- continue;
28516
- }
28517
- if (!isFile || entry.name !== "SKILL.md") continue;
28518
- try {
28519
- const content = fs24.readFileSync(full, "utf-8");
28520
- const frontmatter = parseFrontmatter(content);
28521
- if (!frontmatter.name) {
28522
- console.warn(`[skills] Skipping ${full}: missing 'name' in frontmatter`);
28523
- continue;
28524
- }
28525
- const rel = path28.relative(skillsDir, full).split(path28.sep).join("/");
28526
- skills.push({
28527
- name: frontmatter.name,
28528
- description: frontmatter.description || "",
28529
- location: `skills/${rel}`,
28530
- ...frontmatter
28531
- });
28532
- } catch (err) {
28533
- console.warn(`[skills] Error parsing ${full}: ${err.message}`);
28534
- }
28535
- }
28536
- };
28537
- scanDir(skillsDir, 0, /* @__PURE__ */ new Set([fs24.realpathSync(skillsDir)]));
28538
- console.log(`[skills] Scanned ${skills.length} skills from ${skillsDir}`);
28539
- return skills;
28540
- }
28541
- function parseFrontmatter(content) {
28542
- const result = {};
28543
- const match = content.match(/^---\s*\n([\s\S]*?)\n---/);
28544
- if (!match) return result;
28545
- const lines = match[1].split("\n");
28546
- let i = 0;
28547
- while (i < lines.length) {
28548
- const line = lines[i];
28549
- const colonIdx = line.indexOf(":");
28550
- if (colonIdx === -1) {
28551
- i++;
28552
- continue;
28553
- }
28554
- const key3 = line.slice(0, colonIdx).trim();
28555
- let value2 = line.slice(colonIdx + 1).trim();
28556
- if (value2.startsWith('"') && value2.endsWith('"') || value2.startsWith("'") && value2.endsWith("'")) {
28557
- value2 = value2.slice(1, -1);
28558
- result[key3] = value2;
28559
- i++;
28560
- continue;
28561
- } else if (value2 === "|" || value2 === ">") {
28562
- const blockLines = [];
28563
- i++;
28564
- while (i < lines.length && lines[i].startsWith(" ")) {
28565
- blockLines.push(lines[i].slice(2));
28566
- i++;
28567
- }
28568
- result[key3] = blockLines.join("\n").trim();
28569
- continue;
28570
- } else if (value2.startsWith("[") && value2.endsWith("]")) {
28571
- result[key3] = value2.slice(1, -1).split(",").map((s) => s.trim());
28572
- i++;
28573
- continue;
28574
- } else if (value2.includes(" ") && !value2.startsWith('"')) {
28575
- result[key3] = value2;
28576
- } else {
28577
- result[key3] = value2;
28578
- }
28579
- i++;
28580
- }
28581
- return result;
28582
- }
28583
- var init_scanner = __esm({
28584
- "src/skills/scanner.ts"() {
28585
- "use strict";
28586
- }
28587
- });
28588
-
28589
- // src/tools/SkillTool/SkillTool.ts
28590
- import * as fs25 from "node:fs";
28591
- import * as path29 from "node:path";
28592
- function getCharBudget(contextWindowTokens) {
28593
- if (contextWindowTokens) {
28594
- return Math.floor(contextWindowTokens * CHARS_PER_TOKEN * SKILL_BUDGET_CONTEXT_PERCENT);
28595
- }
28596
- return DEFAULT_CHAR_BUDGET;
28597
- }
28598
- function stringWidth(str) {
28599
- return str.length;
28600
- }
28601
- function truncate(str, maxLen) {
28602
- if (str.length <= maxLen) return str;
28603
- return str.slice(0, maxLen - 1) + "\u2026";
28604
- }
28605
- function getCommandDescription(skill) {
28606
- return (skill.description || "").length > MAX_LISTING_DESC_CHARS ? (skill.description || "").slice(0, MAX_LISTING_DESC_CHARS - 1) + "\u2026" : skill.description || "";
28607
- }
28608
- function formatSkillsListing(skills, contextWindowTokens) {
28609
- if (skills.length === 0) return "";
28610
- const budget = getCharBudget(contextWindowTokens);
28611
- const fullEntries = skills.map((s) => ({
28612
- skill: s,
28613
- full: `- ${s.name}: ${getCommandDescription(s)}`
28614
- }));
28615
- const fullTotal = fullEntries.reduce((sum, e) => sum + stringWidth(e.full), 0) + (fullEntries.length - 1);
28616
- if (fullTotal <= budget) {
28617
- return fullEntries.map((e) => e.full).join("\n");
28618
- }
28619
- const nameOverhead = skills.reduce((sum, s) => sum + stringWidth(s.name) + 4, 0) + (skills.length - 1);
28620
- const availableForDescs = budget - nameOverhead;
28621
- const maxDescLen = Math.floor(availableForDescs / skills.length);
28622
- if (maxDescLen < MIN_DESC_LENGTH) {
28623
- return skills.map((s) => `- ${s.name}`).join("\n");
28624
- }
28625
- return skills.map((s) => {
28626
- const description = getCommandDescription(s);
28627
- return `- ${s.name}: ${truncate(description, maxDescLen)}`;
28628
- }).join("\n");
28629
- }
28630
- function buildSkillToolPrompt() {
28631
- return `Execute a skill within the main conversation
28632
-
28633
- Skills provide specialized capabilities and domain knowledge.
28634
-
28635
- When users reference a "slash command" or "/<something>" (e.g., "/commit", "/review-pr"), they are referring to a skill. Use this tool to invoke it.
28636
-
28637
- How to invoke:
28638
- - Use this tool with the skill name and optional arguments
28639
- - Examples:
28640
- - \`skill: "pdf"\` - invoke the pdf skill
28641
- - \`skill: "commit", args: "-m 'Fix bug'"\` - invoke with arguments
28642
- - \`skill: "review-pr", args: "123"\` - invoke with arguments
28643
- - \`skill: "ms-office-suite:pdf"\` - invoke using fully qualified name
28644
-
28645
- Important:
28646
- - Available skills are listed in system-reminder messages in the conversation
28647
- - Do not invoke a skill that is already running
28648
- - Do not use this tool for built-in CLI commands (like /help, /clear, etc.)
28649
- - If you see a <${COMMAND_NAME_TAG}> tag in the current conversation turn, the skill has ALREADY been loaded - follow the instructions directly instead of calling this tool again
28650
- `;
28651
- }
28652
- function loadSkillContent(skillsDir, skill) {
28653
- const skillMdPath = skill.location ? path29.join(skillsDir, skill.location.slice("skills/".length)) : path29.join(skillsDir, skill.name, "SKILL.md");
28654
- if (!fs25.existsSync(skillMdPath)) return null;
28655
- const content = fs25.readFileSync(skillMdPath, "utf-8");
28656
- const dependencies2 = parseFrontmatter(content)["requires-tools"];
28657
- const requiredTools = [...new Set((Array.isArray(dependencies2) ? dependencies2 : typeof dependencies2 === "string" ? dependencies2.split(/[\s,]+/) : []).filter((n) => typeof n === "string").map((n) => n.trim().replace(/^(['"])(.*)\1$/, "$2")).filter(Boolean))];
28658
- const bodyMatch = content.match(/^---\s*\n[\s\S]*?\n---\s*\n([\s\S]*)/);
28659
- const body = bodyMatch ? bodyMatch[1] : content;
28660
- const skillDir = path29.dirname(skillMdPath);
28661
- const normalizedDir = process.platform === "win32" ? skillDir.replace(/\\/g, "/") : skillDir;
28662
- let finalContent = `Base directory for this skill: ${normalizedDir}
28663
-
28664
- ${body}`;
28665
- finalContent = finalContent.replace(/\$\{CLAUDE_SKILL_DIR\}/g, normalizedDir);
28666
- finalContent = finalContent.replace(/\$\{CLAUDE_SESSION_ID\}/g, getSessionId());
28667
- return { content: finalContent, requiredTools };
28668
- }
28669
- function getSessionId() {
28670
- return String(process.pid);
28671
- }
28672
- function registerSkillTool(skillsDir, skills, contextWindowTokens) {
28673
- skillsDirPath = skillsDir;
28674
- cachedSkills = skills;
28675
- cachedContextWindowTokens = contextWindowTokens;
28676
- const groupedSkills = /* @__PURE__ */ new Map();
28677
- for (const skill of skills) {
28678
- const parts = skill.location?.split("/");
28679
- if (!parts || parts[0] !== "skills" || parts.length < 4 || skill.name.includes(":")) continue;
28680
- const qualifiedName = `${parts[1]}:${skill.name}`;
28681
- if (!groupedSkills.has(qualifiedName)) groupedSkills.set(qualifiedName, skill);
28682
- }
28683
- const descriptionText = buildSkillToolPrompt();
28684
- cachedListing = formatSkillsListing(cachedSkills, contextWindowTokens);
28685
- registry.register({
28686
- name: SKILL_TOOL_NAME,
28687
- description: descriptionText,
28688
- schema: {
28689
- type: "object",
28690
- properties: {
28691
- skill: { type: "string", description: 'The skill name. E.g., "commit", "review-pr", or "pdf"' },
28692
- args: { type: "string", description: "Optional arguments for the skill" }
28693
- },
28694
- required: ["skill"]
28695
- },
28696
- // 对齐 CC SkillTool.call()
28697
- handler: async (args, ctx) => {
28698
- const skillName = (args.skill || "").trim();
28699
- const skillArgs = args.args || "";
28700
- if (!skillName) {
28701
- return { content: "Invalid skill: empty name", isError: true };
28702
- }
28703
- const normalizedName = skillName.startsWith("/") ? skillName.substring(1) : skillName;
28704
- const skill = skills.find((s) => s.name === normalizedName) ?? groupedSkills.get(normalizedName);
28705
- if (!skill) {
28706
- const available = skills.map((s) => s.name).join(", ");
28707
- return { content: `Unknown skill: ${normalizedName}. Available: ${available}`, isError: true };
28708
- }
28709
- const content = loadSkillContent(skillsDir, skill);
28710
- if (!content) {
28711
- return { content: `Skill file not found: ${normalizedName}`, isError: true };
28712
- }
28713
- let dependencyContent = "";
28714
- if (content.requiredTools.length) {
28715
- const loaded = loadToolSchemas(content.requiredTools, ctx);
28716
- if (loaded.isError) return loaded;
28717
- dependencyContent = `
28718
- <${SKILL_DEPENDENCIES_TAG}>
28719
- ${content.requiredTools.join("\n")}
28720
- </${SKILL_DEPENDENCIES_TAG}>
28721
- ${loaded.content}
28722
- `;
28723
- }
28724
- const argLine = skillArgs ? `
28725
-
28726
- User arguments: ${skillArgs}` : "";
28727
- return { content: `Skill "${skill.name}" loaded.${dependencyContent}
28728
-
28729
- ${content.content}${argLine}` };
28730
- },
28731
- // 对齐 CC SkillTool properties
28732
- isConcurrencySafe: () => false,
28733
- isDestructive: () => false,
28734
- isReadOnly: () => true
28735
- });
28736
- console.log(`[skills] SkillTool registered with ${cachedSkills.length} skills (budget: ${getCharBudget(contextWindowTokens)} chars)`);
28737
- }
28738
- function getSkillToolState() {
28739
- return { skillsDirPath, contextWindowTokens: cachedContextWindowTokens, skillNames: cachedSkills.map((s) => s.name) };
28740
- }
28741
- var COMMAND_NAME_TAG, MIN_DESC_LENGTH, skillsDirPath, cachedSkills, cachedListing, cachedContextWindowTokens;
28742
- var init_SkillTool = __esm({
28743
- "src/tools/SkillTool/SkillTool.ts"() {
28744
- "use strict";
28745
- init_registry();
28746
- init_scanner();
28747
- init_tool_loading();
28748
- init_constants4();
28749
- COMMAND_NAME_TAG = "command-name";
28750
- MIN_DESC_LENGTH = 20;
28751
- skillsDirPath = "";
28752
- cachedSkills = [];
28753
- cachedListing = "";
28754
- }
28755
- });
28756
-
28757
28983
  // src/startup/skill-sync.ts
28758
28984
  import * as fs26 from "node:fs";
28759
28985
  import * as path30 from "node:path";
@@ -31844,7 +32070,7 @@ import { request as request8 } from "node:https";
31844
32070
  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";
31845
32071
  import { join as join46 } from "node:path";
31846
32072
  import { homedir as homedir3 } from "node:os";
31847
- import { randomBytes as randomBytes4, createHash as createHash36, X509Certificate } from "node:crypto";
32073
+ import { randomBytes as randomBytes4, createHash as createHash37, X509Certificate } from "node:crypto";
31848
32074
  import { execFileSync as execFileSync2 } from "node:child_process";
31849
32075
  import { createServer } from "node:net";
31850
32076
 
@@ -34163,7 +34389,7 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
34163
34389
  }
34164
34390
  };
34165
34391
  async function verifyContent(objects, content) {
34166
- const { createHash: createHash56 } = await import("node:crypto"), hash12 = createHash56("sha256");
34392
+ const { createHash: createHash57 } = await import("node:crypto"), hash12 = createHash57("sha256");
34167
34393
  for (const ref of content.chunks) hash12.update(await objects.read(ref));
34168
34394
  if (hash12.digest("hex") !== content.sha256) throw new Error("RECOVERY_CONTENT_CORRUPT");
34169
34395
  }
@@ -34875,7 +35101,7 @@ function resolveRequiredTools(features, licensedFeatures) {
34875
35101
  }
34876
35102
 
34877
35103
  // src/continuity/pairing-setup.ts
34878
- var sha6 = (value2) => createHash36("sha256").update(value2).digest("hex");
35104
+ var sha6 = (value2) => createHash37("sha256").update(value2).digest("hex");
34879
35105
  var write = (file2, value2) => writeFileSync23(file2, JSON.stringify(value2), { mode: 384, flush: true });
34880
35106
  var free = () => new Promise((done, reject) => {
34881
35107
  const server = createServer();
@@ -35165,7 +35391,7 @@ import { readFileSync as readFileSync32, lstatSync as lstatSync29, realpathSync
35165
35391
  import { DatabaseSync as DatabaseSync37 } from "node:sqlite";
35166
35392
  import { isAbsolute as isAbsolute13, resolve as resolve41 } from "node:path";
35167
35393
  import { fileURLToPath as fileURLToPath7 } from "node:url";
35168
- import { randomUUID as randomUUID24, createHash as createHash50 } from "node:crypto";
35394
+ import { randomUUID as randomUUID24, createHash as createHash51 } from "node:crypto";
35169
35395
 
35170
35396
  // src/continuity/node-agent.ts
35171
35397
  import { DatabaseSync as DatabaseSync36 } from "node:sqlite";
@@ -35198,7 +35424,7 @@ function runtimeEngineConfig(original, stateDir, workspace) {
35198
35424
  // src/continuity/node-agent.ts
35199
35425
  import { existsSync as existsSync38, lstatSync as lstatSync28, mkdirSync as mkdirSync31, readFileSync as readFileSync31, realpathSync as realpathSync27, writeFileSync as writeFileSync40 } from "node:fs";
35200
35426
  import { isAbsolute as isAbsolute12, join as join70, resolve as resolve40 } from "node:path";
35201
- import { createHash as createHash48, randomUUID as randomUUID23 } from "node:crypto";
35427
+ import { createHash as createHash49, randomUUID as randomUUID23 } from "node:crypto";
35202
35428
  import { isIP as isIP2 } from "node:net";
35203
35429
 
35204
35430
  // src/continuity/activation.ts
@@ -35312,7 +35538,7 @@ init_schema_migrations();
35312
35538
  init_key_service_store();
35313
35539
 
35314
35540
  // src/continuity/generation-integrity.ts
35315
- import { createHash as createHash37 } from "node:crypto";
35541
+ import { createHash as createHash38 } from "node:crypto";
35316
35542
  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";
35317
35543
  import { join as join50, resolve as resolve28 } from "node:path";
35318
35544
  import { open as open5 } from "node:fs/promises";
@@ -35346,7 +35572,7 @@ function runtimeGenerationIntegrity(directory2) {
35346
35572
  const files = generationFiles(root);
35347
35573
  for (const { path: path37, stat: before } of files) {
35348
35574
  const file2 = join50(root, path37);
35349
- const fd = openSync18(file2, constants11.O_RDONLY | (constants11.O_NOFOLLOW ?? 0)), hash12 = createHash37("sha256");
35575
+ const fd = openSync18(file2, constants11.O_RDONLY | (constants11.O_NOFOLLOW ?? 0)), hash12 = createHash38("sha256");
35350
35576
  let bytes = 0;
35351
35577
  try {
35352
35578
  while (true) {
@@ -35369,7 +35595,7 @@ async function runtimeGenerationIntegrityAsync(directory2) {
35369
35595
  const root = resolve28(directory2), result = [], buffer = Buffer.allocUnsafe(1024 * 1024);
35370
35596
  const files = generationFiles(root);
35371
35597
  for (const { path: path37, stat: before } of files) {
35372
- const file2 = join50(root, path37), handle = await open5(file2, constants11.O_RDONLY | (constants11.O_NOFOLLOW ?? 0)), hash12 = createHash37("sha256");
35598
+ const file2 = join50(root, path37), handle = await open5(file2, constants11.O_RDONLY | (constants11.O_NOFOLLOW ?? 0)), hash12 = createHash38("sha256");
35373
35599
  let bytes = 0;
35374
35600
  try {
35375
35601
  while (true) {
@@ -35406,13 +35632,13 @@ async function verifyRuntimeGenerationIntegrityAsync(directory2, expected) {
35406
35632
  // src/continuity/recovery-deletion-visibility.ts
35407
35633
  init_key_service_store();
35408
35634
  import { DatabaseSync as DatabaseSync22 } from "node:sqlite";
35409
- import { createHash as createHash40, randomUUID as randomUUID19 } from "node:crypto";
35635
+ import { createHash as createHash41, randomUUID as randomUUID19 } from "node:crypto";
35410
35636
  import { existsSync as existsSync31, realpathSync as realpathSync17, renameSync as renameSync11, unlinkSync as unlinkSync11, writeFileSync as writeFileSync28 } from "node:fs";
35411
35637
  import { join as join53, resolve as resolve30 } from "node:path";
35412
35638
 
35413
35639
  // src/continuity/recovery-deletion-overlay.ts
35414
35640
  import { DatabaseSync as DatabaseSync21 } from "node:sqlite";
35415
- import { createHash as createHash39, randomUUID as randomUUID18 } from "node:crypto";
35641
+ import { createHash as createHash40, randomUUID as randomUUID18 } from "node:crypto";
35416
35642
  import { existsSync as existsSync30, realpathSync as realpathSync16, renameSync as renameSync10, unlinkSync as unlinkSync10, writeFileSync as writeFileSync27 } from "node:fs";
35417
35643
  import { dirname as dirname21, join as join52, resolve as resolve29 } from "node:path";
35418
35644
  init_key_service_store();
@@ -35432,7 +35658,7 @@ init_vector_publications();
35432
35658
  init_scope();
35433
35659
  init_schema_migrations();
35434
35660
  import { DatabaseSync as DatabaseSync20 } from "node:sqlite";
35435
- import { createHash as createHash38 } from "node:crypto";
35661
+ import { createHash as createHash39 } from "node:crypto";
35436
35662
  import { gunzipSync as gunzipSync3 } from "node:zlib";
35437
35663
  import { isUtf8 } from "node:buffer";
35438
35664
  import { rmSync as rmSync4, writeFileSync as writeFileSync26, existsSync as existsSync29, unlinkSync as unlinkSync9 } from "node:fs";
@@ -35441,7 +35667,7 @@ init_sqlite_replication();
35441
35667
  init_key_service_store();
35442
35668
  init_attachments();
35443
35669
  init_result_snapshot();
35444
- var sha7 = (bytes) => createHash38("sha256").update(bytes).digest("hex");
35670
+ var sha7 = (bytes) => createHash39("sha256").update(bytes).digest("hex");
35445
35671
  var object3 = (value2) => !!value2 && typeof value2 === "object" && !Array.isArray(value2);
35446
35672
  var currentDebugCaches = /* @__PURE__ */ new Set([".context-debug.txt", ".system-prompt.txt"]);
35447
35673
  async function cleanRecoveryDeletionRuntimeCopies(options) {
@@ -35764,7 +35990,7 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
35764
35990
 
35765
35991
  // src/continuity/recovery-deletion-overlay.ts
35766
35992
  var same4 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
35767
- var sha8 = (value2) => createHash39("sha256").update(value2).digest("hex");
35993
+ var sha8 = (value2) => createHash40("sha256").update(value2).digest("hex");
35768
35994
  var evidenceRow = (row) => Object.fromEntries(Object.entries(row).map(([key3, value2]) => [
35769
35995
  key3,
35770
35996
  value2 === null ? ["null"] : typeof value2 === "string" ? ["text", value2] : typeof value2 === "bigint" ? ["integer", String(value2)] : typeof value2 === "number" ? ["real", String(value2)] : ["blob", Buffer.from(value2).toString("base64")]
@@ -35997,7 +36223,7 @@ async function deletionOverlay(options, runtimeCopies) {
35997
36223
  // src/continuity/recovery-deletion-visibility.ts
35998
36224
  init_schema_migrations();
35999
36225
  var same5 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
36000
- var sha9 = (value2) => createHash40("sha256").update(value2).digest("hex");
36226
+ var sha9 = (value2) => createHash41("sha256").update(value2).digest("hex");
36001
36227
  var format2 = "engine7-current-h-deletion-visibility-v1";
36002
36228
  function receipt(options) {
36003
36229
  const root = resolve30(options.snapshot);
@@ -36288,7 +36514,7 @@ import { fork } from "node:child_process";
36288
36514
  import { DatabaseSync as DatabaseSync24 } from "node:sqlite";
36289
36515
  import { closeSync as closeSync18, lstatSync as lstatSync20, openSync as openSync19, readFileSync as readFileSync29, realpathSync as realpathSync19 } from "node:fs";
36290
36516
  import { isAbsolute as isAbsolute7, join as join55 } from "node:path";
36291
- import { createHash as createHash41, randomUUID as randomUUID20 } from "node:crypto";
36517
+ import { createHash as createHash42, randomUUID as randomUUID20 } from "node:crypto";
36292
36518
 
36293
36519
  // src/continuity/engine-control.ts
36294
36520
  init_runtime_authority();
@@ -36402,7 +36628,7 @@ var SupervisedRuntimeProcess = class {
36402
36628
  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");
36403
36629
  if (recovery && !retired) throw new Error("TRAVEL_PROCESS_GENERATION_RETIRED");
36404
36630
  const info = lstatSync20(this.options.entry);
36405
- if (!info.isFile() || info.isSymbolicLink() || info.size > 64 * 1024 * 1024 || realpathSync19(this.options.entry) !== this.options.entry || createHash41("sha256").update(readFileSync29(this.options.entry)).digest("hex") !== this.options.entrySha256) throw new Error("TRAVEL_PROCESS_BUILD");
36631
+ if (!info.isFile() || info.isSymbolicLink() || info.size > 64 * 1024 * 1024 || realpathSync19(this.options.entry) !== this.options.entry || createHash42("sha256").update(readFileSync29(this.options.entry)).digest("hex") !== this.options.entrySha256) throw new Error("TRAVEL_PROCESS_BUILD");
36406
36632
  let environment;
36407
36633
  try {
36408
36634
  environment = supervisedRuntimeEnvironment(JSON.parse(readPrivateFile(this.options.configFile, 1024 * 1024).toString()), process.env, this.options.environmentNames);
@@ -36743,7 +36969,7 @@ init_key_service_store();
36743
36969
  init_publication_objects();
36744
36970
  import { DatabaseSync as DatabaseSync27 } from "node:sqlite";
36745
36971
  import { existsSync as existsSync33, lstatSync as lstatSync22, realpathSync as realpathSync21 } from "node:fs";
36746
- import { createHash as createHash42 } from "node:crypto";
36972
+ import { createHash as createHash43 } from "node:crypto";
36747
36973
  import { isAbsolute as isAbsolute8, join as join58, resolve as resolve34 } from "node:path";
36748
36974
  init_sqlite_replication();
36749
36975
  init_schema_migrations();
@@ -36826,7 +37052,7 @@ async function openRuntimeGenerationSource(options) {
36826
37052
  }
36827
37053
  if (sessionTrees.length !== profile.trees.filter((tree) => tree.kind === "session").length) throw new Error("TRAVEL_SOURCE_LAYOUT");
36828
37054
  const lanceStores = profile.trees.filter((tree) => tree.kind === "vector").map((tree) => ({ treeId: tree.id, directory: join58(stateDir, layout.trees[tree.id]) }));
36829
- const layoutDigest = createHash42("sha256").update(JSON.stringify([stateDir, profile, layout])).digest("hex");
37055
+ const layoutDigest = createHash43("sha256").update(JSON.stringify([stateDir, profile, layout])).digest("hex");
36830
37056
  trees = await RuntimeTreeSource.open({ directory: join58(dataDirectory, "runtime-trees"), profile, objects: options.objects, initialize: options.initialize });
36831
37057
  source = await RuntimePublicationSource.open({ directory: join58(dataDirectory, "runtime-publications"), profile, objects: options.objects, trees, layoutDigest, initialize: options.initialize });
36832
37058
  const capture2 = () => {
@@ -38669,7 +38895,7 @@ import { createServer as createServer4 } from "node:https";
38669
38895
 
38670
38896
  // src/continuity/publication-transport.ts
38671
38897
  import { createServer as createServer3, request as request4, Agent as Agent3 } from "node:https";
38672
- import { createHash as createHash43 } from "node:crypto";
38898
+ import { createHash as createHash44 } from "node:crypto";
38673
38899
  init_publication_objects();
38674
38900
  var BODY_LIMIT = PUBLICATION_MANIFEST_BYTES + 65536;
38675
38901
  var safeCode = (error) => error instanceof Error && /^(PUBLICATION|REPLICATION)_[A-Z_]+$/.test(error.message) ? error.message : "PUBLICATION_OPERATION_FAILED";
@@ -38779,7 +39005,7 @@ function createPublicationServer(options) {
38779
39005
  case "object": {
38780
39006
  validateObjectRef(value2.ref);
38781
39007
  const body = decodeChunk(value2.body);
38782
- if (body.length !== value2.ref.bytes || createHash43("sha256").update(body).digest("hex") !== value2.ref.sha256) throw new Error("PUBLICATION_OBJECT_MISMATCH");
39008
+ if (body.length !== value2.ref.bytes || createHash44("sha256").update(body).digest("hex") !== value2.ref.sha256) throw new Error("PUBLICATION_OBJECT_MISMATCH");
38783
39009
  await check();
38784
39010
  result = await receiver.objects.put(body);
38785
39011
  break;
@@ -38876,13 +39102,13 @@ import { isAbsolute as isAbsolute11, join as join68, resolve as resolve39 } from
38876
39102
 
38877
39103
  // src/continuity/recovery-admission.ts
38878
39104
  import { DatabaseSync as DatabaseSync34 } from "node:sqlite";
38879
- import { createHash as createHash45 } from "node:crypto";
39105
+ import { createHash as createHash46 } from "node:crypto";
38880
39106
  import { mkdtempSync as mkdtempSync3, rmSync as rmSync6, writeFileSync as writeFileSync37 } from "node:fs";
38881
39107
  import { join as join66 } from "node:path";
38882
39108
 
38883
39109
  // src/continuity/recovery-diff.ts
38884
39110
  import { DatabaseSync as DatabaseSync33 } from "node:sqlite";
38885
- import { createHash as createHash44 } from "node:crypto";
39111
+ import { createHash as createHash45 } from "node:crypto";
38886
39112
  import { mkdtempSync as mkdtempSync2, rmSync as rmSync5, writeFileSync as writeFileSync36 } from "node:fs";
38887
39113
  import { join as join65 } from "node:path";
38888
39114
  init_legacy_sqlite_indexes();
@@ -38958,7 +39184,7 @@ async function compareRecoveryArchives(options) {
38958
39184
  counts[s]++;
38959
39185
  scannedRecords++;
38960
39186
  if (s !== "UNCHANGED") {
38961
- const item = { ...identity3, state: s, common: c, local: l, remote: r, originalHash: createHash44("sha256").update(JSON.stringify(l)).digest("hex") };
39187
+ const item = { ...identity3, state: s, common: c, local: l, remote: r, originalHash: createHash45("sha256").update(JSON.stringify(l)).digest("hex") };
38962
39188
  resultBytes += Buffer.byteLength(JSON.stringify(item));
38963
39189
  if (resultBytes > maximumResultBytes) throw new Error("RECOVERY_DIFF_LIMIT");
38964
39190
  items.push(item);
@@ -39058,7 +39284,7 @@ async function compareRecoveryArchives(options) {
39058
39284
  return map;
39059
39285
  });
39060
39286
  for (let i = 0; i < entries.length; i++) for (const file2 of entries[i].manifest.trees.find((t) => t.id === treeId).files) {
39061
- const hash12 = createHash44("sha256");
39287
+ const hash12 = createHash45("sha256");
39062
39288
  for (const chunk of file2.content.chunks) {
39063
39289
  await check();
39064
39290
  hash12.update(await references[i].archive.objects.read(chunk));
@@ -39089,7 +39315,7 @@ async function compareRecoveryArchives(options) {
39089
39315
  activationAllowed: false,
39090
39316
  ancestryVerified: false
39091
39317
  };
39092
- return { ...body, digest: createHash44("sha256").update(JSON.stringify(body)).digest("hex") };
39318
+ return { ...body, digest: createHash45("sha256").update(JSON.stringify(body)).digest("hex") };
39093
39319
  } finally {
39094
39320
  for (const dir of temporaries) rmSync5(dir, { recursive: true, force: true });
39095
39321
  }
@@ -39101,7 +39327,7 @@ init_artifact_history();
39101
39327
  init_recovery_deletion();
39102
39328
  init_job_retention();
39103
39329
  init_protocol();
39104
- var hash8 = (value2) => createHash45("sha256").update(value2).digest("hex");
39330
+ var hash8 = (value2) => createHash46("sha256").update(value2).digest("hex");
39105
39331
  var same10 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
39106
39332
  var quote3 = (s) => '"' + s.replaceAll('"', '""') + '"';
39107
39333
  function authReadinessHistory(body) {
@@ -40172,13 +40398,13 @@ async function admitRecoveryArchives(options) {
40172
40398
  }
40173
40399
 
40174
40400
  // src/continuity/recovery-artifact-projection.ts
40175
- import { createHash as createHash46, randomUUID as randomUUID22 } from "node:crypto";
40401
+ import { createHash as createHash47, randomUUID as randomUUID22 } from "node:crypto";
40176
40402
  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";
40177
40403
  import { dirname as dirname26, join as join67, resolve as resolve38 } from "node:path";
40178
40404
  import { createRequire as createRequire9 } from "node:module";
40179
40405
  init_runtime_authority();
40180
40406
  init_dependencies();
40181
- var sha10 = (bytes) => createHash46("sha256").update(bytes).digest("hex");
40407
+ var sha10 = (bytes) => createHash47("sha256").update(bytes).digest("hex");
40182
40408
  var require5 = createRequire9(import.meta.url);
40183
40409
  function privateParents(root, path37) {
40184
40410
  if (realpathSync25(root) !== root) throw new Error("RECOVERY_PROJECTION_UNSAFE_PATH");
@@ -40512,10 +40738,10 @@ init_runtime_lock();
40512
40738
  // src/continuity/local-exit-proof.ts
40513
40739
  init_runtime_lock();
40514
40740
  init_key_service_store();
40515
- import { createHash as createHash47, verify as verify2 } from "node:crypto";
40741
+ import { createHash as createHash48, verify as verify2 } from "node:crypto";
40516
40742
  import { createReadStream, mkdirSync as mkdirSync30, readdirSync as readdirSync14, writeFileSync as writeFileSync39 } from "node:fs";
40517
40743
  import { join as join69, relative as relative14 } from "node:path";
40518
- var hash9 = (value2) => createHash47("sha256").update(value2).digest("hex");
40744
+ var hash9 = (value2) => createHash48("sha256").update(value2).digest("hex");
40519
40745
  var equal2 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
40520
40746
  function copyLocalExitPath(source, path37) {
40521
40747
  const name = relative14(source, path37).replaceAll("\\", "/");
@@ -40533,7 +40759,7 @@ async function localExitFilesDigest(root, ordinary = false) {
40533
40759
  continue;
40534
40760
  }
40535
40761
  if (!entry.isFile() || files.length >= 1e6) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
40536
- const digest7 = createHash47("sha256");
40762
+ const digest7 = createHash48("sha256");
40537
40763
  for await (const chunk of createReadStream(file2)) digest7.update(chunk);
40538
40764
  files.push({ path: relative14(root, file2).replaceAll("\\", "/"), sha256: digest7.digest("hex") });
40539
40765
  }
@@ -40583,7 +40809,7 @@ async function verifyStoppedLocalExitProof(options) {
40583
40809
 
40584
40810
  // src/continuity/node-agent.ts
40585
40811
  var clock = () => Number(process.hrtime.bigint() / 1000000n);
40586
- var hash10 = (value2) => createHash48("sha256").update(value2).digest("hex");
40812
+ var hash10 = (value2) => createHash49("sha256").update(value2).digest("hex");
40587
40813
  var same12 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
40588
40814
  var TravelNodeAgent = class _TravelNodeAgent {
40589
40815
  constructor(options) {
@@ -42259,7 +42485,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
42259
42485
  import { createPublicKey } from "node:crypto";
42260
42486
 
42261
42487
  // src/continuity/node-data-authority.ts
42262
- import { createHash as createHash49 } from "node:crypto";
42488
+ import { createHash as createHash50 } from "node:crypto";
42263
42489
  var fields = ["tenantId", "companionId", "seatId", "nodeId", "role", "credentialHash"];
42264
42490
  var equal3 = (left, right) => !!left && fields.every((field) => left[field] === right[field]);
42265
42491
  var RemoteTravelDataAuthority = class {
@@ -42267,7 +42493,7 @@ var RemoteTravelDataAuthority = class {
42267
42493
  reads = /* @__PURE__ */ new Map();
42268
42494
  grants;
42269
42495
  constructor(grants) {
42270
- if (!grants.length || grants.length > 2 || new Set(grants.map((grant) => grant.credential)).size !== grants.length || grants.some((grant) => !/^e7t_[a-f0-9]{64}$/.test(grant.credential) || createHash49("sha256").update(grant.credential).digest("hex") !== grant.principal.credentialHash)) throw new Error("TRAVEL_AUTH_DENIED");
42496
+ if (!grants.length || grants.length > 2 || new Set(grants.map((grant) => grant.credential)).size !== grants.length || grants.some((grant) => !/^e7t_[a-f0-9]{64}$/.test(grant.credential) || createHash50("sha256").update(grant.credential).digest("hex") !== grant.principal.credentialHash)) throw new Error("TRAVEL_AUTH_DENIED");
42271
42497
  this.grants = grants.map((grant) => ({ ...grant, principal: Object.freeze({ ...grant.principal }) }));
42272
42498
  }
42273
42499
  async authenticate(credential) {
@@ -43262,7 +43488,7 @@ async function startTravelNodeService(input) {
43262
43488
  const keyService = { ...clientTls, url: config.keyService?.url, identity: config.keyService?.identity, minimumDeletionWatermark: (await authority.status(config.principal)).deletionWatermark };
43263
43489
  const material = await fetchTravelKey(keyService);
43264
43490
  try {
43265
- if (createHash50("sha256").update(material.key).digest("hex") !== config.keySha256) throw new Error("TRAVEL_NODE_KEY_BARRIER");
43491
+ if (createHash51("sha256").update(material.key).digest("hex") !== config.keySha256) throw new Error("TRAVEL_NODE_KEY_BARRIER");
43266
43492
  objects = await PublicationObjects.open({ directory: path34(config.objectsDirectory), identity: { tenantId: config.principal.tenantId, companionId: config.principal.companionId, seatId: config.principal.seatId }, key: material.key });
43267
43493
  } finally {
43268
43494
  material.key.fill(0);
@@ -43596,11 +43822,11 @@ import { isAbsolute as isAbsolute17, resolve as resolve45 } from "node:path";
43596
43822
  import { fileURLToPath as fileURLToPath8 } from "node:url";
43597
43823
  import { execFile as execFile6 } from "node:child_process";
43598
43824
  import { promisify as promisify6 } from "node:util";
43599
- import { createHash as createHash55 } from "node:crypto";
43825
+ import { createHash as createHash56 } from "node:crypto";
43600
43826
 
43601
43827
  // src/continuity/user-seat-resource.ts
43602
43828
  import { spawn as spawn7 } from "node:child_process";
43603
- import { createHash as createHash51 } from "node:crypto";
43829
+ import { createHash as createHash52 } from "node:crypto";
43604
43830
  import { isAbsolute as isAbsolute14, resolve as resolve42 } from "node:path";
43605
43831
  var UserSeatResource = class {
43606
43832
  constructor(config) {
@@ -43608,7 +43834,7 @@ var UserSeatResource = class {
43608
43834
  if (!/^[a-z_][a-z0-9_-]{0,31}$/.test(config.runAs.user) || [config.directory, config.runAs.node, config.runAs.entry, config.runAs.configFile].some((path37) => !isAbsolute14(path37) || resolve42(path37) !== path37 || /[\r\n\0]/.test(path37))) throw new Error("TRAVEL_RETIREMENT_CONFIG");
43609
43835
  this.identity = config.identity;
43610
43836
  this.path = config.directory;
43611
- this.id = "directory-" + createHash51("sha256").update(this.path).digest("hex");
43837
+ this.id = "directory-" + createHash52("sha256").update(this.path).digest("hex");
43612
43838
  }
43613
43839
  id;
43614
43840
  path;
@@ -43661,12 +43887,12 @@ var UserSeatResource = class {
43661
43887
  init_publication_objects();
43662
43888
  init_key_service_store();
43663
43889
  import { DatabaseSync as DatabaseSync39 } from "node:sqlite";
43664
- import { createHash as createHash52 } from "node:crypto";
43890
+ import { createHash as createHash53 } from "node:crypto";
43665
43891
  import { existsSync as existsSync39 } from "node:fs";
43666
43892
  import { accessSync, constants as constants14, lstatSync as lstatSync30, readdirSync as readdirSync15, readFileSync as readFileSync33, readlinkSync, realpathSync as realpathSync29, rmSync as rmSync7 } from "node:fs";
43667
43893
  import { dirname as dirname27, isAbsolute as isAbsolute15, join as join71, resolve as resolve43, relative as relative15 } from "node:path";
43668
43894
  var identity = (value2) => JSON.stringify([value2.tenantId, value2.companionId, value2.seatId]);
43669
- var sha11 = (value2) => createHash52("sha256").update(value2).digest("hex");
43895
+ var sha11 = (value2) => createHash53("sha256").update(value2).digest("hex");
43670
43896
  var LocalSeatResource = class {
43671
43897
  constructor(path37, identity3) {
43672
43898
  this.path = path37;
@@ -43834,14 +44060,14 @@ init_runtime_lock();
43834
44060
  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";
43835
44061
  import { DatabaseSync as DatabaseSync41 } from "node:sqlite";
43836
44062
  import { isAbsolute as isAbsolute16, join as join72, dirname as dirname29, resolve as resolve44 } from "node:path";
43837
- import { createHash as createHash54, verify as verify3 } from "node:crypto";
44063
+ import { createHash as createHash55, verify as verify3 } from "node:crypto";
43838
44064
 
43839
44065
  // src/continuity/local-dedupe.ts
43840
44066
  init_publication_objects();
43841
44067
  import { DatabaseSync as DatabaseSync40 } from "node:sqlite";
43842
- import { createHash as createHash53 } from "node:crypto";
44068
+ import { createHash as createHash54 } from "node:crypto";
43843
44069
  import { dirname as dirname28 } from "node:path";
43844
- var sha12 = (value2) => createHash53("sha256").update(value2).digest("hex");
44070
+ var sha12 = (value2) => createHash54("sha256").update(value2).digest("hex");
43845
44071
  var hash11 = (value2) => typeof value2 === "string" && /^[a-f0-9]{64}$/.test(value2);
43846
44072
  var PlatformReceiptStore = class {
43847
44073
  db;
@@ -43909,7 +44135,7 @@ var PlatformReceiptStore = class {
43909
44135
  // src/continuity/local-exit.ts
43910
44136
  init_key_service_store();
43911
44137
  var identity2 = (value2) => JSON.stringify([value2.tenantId, value2.companionId, value2.seatId]);
43912
- var sha13 = (value2) => createHash54("sha256").update(value2).digest("hex");
44138
+ var sha13 = (value2) => createHash55("sha256").update(value2).digest("hex");
43913
44139
  function detachReplication(directory2) {
43914
44140
  for (const entry of readdirSync16(directory2, { withFileTypes: true })) {
43915
44141
  const file2 = join72(directory2, entry.name);
@@ -43994,7 +44220,7 @@ async function createOrdinaryLocalRecovery(options) {
43994
44220
  init_key_service_store();
43995
44221
  init_key_service_store();
43996
44222
  var command = promisify6(execFile6);
43997
- var sha14 = (value2) => createHash55("sha256").update(value2).digest("hex");
44223
+ var sha14 = (value2) => createHash56("sha256").update(value2).digest("hex");
43998
44224
  var path36 = (value2) => {
43999
44225
  if (typeof value2 !== "string" || !isAbsolute17(value2) || resolve45(value2) !== value2) throw new Error("TRAVEL_RETIREMENT_PATH");
44000
44226
  return value2;