@picassohq/cli 1.0.9 → 1.0.10

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.
@@ -6624,15 +6624,15 @@ function decodeDshZstdFrames(buffer) {
6624
6624
  const parts = [];
6625
6625
  let start = 0;
6626
6626
  while (start < buffer.length) {
6627
- const length = zstdFrameLength(buffer, start);
6628
- if (length === void 0)
6627
+ const length2 = zstdFrameLength(buffer, start);
6628
+ if (length2 === void 0)
6629
6629
  break;
6630
6630
  try {
6631
- parts.push(decompress(buffer.subarray(start, start + length)));
6631
+ parts.push(decompress(buffer.subarray(start, start + length2)));
6632
6632
  } catch {
6633
6633
  break;
6634
6634
  }
6635
- start += length;
6635
+ start += length2;
6636
6636
  }
6637
6637
  if (parts.length === 0)
6638
6638
  throw new Error("dsh session log has no complete zstd frame");
@@ -10491,14 +10491,14 @@ var init_opencode = __esm({
10491
10491
  });
10492
10492
 
10493
10493
  // ../../packages/contributions/dist/api-contract.js
10494
- function classifyApiError(code, status, retryAfterMs) {
10494
+ function classifyApiError(code, status, retryAfterMs2) {
10495
10495
  const known = ERROR_KINDS[code];
10496
10496
  const kind = known ?? (status === 401 ? "auth" : status === 429 || status === 503 ? "backpressure" : status === 413 ? "too_large" : status === 404 || status === 410 ? "not_found" : status === 409 ? "conflict" : status !== void 0 && status >= 400 && status < 500 ? "invalid" : "transient");
10497
10497
  return {
10498
10498
  code,
10499
10499
  kind,
10500
10500
  ...status === void 0 ? {} : { status },
10501
- ...retryAfterMs === void 0 ? {} : { retryAfterMs }
10501
+ ...retryAfterMs2 === void 0 ? {} : { retryAfterMs: retryAfterMs2 }
10502
10502
  };
10503
10503
  }
10504
10504
  var CONTRIBUTION_API_PATHS, ERROR_KINDS;
@@ -11581,7 +11581,7 @@ var init_dsh_source = __esm({
11581
11581
  // ../../packages/contributions/dist/preview.js
11582
11582
  import { createHash as createHash29 } from "node:crypto";
11583
11583
  import { chmod as chmod7, mkdir as mkdir17, readdir as readdir12, readFile as readFile28, rename as rename11, rm as rm13, stat as stat14, writeFile as writeFile14 } from "node:fs/promises";
11584
- import { join as join82 } from "node:path";
11584
+ import { join as join83 } from "node:path";
11585
11585
  function sha2562(text6) {
11586
11586
  return createHash29("sha256").update(text6).digest("hex");
11587
11587
  }
@@ -11727,8 +11727,8 @@ var init_preview = __esm({
11727
11727
  ...frozen.inspection,
11728
11728
  expiresAt: new Date(this.#now().getTime() + this.#ttlMs).toISOString()
11729
11729
  };
11730
- await this.#writePrivate(join82(this.#root, `${id}.bundle`), frozen.artifact.bytes);
11731
- await this.#writePrivate(join82(this.#root, `${id}.inspect.json`), `${JSON.stringify(inspection)}
11730
+ await this.#writePrivate(join83(this.#root, `${id}.bundle`), frozen.artifact.bytes);
11731
+ await this.#writePrivate(join83(this.#root, `${id}.inspect.json`), `${JSON.stringify(inspection)}
11732
11732
  `);
11733
11733
  return { stored: true };
11734
11734
  }
@@ -11737,7 +11737,7 @@ var init_preview = __esm({
11737
11737
  return void 0;
11738
11738
  let inspection;
11739
11739
  try {
11740
- inspection = JSON.parse(await readFile28(join82(this.#root, `${contributionId}.inspect.json`), "utf8"));
11740
+ inspection = JSON.parse(await readFile28(join83(this.#root, `${contributionId}.inspect.json`), "utf8"));
11741
11741
  } catch {
11742
11742
  return void 0;
11743
11743
  }
@@ -11751,8 +11751,8 @@ var init_preview = __esm({
11751
11751
  async remove(contributionId) {
11752
11752
  if (!SAFE_ID2.test(contributionId))
11753
11753
  return;
11754
- await rm13(join82(this.#root, `${contributionId}.bundle`), { force: true });
11755
- await rm13(join82(this.#root, `${contributionId}.inspect.json`), { force: true });
11754
+ await rm13(join83(this.#root, `${contributionId}.bundle`), { force: true });
11755
+ await rm13(join83(this.#root, `${contributionId}.inspect.json`), { force: true });
11756
11756
  }
11757
11757
  /** Delete expired entries; returns how many were removed. */
11758
11758
  async sweep() {
@@ -11760,7 +11760,7 @@ var init_preview = __esm({
11760
11760
  for (const name of await readdir12(this.#root).catch(() => [])) {
11761
11761
  if (!name.endsWith(".inspect.json")) {
11762
11762
  if (name.endsWith(".tmp"))
11763
- await rm13(join82(this.#root, name), { force: true });
11763
+ await rm13(join83(this.#root, name), { force: true });
11764
11764
  continue;
11765
11765
  }
11766
11766
  const id = name.slice(0, -".inspect.json".length);
@@ -11771,21 +11771,21 @@ var init_preview = __esm({
11771
11771
  }
11772
11772
  for (const name of await readdir12(this.#root).catch(() => [])) {
11773
11773
  if (name.endsWith(".bundle") && !await this.#exists(`${name.slice(0, -".bundle".length)}.inspect.json`)) {
11774
- await rm13(join82(this.#root, name), { force: true });
11774
+ await rm13(join83(this.#root, name), { force: true });
11775
11775
  removed += 1;
11776
11776
  }
11777
11777
  }
11778
11778
  return removed;
11779
11779
  }
11780
11780
  async #exists(name) {
11781
- return stat14(join82(this.#root, name)).then(() => true, () => false);
11781
+ return stat14(join83(this.#root, name)).then(() => true, () => false);
11782
11782
  }
11783
11783
  async #usedBytes() {
11784
11784
  let total = 0;
11785
11785
  for (const name of await readdir12(this.#root).catch(() => [])) {
11786
11786
  if (!name.endsWith(".bundle"))
11787
11787
  continue;
11788
- total += await stat14(join82(this.#root, name)).then((s) => s.size, () => 0);
11788
+ total += await stat14(join83(this.#root, name)).then((s) => s.size, () => 0);
11789
11789
  }
11790
11790
  return total;
11791
11791
  }
@@ -11859,7 +11859,7 @@ async function acquireFileLock2(path2, options = {}) {
11859
11859
  if (Date.now() >= deadline) {
11860
11860
  throw new ContributionOutboxError("lock_timeout", "timed out waiting for the outbox lock");
11861
11861
  }
11862
- await delay2(retryDelayMs + Math.floor(jitterUnit2() * retryDelayMs));
11862
+ await delay3(retryDelayMs + Math.floor(jitterUnit2() * retryDelayMs));
11863
11863
  }
11864
11864
  }
11865
11865
  async function withFileLock2(path2, fn, options = {}) {
@@ -11928,7 +11928,7 @@ async function breakStaleLock2(path2, observed2, staleMs) {
11928
11928
  if (observed2 === void 0) {
11929
11929
  const info = await stat15(path2).catch(() => void 0);
11930
11930
  if (info === void 0 || Date.now() - info.mtimeMs <= Math.min(staleMs, 2e3)) {
11931
- await delay2(DEFAULT_RETRY_DELAY_MS2);
11931
+ await delay3(DEFAULT_RETRY_DELAY_MS2);
11932
11932
  return;
11933
11933
  }
11934
11934
  }
@@ -11955,7 +11955,7 @@ function isProcessAlive3(pid) {
11955
11955
  return error.code === "EPERM";
11956
11956
  }
11957
11957
  }
11958
- function delay2(ms) {
11958
+ function delay3(ms) {
11959
11959
  return new Promise((resolve21) => setTimeout(resolve21, ms));
11960
11960
  }
11961
11961
  function jitterUnit2() {
@@ -11978,7 +11978,7 @@ var init_lock2 = __esm({
11978
11978
  import { createHmac as createHmac3, randomBytes as randomBytes18 } from "node:crypto";
11979
11979
  import { execFile as execFile12 } from "node:child_process";
11980
11980
  import { mkdir as mkdir19, open as open8, readFile as readFile30, realpath as realpath5, rename as rename13, rm as rm15, stat as stat16 } from "node:fs/promises";
11981
- import { dirname as dirname38, isAbsolute as isAbsolute13, join as join83, relative as relative8, resolve as resolve18, sep as sep7 } from "node:path";
11981
+ import { dirname as dirname38, isAbsolute as isAbsolute13, join as join84, relative as relative8, resolve as resolve18, sep as sep7 } from "node:path";
11982
11982
  function toManifestScope(scope) {
11983
11983
  return { captureProjectId: scope.captureProjectId, worktreeRef: scope.worktreeRef, kind: scope.kind };
11984
11984
  }
@@ -12704,11 +12704,11 @@ var init_service = __esm({
12704
12704
 
12705
12705
  // ../../packages/contributions/dist/capture-wiring.js
12706
12706
  import { execFile as execFile13 } from "node:child_process";
12707
- import { join as join84 } from "node:path";
12707
+ import { join as join85 } from "node:path";
12708
12708
  function captureStatePaths(credentialRoot) {
12709
12709
  return {
12710
- stateFile: join84(credentialRoot, "contributions", "capture-sessions.json"),
12711
- previewRoot: join84(credentialRoot, "contributions", "preview")
12710
+ stateFile: join85(credentialRoot, "contributions", "capture-sessions.json"),
12711
+ previewRoot: join85(credentialRoot, "contributions", "preview")
12712
12712
  };
12713
12713
  }
12714
12714
  function dshSessionIndexOver(list) {
@@ -13109,7 +13109,7 @@ var init_idempotency = __esm({
13109
13109
  import { createCipheriv as createCipheriv4, createDecipheriv as createDecipheriv4, randomBytes as randomBytes19 } from "node:crypto";
13110
13110
  import { execFileSync } from "node:child_process";
13111
13111
  import { mkdir as mkdir21, readFile as readFile32, rename as rename15, rm as rm17, writeFile as writeFile16 } from "node:fs/promises";
13112
- import { join as join85 } from "node:path";
13112
+ import { join as join86 } from "node:path";
13113
13113
  function createPlatformKeyProvider(input) {
13114
13114
  const kind = input.kind ?? "auto";
13115
13115
  if (process.env["PICASSO_TEST_HERMETIC"]?.trim() === "1")
@@ -13190,7 +13190,7 @@ var init_keys = __esm({
13190
13190
  this.keyRoot = keyRoot;
13191
13191
  }
13192
13192
  async loadKey() {
13193
- const path2 = join85(this.keyRoot, OUTBOX_KEY_FILE);
13193
+ const path2 = join86(this.keyRoot, OUTBOX_KEY_FILE);
13194
13194
  try {
13195
13195
  const existing = await readFile32(path2);
13196
13196
  if (existing.length === 32) {
@@ -13358,9 +13358,9 @@ var init_outbox_index = __esm({
13358
13358
  import { createHash as createHash33, randomUUID as randomUUID14 } from "node:crypto";
13359
13359
  import { mkdir as mkdir22, open as open9, readFile as readFile33, readdir as readdir13, rename as rename16, rm as rm18, stat as stat17 } from "node:fs/promises";
13360
13360
  import { homedir as homedir13 } from "node:os";
13361
- import { join as join86 } from "node:path";
13361
+ import { join as join87 } from "node:path";
13362
13362
  function defaultOutboxRoot(credentialRoot) {
13363
- return join86(credentialRoot ?? process.env["PICASSO_CREDENTIAL_ROOT"] ?? join86(homedir13(), ".picasso"), "research-outbox");
13363
+ return join87(credentialRoot ?? process.env["PICASSO_CREDENTIAL_ROOT"] ?? join87(homedir13(), ".picasso"), "research-outbox");
13364
13364
  }
13365
13365
  function diskError(error) {
13366
13366
  return isDiskFullError(error) ? new ContributionOutboxError("outbox_disk_full", "local disk is full; the contribution was not queued") : error;
@@ -13736,7 +13736,7 @@ var init_outbox = __esm({
13736
13736
  next.push(entry);
13737
13737
  }
13738
13738
  const keep = new Set(next.filter((entry) => UNDELIVERED.has(entry.state) && entry.payloadBytes > 0).map((entry) => entry.entryId));
13739
- const payloadDir = join86(this.rootDir, "payloads");
13739
+ const payloadDir = join87(this.rootDir, "payloads");
13740
13740
  for (const name of await readdir13(payloadDir).catch(() => [])) {
13741
13741
  const entryId = name.endsWith(".enc") ? name.slice(0, -4) : void 0;
13742
13742
  if (entryId !== void 0 && keep.has(entryId)) {
@@ -13745,12 +13745,12 @@ var init_outbox = __esm({
13745
13745
  if (entryId === void 0 && !name.endsWith(".tmp")) {
13746
13746
  continue;
13747
13747
  }
13748
- await rm18(join86(payloadDir, name), { force: true });
13748
+ await rm18(join87(payloadDir, name), { force: true });
13749
13749
  orphanPayloads += 1;
13750
13750
  }
13751
13751
  for (const name of await readdir13(this.rootDir).catch(() => [])) {
13752
13752
  if (name.startsWith("queue.json.") && name.endsWith(".tmp")) {
13753
- await rm18(join86(this.rootDir, name), { force: true });
13753
+ await rm18(join87(this.rootDir, name), { force: true });
13754
13754
  }
13755
13755
  }
13756
13756
  return { entries: expired > 0 || pruned > 0 ? next : entries2, result: void 0 };
@@ -13830,7 +13830,7 @@ var init_outbox = __esm({
13830
13830
  }
13831
13831
  async #mutate(fn) {
13832
13832
  await mkdir22(this.rootDir, { recursive: true });
13833
- const lock = await acquireFileLock2(join86(this.rootDir, "queue.lock"), this.#lockOptions);
13833
+ const lock = await acquireFileLock2(join87(this.rootDir, "queue.lock"), this.#lockOptions);
13834
13834
  try {
13835
13835
  const index2 = await this.#readIndex(true);
13836
13836
  const { entries: entries2, result } = await fn(index2.entries);
@@ -13843,10 +13843,10 @@ var init_outbox = __esm({
13843
13843
  }
13844
13844
  }
13845
13845
  #indexPath() {
13846
- return join86(this.rootDir, "queue.json");
13846
+ return join87(this.rootDir, "queue.json");
13847
13847
  }
13848
13848
  #payloadPath(entryId) {
13849
- return join86(this.rootDir, "payloads", `${entryId}.enc`);
13849
+ return join87(this.rootDir, "payloads", `${entryId}.enc`);
13850
13850
  }
13851
13851
  async #readIndex(underLock) {
13852
13852
  let raw;
@@ -13880,7 +13880,7 @@ var init_outbox = __esm({
13880
13880
  async #writePayload(entryId, body) {
13881
13881
  const sealed = sealPayload(await this.#keyProvider.loadKey(), entryId, body);
13882
13882
  const target = this.#payloadPath(entryId);
13883
- await mkdir22(join86(this.rootDir, "payloads"), { recursive: true });
13883
+ await mkdir22(join87(this.rootDir, "payloads"), { recursive: true });
13884
13884
  const tmp = `${target}.${process.pid}.${randomUUID14()}.tmp`;
13885
13885
  try {
13886
13886
  await this.#io.writeDurable(tmp, sealed);
@@ -14087,11 +14087,11 @@ var init_uploader = __esm({
14087
14087
  return released({ kind: "block", reason: "policy_receipt_invalid", dropPayload: true });
14088
14088
  }
14089
14089
  if (entry.delivery.stage !== "none" || entry.attempts > 0) {
14090
- const lookup = await this.#api.lookupReceipt(session, entry.idempotencyKey);
14091
- if (!lookup.ok)
14092
- return this.#fromApiError(lookup.error, false);
14093
- if (lookup.value.found) {
14094
- return this.#accept(claim, lookup.value.receipt, "lookup");
14090
+ const lookup2 = await this.#api.lookupReceipt(session, entry.idempotencyKey);
14091
+ if (!lookup2.ok)
14092
+ return this.#fromApiError(lookup2.error, false);
14093
+ if (lookup2.value.found) {
14094
+ return this.#accept(claim, lookup2.value.receipt, "lookup");
14095
14095
  }
14096
14096
  }
14097
14097
  if (isAborted(signal))
@@ -14138,11 +14138,11 @@ var init_uploader = __esm({
14138
14138
  if (!put.ok) {
14139
14139
  if (put.error.status !== 409 && put.error.status !== 412)
14140
14140
  return this.#fromApiError(put.error, true);
14141
- const lookup = await this.#api.lookupReceipt(session, entry.idempotencyKey);
14142
- if (!lookup.ok)
14143
- return this.#fromApiError(lookup.error, true);
14144
- if (lookup.value.found)
14145
- return this.#accept(claim, lookup.value.receipt, "lookup");
14141
+ const lookup2 = await this.#api.lookupReceipt(session, entry.idempotencyKey);
14142
+ if (!lookup2.ok)
14143
+ return this.#fromApiError(lookup2.error, true);
14144
+ if (lookup2.value.found)
14145
+ return this.#accept(claim, lookup2.value.receipt, "lookup");
14146
14146
  }
14147
14147
  claim = await this.#outbox.recordProgress(claim, { ...claim.entry.delivery, stage: "bytes_uploaded" });
14148
14148
  this.#outbox.fault("upload:after-put");
@@ -14262,7 +14262,7 @@ var init_dist4 = __esm({
14262
14262
 
14263
14263
  // src/trajectory-data.ts
14264
14264
  import { userInfo as userInfo2 } from "node:os";
14265
- import { join as join87 } from "node:path";
14265
+ import { join as join88 } from "node:path";
14266
14266
  function normalizeApiUrl(value) {
14267
14267
  if (typeof value !== "string" || value.length > 2048) return void 0;
14268
14268
  let url;
@@ -14338,7 +14338,7 @@ function isRecord51(value) {
14338
14338
  }
14339
14339
  function resolveCredentialRoot(env2) {
14340
14340
  const explicit = env2["PICASSO_CREDENTIAL_ROOT"];
14341
- return explicit !== void 0 && explicit !== "" ? explicit : join87(userInfo2().homedir, ".picasso");
14341
+ return explicit !== void 0 && explicit !== "" ? explicit : join88(userInfo2().homedir, ".picasso");
14342
14342
  }
14343
14343
  async function readRegisteredProjects(env2) {
14344
14344
  const { value } = await readStore(projectsFile(env2), PROJECTS_SPEC);
@@ -14481,7 +14481,7 @@ var init_trajectory_data = __esm({
14481
14481
  ...options.logger === void 0 ? {} : { logger: options.logger }
14482
14482
  });
14483
14483
  this.projectScope = new ProjectScopeResolver({
14484
- stateFile: join87(credentialRoot, "contributions", "capture-projects.json"),
14484
+ stateFile: join88(credentialRoot, "contributions", "capture-projects.json"),
14485
14485
  now: this.#now,
14486
14486
  ...options.git === void 0 ? {} : { git: options.git }
14487
14487
  });
@@ -15063,7 +15063,7 @@ var init_components = __esm({
15063
15063
 
15064
15064
  // ../../packages/cache-harness/dist/src/config.js
15065
15065
  import { readFile as readFile36 } from "node:fs/promises";
15066
- import { join as join88, resolve as resolve19 } from "node:path";
15066
+ import { join as join89, resolve as resolve19 } from "node:path";
15067
15067
  var init_config = __esm({
15068
15068
  "../../packages/cache-harness/dist/src/config.js"() {
15069
15069
  "use strict";
@@ -15112,7 +15112,7 @@ var init_privacy = __esm({
15112
15112
 
15113
15113
  // ../../packages/cache-harness/dist/src/episode-package.js
15114
15114
  import { mkdir as mkdir24, writeFile as writeFile17 } from "node:fs/promises";
15115
- import { join as join89 } from "node:path";
15115
+ import { join as join90 } from "node:path";
15116
15116
  var init_episode_package = __esm({
15117
15117
  "../../packages/cache-harness/dist/src/episode-package.js"() {
15118
15118
  "use strict";
@@ -15142,7 +15142,7 @@ var init_trajectory = __esm({
15142
15142
  });
15143
15143
 
15144
15144
  // ../../packages/cache-harness/dist/src/harness-runner.js
15145
- import { join as join90 } from "node:path";
15145
+ import { join as join91 } from "node:path";
15146
15146
  var init_harness_runner = __esm({
15147
15147
  "../../packages/cache-harness/dist/src/harness-runner.js"() {
15148
15148
  "use strict";
@@ -16056,7 +16056,7 @@ var init_research_trace = __esm({
16056
16056
 
16057
16057
  // ../../packages/cache-harness/dist/src/research-export.js
16058
16058
  import { lstat as lstat6, readdir as readdir14, readFile as readFile37, realpath as realpath6 } from "node:fs/promises";
16059
- import { join as join91, resolve as resolve20 } from "node:path";
16059
+ import { join as join92, resolve as resolve20 } from "node:path";
16060
16060
  function blocked(code, details = [], exclusions = []) {
16061
16061
  return { status: "blocked", code, details, exclusions };
16062
16062
  }
@@ -16419,7 +16419,7 @@ async function readEpisodeSidecars(episodeDir, exclusions) {
16419
16419
  exclusions.push({ ref: `episode/${dir ? `${name}/` : name}`, kind: "scope_denied", detail: "file is not in the contribution sidecar allowlist; never read" });
16420
16420
  continue;
16421
16421
  }
16422
- const candidate = join91(root, name);
16422
+ const candidate = join92(root, name);
16423
16423
  try {
16424
16424
  const stat18 = await lstat6(candidate);
16425
16425
  if (stat18.isSymbolicLink()) {
@@ -16428,7 +16428,7 @@ async function readEpisodeSidecars(episodeDir, exclusions) {
16428
16428
  }
16429
16429
  if (!stat18.isFile())
16430
16430
  continue;
16431
- if (await realpath6(candidate) !== join91(realRoot, name)) {
16431
+ if (await realpath6(candidate) !== join92(realRoot, name)) {
16432
16432
  exclusions.push({ ref: name, kind: "symlink_escape", detail: "sidecar resolves outside the episode directory" });
16433
16433
  continue;
16434
16434
  }
@@ -16477,7 +16477,7 @@ var init_research_export = __esm({
16477
16477
  // ../../packages/cache-harness/dist/src/research-archive.js
16478
16478
  import { createHash as createHash37 } from "node:crypto";
16479
16479
  import { lstat as lstat7, readdir as readdir15, readFile as readFile38 } from "node:fs/promises";
16480
- import { join as join92 } from "node:path";
16480
+ import { join as join93 } from "node:path";
16481
16481
  import { gunzipSync, gzipSync } from "node:zlib";
16482
16482
  var MAX_ENTRY_BYTES;
16483
16483
  var init_research_archive = __esm({
@@ -17588,8 +17588,8 @@ init_home();
17588
17588
  init_dist();
17589
17589
  init_dist2();
17590
17590
  init_discovery();
17591
- import { existsSync as existsSync30, readFileSync as readFileSync45, rmSync as rmSync19 } from "node:fs";
17592
- import { dirname as dirname41, join as join93 } from "node:path";
17591
+ import { existsSync as existsSync30, readFileSync as readFileSync46, rmSync as rmSync19 } from "node:fs";
17592
+ import { dirname as dirname41, join as join94 } from "node:path";
17593
17593
 
17594
17594
  // src/bind-policy.ts
17595
17595
  import { isIP as isIP2 } from "node:net";
@@ -18583,12 +18583,12 @@ function unavailableBrowserExecutor(reason) {
18583
18583
  };
18584
18584
  }
18585
18585
  function chromiumExecutorFor(env2, platform2, options = {}) {
18586
- const lookup = (options.find ?? findChromium)({ env: env2, platform: platform2 });
18587
- if (!lookup.found)
18588
- return unavailableBrowserExecutor(lookup.reason);
18586
+ const lookup2 = (options.find ?? findChromium)({ env: env2, platform: platform2 });
18587
+ if (!lookup2.found)
18588
+ return unavailableBrowserExecutor(lookup2.reason);
18589
18589
  const launch = options.launch ?? ((executable) => launchChromium(executable, { platform: platform2 }));
18590
18590
  return new ChromiumBrowserExecutor({
18591
- launch: () => launch(lookup.path),
18591
+ launch: () => launch(lookup2.path),
18592
18592
  ...options.policy === void 0 ? {} : { policy: options.policy },
18593
18593
  ...options.snapshotScript === void 0 ? {} : { snapshotScript: options.snapshotScript }
18594
18594
  });
@@ -24393,11 +24393,11 @@ var FAT_MAGIC_64 = 3405691583;
24393
24393
  var MH_DYLIB = 6;
24394
24394
  var MH_BUNDLE = 8;
24395
24395
  var CPU_TYPE = { arm64: 16777228, x64: 16777223 };
24396
- function readAt(file, length, position) {
24397
- const buffer = Buffer.alloc(length);
24396
+ function readAt(file, length2, position) {
24397
+ const buffer = Buffer.alloc(length2);
24398
24398
  const fd = openSync2(file, "r");
24399
24399
  try {
24400
- return buffer.subarray(0, readSync(fd, buffer, 0, length, position));
24400
+ return buffer.subarray(0, readSync(fd, buffer, 0, length2, position));
24401
24401
  } finally {
24402
24402
  closeSync2(fd);
24403
24403
  }
@@ -26455,7 +26455,7 @@ function createParentAttestBridge(options) {
26455
26455
  options.input.on("data", onData);
26456
26456
  options.input.on("end", finishAll);
26457
26457
  options.input.on("close", finishAll);
26458
- const sign2 = (request) => {
26458
+ const sign3 = (request) => {
26459
26459
  if (closed) return Promise.resolve(void 0);
26460
26460
  const id = String(++seq);
26461
26461
  return new Promise((resolve21) => {
@@ -26480,7 +26480,7 @@ function createParentAttestBridge(options) {
26480
26480
  });
26481
26481
  };
26482
26482
  return {
26483
- sign: sign2,
26483
+ sign: sign3,
26484
26484
  close: () => {
26485
26485
  closed = true;
26486
26486
  options.input.off("data", onData);
@@ -29325,7 +29325,7 @@ ${body}`, createdAt: previous.createdAt };
29325
29325
  const memory = record3.memory ?? (record3.baseline ? baselineMemory(snapshot) : EMPTY_MEMORY);
29326
29326
  const step = stepWatch(memory, snapshot);
29327
29327
  const status = prStatus(record3.number, snapshot);
29328
- const delay3 = nextPollDelay({ snapshot, consecutiveErrors: 0, watchAgeMs: at2 - Date.parse(record3.addedAt) });
29328
+ const delay4 = nextPollDelay({ snapshot, consecutiveErrors: 0, watchAgeMs: at2 - Date.parse(record3.addedAt) });
29329
29329
  const { lastError: _cleared, nextPollAt: _next, ...base2 } = record3;
29330
29330
  let next = {
29331
29331
  ...base2,
@@ -29337,8 +29337,8 @@ ${body}`, createdAt: previous.createdAt };
29337
29337
  ...snapshot.title === void 0 ? {} : { title: snapshot.title },
29338
29338
  lastPolledAt: iso3(at2),
29339
29339
  errors: 0,
29340
- active: delay3 !== void 0,
29341
- ...delay3 === void 0 ? {} : { nextPollAt: iso3(at2 + delay3) }
29340
+ active: delay4 !== void 0,
29341
+ ...delay4 === void 0 ? {} : { nextPollAt: iso3(at2 + delay4) }
29342
29342
  };
29343
29343
  if (step.events.length === 0)
29344
29344
  return next;
@@ -36815,13 +36815,13 @@ function decodeXmlText(text6) {
36815
36815
  });
36816
36816
  }
36817
36817
  function* xmlEvents(xml) {
36818
- const length = xml.length;
36818
+ const length2 = xml.length;
36819
36819
  let at2 = 0;
36820
36820
  const malformed = () => {
36821
36821
  throw unreadable("document-damaged", "This document is damaged: its text could not be parsed.");
36822
36822
  };
36823
36823
  let steps = 0;
36824
- while (at2 < length) {
36824
+ while (at2 < length2) {
36825
36825
  if ((steps++ & 4095) === 0 && Date.now() > OFFICE_DEADLINE.at) throw unreadable("timed-out", deadlineMessage(OFFICE_DEADLINE.seconds), { seconds: Math.round(OFFICE_DEADLINE.seconds) });
36826
36826
  const lt = xml.indexOf("<", at2);
36827
36827
  if (lt < 0) {
@@ -36845,14 +36845,14 @@ function* xmlEvents(xml) {
36845
36845
  } else if (xml.startsWith("<!", lt)) {
36846
36846
  const end = xml.indexOf(">", lt + 2);
36847
36847
  if (end < 0) malformed();
36848
- if (xml.slice(lt, end).includes("[") || /<!ENTITY/i.test(xml.slice(lt, Math.min(length, end + 1)))) {
36848
+ if (xml.slice(lt, end).includes("[") || /<!ENTITY/i.test(xml.slice(lt, Math.min(length2, end + 1)))) {
36849
36849
  throw unreadable("xml-entities", "This document declares XML entities, which Picasso does not read.");
36850
36850
  }
36851
36851
  at2 = end + 1;
36852
36852
  } else {
36853
36853
  let end = lt + 1;
36854
36854
  let quote = "";
36855
- for (; end < length; end += 1) {
36855
+ for (; end < length2; end += 1) {
36856
36856
  const ch = xml[end];
36857
36857
  if (quote !== "") {
36858
36858
  if (ch === quote) quote = "";
@@ -36861,7 +36861,7 @@ function* xmlEvents(xml) {
36861
36861
  if (ch === '"' || ch === "'") quote = ch;
36862
36862
  else if (ch === ">") break;
36863
36863
  }
36864
- if (end >= length) malformed();
36864
+ if (end >= length2) malformed();
36865
36865
  const raw = xml.slice(lt + 1, end);
36866
36866
  at2 = end + 1;
36867
36867
  if (raw.startsWith("/")) {
@@ -39036,11 +39036,11 @@ function parsePorcelainV2(text6) {
39036
39036
  if (token2.length === 0)
39037
39037
  continue;
39038
39038
  if (token2.startsWith("# branch.oid ")) {
39039
- const oid = token2.slice("# branch.oid ".length);
39040
- if (oid === "(initial)")
39039
+ const oid2 = token2.slice("# branch.oid ".length);
39040
+ if (oid2 === "(initial)")
39041
39041
  result.unborn = true;
39042
39042
  else
39043
- result.head = oid;
39043
+ result.head = oid2;
39044
39044
  } else if (token2.startsWith("# branch.head ")) {
39045
39045
  const head = token2.slice("# branch.head ".length);
39046
39046
  if (head === "(detached)")
@@ -40951,8 +40951,8 @@ function scorePositions(text6, positions) {
40951
40951
  }
40952
40952
  return score;
40953
40953
  }
40954
- function range(start, length) {
40955
- return Array.from({ length }, (_, index2) => start + index2);
40954
+ function range(start, length2) {
40955
+ return Array.from({ length: length2 }, (_, index2) => start + index2);
40956
40956
  }
40957
40957
  var NO_POSITIONS = [];
40958
40958
  function matchEntry(query, entry, withPositions = true) {
@@ -42764,8 +42764,8 @@ function advertisedEfforts(entry, api) {
42764
42764
  }
42765
42765
  return void 0;
42766
42766
  }
42767
- function sourced(id, found, route, lookup, saved = {}) {
42768
- const looked = lookup({ provider: route.provider, baseURL: route.baseURL, modelId: id });
42767
+ function sourced(id, found, route, lookup2, saved = {}) {
42768
+ const looked = lookup2({ provider: route.provider, baseURL: route.baseURL, modelId: id });
42769
42769
  const facts = looked?.viaOtherProvider === true ? withoutSaved(looked, saved) : looked;
42770
42770
  const contextWindow = found?.contextWindow ?? facts?.contextWindow;
42771
42771
  const output = found?.maxOutput ?? facts?.maxOutput;
@@ -42794,7 +42794,7 @@ function withoutSaved(facts, saved) {
42794
42794
  sources
42795
42795
  };
42796
42796
  }
42797
- function syncDeclaredModels(models, advertised, route = {}, lookup = catalogModel) {
42797
+ function syncDeclaredModels(models, advertised, route = {}, lookup2 = catalogModel) {
42798
42798
  const where = typeof route === "string" ? { baseURL: route } : route;
42799
42799
  const byId = new Map(advertised.map((model) => [model.id, model]));
42800
42800
  const updated = [];
@@ -42803,7 +42803,7 @@ function syncDeclaredModels(models, advertised, route = {}, lookup = catalogMode
42803
42803
  const id = typeof model["id"] === "string" ? model["id"] : "";
42804
42804
  const found = byId.get(id);
42805
42805
  if (!found) unlisted.push(id);
42806
- const known = sourced(id, found, where, lookup, model);
42806
+ const known = sourced(id, found, where, lookup2, model);
42807
42807
  const merged = { ...model };
42808
42808
  if (known.contextWindow !== void 0) merged["contextWindow"] = known.contextWindow;
42809
42809
  if (known.maxOutput !== void 0) merged["maxTokens"] = known.maxOutput;
@@ -42815,10 +42815,10 @@ function syncDeclaredModels(models, advertised, route = {}, lookup = catalogMode
42815
42815
  });
42816
42816
  return { models: next, updated, unlisted };
42817
42817
  }
42818
- function describedModel(model, route, lookup = catalogModel) {
42818
+ function describedModel(model, route, lookup2 = catalogModel) {
42819
42819
  const where = typeof route === "string" || route === void 0 ? { baseURL: route } : route;
42820
42820
  const id = typeof model["id"] === "string" ? model["id"] : "";
42821
- const known = sourced(id, void 0, where, lookup, model);
42821
+ const known = sourced(id, void 0, where, lookup2, model);
42822
42822
  const savedWindow = typeof model["contextWindow"] === "number" && model["contextWindow"] > 0 ? model["contextWindow"] : void 0;
42823
42823
  const savedOutput = typeof model["maxTokens"] === "number" && model["maxTokens"] > 0 ? model["maxTokens"] : void 0;
42824
42824
  const savedLevels = declaredLevels(model["reasoningEfforts"]);
@@ -43267,10 +43267,10 @@ async function readFileBytes(remote2, sessionId, query) {
43267
43267
  const path2 = query.get("path");
43268
43268
  if (path2 === null || path2 === "") return failure4(400, { code: "relay/bad-request", message: "file-bytes needs a path." });
43269
43269
  const offset = nonNegativeInt(query.get("offset"));
43270
- const length = nonNegativeInt(query.get("length"));
43271
- if (Number.isNaN(offset) || Number.isNaN(length)) return failure4(400, { code: "relay/bad-request", message: "offset and length are non-negative integers." });
43270
+ const length2 = nonNegativeInt(query.get("length"));
43271
+ if (Number.isNaN(offset) || Number.isNaN(length2)) return failure4(400, { code: "relay/bad-request", message: "offset and length are non-negative integers." });
43272
43272
  const base2 = query.get("base");
43273
- const range2 = offset !== void 0 || length !== void 0 ? { range: { ...offset !== void 0 ? { offset } : {}, ...length !== void 0 ? { length } : {} } } : {};
43273
+ const range2 = offset !== void 0 || length2 !== void 0 ? { range: { ...offset !== void 0 ? { offset } : {}, ...length2 !== void 0 ? { length: length2 } : {} } } : {};
43274
43274
  const result = await remote2.call("workspaceFiles/readBytes", {
43275
43275
  workspaceFileScopeId: sessionId,
43276
43276
  path: path2,
@@ -44965,7 +44965,13 @@ var Relay = class _Relay {
44965
44965
  if (event === "permission-presets/catalog-changed") this.broadcast(void 0, "catalog", isRecord49(args[0]) ? args[0] : { event });
44966
44966
  });
44967
44967
  const handle = (req, res) => this.dispatch(req, res);
44968
- this.server = options.tls ? createTlsServer(options.tls, handle) : createServer7(handle);
44968
+ const trustedLink = options.trustedLink;
44969
+ const tlsOptions = options.tls === void 0 ? void 0 : {
44970
+ ...options.tls,
44971
+ // A name under the trusted link's domain gets its certificate; anything else (no SNI for an IP) the default.
44972
+ ...trustedLink === void 0 ? {} : { SNICallback: (servername, done2) => done2(null, trustedLink.secureContext(servername)) }
44973
+ };
44974
+ this.server = tlsOptions ? createTlsServer(tlsOptions, handle) : createServer7(handle);
44969
44975
  if (options.tls) answerPlainHttpOnTls(this.server, (host2) => this.hostAllowed(host2));
44970
44976
  this.trackConnections(this.server);
44971
44977
  this.tlsMaterial = options.tls;
@@ -45146,6 +45152,7 @@ var Relay = class _Relay {
45146
45152
  this.closePromise = Promise.resolve().then(async () => {
45147
45153
  this.stopBrowserPump();
45148
45154
  this.computerPump.stop();
45155
+ this.options.trustedLink?.close();
45149
45156
  this.prWatch?.stop();
45150
45157
  this.crashResume?.close();
45151
45158
  this.librarian?.stop();
@@ -45210,7 +45217,7 @@ var Relay = class _Relay {
45210
45217
  * tailnet. An invalid explicit origin is an error (nothing is minted); an address the certificate does not name is
45211
45218
  * skipped. Re-read on every call, after reloading a certificate that changed on disk.
45212
45219
  */
45213
- pairingOrigins() {
45220
+ pairingOrigins(trusted) {
45214
45221
  this.reloadTlsIfChanged();
45215
45222
  const explicit = (this.options.advertisedOrigin ?? "").split(",").map((item) => item.trim()).filter((item) => item !== "");
45216
45223
  const bind = this.server.address();
@@ -45240,14 +45247,31 @@ var Relay = class _Relay {
45240
45247
  }
45241
45248
  }
45242
45249
  if (this.options.advertiseInterfaces === true && usable && typeof bind === "object" && bind !== null && isWildcardBind(bind.address)) {
45243
- for (const address of (this.options.interfaceAddresses ?? privateInterfaceAddresses)()) {
45244
- if (!isPrivatePeer(address) || isLoopbackBindHost(address) || !covers(address)) continue;
45245
- add(new URL(`https://${isIP4(address) === 6 ? `[${address}]` : address}:${bind.port}`).origin, address);
45250
+ const addresses = (this.options.interfaceAddresses ?? privateInterfaceAddresses)();
45251
+ for (const network of ["lan", "tailnet"]) {
45252
+ for (const row of trusted?.names ?? []) {
45253
+ if (row.network === "tailnet" !== (network === "tailnet")) continue;
45254
+ const origin = new URL(`https://${row.name}:${bind.port}`).origin;
45255
+ if (!origins.some((o) => o.origin === origin)) origins.push({ origin, network: row.network, trusted: true });
45256
+ }
45257
+ for (const address of addresses) {
45258
+ if (reachNetwork(address) === "tailnet" !== (network === "tailnet")) continue;
45259
+ if (!isPrivatePeer(address) || isLoopbackBindHost(address) || !covers(address)) continue;
45260
+ add(new URL(`https://${isIP4(address) === 6 ? `[${address}]` : address}:${bind.port}`).origin, address);
45261
+ }
45246
45262
  }
45247
45263
  }
45248
45264
  if (origins.length === 0) return { origins, error: explicit.length === 0 ? "pairing_origin_not_configured" : "pairing_origin_invalid" };
45249
45265
  return { origins, error: null };
45250
45266
  }
45267
+ /** The trusted link's view when this relay can serve it (TLS on a wildcard bind that advertises its interfaces). */
45268
+ trustedLinkFor() {
45269
+ const link3 = this.options.trustedLink;
45270
+ const bind = this.server.address();
45271
+ if (link3 === void 0 || this.tlsMaterial === void 0 || this.options.advertiseInterfaces !== true) return void 0;
45272
+ if (bind === null || typeof bind !== "object" || !isWildcardBind(bind.address)) return void 0;
45273
+ return link3.snapshot();
45274
+ }
45251
45275
  /** Swaps in the certificate and key from `tlsFiles` when the certificate file changed since it was read. */
45252
45276
  reloadTlsIfChanged() {
45253
45277
  const files = this.options.tlsFiles;
@@ -45633,8 +45657,15 @@ var Relay = class _Relay {
45633
45657
  addresses: lanIPv4Addresses(),
45634
45658
  port: typeof bind === "object" && bind !== null ? bind.port : null,
45635
45659
  ...(() => {
45636
- const all = this.pairingOrigins();
45637
- return { advertisedOrigin: all.origins[0]?.origin ?? null, advertisedOrigins: all.origins, pairingOriginError: all.error };
45660
+ const trusted = this.trustedLinkFor();
45661
+ if (trusted !== void 0) void this.options.trustedLink?.prepare({ waitMs: 0 }).catch(() => void 0);
45662
+ const all = this.pairingOrigins(trusted);
45663
+ return {
45664
+ advertisedOrigin: all.origins[0]?.origin ?? null,
45665
+ advertisedOrigins: all.origins,
45666
+ pairingOriginError: all.error,
45667
+ ...trusted === void 0 ? {} : { trustedLink: { state: trusted.state, message: trusted.message } }
45668
+ };
45638
45669
  })()
45639
45670
  });
45640
45671
  }
@@ -45642,12 +45673,19 @@ var Relay = class _Relay {
45642
45673
  if (!this.options.pairing) return send(res, 404, { error: "pairing is not enabled" });
45643
45674
  const scopes = body["scopes"] === void 0 ? REMOTE_SCOPES : parseRemoteScopes(body["scopes"]);
45644
45675
  if (scopes === void 0) return send(res, 400, { error: { code: "pair/invalid-scopes", message: `scopes must name at least one of ${REMOTE_SCOPES.join(", ")}` } });
45645
- const advertised = this.pairingOrigins();
45676
+ const trusted = this.trustedLinkFor() === void 0 ? void 0 : await this.options.trustedLink?.prepare().catch(() => void 0);
45677
+ const advertised = this.pairingOrigins(trusted);
45646
45678
  const primary = advertised.origins[0];
45647
45679
  if (primary === void 0) return send(res, 409, { error: advertised.error });
45648
45680
  const minted = this.options.pairing.mintCode(scopes);
45649
- const remoteUrls = advertised.origins.map(({ origin, network }) => ({ url: `${origin}/remote#c=${minted.code}`, network }));
45650
- return send(res, 200, { ...minted, url: `${primary.origin}/pair#c=${minted.code}`, remoteUrl: `${primary.origin}/remote#c=${minted.code}`, remoteUrls });
45681
+ const remoteUrls = advertised.origins.map(({ origin, network, trusted: isTrusted }) => ({ url: `${origin}/remote#c=${minted.code}`, network, ...isTrusted === true ? { trusted: true } : {} }));
45682
+ return send(res, 200, {
45683
+ ...minted,
45684
+ url: `${primary.origin}/pair#c=${minted.code}`,
45685
+ remoteUrl: `${primary.origin}/remote#c=${minted.code}`,
45686
+ remoteUrls,
45687
+ ...trusted === void 0 ? {} : { trustedLink: { state: trusted.state, message: trusted.message } }
45688
+ });
45651
45689
  }
45652
45690
  if (head === "pair" && id === "devices" && !action && req.method === "GET") {
45653
45691
  return send(res, 200, { devices: (this.options.pairing?.devices() ?? []).map((d) => ({ ...d, connected: this.remoteHub.connected(d.id) })) });
@@ -50030,6 +50068,7 @@ var Relay = class _Relay {
50030
50068
  const hostname4 = hostnameOf(hostHeader);
50031
50069
  if (hostname4 === void 0) return false;
50032
50070
  if (hostname4 === "localhost" || isLoopbackBindHost(hostname4)) return true;
50071
+ if (this.options.trustedLink?.ownsHost(hostname4) === true) return true;
50033
50072
  const allowed = /* @__PURE__ */ new Set();
50034
50073
  for (const server of [this.server, this.loopbackServer]) {
50035
50074
  const bound = server?.address();
@@ -50786,8 +50825,8 @@ var uploadBytes = (item) => {
50786
50825
  return void 0;
50787
50826
  };
50788
50827
  async function pipeUpstream(res, response, headers) {
50789
- const length = response.headers.get("content-length");
50790
- res.writeHead(200, { ...headers, ...length !== null && /^\d+$/.test(length) ? { "content-length": length } : {} });
50828
+ const length2 = response.headers.get("content-length");
50829
+ res.writeHead(200, { ...headers, ...length2 !== null && /^\d+$/.test(length2) ? { "content-length": length2 } : {} });
50791
50830
  if (response.body === null) {
50792
50831
  res.end();
50793
50832
  return;
@@ -51216,6 +51255,515 @@ async function readJson5(req, limit = BODY_LIMIT_BYTES) {
51216
51255
  return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
51217
51256
  }
51218
51257
 
51258
+ // src/trusted-link.ts
51259
+ init_home();
51260
+ import { createPrivateKey as createPrivateKey4, X509Certificate as X509Certificate3 } from "node:crypto";
51261
+ import { lookup, Resolver } from "node:dns/promises";
51262
+ import { mkdirSync as mkdirSync29, readFileSync as readFileSync43, renameSync as renameSync20, statSync as statSync18, writeFileSync as writeFileSync24 } from "node:fs";
51263
+ import { hostname as osHostname } from "node:os";
51264
+ import { join as join80 } from "node:path";
51265
+ import { createSecureContext } from "node:tls";
51266
+
51267
+ // src/trusted-link-csr.ts
51268
+ import { createPrivateKey as createPrivateKey3, createPublicKey as createPublicKey3, generateKeyPairSync as generateKeyPairSync2, sign as sign2 } from "node:crypto";
51269
+ function length(n) {
51270
+ if (n < 128) return Buffer.from([n]);
51271
+ const bytes = [];
51272
+ for (let rest = n; rest > 0; rest >>= 8) bytes.unshift(rest & 255);
51273
+ return Buffer.from([128 | bytes.length, ...bytes]);
51274
+ }
51275
+ function tlv(tag, ...content) {
51276
+ const body = Buffer.concat(content);
51277
+ return Buffer.concat([Buffer.from([tag]), length(body.length), body]);
51278
+ }
51279
+ function oid(dotted) {
51280
+ const parts = dotted.split(".").map(Number);
51281
+ const first = parts[0] ?? 0;
51282
+ const second = parts[1] ?? 0;
51283
+ const bytes = [first * 40 + second];
51284
+ for (const part of parts.slice(2)) {
51285
+ const chunk = [part & 127];
51286
+ for (let rest = part >>> 7; rest > 0; rest >>>= 7) chunk.unshift(rest & 127 | 128);
51287
+ bytes.push(...chunk);
51288
+ }
51289
+ return tlv(6, Buffer.from(bytes));
51290
+ }
51291
+ var SEQUENCE = 48;
51292
+ var SET = 49;
51293
+ var OID_COMMON_NAME = "2.5.4.3";
51294
+ var OID_EXTENSION_REQUEST = "1.2.840.113549.1.9.14";
51295
+ var OID_SUBJECT_ALT_NAME = "2.5.29.17";
51296
+ var OID_ECDSA_SHA256 = "1.2.840.10045.4.3.2";
51297
+ var CSR_NAME = /^(\*\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/u;
51298
+ function buildCsrDer(name, privateKey) {
51299
+ if (!CSR_NAME.test(name) || name.length > 253) throw new Error("not a certificate name");
51300
+ const spki = createPublicKey3(privateKey).export({ type: "spki", format: "der" });
51301
+ const subject = tlv(SEQUENCE, tlv(SET, tlv(SEQUENCE, oid(OID_COMMON_NAME), tlv(12, Buffer.from(name, "utf8")))));
51302
+ const generalNames = tlv(SEQUENCE, tlv(130, Buffer.from(name, "ascii")));
51303
+ const extensions = tlv(SEQUENCE, tlv(SEQUENCE, oid(OID_SUBJECT_ALT_NAME), tlv(4, generalNames)));
51304
+ const attributes = tlv(160, tlv(SEQUENCE, oid(OID_EXTENSION_REQUEST), tlv(SET, extensions)));
51305
+ const info = tlv(SEQUENCE, tlv(2, Buffer.from([0])), subject, spki, attributes);
51306
+ const signature = sign2("sha256", info, privateKey);
51307
+ return tlv(SEQUENCE, info, tlv(SEQUENCE, oid(OID_ECDSA_SHA256)), tlv(3, Buffer.from([0]), signature));
51308
+ }
51309
+ function csrPem(der) {
51310
+ const lines = der.toString("base64").match(/.{1,64}/gu) ?? [];
51311
+ return `-----BEGIN CERTIFICATE REQUEST-----
51312
+ ${lines.join("\n")}
51313
+ -----END CERTIFICATE REQUEST-----
51314
+ `;
51315
+ }
51316
+ function newKeyAndCsr(name) {
51317
+ const { privateKey } = generateKeyPairSync2("ec", { namedCurve: "P-256" });
51318
+ const keyPem = privateKey.export({ type: "pkcs8", format: "pem" }).toString();
51319
+ return { keyPem, csrPem: csrPem(buildCsrDer(name, createPrivateKey3(keyPem))) };
51320
+ }
51321
+
51322
+ // src/trusted-link.ts
51323
+ var TRUSTED_LINK_MESSAGES = {
51324
+ pending: "The secure link for this computer is still being set up, so this link uses the IP address and the phone may warn that the connection is not private. Pair again in a minute.",
51325
+ "signed-out": "Sign in to Picasso on this computer for a link the phone trusts; this link uses the IP address, so the phone may warn that the connection is not private.",
51326
+ invite: "Your Picasso account cannot get a secure link yet, so this link uses the IP address and the phone may warn that the connection is not private.",
51327
+ unavailable: "The secure link service is not available right now, so this link uses the IP address and the phone may warn that the connection is not private.",
51328
+ "dns-blocked": "This network's router blocks the secure name for this computer (DNS rebinding protection), so this link uses the IP address and the phone may warn that the connection is not private."
51329
+ };
51330
+ var TrustedLinkApiError = class extends Error {
51331
+ status;
51332
+ code;
51333
+ retryAfterMs;
51334
+ constructor(status, code, retryAfterMs2) {
51335
+ super(`trusted link: ${status} ${code}`);
51336
+ this.name = "TrustedLinkApiError";
51337
+ this.status = status;
51338
+ this.code = code;
51339
+ this.retryAfterMs = retryAfterMs2;
51340
+ }
51341
+ };
51342
+ var HOST_ID = /^[a-z2-7]{16}$/u;
51343
+ var DOMAIN = /^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/u;
51344
+ function retryAfterMs(value) {
51345
+ if (value === null) return void 0;
51346
+ const seconds2 = Number(value);
51347
+ if (Number.isFinite(seconds2) && seconds2 >= 0) return seconds2 * 1e3;
51348
+ const at2 = Date.parse(value);
51349
+ return Number.isNaN(at2) ? void 0 : Math.max(0, at2 - Date.now());
51350
+ }
51351
+ function accountTrustedLinkApi(options) {
51352
+ const fetchImpl = options.fetch ?? fetch;
51353
+ const call = async (method, path2, body, timeoutMs) => {
51354
+ const account = await currentAccount(options.read);
51355
+ if (account === void 0) throw new TrustedLinkApiError(401, "signed_out");
51356
+ let response;
51357
+ try {
51358
+ response = await fetchImpl(`${account.apiOrigin.replace(/\/+$/u, "")}${path2}`, {
51359
+ method,
51360
+ headers: { authorization: `Bearer ${account.accessToken}`, "content-type": "application/json", ...await clientHeaders(options.env) },
51361
+ body: JSON.stringify(body),
51362
+ signal: AbortSignal.timeout(timeoutMs)
51363
+ });
51364
+ } catch (error) {
51365
+ throw new TrustedLinkApiError(0, error instanceof Error && error.name === "TimeoutError" ? "timeout" : "network");
51366
+ }
51367
+ const parsed = await response.json().catch(() => ({}));
51368
+ const json4 = typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : {};
51369
+ if (!response.ok) {
51370
+ const code = typeof json4["error"] === "string" && /^[a-z_]{1,64}$/u.test(json4["error"]) ? json4["error"] : `http_${response.status}`;
51371
+ throw new TrustedLinkApiError(response.status, code, retryAfterMs(response.headers.get("retry-after")));
51372
+ }
51373
+ return json4;
51374
+ };
51375
+ return {
51376
+ async account() {
51377
+ const account = await currentAccount(options.read);
51378
+ return account === void 0 ? void 0 : { apiOrigin: account.apiOrigin, accountId: account.accountId };
51379
+ },
51380
+ async register(label2) {
51381
+ const json4 = await call("POST", "/v1/remote-hosts", { label: label2 }, 2e4);
51382
+ const hostId = json4["hostId"];
51383
+ const domain = json4["domain"];
51384
+ if (typeof hostId !== "string" || !HOST_ID.test(hostId) || typeof domain !== "string" || !DOMAIN.test(domain) || !domain.startsWith(`${hostId}.`)) {
51385
+ throw new TrustedLinkApiError(502, "bad_answer");
51386
+ }
51387
+ return { hostId, domain };
51388
+ },
51389
+ async putAddresses(hostId, addresses) {
51390
+ const json4 = await call("PUT", `/v1/remote-hosts/${hostId}/addresses`, { addresses }, 2e4);
51391
+ const names = Array.isArray(json4["names"]) ? json4["names"].flatMap((row) => {
51392
+ const item = row;
51393
+ return item !== null && typeof item === "object" && typeof item.address === "string" && typeof item.name === "string" && DOMAIN.test(item.name) ? [{ address: item.address, name: item.name }] : [];
51394
+ }) : [];
51395
+ return { names };
51396
+ },
51397
+ async issue(hostId, csrPem2) {
51398
+ const json4 = await call("POST", `/v1/remote-hosts/${hostId}/certificate`, { csr: csrPem2 }, 24e4);
51399
+ if (typeof json4["certificate"] !== "string") throw new TrustedLinkApiError(502, "bad_answer");
51400
+ return { certificate: json4["certificate"] };
51401
+ }
51402
+ };
51403
+ }
51404
+ var withTimeout = (work, ms) => new Promise((resolve21, reject) => {
51405
+ const timer = setTimeout(() => reject(new Error("timeout")), ms);
51406
+ timer.unref?.();
51407
+ work.then((value) => {
51408
+ clearTimeout(timer);
51409
+ resolve21(value);
51410
+ }, (error) => {
51411
+ clearTimeout(timer);
51412
+ reject(error instanceof Error ? error : new Error(String(error)));
51413
+ });
51414
+ });
51415
+ var systemResolver = {
51416
+ local: async (name) => (await withTimeout(lookup(name, { all: true, family: 4 }), 2500)).map((row) => row.address),
51417
+ public: async (name) => {
51418
+ const resolver = new Resolver({ timeout: 2e3, tries: 1 });
51419
+ resolver.setServers(["1.1.1.1", "8.8.8.8"]);
51420
+ return withTimeout(resolver.resolve4(name), 3e3);
51421
+ }
51422
+ };
51423
+ async function checkName(resolver, name, address) {
51424
+ const local2 = await resolver.local(name).catch(() => []);
51425
+ if (local2.includes(address)) return "ok";
51426
+ const remote2 = await resolver.public(name).catch(() => []);
51427
+ return remote2.includes(address) ? "blocked" : "pending";
51428
+ }
51429
+ var CHECK_TTL_MS = { ok: 30 * 6e4, blocked: 10 * 6e4, pending: 15e3 };
51430
+ var FIRST_ISSUE_WAIT_MS = 45e3;
51431
+ var UPDATE_WAIT_MS = 6e3;
51432
+ var NAMES_REFRESH_MS = 12 * 60 * 6e4;
51433
+ var MAX_ADDRESSES = 4;
51434
+ var ipv4 = (address) => /^\d{1,3}(\.\d{1,3}){3}$/u.test(address);
51435
+ var TrustedLink = class {
51436
+ options;
51437
+ now;
51438
+ resolver;
51439
+ state;
51440
+ material;
51441
+ problem;
51442
+ failures = 0;
51443
+ lastSyncAt = Number.NEGATIVE_INFINITY;
51444
+ running;
51445
+ timer;
51446
+ closed = false;
51447
+ checks = /* @__PURE__ */ new Map();
51448
+ constructor(options) {
51449
+ this.options = options;
51450
+ this.now = options.now ?? Date.now;
51451
+ this.resolver = options.resolver ?? systemResolver;
51452
+ this.load();
51453
+ }
51454
+ get files() {
51455
+ return { state: join80(this.options.dir, "state.json"), key: join80(this.options.dir, "key.pem"), cert: join80(this.options.dir, "cert.pem") };
51456
+ }
51457
+ /** Background work: now, then every `refreshMs`. The timer never keeps the process alive. */
51458
+ start() {
51459
+ void this.sync();
51460
+ this.timer = setInterval(() => {
51461
+ void this.sync();
51462
+ }, this.options.refreshMs ?? 6 * 60 * 6e4);
51463
+ this.timer.unref?.();
51464
+ return this;
51465
+ }
51466
+ close() {
51467
+ this.closed = true;
51468
+ if (this.timer !== void 0) clearInterval(this.timer);
51469
+ }
51470
+ // ---- what the relay asks ----
51471
+ /** The trusted certificate for a name under this host's domain, while it is valid; else the default (self-signed). */
51472
+ secureContext(servername) {
51473
+ const material = this.material;
51474
+ if (material === void 0 || material.notAfter <= this.now()) return void 0;
51475
+ const host2 = servername.toLowerCase().replace(/\.$/u, "");
51476
+ const suffix = `.${material.domain}`;
51477
+ if (!host2.endsWith(suffix)) return void 0;
51478
+ const label2 = host2.slice(0, -suffix.length);
51479
+ return /^[a-z0-9-]{1,63}$/u.test(label2) ? material.context : void 0;
51480
+ }
51481
+ /** A name of this machine's (`<a-b-c-d>.<domain>` for one of its current addresses): the Host-header guard lets it in. */
51482
+ ownsHost(hostname4) {
51483
+ const domain = this.state?.domain;
51484
+ if (domain === void 0) return false;
51485
+ const host2 = hostname4.toLowerCase().replace(/\.$/u, "");
51486
+ if (!host2.endsWith(`.${domain}`)) return false;
51487
+ const address = host2.slice(0, -(domain.length + 1)).replace(/-/gu, ".");
51488
+ return ipv4(address) && this.addresses().includes(address);
51489
+ }
51490
+ /** The pairing's view now, without waiting: trusted names whose certificate is valid and whose name resolves here. */
51491
+ snapshot() {
51492
+ this.reloadIfChanged();
51493
+ const addresses = this.addresses();
51494
+ const state = this.state;
51495
+ const material = this.material;
51496
+ const certOk = material !== void 0 && state !== void 0 && material.domain === state.domain && material.notAfter > this.now() + 6e4;
51497
+ const named = certOk && state !== void 0 ? addresses.flatMap((address) => {
51498
+ const name = state.names[address];
51499
+ return name === void 0 ? [] : [{ address, name, network: reachNetwork(address) }];
51500
+ }) : [];
51501
+ const checked = named.map((row) => ({ row, check: this.cachedCheck(row.name, row.address) }));
51502
+ const names = checked.filter((item) => item.check === "ok").map((item) => item.row);
51503
+ const primaryNetwork = addresses.some((address) => !isTailnetHost(address)) ? "lan" : "tailnet";
51504
+ if (names.some((row) => row.network === primaryNetwork)) return { state: "ready", message: null, names };
51505
+ const problem = this.problem;
51506
+ if (problem === "signed-out") return { state: "signed-out", message: TRUSTED_LINK_MESSAGES["signed-out"], names };
51507
+ if (checked.some((item) => item.row.network === primaryNetwork && item.check === "blocked")) {
51508
+ return { state: "dns-blocked", message: TRUSTED_LINK_MESSAGES["dns-blocked"], names };
51509
+ }
51510
+ if (problem === "invite") return { state: "unavailable", message: TRUSTED_LINK_MESSAGES.invite, names };
51511
+ if (problem === "unavailable" || problem === "error" && !certOk) return { state: "unavailable", message: TRUSTED_LINK_MESSAGES.unavailable, names };
51512
+ return { state: "pending", message: TRUSTED_LINK_MESSAGES.pending, names };
51513
+ }
51514
+ /**
51515
+ * At each pairing: bring names and certificate up to date (waiting up to `FIRST_ISSUE_WAIT_MS` for this machine's very
51516
+ * first certificate, `UPDATE_WAIT_MS` otherwise), then check how the names resolve here.
51517
+ */
51518
+ async prepare(options = {}) {
51519
+ this.reloadIfChanged();
51520
+ const first = this.material === void 0;
51521
+ const wait = options.waitMs ?? (first ? FIRST_ISSUE_WAIT_MS : UPDATE_WAIT_MS);
51522
+ const since = this.now() - this.lastSyncAt;
51523
+ const due = this.needsWork() ? since > (options.waitMs === 0 ? 6e4 : 0) : since > 10 * 6e4;
51524
+ const work = due || this.running !== void 0 ? this.sync() : Promise.resolve();
51525
+ if (wait > 0) await Promise.race([work, delay2(wait)]);
51526
+ const state = this.state;
51527
+ if (state !== void 0) {
51528
+ await Promise.race([
51529
+ Promise.all(this.addresses().flatMap((address) => {
51530
+ const name = state.names[address];
51531
+ return name === void 0 ? [] : [this.check(name, address)];
51532
+ })),
51533
+ delay2(4e3)
51534
+ ]);
51535
+ }
51536
+ return this.snapshot();
51537
+ }
51538
+ /** One pass (single-flight): host id, names for the current addresses, a certificate when missing or due. */
51539
+ sync() {
51540
+ if (this.closed) return Promise.resolve();
51541
+ this.running ??= this.syncOnce(true).finally(() => {
51542
+ this.running = void 0;
51543
+ this.lastSyncAt = this.now();
51544
+ });
51545
+ return this.running;
51546
+ }
51547
+ // ---- internals ----
51548
+ /** Something to do: no host id, an address without a name, a certificate missing or due, or the last pass failed. */
51549
+ needsWork() {
51550
+ const state = this.state;
51551
+ if (state === void 0 || this.problem !== void 0) return true;
51552
+ if (this.addresses().some((address) => state.names[address] === void 0)) return true;
51553
+ return this.certificateDue(state, this.now());
51554
+ }
51555
+ addresses() {
51556
+ return [...(this.options.addresses ?? privateInterfaceAddresses)()].filter(ipv4).slice(0, MAX_ADDRESSES);
51557
+ }
51558
+ cachedCheck(name, address) {
51559
+ const hit = this.checks.get(`${name} ${address}`);
51560
+ return hit === void 0 || this.now() - hit.at > CHECK_TTL_MS[hit.result] ? void 0 : hit.result;
51561
+ }
51562
+ async check(name, address) {
51563
+ const cached = this.cachedCheck(name, address);
51564
+ if (cached !== void 0) return cached;
51565
+ const result = await checkName(this.resolver, name, address);
51566
+ this.checks.set(`${name} ${address}`, { result, at: this.now() });
51567
+ return result;
51568
+ }
51569
+ async syncOnce(retryUnknownHost) {
51570
+ this.reloadIfChanged();
51571
+ const now = this.now();
51572
+ const account = await this.options.api.account().catch(() => void 0);
51573
+ if (account === void 0) {
51574
+ this.problem = "signed-out";
51575
+ return;
51576
+ }
51577
+ if (this.problem === "signed-out") this.problem = void 0;
51578
+ let state = this.state;
51579
+ if (state !== void 0 && (state.apiOrigin !== account.apiOrigin || state.accountId !== void 0 && account.accountId !== void 0 && state.accountId !== account.accountId)) {
51580
+ state = void 0;
51581
+ this.forgetHost();
51582
+ }
51583
+ if (state?.retryAt !== void 0 && state.retryAt > now) {
51584
+ if (state.problem !== void 0) this.problem = state.problem;
51585
+ return;
51586
+ }
51587
+ try {
51588
+ if (state === void 0) {
51589
+ const registered = await this.options.api.register(this.label());
51590
+ state = { version: 1, apiOrigin: account.apiOrigin, ...account.accountId === void 0 ? {} : { accountId: account.accountId }, hostId: registered.hostId, domain: registered.domain, names: {}, namesAt: 0 };
51591
+ this.save(state);
51592
+ }
51593
+ const addresses = this.addresses();
51594
+ const current = state;
51595
+ if (addresses.length > 0 && (addresses.some((address) => current.names[address] === void 0) || now - current.namesAt > NAMES_REFRESH_MS)) {
51596
+ const answered = await this.options.api.putAddresses(current.hostId, addresses);
51597
+ const names = {};
51598
+ for (const row of answered.names) {
51599
+ if (addresses.includes(row.address) && row.name.endsWith(`.${current.domain}`)) names[row.address] = row.name;
51600
+ }
51601
+ state = { ...current, names, namesAt: now };
51602
+ this.save(state);
51603
+ }
51604
+ if (this.certificateDue(state, now)) await this.issue(state);
51605
+ this.problem = void 0;
51606
+ this.failures = 0;
51607
+ if (state.retryAt !== void 0 || state.problem !== void 0) {
51608
+ const { retryAt: _retryAt, problem: _problem, ...rest } = state;
51609
+ this.save(rest);
51610
+ }
51611
+ } catch (error) {
51612
+ if (error instanceof TrustedLinkApiError && error.status === 404 && retryUnknownHost && state !== void 0) {
51613
+ this.forgetHost();
51614
+ return this.syncOnce(false);
51615
+ }
51616
+ this.fail(error, state);
51617
+ }
51618
+ }
51619
+ fail(error, state) {
51620
+ const now = this.now();
51621
+ const api = error instanceof TrustedLinkApiError ? error : void 0;
51622
+ let problem = "error";
51623
+ let retryIn;
51624
+ if (api?.status === 401) {
51625
+ problem = "signed-out";
51626
+ retryIn = 0;
51627
+ } else if (api?.status === 403) {
51628
+ problem = api.code === "invite_required" ? "invite" : "unavailable";
51629
+ retryIn = 6 * 60 * 6e4;
51630
+ } else if (api?.status === 503 && api.code === "lan_tls_unavailable") {
51631
+ problem = "unavailable";
51632
+ retryIn = 60 * 6e4;
51633
+ } else if (api?.status === 429) {
51634
+ retryIn = Math.max(6e4, api.retryAfterMs ?? 15 * 6e4);
51635
+ } else if (api?.status === 409) {
51636
+ retryIn = 2e4;
51637
+ } else {
51638
+ this.failures += 1;
51639
+ retryIn = Math.min(60 * 6e4, 6e4 * 2 ** Math.min(6, this.failures - 1));
51640
+ }
51641
+ this.problem = problem;
51642
+ this.options.log?.(`picasso-helper: secure link: ${api === void 0 ? error instanceof Error ? error.message : String(error) : `${api.status} ${api.code}`}; using the IP address link${retryIn > 0 ? `, trying again in ${Math.round(retryIn / 6e4)} min` : ""}`);
51643
+ if (state !== void 0 && retryIn > 0) this.save({ ...state, retryAt: now + retryIn, problem });
51644
+ }
51645
+ certificateDue(state, now) {
51646
+ const material = this.material;
51647
+ if (material === void 0 || material.domain !== state.domain) return true;
51648
+ return now >= material.notBefore + (material.notAfter - material.notBefore) * 2 / 3;
51649
+ }
51650
+ async issue(state) {
51651
+ const { keyPem, csrPem: csrPem2 } = newKeyAndCsr(`*.${state.domain}`);
51652
+ const answered = await this.options.api.issue(state.hostId, csrPem2);
51653
+ const checked = readMaterial(answered.certificate, keyPem, 0);
51654
+ if (checked === void 0 || checked.domain !== state.domain) throw new TrustedLinkApiError(502, "bad_certificate");
51655
+ const files = this.files;
51656
+ mkdirSync29(this.options.dir, { recursive: true, mode: 448 });
51657
+ writePrivate2(files.key, keyPem);
51658
+ writePrivate2(files.cert, answered.certificate);
51659
+ this.material = { ...checked, mtimeMs: statSync18(files.cert).mtimeMs };
51660
+ this.options.log?.(`picasso-helper: secure link: certificate for *.${state.domain} until ${new Date(checked.notAfter).toISOString().slice(0, 10)}`);
51661
+ }
51662
+ label() {
51663
+ const label2 = (this.options.label ?? osHostname()).replace(/\.local$/u, "").replace(new RegExp("\\p{Cc}", "gu"), "").trim();
51664
+ return (label2 || "Picasso").slice(0, 64);
51665
+ }
51666
+ forgetHost() {
51667
+ this.state = void 0;
51668
+ this.material = void 0;
51669
+ this.checks.clear();
51670
+ try {
51671
+ writePrivate2(this.files.state, "{}\n");
51672
+ } catch {
51673
+ }
51674
+ }
51675
+ save(state) {
51676
+ mkdirSync29(this.options.dir, { recursive: true, mode: 448 });
51677
+ writePrivate2(this.files.state, `${JSON.stringify(state)}
51678
+ `);
51679
+ this.state = state;
51680
+ }
51681
+ load() {
51682
+ this.state = readState(this.files.state);
51683
+ this.material = void 0;
51684
+ this.reloadIfChanged();
51685
+ }
51686
+ /** Re-reads the certificate when its file changed (another relay on this machine renewed it). */
51687
+ reloadIfChanged() {
51688
+ const files = this.files;
51689
+ let mtimeMs;
51690
+ try {
51691
+ mtimeMs = statSync18(files.cert).mtimeMs;
51692
+ } catch {
51693
+ return;
51694
+ }
51695
+ if (this.material !== void 0 && this.material.mtimeMs === mtimeMs) return;
51696
+ try {
51697
+ const loaded = readMaterial(readFileSync43(files.cert, "utf8"), readFileSync43(files.key, "utf8"), mtimeMs);
51698
+ if (loaded !== void 0) {
51699
+ this.material = loaded;
51700
+ const stored = readState(files.state);
51701
+ if (stored !== void 0) this.state = stored;
51702
+ }
51703
+ } catch {
51704
+ }
51705
+ }
51706
+ };
51707
+ function readState(file) {
51708
+ try {
51709
+ const parsed = JSON.parse(readFileSync43(file, "utf8"));
51710
+ if (parsed.version !== 1 || typeof parsed.hostId !== "string" || !HOST_ID.test(parsed.hostId) || typeof parsed.domain !== "string" || !DOMAIN.test(parsed.domain) || typeof parsed.apiOrigin !== "string") return void 0;
51711
+ const names = {};
51712
+ if (typeof parsed.names === "object" && parsed.names !== null) {
51713
+ for (const [address, name] of Object.entries(parsed.names)) if (ipv4(address) && typeof name === "string" && name.endsWith(`.${parsed.domain}`)) names[address] = name;
51714
+ }
51715
+ return {
51716
+ version: 1,
51717
+ apiOrigin: parsed.apiOrigin,
51718
+ ...typeof parsed.accountId === "string" ? { accountId: parsed.accountId } : {},
51719
+ hostId: parsed.hostId,
51720
+ domain: parsed.domain,
51721
+ names,
51722
+ namesAt: typeof parsed.namesAt === "number" ? parsed.namesAt : 0,
51723
+ ...typeof parsed.retryAt === "number" ? { retryAt: parsed.retryAt } : {},
51724
+ ...parsed.problem === "invite" || parsed.problem === "unavailable" || parsed.problem === "error" ? { problem: parsed.problem } : {}
51725
+ };
51726
+ } catch {
51727
+ return void 0;
51728
+ }
51729
+ }
51730
+ function readMaterial(chainPem, keyPem, mtimeMs) {
51731
+ try {
51732
+ const leaf = new X509Certificate3(chainPem);
51733
+ if (!leaf.checkPrivateKey(createPrivateKey4(keyPem))) return void 0;
51734
+ const san = /DNS:\*\.([a-z0-9.-]+)/u.exec(leaf.subjectAltName ?? "");
51735
+ const domain = san?.[1];
51736
+ if (domain === void 0 || !DOMAIN.test(domain)) return void 0;
51737
+ const notBefore = Date.parse(leaf.validFrom);
51738
+ const notAfter = Date.parse(leaf.validTo);
51739
+ if (!Number.isFinite(notBefore) || !Number.isFinite(notAfter) || notAfter <= notBefore) return void 0;
51740
+ return { domain, notBefore, notAfter, context: createSecureContext({ cert: chainPem, key: keyPem }), mtimeMs };
51741
+ } catch {
51742
+ return void 0;
51743
+ }
51744
+ }
51745
+ function writePrivate2(file, text6) {
51746
+ const temp = `${file}.${process.pid}.${Date.now()}.tmp`;
51747
+ writeFileSync24(temp, text6, { mode: 384 });
51748
+ renameSync20(temp, file);
51749
+ }
51750
+ var delay2 = (ms) => new Promise((resolve21) => {
51751
+ const timer = setTimeout(resolve21, ms);
51752
+ timer.unref?.();
51753
+ });
51754
+ function trustedLinkDir(env2) {
51755
+ return join80(picassoHome(env2), "remote-tls");
51756
+ }
51757
+ function startTrustedLink(options) {
51758
+ if (options.env["PICASSO_REMOTE_TRUSTED_LINK"] === "0") return void 0;
51759
+ return new TrustedLink({
51760
+ api: accountTrustedLinkApi({ read: options.read, env: options.env }),
51761
+ dir: trustedLinkDir(options.env),
51762
+ ...options.env["PICASSO_HOST_NAME"]?.trim() ? { label: options.env["PICASSO_HOST_NAME"].trim() } : {},
51763
+ ...options.log ? { log: options.log } : {}
51764
+ }).start();
51765
+ }
51766
+
51219
51767
  // src/container-merge.ts
51220
51768
  import { readFile as readFile27 } from "node:fs/promises";
51221
51769
  import { resolve as resolve17 } from "node:path";
@@ -51312,8 +51860,8 @@ init_memory_guard();
51312
51860
 
51313
51861
  // ../../packages/shared-home/dist/retired-models.js
51314
51862
  init_active_models();
51315
- import { copyFileSync as copyFileSync5, existsSync as existsSync29, readFileSync as readFileSync43 } from "node:fs";
51316
- import { join as join80 } from "node:path";
51863
+ import { copyFileSync as copyFileSync5, existsSync as existsSync29, readFileSync as readFileSync44 } from "node:fs";
51864
+ import { join as join81 } from "node:path";
51317
51865
  import { isMap as isMap5, isScalar as isScalar3, isSeq as isSeq4, parseDocument as parseDocument5 } from "yaml";
51318
51866
  init_store();
51319
51867
  var RETIRED_PRISM_IDS = ["qwen3-8-max-vl-thinking", "glm-5-3-flash"];
@@ -51396,7 +51944,7 @@ async function retireHomeRouteModels(input) {
51396
51944
  const out = [];
51397
51945
  for (const file of homeRoutePatchFiles(input.dshHome)) {
51398
51946
  try {
51399
- const text6 = readFileSync43(file, "utf8");
51947
+ const text6 = readFileSync44(file, "utf8");
51400
51948
  const result = retireRouteModelsText(text6);
51401
51949
  if (result === void 0)
51402
51950
  continue;
@@ -51410,11 +51958,11 @@ async function retireHomeRouteModels(input) {
51410
51958
  }
51411
51959
  }
51412
51960
  try {
51413
- const providerFile = join80(input.dshHome, "active-provider");
51414
- const modelFile = join80(input.dshHome, "active-model");
51961
+ const providerFile = join81(input.dshHome, "active-provider");
51962
+ const modelFile = join81(input.dshHome, "active-model");
51415
51963
  if (existsSync29(providerFile) && existsSync29(modelFile)) {
51416
- const route = readFileSync43(providerFile, "utf8").trim();
51417
- const model = readFileSync43(modelFile, "utf8").trim();
51964
+ const route = readFileSync44(providerFile, "utf8").trim();
51965
+ const model = readFileSync44(modelFile, "utf8").trim();
51418
51966
  const to = isRetiredRouteModel(route, model) ? retiredModelReplacement(route) : void 0;
51419
51967
  if (to !== void 0) {
51420
51968
  await writeFileAtomic(modelFile, `${to}
@@ -51447,8 +51995,8 @@ init_dist3();
51447
51995
 
51448
51996
  // src/resident-runner.ts
51449
51997
  init_runner();
51450
- import { readFileSync as readFileSync44, statSync as statSync18 } from "node:fs";
51451
- import { basename as basename17, delimiter as delimiter3, dirname as dirname36, join as join81 } from "node:path";
51998
+ import { readFileSync as readFileSync45, statSync as statSync19 } from "node:fs";
51999
+ import { basename as basename17, delimiter as delimiter3, dirname as dirname36, join as join82 } from "node:path";
51452
52000
  var RESIDENT_WATCH_INTERVAL_MS = 6e4;
51453
52001
  var RESIDENT_SETTLE_MS = 3e4;
51454
52002
  function isResident(env2) {
@@ -51468,12 +52016,12 @@ function residentBundle(engineRoot) {
51468
52016
  const contents = dirname36(dirname36(engineRoot));
51469
52017
  const bundlePath = dirname36(contents);
51470
52018
  if (basename17(contents) !== "Contents" || !bundlePath.endsWith(".app")) return { bundlePath: null, bundleVersion: null, infoPlist: null };
51471
- const infoPlist = join81(contents, "Info.plist");
52019
+ const infoPlist = join82(contents, "Info.plist");
51472
52020
  return { bundlePath, bundleVersion: bundleShortVersion(infoPlist), infoPlist };
51473
52021
  }
51474
52022
  function bundleShortVersion(infoPlist) {
51475
52023
  try {
51476
- const match = /<key>CFBundleShortVersionString<\/key>\s*<string>([^<]+)<\/string>/u.exec(readFileSync44(infoPlist, "utf8"));
52024
+ const match = /<key>CFBundleShortVersionString<\/key>\s*<string>([^<]+)<\/string>/u.exec(readFileSync45(infoPlist, "utf8"));
51477
52025
  return match?.[1]?.trim() || null;
51478
52026
  } catch {
51479
52027
  return null;
@@ -51485,7 +52033,7 @@ function residentWatchList(env2, infoPlist, separator = delimiter3) {
51485
52033
  }
51486
52034
  var fileStamp = (path2) => {
51487
52035
  try {
51488
- const info = statSync18(path2);
52036
+ const info = statSync19(path2);
51489
52037
  return `${info.ino}:${info.size}:${info.mtimeMs}`;
51490
52038
  } catch {
51491
52039
  return "missing";
@@ -51497,7 +52045,7 @@ async function waitForAppRelay(engineRecordFile2, options) {
51497
52045
  for (; ; ) {
51498
52046
  let relayPid;
51499
52047
  try {
51500
- const record3 = JSON.parse(readFileSync44(engineRecordFile2, "utf8"));
52048
+ const record3 = JSON.parse(readFileSync45(engineRecordFile2, "utf8"));
51501
52049
  relayPid = typeof record3.relayPid === "number" && record3.resident !== true ? record3.relayPid : void 0;
51502
52050
  } catch {
51503
52051
  relayPid = void 0;
@@ -51639,7 +52187,7 @@ var residentOwner = resident ? applyResidentEnv(env) : void 0;
51639
52187
  process.exit(3);
51640
52188
  }
51641
52189
  }
51642
- var version = JSON.parse(readFileSync45(new URL("../package.json", import.meta.url), "utf8")).version;
52190
+ var version = JSON.parse(readFileSync46(new URL("../package.json", import.meta.url), "utf8")).version;
51643
52191
  var token = env["PICASSO_HELPER_TOKEN"] ?? (env["PICASSO_HELPER_DEV"] === "1" ? void 0 : fail6("PICASSO_HELPER_TOKEN is required (set PICASSO_HELPER_DEV=1 for an unauthenticated dev relay)"));
51644
52192
  var crashEngineVersion = null;
51645
52193
  installHelperCrashCapture({ env, appVersion: version, engineVersion: () => crashEngineVersion });
@@ -51659,7 +52207,7 @@ if (!env["DSH_HOME"]?.trim()) {
51659
52207
  var dshHome2 = env["DSH_HOME"];
51660
52208
  await migrateModelIds({
51661
52209
  dshHome: dshHome2 ?? dshHome(env),
51662
- connectionsFile: join93(dirname41(settingsFile(env)), "model-connections.json"),
52210
+ connectionsFile: join94(dirname41(settingsFile(env)), "model-connections.json"),
51663
52211
  surface: "mac",
51664
52212
  env,
51665
52213
  modelKey: modelIdKey,
@@ -51671,12 +52219,12 @@ await migrateModelIds({
51671
52219
  }, () => void 0);
51672
52220
  await retireHomeRouteModels({
51673
52221
  dshHome: dshHome2 ?? dshHome(env),
51674
- connectionsFile: join93(dirname41(settingsFile(env)), "model-connections.json")
52222
+ connectionsFile: join94(dirname41(settingsFile(env)), "model-connections.json")
51675
52223
  }).then((changes) => {
51676
52224
  if (changes.length > 0) console.error(`picasso-helper: ${formatRetiredModels(changes)}`);
51677
52225
  }, () => void 0);
51678
- env["PICASSO_MEMORY_FILE"] ??= join93(picassoHome(env), "memory.json");
51679
- env["PICASSO_MCP_SERVERS"] ??= join93(dshHome2 ?? dshHome(env), "profiles", env["PICASSO_DSH_PROFILE"] ?? "web", "mcp-servers.json");
52226
+ env["PICASSO_MEMORY_FILE"] ??= join94(picassoHome(env), "memory.json");
52227
+ env["PICASSO_MCP_SERVERS"] ??= join94(dshHome2 ?? dshHome(env), "profiles", env["PICASSO_DSH_PROFILE"] ?? "web", "mcp-servers.json");
51680
52228
  var profileSeed = env["PICASSO_DSH_PROFILE_SEED"];
51681
52229
  if (dshHome2 && profileSeed && seedProfile(dshHome2, env["PICASSO_DSH_PROFILE"] ?? "web", profileSeed) === "replaced") {
51682
52230
  console.error(`picasso-helper: the engine profile had an older layout; it was moved aside and seeded again`);
@@ -51694,7 +52242,7 @@ try {
51694
52242
  console.error(`picasso-helper: shared MCP servers not mounted: ${error instanceof Error ? error.message : String(error)}`);
51695
52243
  }
51696
52244
  try {
51697
- const startupCatalogDir = env["PICASSO_MCP_CATALOG_DIR"] || join93(picassoHome(env), "mcp-catalog");
52245
+ const startupCatalogDir = env["PICASSO_MCP_CATALOG_DIR"] || join94(picassoHome(env), "mcp-catalog");
51698
52246
  const profileMcpFile = env["PICASSO_MCP_SERVERS"];
51699
52247
  if (existsSync30(profileMcpFile) || existsSync30(startupCatalogDir)) {
51700
52248
  syncRelayMcpCatalogIndex(readMcpServersStrict(profileMcpFile), startupCatalogDir);
@@ -51717,7 +52265,7 @@ var managedAttest = parentAttestSigner(env);
51717
52265
  var managedLane = await startManagedLane({ readSession: () => readAccountSession({ env }), ...managedAttest === void 0 ? {} : { attest: managedAttest } });
51718
52266
  var mcpOAuth = new McpOAuthManager();
51719
52267
  var mcpAuthProxy = await startMcpAuthProxy({ manager: mcpOAuth });
51720
- var engineRecordFile = env["PICASSO_PARENT_PID"] || resident ? join93(picassoHome(env), "run", "mac-engine.json") : void 0;
52268
+ var engineRecordFile = env["PICASSO_PARENT_PID"] || resident ? join94(picassoHome(env), "run", "mac-engine.json") : void 0;
51721
52269
  if (resident && engineRecordFile !== void 0) {
51722
52270
  await waitForAppRelay(engineRecordFile, { alive: isProcessAlive2, log: (line) => console.error(`picasso-helper: ${line}`) });
51723
52271
  }
@@ -51876,11 +52424,11 @@ try {
51876
52424
  research = env["PICASSO_RESEARCH_CAPTURE"] === "1" ? await startResearch() : void 0;
51877
52425
  const dshProfile = env["PICASSO_DSH_PROFILE"] ?? "web";
51878
52426
  const stateHome = dshHome2 ?? dshHome(env);
51879
- const providerStash = fileProviderStash(join93(stateHome, `picasso-providers-off.${dshProfile}.json`));
51880
- const dshImport = fileDshImportStore(join93(stateHome, `picasso-providers-dsh.${dshProfile}.json`));
51881
- const pairing = new PairingStore({ persistence: filePairingPersistence(join93(stateHome, `picasso-paired-devices.${dshProfile}.json`)) });
51882
- const webPush = new WebPush({ persistence: fileWebPushPersistence(join93(stateHome, `picasso-web-push.${dshProfile}.json`)) });
51883
- const remoteAudit = new RemoteAuditLog({ file: join93(stateHome, `picasso-remote-audit.${dshProfile}.jsonl`) });
52427
+ const providerStash = fileProviderStash(join94(stateHome, `picasso-providers-off.${dshProfile}.json`));
52428
+ const dshImport = fileDshImportStore(join94(stateHome, `picasso-providers-dsh.${dshProfile}.json`));
52429
+ const pairing = new PairingStore({ persistence: filePairingPersistence(join94(stateHome, `picasso-paired-devices.${dshProfile}.json`)) });
52430
+ const webPush = new WebPush({ persistence: fileWebPushPersistence(join94(stateHome, `picasso-web-push.${dshProfile}.json`)) });
52431
+ const remoteAudit = new RemoteAuditLog({ file: join94(stateHome, `picasso-remote-audit.${dshProfile}.jsonl`) });
51884
52432
  const remoteSurface = env["PICASSO_HOST_MODE"] === "1" ? "host" : resident ? "runner" : env["PICASSO_PARENT_PID"] ? "mac" : "helper";
51885
52433
  const remoteControl = {
51886
52434
  audit: remoteAudit,
@@ -51898,8 +52446,8 @@ try {
51898
52446
  };
51899
52447
  const bindHost = env["PICASSO_HELPER_HOST"] ?? "127.0.0.1";
51900
52448
  const loopbackBind = isLoopbackBindHost(bindHost);
51901
- const tlsCert = env["PICASSO_HELPER_TLS_CERT"] ? readFileSync45(env["PICASSO_HELPER_TLS_CERT"]) : void 0;
51902
- const tlsKey = env["PICASSO_HELPER_TLS_KEY"] ? readFileSync45(env["PICASSO_HELPER_TLS_KEY"]) : void 0;
52449
+ const tlsCert = env["PICASSO_HELPER_TLS_CERT"] ? readFileSync46(env["PICASSO_HELPER_TLS_CERT"]) : void 0;
52450
+ const tlsKey = env["PICASSO_HELPER_TLS_KEY"] ? readFileSync46(env["PICASSO_HELPER_TLS_KEY"]) : void 0;
51903
52451
  const tls = tlsCert && tlsKey ? { cert: tlsCert, key: tlsKey } : void 0;
51904
52452
  if (tlsCert === void 0 !== (tlsKey === void 0)) {
51905
52453
  fail6("PICASSO_HELPER_TLS_CERT and PICASSO_HELPER_TLS_KEY must be set together");
@@ -51910,9 +52458,11 @@ try {
51910
52458
  const attach = loopbackBind && attachToken !== void 0 ? { attachToken } : {};
51911
52459
  const desktopSettings = desktopSettingsStore({ env });
51912
52460
  const browserExecutor = browserExecutorFor(env, process.platform);
51913
- relay = new Relay({ remote, token, ...attach, version, dshVersion, personas: host.engine.personas, managed: managedLane, mcpOAuth, mcpAuthProxy, onShutdown: () => {
52461
+ const advertiseInterfaces = env["PICASSO_HELPER_ADVERTISE_INTERFACES"] === "1";
52462
+ const trustedLink = tls !== void 0 && !loopbackBind && advertiseInterfaces ? startTrustedLink({ env, read: keychainAccountReader(env), log: (line) => console.error(line) }) : void 0;
52463
+ relay = new Relay({ remote, token, ...attach, version, dshVersion, personas: host.engine.personas, ...trustedLink ? { trustedLink } : {}, managed: managedLane, mcpOAuth, mcpAuthProxy, onShutdown: () => {
51914
52464
  void shutdown();
51915
- }, advertisedOrigin: env["PICASSO_HELPER_ADVERTISED_ORIGIN"], advertiseInterfaces: env["PICASSO_HELPER_ADVERTISE_INTERFACES"] === "1", ...tls && env["PICASSO_HELPER_TLS_CERT"] && env["PICASSO_HELPER_TLS_KEY"] ? { tlsFiles: { cert: env["PICASSO_HELPER_TLS_CERT"], key: env["PICASSO_HELPER_TLS_KEY"] } } : {}, providerStash, dshImport, profileDir: join93(stateHome, "profiles", dshProfile), progressSeedCache: fileProgressSeedCache(join93(stateHome, "picasso-progress-seed", dshProfile)), pairing, webPush, remoteControl, tls, untrustedTransport: !loopbackBind && !tls, desktopSettings, desktopXReader: desktopXReader({ env }), prWatch: { file: prWatchFile(env), ...dshHome2 ? { dshHome: dshHome2 } : {}, env, wakeEnabled: () => desktopSettings.wakeOnPrUpdates() }, librarian: { env }, pageComments: { env }, providerStore: { dshHome: stateHome, profileDir: join93(stateHome, "profiles", dshProfile), connectionsFile: join93(dirname41(settingsFile(env)), "model-connections.json") }, desktopCloudSessions: desktopCloudSessions({ settingsFile: desktopSettings.file, env }), desktopMemory: desktopMemoryStore({ env }), desktopDiagnostics: diagnosticsSender({ env, crashReportsEnabled: () => desktopSettings.crashReportsEnabled() }), sharedMcpServersFile: sharedMcpServers, ...research ? { research: research.routes } : {}, ...runner ? { runner } : {}, scheduleState: fileScheduleState(join93(stateHome, `picasso-schedules.${dshProfile}.json`)), threadActivity: new EngineSessionActivity(stateHome), centerLogs: new CenterLogCache(stateHome), crashResume: { dshHome: stateHome, env }, ...startHostMode(env, tlsCert), ...browserExecutor ? { browserExecutor } : {} });
52465
+ }, advertisedOrigin: env["PICASSO_HELPER_ADVERTISED_ORIGIN"], advertiseInterfaces: env["PICASSO_HELPER_ADVERTISE_INTERFACES"] === "1", ...tls && env["PICASSO_HELPER_TLS_CERT"] && env["PICASSO_HELPER_TLS_KEY"] ? { tlsFiles: { cert: env["PICASSO_HELPER_TLS_CERT"], key: env["PICASSO_HELPER_TLS_KEY"] } } : {}, providerStash, dshImport, profileDir: join94(stateHome, "profiles", dshProfile), progressSeedCache: fileProgressSeedCache(join94(stateHome, "picasso-progress-seed", dshProfile)), pairing, webPush, remoteControl, tls, untrustedTransport: !loopbackBind && !tls, desktopSettings, desktopXReader: desktopXReader({ env }), prWatch: { file: prWatchFile(env), ...dshHome2 ? { dshHome: dshHome2 } : {}, env, wakeEnabled: () => desktopSettings.wakeOnPrUpdates() }, librarian: { env }, pageComments: { env }, providerStore: { dshHome: stateHome, profileDir: join94(stateHome, "profiles", dshProfile), connectionsFile: join94(dirname41(settingsFile(env)), "model-connections.json") }, desktopCloudSessions: desktopCloudSessions({ settingsFile: desktopSettings.file, env }), desktopMemory: desktopMemoryStore({ env }), desktopDiagnostics: diagnosticsSender({ env, crashReportsEnabled: () => desktopSettings.crashReportsEnabled() }), sharedMcpServersFile: sharedMcpServers, ...research ? { research: research.routes } : {}, ...runner ? { runner } : {}, scheduleState: fileScheduleState(join94(stateHome, `picasso-schedules.${dshProfile}.json`)), threadActivity: new EngineSessionActivity(stateHome), centerLogs: new CenterLogCache(stateHome), crashResume: { dshHome: stateHome, env }, ...startHostMode(env, tlsCert), ...browserExecutor ? { browserExecutor } : {} });
51916
52466
  relay.startBrowserPump();
51917
52467
  relay.startComputerPump();
51918
52468
  const started = relay;