@alook/daemon 0.1.46 → 0.1.47

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.
Files changed (3) hide show
  1. package/dist/cli/index.js +418 -303
  2. package/dist/index.js +370 -272
  3. package/package.json +1 -1
package/dist/cli/index.js CHANGED
@@ -22343,8 +22343,8 @@ var MAX_PROFILE_ABOUT_LENGTH = 1000;
22343
22343
  var MAX_MESSAGE_CONTENT_LENGTH = 4000;
22344
22344
  var MAX_ATTACHMENTS_PER_MESSAGE = 10;
22345
22345
  var MAX_ATTACHMENT_SIZE_BYTES = 25 * 1024 * 1024;
22346
- var MAX_ATTACHMENT_THUMBNAIL_EDGE_PX = 1024;
22347
- var MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES = 512 * 1024;
22346
+ var MAX_ATTACHMENT_THUMBNAIL_EDGE_PX = 720;
22347
+ var MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES = 256 * 1024;
22348
22348
  var MAX_SERVER_ICON_SIZE_BYTES = 5 * 1024 * 1024;
22349
22349
  var ALLOWED_ICON_MIME_TYPES = [
22350
22350
  "image/png",
@@ -25511,13 +25511,13 @@ function createProxyServerApi(config2) {
25511
25511
 
25512
25512
  // src/cli/daemonStart.ts
25513
25513
  import * as fs12 from "fs";
25514
- import * as path17 from "path";
25514
+ import * as path18 from "path";
25515
25515
  import * as crypto5 from "crypto";
25516
25516
  import * as os3 from "os";
25517
- import { homedir as homedir11 } from "os";
25517
+ import { homedir as homedir13 } from "os";
25518
25518
 
25519
25519
  // src/discovery.ts
25520
- import * as path13 from "path";
25520
+ import * as path14 from "path";
25521
25521
  import * as fs6 from "fs";
25522
25522
  import { fileURLToPath } from "url";
25523
25523
  // agent-driver/dist/host/default-host.js
@@ -25597,6 +25597,18 @@ function resolveLaunchFieldsOrDefault(input2) {
25597
25597
  // agent-driver/dist/internal/cliLink.js
25598
25598
  import * as fs2 from "fs";
25599
25599
  import * as path2 from "path";
25600
+ function shellQuote(value) {
25601
+ return `'${value.replaceAll("'", "'\\''")}'`;
25602
+ }
25603
+ function writeWindowsBashEnv(binDir, cliName, envPrefix, previous) {
25604
+ const startup = path2.join(binDir, `${cliName}.bash-env`).replaceAll("\\", "/");
25605
+ const envValue = startup.replace(/[$`]/g, "\\$&");
25606
+ const source = previous && previous !== envValue && previous.replaceAll("\\", "/") !== startup ? `. ${shellQuote(previous.replaceAll("\\", "/"))}
25607
+ ` : "";
25608
+ fs2.writeFileSync(startup, source + `export ${shellQuote(`${envPrefix}_CLI=${path2.join(binDir, cliName).replaceAll("\\", "/")}`)}
25609
+ `);
25610
+ return envValue;
25611
+ }
25600
25612
  function writeCliLink(stateDir, cliName, hostCliPath, platform = process.platform) {
25601
25613
  const binDir = path2.join(stateDir, "bin");
25602
25614
  fs2.mkdirSync(binDir, { recursive: true });
@@ -25604,10 +25616,15 @@ function writeCliLink(stateDir, cliName, hostCliPath, platform = process.platfor
25604
25616
  return binDir;
25605
25617
  if (platform === "win32") {
25606
25618
  const cmdFile = path2.join(binDir, `${cliName}.cmd`);
25619
+ const executable = /\.(?:c|m)?js$/i.test(hostCliPath) ? `"${process.execPath}" "${hostCliPath}"` : `"${hostCliPath}"`;
25607
25620
  const body = `@echo off\r
25608
- "${hostCliPath}" %*\r
25621
+ ${executable} %*\r
25609
25622
  `;
25610
25623
  fs2.writeFileSync(cmdFile, body);
25624
+ const bashExecutable = /\.(?:c|m)?js$/i.test(hostCliPath) ? `${shellQuote(process.execPath.replaceAll("\\", "/"))} ${shellQuote(hostCliPath.replaceAll("\\", "/"))}` : shellQuote(hostCliPath.replaceAll("\\", "/"));
25625
+ fs2.writeFileSync(path2.join(binDir, cliName), `#!/bin/sh
25626
+ MSYS2_ARG_CONV_EXCL='*' exec ${bashExecutable} "$@"
25627
+ `, { mode: 493 });
25611
25628
  return binDir;
25612
25629
  }
25613
25630
  const linkPath = path2.join(binDir, cliName);
@@ -25675,7 +25692,12 @@ async function prepareCliTransport(ctx, extraEnv = {}, cli = DEFAULT_CLI_CONFIG,
25675
25692
  {
25676
25693
  name: "platformProtected",
25677
25694
  precedence: 40,
25678
- vars: { ...resource.platformProtected, FORCE_COLOR: "0", NO_COLOR: "1" }
25695
+ vars: {
25696
+ ...resource.platformProtected,
25697
+ ...platform === "win32" && hostCliPath ? { [`${cli.envPrefix}_CLI`]: path3.join(binDir, `${cli.cliName}.cmd`).replaceAll("\\", "/") } : {},
25698
+ FORCE_COLOR: "0",
25699
+ NO_COLOR: "1"
25700
+ }
25679
25701
  },
25680
25702
  { name: "runtimeProtected", precedence: 50, vars: resource.runtimeProtected },
25681
25703
  {
@@ -25692,15 +25714,143 @@ async function prepareCliTransport(ctx, extraEnv = {}, cli = DEFAULT_CLI_CONFIG,
25692
25714
  }
25693
25715
  ];
25694
25716
  const { env: spawnEnv } = mergeEnvLayers(resource.base, layers);
25717
+ if (platform === "win32" && hostCliPath) {
25718
+ spawnEnv.BASH_ENV = writeWindowsBashEnv(binDir, cli.cliName, cli.envPrefix, spawnEnv.BASH_ENV);
25719
+ }
25695
25720
  const tokenFile = String(resource.credentialSensitive.ALOOK_PROXY_TOKEN_FILE ?? "");
25696
25721
  return { stateDir, tokenFile, spawnEnv };
25697
25722
  }
25698
25723
 
25699
25724
  // agent-driver/dist/internal/killTree.js
25700
- import { execFileSync, spawn } from "child_process";
25725
+ import { execFileSync as execFileSync2, spawn } from "child_process";
25701
25726
  import { randomUUID as randomUUID2 } from "node:crypto";
25702
25727
  import { createServer } from "node:net";
25703
25728
  import { PassThrough } from "node:stream";
25729
+
25730
+ // agent-driver/dist/internal/probe.js
25731
+ import { execFileSync } from "child_process";
25732
+ import * as fs4 from "fs";
25733
+ import * as path4 from "path";
25734
+ import { homedir } from "os";
25735
+ var PROBE_TIMEOUT_MS = 5000;
25736
+ var PROBE_OUTPUT_MAX_BYTES = 1024 * 1024;
25737
+ function resolveCommandOnPath(command, deps = {}) {
25738
+ if (deps.which)
25739
+ return deps.which(command);
25740
+ try {
25741
+ if (process.platform === "win32") {
25742
+ const out2 = execFileSync("where", [command], { encoding: "utf8", timeout: PROBE_TIMEOUT_MS });
25743
+ const first = out2.split(/\r?\n/).map((line) => line.trim()).find((line) => /\.(exe|com|cmd|bat)$/i.test(line));
25744
+ return first || null;
25745
+ }
25746
+ const out = execFileSync("which", [command], { encoding: "utf8", timeout: PROBE_TIMEOUT_MS });
25747
+ return out.trim() || null;
25748
+ } catch {
25749
+ return null;
25750
+ }
25751
+ }
25752
+ function firstExistingPath(candidates) {
25753
+ for (const c of candidates) {
25754
+ if (c && fs4.existsSync(c))
25755
+ return c;
25756
+ }
25757
+ return null;
25758
+ }
25759
+ function looksLikeVersion(line) {
25760
+ return /\d+\.\d+/.test(line);
25761
+ }
25762
+ function needsWindowsShimShell(command, platform) {
25763
+ return platform === "win32" && /\.(cmd|bat)$/i.test(command);
25764
+ }
25765
+ function quoteWindowsShimCommand(command, platform = process.platform) {
25766
+ return needsWindowsShimShell(command, platform) && /\s/.test(command) ? `"${command}"` : command;
25767
+ }
25768
+ function probeCommandVersion(command, args = [], deps = {}, platform = process.platform) {
25769
+ try {
25770
+ const shell = needsWindowsShimShell(command, platform);
25771
+ const out = execFileSync(quoteWindowsShimCommand(command, platform), [...args, "--version"], {
25772
+ encoding: "utf8",
25773
+ timeout: PROBE_TIMEOUT_MS,
25774
+ shell,
25775
+ input: "",
25776
+ env: { ...process.env, CI: "1" }
25777
+ });
25778
+ const line = out.split(`
25779
+ `)[0]?.trim();
25780
+ if (!line)
25781
+ return { ok: false, error: "empty_version_output" };
25782
+ if (!looksLikeVersion(line))
25783
+ return { ok: false, error: "invalid_version_output" };
25784
+ return { ok: true, version: line };
25785
+ } catch (err) {
25786
+ const code = err?.code ?? err?.code ?? "version_probe_failed";
25787
+ return { ok: false, error: String(code) };
25788
+ }
25789
+ }
25790
+ function probeCommandOutput(command, args, platform = process.platform) {
25791
+ try {
25792
+ const output2 = execFileSync(quoteWindowsShimCommand(command, platform), args, {
25793
+ encoding: "utf8",
25794
+ timeout: PROBE_TIMEOUT_MS,
25795
+ maxBuffer: PROBE_OUTPUT_MAX_BYTES,
25796
+ shell: needsWindowsShimShell(command, platform),
25797
+ stdio: ["pipe", "pipe", "ignore"],
25798
+ input: "",
25799
+ env: { ...process.env, CI: "1" }
25800
+ });
25801
+ return { ok: true, output: output2 };
25802
+ } catch (err) {
25803
+ const code = err?.code ?? "command_probe_failed";
25804
+ return { ok: false, error: String(code) };
25805
+ }
25806
+ }
25807
+ function resolveHomePath(relativePath, deps = {}) {
25808
+ return path4.join(deps.homeDir || process.env.HOME || ".", relativePath);
25809
+ }
25810
+ function resolveSpawnSpec(command, args, override, deps = {}, platform = process.platform) {
25811
+ const trimmed = override?.trim();
25812
+ const target2 = trimmed && trimmed.length > 0 ? trimmed : command;
25813
+ const looksLikePath = trimmed !== undefined && trimmed.length > 0 && /[\\/]/.test(trimmed);
25814
+ const resolved = looksLikePath ? target2 : resolveCommandOnPath(target2, deps) ?? target2;
25815
+ return { command: resolved, args, shell: needsWindowsShimShell(resolved, platform) };
25816
+ }
25817
+ function resolveClaudeCommand(deps = {}) {
25818
+ const onPath = resolveCommandOnPath("claude", deps);
25819
+ if (onPath)
25820
+ return onPath;
25821
+ if (process.platform === "win32") {
25822
+ const home = deps.homeDir || process.env.USERPROFILE || process.env.HOME || homedir();
25823
+ return firstExistingPath([path4.join(home, ".local", "bin", "claude.exe")]);
25824
+ }
25825
+ if (process.platform === "darwin") {
25826
+ return firstExistingPath([
25827
+ resolveHomePath("Applications/Claude Code URL Handler.app/Contents/MacOS/claude", deps),
25828
+ "/Applications/Claude Code URL Handler.app/Contents/MacOS/claude"
25829
+ ]);
25830
+ }
25831
+ return null;
25832
+ }
25833
+ function probeClaude(deps = {}) {
25834
+ const command = resolveClaudeCommand(deps);
25835
+ if (!command)
25836
+ return { status: "unhealthy", lastError: "not_on_path" };
25837
+ const r = probeCommandVersion(command, [], deps);
25838
+ if (!r.ok)
25839
+ return { status: "unhealthy", lastError: r.error };
25840
+ return { status: "healthy", version: r.version };
25841
+ }
25842
+ function probeCliRuntime(binary, deps = {}, override) {
25843
+ const explicit = override?.trim();
25844
+ const command = explicit || resolveCommandOnPath(binary, deps);
25845
+ if (!command)
25846
+ return { status: "unhealthy", lastError: "not_on_path" };
25847
+ const r = probeCommandVersion(command, [], deps);
25848
+ if (!r.ok)
25849
+ return { status: "unhealthy", lastError: r.error };
25850
+ return { status: "healthy", version: r.version };
25851
+ }
25852
+
25853
+ // agent-driver/dist/internal/killTree.js
25704
25854
  var POLL_MS = 100;
25705
25855
  var FORCE_EXIT_WAIT_MS = 2000;
25706
25856
  var TASKKILL_WAIT_MS = 2000;
@@ -26050,7 +26200,7 @@ function spawnAgentProcess(command, args, opts) {
26050
26200
  const env = {
26051
26201
  ...opts.env,
26052
26202
  [WINDOWS_JOB_NODE_ENV]: process.execPath,
26053
- [WINDOWS_JOB_PAYLOAD_ENV]: Buffer.from(JSON.stringify({ command, args, cwd: opts.cwd, shell: opts.shell ?? false })).toString("base64"),
26203
+ [WINDOWS_JOB_PAYLOAD_ENV]: Buffer.from(JSON.stringify({ command: opts.shell ? quoteWindowsShimCommand(command) : command, args, cwd: opts.cwd, shell: opts.shell ?? false })).toString("base64"),
26054
26204
  [WINDOWS_JOB_RUNNER_ENV]: WINDOWS_JOB_RUNNER,
26055
26205
  ...stdinPipe ? { [WINDOWS_JOB_STDIN_PIPE_ENV]: stdinPipe } : {}
26056
26206
  };
@@ -26112,7 +26262,7 @@ function capturePosixTreeTargets(rootPid, rootOwnsProcessGroup) {
26112
26262
  });
26113
26263
  let output2;
26114
26264
  try {
26115
- output2 = execFileSync("ps", ["-axo", "pid=,ppid=,pgid="], {
26265
+ output2 = execFileSync2("ps", ["-axo", "pid=,ppid=,pgid="], {
26116
26266
  encoding: "utf8",
26117
26267
  timeout: POSIX_TREE_CAPTURE_TIMEOUT_MS,
26118
26268
  maxBuffer: POSIX_TREE_CAPTURE_MAX_BUFFER
@@ -26176,6 +26326,9 @@ function signalPosixTargets(targets, signal) {
26176
26326
  } catch {}
26177
26327
  }
26178
26328
  }
26329
+
26330
+ class WindowsTreeExitError extends Error {
26331
+ }
26179
26332
  function taskkillTree(pid) {
26180
26333
  return new Promise((resolve, reject) => {
26181
26334
  const killer = spawn("taskkill.exe", ["/pid", String(pid), "/t", "/f"], {
@@ -26206,17 +26359,24 @@ function taskkillTree(pid) {
26206
26359
  settle2("resolve");
26207
26360
  return;
26208
26361
  }
26209
- settle2("reject", new Error(`Windows process-tree termination failed (exit=${String(code)}, signal=${String(signal)})`));
26362
+ settle2("reject", new WindowsTreeExitError(`Windows process-tree termination failed (exit=${String(code)}, signal=${String(signal)})`));
26210
26363
  });
26211
26364
  });
26212
26365
  }
26213
26366
  async function killWindowsProcessTree(pid) {
26214
26367
  if (!isAlive(pid))
26215
26368
  return;
26216
- await taskkillTree(pid);
26369
+ let terminationError;
26370
+ try {
26371
+ await taskkillTree(pid);
26372
+ } catch (error62) {
26373
+ if (!(error62 instanceof WindowsTreeExitError))
26374
+ throw error62;
26375
+ terminationError = error62;
26376
+ }
26217
26377
  await waitForProcessExit(pid, FORCE_EXIT_WAIT_MS);
26218
26378
  if (isAlive(pid))
26219
- throw new Error(`Windows process tree ${pid} remained alive after taskkill completed`);
26379
+ throw terminationError ?? new Error(`Windows process tree ${pid} remained alive after taskkill completed`);
26220
26380
  }
26221
26381
  async function waitForProcessExit(pid, timeoutMs) {
26222
26382
  const deadline = Date.now() + timeoutMs;
@@ -26259,8 +26419,8 @@ async function killProcessTree(pid, opts) {
26259
26419
 
26260
26420
  // agent-driver/dist/adapters/antigravity/usage.js
26261
26421
  import { createHash } from "node:crypto";
26262
- import { homedir } from "node:os";
26263
- import { resolve, join as join3 } from "node:path";
26422
+ import { homedir as homedir2 } from "node:os";
26423
+ import { resolve, join as join4 } from "node:path";
26264
26424
 
26265
26425
  // agent-driver/dist/adapters/antigravity/local-data.js
26266
26426
  async function readLocalCommand(command, args, limit = 256 * 1024) {
@@ -26358,7 +26518,7 @@ function parseNativeGeneration(data) {
26358
26518
  return { usage: { input: count(usage, 2), output: count(usage, 3), cache: count(usage, 5) }, occurredAt };
26359
26519
  }
26360
26520
  function nativeUsageHome(env, cwd) {
26361
- return resolve(cwd, env.GEMINI_HOME?.replace(/^~(?=[/\\]|$)/, homedir()) || join3(homedir(), ".gemini"));
26521
+ return resolve(cwd, env.GEMINI_HOME?.replace(/^~(?=[/\\]|$)/, homedir2()) || join4(homedir2(), ".gemini"));
26362
26522
  }
26363
26523
  var QUERY = "WITH pending AS (SELECT idx,data FROM gen_metadata WHERE idx>? ORDER BY idx LIMIT 128), batch AS (SELECT idx,data,sum(length(data)) OVER (ORDER BY idx) AS bytes FROM pending) SELECT idx,hex(substr(data,1,4194305)) AS data,(SELECT COUNT(*) FROM steps WHERE has_subtrajectory=1) AS has_children FROM batch WHERE bytes<=4194304 OR idx=(SELECT min(idx) FROM batch) ORDER BY idx";
26364
26524
 
@@ -26376,12 +26536,12 @@ class NativeUsageReader {
26376
26536
  throw new Error("Invalid native usage session identity");
26377
26537
  }
26378
26538
  async read() {
26379
- const path4 = join3(this.home, "antigravity-acp", "conversations", `${this.sessionId}.db`);
26539
+ const path5 = join4(this.home, "antigravity-acp", "conversations", `${this.sessionId}.db`);
26380
26540
  let cursor = this.cursor;
26381
26541
  let complete = false;
26382
26542
  const result = [];
26383
26543
  for (let batch = 0;batch < 16; batch++) {
26384
- const rows = await this.readRows(path4, cursor);
26544
+ const rows = await this.readRows(path5, cursor);
26385
26545
  for (const row of rows) {
26386
26546
  if (!Number.isSafeInteger(row.idx) || row.idx <= cursor || !/^(?:[a-f0-9]{2})*$/i.test(row.data) || row.data.length > 8 * 1024 * 1024)
26387
26547
  throw new Error("Invalid native usage row");
@@ -26402,11 +26562,11 @@ class NativeUsageReader {
26402
26562
  return { samples: result, complete, ...this.childTrajectories ? { incompleteScope: true } : {} };
26403
26563
  }
26404
26564
  }
26405
- async function queryNativeRowsWithCli(path4, cursor) {
26406
- const output2 = await readLocalCommand("sqlite3", ["-readonly", "-json", path4, QUERY.replace("idx>?", `idx>${cursor}`)], 16 * 1024 * 1024);
26565
+ async function queryNativeRowsWithCli(path5, cursor) {
26566
+ const output2 = await readLocalCommand("sqlite3", ["-readonly", "-json", path5, QUERY.replace("idx>?", `idx>${cursor}`)], 16 * 1024 * 1024);
26407
26567
  return output2.trim() ? JSON.parse(output2) : [];
26408
26568
  }
26409
- async function queryNativeRows(path4, cursor, loadSqlite = async () => {
26569
+ async function queryNativeRows(path5, cursor, loadSqlite = async () => {
26410
26570
  const module = "node:sqlite";
26411
26571
  return await import(module);
26412
26572
  }) {
@@ -26414,9 +26574,9 @@ async function queryNativeRows(path4, cursor, loadSqlite = async () => {
26414
26574
  try {
26415
26575
  sqlite = await loadSqlite();
26416
26576
  } catch {
26417
- return queryNativeRowsWithCli(path4, cursor);
26577
+ return queryNativeRowsWithCli(path5, cursor);
26418
26578
  }
26419
- const db = new sqlite.DatabaseSync(path4, { readOnly: true });
26579
+ const db = new sqlite.DatabaseSync(path5, { readOnly: true });
26420
26580
  try {
26421
26581
  return db.prepare(QUERY).all(cursor);
26422
26582
  } finally {
@@ -27304,132 +27464,15 @@ class AntigravityAcpLane {
27304
27464
  // agent-driver/dist/adapters/antigravity/probe.js
27305
27465
  import { createHash as createHash2, randomUUID as randomUUID4 } from "node:crypto";
27306
27466
  import { mkdirSync as mkdirSync3, readFileSync as readFileSync2, renameSync as renameSync2, writeFileSync as writeFileSync3 } from "node:fs";
27307
- import { homedir as homedir2 } from "node:os";
27467
+ import { homedir as homedir3 } from "node:os";
27308
27468
  import { join as join5 } from "node:path";
27309
-
27310
- // agent-driver/dist/internal/probe.js
27311
- import { execFileSync as execFileSync2 } from "child_process";
27312
- import * as fs4 from "fs";
27313
- import * as path4 from "path";
27314
- var PROBE_TIMEOUT_MS = 5000;
27315
- var PROBE_OUTPUT_MAX_BYTES = 1024 * 1024;
27316
- function resolveCommandOnPath(command, deps = {}) {
27317
- if (deps.which)
27318
- return deps.which(command);
27319
- try {
27320
- if (process.platform === "win32") {
27321
- const out2 = execFileSync2("where", [command], { encoding: "utf8", timeout: PROBE_TIMEOUT_MS });
27322
- const first = out2.split(/\r?\n/).find((line) => line.trim().length > 0);
27323
- return first?.trim() || null;
27324
- }
27325
- const out = execFileSync2("which", [command], { encoding: "utf8", timeout: PROBE_TIMEOUT_MS });
27326
- return out.trim() || null;
27327
- } catch {
27328
- return null;
27329
- }
27330
- }
27331
- function firstExistingPath(candidates) {
27332
- for (const c of candidates) {
27333
- if (c && fs4.existsSync(c))
27334
- return c;
27335
- }
27336
- return null;
27337
- }
27338
- function looksLikeVersion(line) {
27339
- return /\d+\.\d+/.test(line);
27340
- }
27341
- function needsWindowsShimShell(command, platform) {
27342
- return platform === "win32" && /\.(cmd|bat)$/i.test(command);
27343
- }
27344
- function probeCommandVersion(command, args = [], deps = {}, platform = process.platform) {
27345
- try {
27346
- const shell = needsWindowsShimShell(command, platform);
27347
- const out = execFileSync2(command, [...args, "--version"], {
27348
- encoding: "utf8",
27349
- timeout: PROBE_TIMEOUT_MS,
27350
- shell,
27351
- input: "",
27352
- env: { ...process.env, CI: "1" }
27353
- });
27354
- const line = out.split(`
27355
- `)[0]?.trim();
27356
- if (!line)
27357
- return { ok: false, error: "empty_version_output" };
27358
- if (!looksLikeVersion(line))
27359
- return { ok: false, error: "invalid_version_output" };
27360
- return { ok: true, version: line };
27361
- } catch (err) {
27362
- const code = err?.code ?? err?.code ?? "version_probe_failed";
27363
- return { ok: false, error: String(code) };
27364
- }
27365
- }
27366
- function probeCommandOutput(command, args, platform = process.platform) {
27367
- try {
27368
- const output2 = execFileSync2(command, args, {
27369
- encoding: "utf8",
27370
- timeout: PROBE_TIMEOUT_MS,
27371
- maxBuffer: PROBE_OUTPUT_MAX_BYTES,
27372
- shell: needsWindowsShimShell(command, platform),
27373
- stdio: ["pipe", "pipe", "ignore"],
27374
- input: "",
27375
- env: { ...process.env, CI: "1" }
27376
- });
27377
- return { ok: true, output: output2 };
27378
- } catch (err) {
27379
- const code = err?.code ?? "command_probe_failed";
27380
- return { ok: false, error: String(code) };
27381
- }
27382
- }
27383
- function resolveHomePath(relativePath, deps = {}) {
27384
- return path4.join(deps.homeDir || process.env.HOME || ".", relativePath);
27385
- }
27386
- function resolveSpawnSpec(command, args, override, deps = {}, platform = process.platform) {
27387
- const trimmed = override?.trim();
27388
- const target2 = trimmed && trimmed.length > 0 ? trimmed : command;
27389
- const looksLikePath = trimmed !== undefined && trimmed.length > 0 && /[\\/]/.test(trimmed);
27390
- const resolved = looksLikePath ? target2 : resolveCommandOnPath(target2, deps) ?? target2;
27391
- return { command: resolved, args, shell: needsWindowsShimShell(resolved, platform) };
27392
- }
27393
- function resolveClaudeCommand(deps = {}) {
27394
- const onPath = resolveCommandOnPath("claude", deps);
27395
- if (onPath)
27396
- return onPath;
27397
- if (process.platform === "darwin") {
27398
- return firstExistingPath([
27399
- resolveHomePath("Applications/Claude Code URL Handler.app/Contents/MacOS/claude", deps),
27400
- "/Applications/Claude Code URL Handler.app/Contents/MacOS/claude"
27401
- ]);
27402
- }
27403
- return null;
27404
- }
27405
- function probeClaude(deps = {}) {
27406
- const command = resolveClaudeCommand(deps);
27407
- if (!command)
27408
- return { status: "unhealthy", lastError: "not_on_path" };
27409
- const r = probeCommandVersion(command, [], deps);
27410
- if (!r.ok)
27411
- return { status: "unhealthy", lastError: r.error };
27412
- return { status: "healthy", version: r.version };
27413
- }
27414
- function probeCliRuntime(binary, deps = {}, override) {
27415
- const explicit = override?.trim();
27416
- const command = explicit || resolveCommandOnPath(binary, deps);
27417
- if (!command)
27418
- return { status: "unhealthy", lastError: "not_on_path" };
27419
- const r = probeCommandVersion(command, [], deps);
27420
- if (!r.ok)
27421
- return { status: "unhealthy", lastError: r.error };
27422
- return { status: "healthy", version: r.version };
27423
- }
27424
-
27425
- // agent-driver/dist/adapters/antigravity/probe.js
27426
27469
  function antigravitySpawnSpec(command, platform = process.platform) {
27427
27470
  return resolveSpawnSpec(platform === "win32" ? "agy_acp_server.exe" : "agy_acp_server.par", platform === "linux" ? ["--uid="] : [], command);
27428
27471
  }
27429
27472
  async function probeAntigravity(command, options = {}) {
27430
27473
  const spec = antigravitySpawnSpec(command);
27431
27474
  const identity = createHash2("sha256").update(JSON.stringify([spec.command, process.env.GEMINI_HOME ?? ""])).digest("hex").slice(0, 16);
27432
- const directory = options.cacheDirectory ?? join5(homedir2(), ".cache", "alook", "antigravity-probe", identity);
27475
+ const directory = options.cacheDirectory ?? join5(homedir3(), ".cache", "alook", "antigravity-probe", identity);
27433
27476
  const cacheFile = join5(directory, "session");
27434
27477
  let cachedSessionId;
27435
27478
  try {
@@ -27476,7 +27519,7 @@ async function probeAntigravity(command, options = {}) {
27476
27519
  cleanup(proc).then(() => resolve2(result), () => resolve2({ status: "unhealthy", lastError: "antigravity_acp_cleanup_failed" }));
27477
27520
  };
27478
27521
  const fail = (lastError) => finish({ status: "unhealthy", lastError });
27479
- const timer = setTimeout(() => fail("antigravity_acp_timeout"), options.timeoutMs ?? 1e4);
27522
+ const timer = setTimeout(() => fail("antigravity_acp_timeout"), options.timeoutMs ?? (process.platform === "win32" ? 30000 : 1e4));
27480
27523
  const write = (value) => {
27481
27524
  try {
27482
27525
  if (!proc.stdin || proc.stdin.destroyed || proc.stdin.writableEnded || proc.stdin.writable === false) {
@@ -28381,7 +28424,7 @@ class ClaudeTurnProtocol {
28381
28424
 
28382
28425
  // agent-driver/dist/adapters/claude/recent-context.js
28383
28426
  import { createReadStream as createReadStream2 } from "node:fs";
28384
- import { homedir as homedir3 } from "node:os";
28427
+ import { homedir as homedir4 } from "node:os";
28385
28428
  import path7 from "node:path";
28386
28429
  import { createInterface } from "node:readline";
28387
28430
 
@@ -28590,7 +28633,7 @@ async function discoverClaudeRecentContext(request, dependencies = {}) {
28590
28633
  const collector = new RecentContextCollector(request, "supported");
28591
28634
  if (collector.satisfied)
28592
28635
  return collector.result();
28593
- const projectsRoot = path7.resolve(dependencies.projectsRoot ?? path7.join(process.env.CLAUDE_CONFIG_DIR || path7.join(homedir3(), ".claude"), "projects"));
28636
+ const projectsRoot = path7.resolve(dependencies.projectsRoot ?? path7.join(process.env.CLAUDE_CONFIG_DIR || path7.join(homedir4(), ".claude"), "projects"));
28594
28637
  const readProjectPath = dependencies.readProjectPath ?? readClaudeProjectPath;
28595
28638
  const candidates = await collectJsonlFileCandidates(projectsRoot, {
28596
28639
  includeRootFiles: false,
@@ -33187,6 +33230,59 @@ class OpenCodeServiceLane {
33187
33230
  }
33188
33231
  }
33189
33232
 
33233
+ // agent-driver/dist/adapters/opencode/legacy-auth.js
33234
+ import { open as open2 } from "node:fs/promises";
33235
+ import { homedir as homedir6 } from "node:os";
33236
+ import path10 from "node:path";
33237
+ function record6(value) {
33238
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
33239
+ }
33240
+ function parse5(value) {
33241
+ try {
33242
+ return record6(JSON.parse(value));
33243
+ } catch {
33244
+ return;
33245
+ }
33246
+ }
33247
+ async function readJson(filename, maxBytes) {
33248
+ try {
33249
+ const file2 = await open2(filename, "r");
33250
+ try {
33251
+ if ((await file2.stat()).size > maxBytes)
33252
+ return;
33253
+ return parse5(await file2.readFile("utf8"));
33254
+ } finally {
33255
+ await file2.close();
33256
+ }
33257
+ } catch {
33258
+ return;
33259
+ }
33260
+ }
33261
+ function xdgRoot(value, fallback) {
33262
+ return value && path10.isAbsolute(value) ? value : fallback;
33263
+ }
33264
+ async function legacyOpenCodeApiEnvironment(environment, model) {
33265
+ if (!model || model.indexOf("/") < 1)
33266
+ return {};
33267
+ if (environment.OPENCODE_MODELS_URL && environment.OPENCODE_MODELS_URL !== "https://models.opencode.ai" && !environment.OPENCODE_MODELS_PATH)
33268
+ return {};
33269
+ const provider = model.slice(0, model.indexOf("/"));
33270
+ const home = (process.platform === "win32" ? environment.USERPROFILE : undefined) || environment.HOME || homedir6();
33271
+ const cache = xdgRoot(environment.XDG_CACHE_HOME, path10.join(home, ".cache"));
33272
+ const catalog = await readJson(environment.OPENCODE_MODELS_PATH || path10.join(cache, "opencode", "models.json"), 16 * 1024 * 1024);
33273
+ const providerInfo = record6(catalog?.[provider]);
33274
+ const names = Array.isArray(providerInfo?.env) ? providerInfo.env.filter((name2) => typeof name2 === "string") : [];
33275
+ if (names.some((name2) => environment[name2] !== undefined))
33276
+ return {};
33277
+ const name = names.find((name2) => /^[A-Z][A-Z0-9_]*(?:_API_KEY|_TOKEN)$/.test(name2));
33278
+ if (!name)
33279
+ return {};
33280
+ const data = xdgRoot(environment.XDG_DATA_HOME, path10.join(home, ".local", "share"));
33281
+ const auth = (environment.OPENCODE_AUTH_CONTENT ? parse5(environment.OPENCODE_AUTH_CONTENT) : undefined) ?? await readJson(path10.join(data, "opencode", "auth.json"), 1024 * 1024);
33282
+ const credential = record6(auth?.[provider]);
33283
+ return credential?.type === "api" && typeof credential.key === "string" && credential.key.trim() ? { [name]: credential.key } : {};
33284
+ }
33285
+
33190
33286
  // agent-driver/dist/adapters/opencode/recent-context.js
33191
33287
  var OPENCODE_DISCOVERY_TIMEOUT_MS = 15000;
33192
33288
  var OPENCODE_DISCOVERY_OUTPUT_MAX_BYTES = 4 * 1024 * 1024;
@@ -33300,7 +33396,9 @@ class OpenCodeDriver {
33300
33396
  const { spawnEnv } = await prepareCliTransport(ctx, {
33301
33397
  OPENCODE_SERVER_PASSWORD: password
33302
33398
  });
33303
- const override = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig).command;
33399
+ const fields2 = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig);
33400
+ Object.assign(spawnEnv, await legacyOpenCodeApiEnvironment(spawnEnv, fields2.model));
33401
+ const override = fields2.command;
33304
33402
  const args = [
33305
33403
  "serve",
33306
33404
  "--pure",
@@ -33323,8 +33421,8 @@ class OpenCodeDriver {
33323
33421
  // agent-driver/dist/adapters/pi/index.js
33324
33422
  import { createRequire as createRequire2 } from "module";
33325
33423
  import { existsSync as existsSync3, readdirSync, readFileSync as readFileSync4, realpathSync } from "fs";
33326
- import { homedir as homedir6 } from "os";
33327
- import * as path12 from "path";
33424
+ import { homedir as homedir8 } from "os";
33425
+ import * as path13 from "path";
33328
33426
 
33329
33427
  // agent-driver/dist/controller/sdk-host.js
33330
33428
  import { EventEmitter as EventEmitter6 } from "events";
@@ -33439,7 +33537,7 @@ class SdkLane {
33439
33537
 
33440
33538
  // agent-driver/dist/adapters/pi/sessionDeps.js
33441
33539
  import { readFileSync as readFileSync3 } from "fs";
33442
- import * as path10 from "path";
33540
+ import * as path11 from "path";
33443
33541
  import { pathToFileURL } from "url";
33444
33542
  var PI_SDK_PACKAGE_NAME = "@earendil-works/pi-coding-agent";
33445
33543
  var cachedSdkPromise = null;
@@ -33448,9 +33546,9 @@ async function importPiSdkFromGlobalInstall() {
33448
33546
  if (!dir) {
33449
33547
  throw new Error(`${PI_SDK_PACKAGE_NAME} not found — install it (e.g. \`npm install -g ${PI_SDK_PACKAGE_NAME}\`) before launching a pi agent`);
33450
33548
  }
33451
- const pkg = JSON.parse(readFileSync3(path10.join(dir, "package.json"), "utf-8"));
33549
+ const pkg = JSON.parse(readFileSync3(path11.join(dir, "package.json"), "utf-8"));
33452
33550
  const entry = pkg.exports?.["."]?.import ?? pkg.main ?? "./dist/index.js";
33453
- const entryPath = path10.join(dir, entry);
33551
+ const entryPath = path11.join(dir, entry);
33454
33552
  const barrel = await import(pathToFileURL(entryPath).href);
33455
33553
  return withSessionDirHelper(barrel, entryPath);
33456
33554
  }
@@ -33458,7 +33556,7 @@ async function withSessionDirHelper(barrel, entryPath) {
33458
33556
  if (typeof barrel.getDefaultSessionDir === "function")
33459
33557
  return barrel;
33460
33558
  try {
33461
- const deepPath = path10.join(path10.dirname(entryPath), "core", "session-manager.js");
33559
+ const deepPath = path11.join(path11.dirname(entryPath), "core", "session-manager.js");
33462
33560
  const deep = await import(pathToFileURL(deepPath).href);
33463
33561
  if (typeof deep.getDefaultSessionDir !== "function")
33464
33562
  return barrel;
@@ -33539,13 +33637,13 @@ function createPiSessionDependencies(ctx, loadSdk = loadPiSdkModule) {
33539
33637
  }
33540
33638
 
33541
33639
  // agent-driver/dist/adapters/pi/recent-context.js
33542
- import { homedir as homedir5 } from "node:os";
33543
- import path11 from "node:path";
33640
+ import { homedir as homedir7 } from "node:os";
33641
+ import path12 from "node:path";
33544
33642
  function expandTildePath(value) {
33545
33643
  if (value === "~")
33546
- return homedir5();
33644
+ return homedir7();
33547
33645
  if (value.startsWith("~/"))
33548
- return path11.join(homedir5(), value.slice(2));
33646
+ return path12.join(homedir7(), value.slice(2));
33549
33647
  return value;
33550
33648
  }
33551
33649
  async function discoverPiRecentContext(request, dependencies = {}) {
@@ -33553,7 +33651,7 @@ async function discoverPiRecentContext(request, dependencies = {}) {
33553
33651
  if (collector.satisfied)
33554
33652
  return collector.result();
33555
33653
  const customSessionDirectory = process.env.PI_CODING_AGENT_SESSION_DIR;
33556
- const sessionsRoot = path11.resolve(expandTildePath(dependencies.sessionsRoot ?? customSessionDirectory ?? path11.join(process.env.PI_CODING_AGENT_DIR || path11.join(homedir5(), ".pi", "agent"), "sessions")));
33654
+ const sessionsRoot = path12.resolve(expandTildePath(dependencies.sessionsRoot ?? customSessionDirectory ?? path12.join(process.env.PI_CODING_AGENT_DIR || path12.join(homedir7(), ".pi", "agent"), "sessions")));
33557
33655
  const scanDirectSessions = dependencies.sessionsRoot == null && customSessionDirectory != null;
33558
33656
  const readHeader = dependencies.readHeader ?? readFirstLine;
33559
33657
  const candidates = await collectJsonlFileCandidates(sessionsRoot, {
@@ -33601,15 +33699,15 @@ function resolvePiSdkPackageDir(deps = {}) {
33601
33699
  if (!binPath)
33602
33700
  return;
33603
33701
  try {
33604
- let dir = path12.dirname(realpathSync(binPath));
33702
+ let dir = path13.dirname(realpathSync(binPath));
33605
33703
  const MAX_DEPTH = 8;
33606
33704
  for (let i = 0;i < MAX_DEPTH; i++) {
33607
- if (isPiSdkPackageJson(path12.join(dir, "package.json")))
33705
+ if (isPiSdkPackageJson(path13.join(dir, "package.json")))
33608
33706
  return dir;
33609
- const siblingDir = path12.join(dir, "node_modules", PI_SDK_PACKAGE_NAME2);
33610
- if (isPiSdkPackageJson(path12.join(siblingDir, "package.json")))
33707
+ const siblingDir = path13.join(dir, "node_modules", PI_SDK_PACKAGE_NAME2);
33708
+ if (isPiSdkPackageJson(path13.join(siblingDir, "package.json")))
33611
33709
  return siblingDir;
33612
- const parent = path12.dirname(dir);
33710
+ const parent = path13.dirname(dir);
33613
33711
  if (parent === dir)
33614
33712
  break;
33615
33713
  dir = parent;
@@ -33626,21 +33724,21 @@ function findPiSessionFile(sessionDir, sessionId) {
33626
33724
  }
33627
33725
  const suffix = `_${sessionId}.jsonl`;
33628
33726
  const match = entries.find((entry) => entry.endsWith(suffix));
33629
- return match ? path12.join(sessionDir, match) : null;
33727
+ return match ? path13.join(sessionDir, match) : null;
33630
33728
  }
33631
33729
  function resolvePiSessionDir(sdk, cwd) {
33632
33730
  if (typeof sdk.getDefaultSessionDir === "function")
33633
33731
  return sdk.getDefaultSessionDir(cwd);
33634
- const agentDir = typeof sdk.getAgentDir === "function" ? sdk.getAgentDir() : path12.join(homedir6(), ".pi", "agent");
33635
- const encoded = `--${path12.resolve(cwd).replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
33636
- return path12.join(agentDir, "sessions", encoded);
33732
+ const agentDir = typeof sdk.getAgentDir === "function" ? sdk.getAgentDir() : path13.join(homedir8(), ".pi", "agent");
33733
+ const encoded = `--${path13.resolve(cwd).replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
33734
+ return path13.join(agentDir, "sessions", encoded);
33637
33735
  }
33638
33736
  function resolvePiSdkVersionFromPath(deps = {}) {
33639
33737
  const dir = resolvePiSdkPackageDir(deps);
33640
33738
  if (!dir)
33641
33739
  return;
33642
33740
  try {
33643
- const pkg = JSON.parse(readFileSync4(path12.join(dir, "package.json"), "utf-8"));
33741
+ const pkg = JSON.parse(readFileSync4(path13.join(dir, "package.json"), "utf-8"));
33644
33742
  return pkg.version;
33645
33743
  } catch {
33646
33744
  return;
@@ -35743,22 +35841,22 @@ function listRuntimeIds() {
35743
35841
 
35744
35842
  // src/discovery.ts
35745
35843
  function resolveAlookCliPath(moduleDir) {
35746
- const thisDir = moduleDir ?? path13.dirname(fileURLToPath(import.meta.url));
35747
- const target2 = path13.basename(thisDir) === "dist" ? path13.resolve(thisDir, "cli", "index.js") : path13.resolve(thisDir, "..", "scripts", "alook-shim.mjs");
35844
+ const thisDir = moduleDir ?? path14.dirname(fileURLToPath(import.meta.url));
35845
+ const target2 = path14.basename(thisDir) === "dist" ? path14.resolve(thisDir, "cli", "index.js") : path14.resolve(thisDir, "..", "scripts", "alook-shim.mjs");
35748
35846
  return fs6.existsSync(target2) ? target2 : null;
35749
35847
  }
35750
35848
  function deriveCliFallbackCandidates(cliPath) {
35751
35849
  if (!cliPath)
35752
35850
  return [];
35753
- const normalized = cliPath.split(path13.sep).join("/");
35851
+ const normalized = cliPath.split(path14.sep).join("/");
35754
35852
  const marker = "/node_modules/";
35755
35853
  const idx = normalized.indexOf(marker);
35756
35854
  if (idx === -1)
35757
35855
  return [];
35758
35856
  const globalRoot = cliPath.slice(0, idx + marker.length - 1);
35759
- const tail = path13.join("dist", "cli", "index.js");
35857
+ const tail = path14.join("dist", "cli", "index.js");
35760
35858
  return [
35761
- path13.join(globalRoot, "@alook", "daemon", tail)
35859
+ path14.join(globalRoot, "@alook", "daemon", tail)
35762
35860
  ].filter((candidate) => candidate !== cliPath);
35763
35861
  }
35764
35862
  function resolveAlookCliPathWithFallback(primary) {
@@ -35861,14 +35959,14 @@ function createLogger2(options = {}) {
35861
35959
  `));
35862
35960
  const err = options.err ?? ((line) => process.stderr.write(line + `
35863
35961
  `));
35864
- const record6 = options.record;
35962
+ const record7 = options.record;
35865
35963
  const emit = (level, message2, data) => {
35866
35964
  if (LEVEL_RANK[level] < minRank)
35867
35965
  return;
35868
35966
  const time3 = now();
35869
35967
  const line = `${time3} ${header} ${level.toUpperCase().padEnd(5)} ${message2}${formatData(data)}`;
35870
35968
  try {
35871
- record6?.({ time: time3, header, level, message: message2, fields: recordFields(data) });
35969
+ record7?.({ time: time3, header, level, message: message2, fields: recordFields(data) });
35872
35970
  } catch {}
35873
35971
  (level === "warn" || level === "error" ? err : out)(line);
35874
35972
  };
@@ -35900,11 +35998,11 @@ function readDaemonVersion() {
35900
35998
 
35901
35999
  // src/cli/daemonRunner.ts
35902
36000
  import * as fs11 from "node:fs";
35903
- import * as path16 from "node:path";
36001
+ import * as path17 from "node:path";
35904
36002
  import { WebSocket } from "ws";
35905
36003
 
35906
36004
  // src/daemon/createDaemon.ts
35907
- import { homedir as homedir10 } from "os";
36005
+ import { homedir as homedir12 } from "os";
35908
36006
  import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync9 } from "node:fs";
35909
36007
 
35910
36008
  // src/util/rotatingFileSink.ts
@@ -35921,7 +36019,7 @@ import {
35921
36019
  statSync,
35922
36020
  unlinkSync as unlinkSync3
35923
36021
  } from "node:fs";
35924
- function createRotatingFileSink(path14, maxBytes, opts = {}) {
36022
+ function createRotatingFileSink(path15, maxBytes, opts = {}) {
35925
36023
  const report = (operation, error62) => {
35926
36024
  try {
35927
36025
  opts.onError?.({ operation, error: error62 });
@@ -35957,9 +36055,9 @@ function createRotatingFileSink(path14, maxBytes, opts = {}) {
35957
36055
  };
35958
36056
  const rotate = () => {
35959
36057
  try {
35960
- renameSync3(path14, `${path14}.1`);
36058
+ renameSync3(path15, `${path15}.1`);
35961
36059
  if (opts.mode !== undefined)
35962
- chmodSync(`${path14}.1`, opts.mode);
36060
+ chmodSync(`${path15}.1`, opts.mode);
35963
36061
  return true;
35964
36062
  } catch (error62) {
35965
36063
  report("rotate", error62);
@@ -35968,7 +36066,7 @@ function createRotatingFileSink(path14, maxBytes, opts = {}) {
35968
36066
  };
35969
36067
  const currentSize = () => {
35970
36068
  try {
35971
- return existsSync6(path14) ? statSync(path14).size : 0;
36069
+ return existsSync6(path15) ? statSync(path15).size : 0;
35972
36070
  } catch (error62) {
35973
36071
  report("stat", error62);
35974
36072
  return null;
@@ -35976,7 +36074,7 @@ function createRotatingFileSink(path14, maxBytes, opts = {}) {
35976
36074
  };
35977
36075
  const sink = {
35978
36076
  secure() {
35979
- return secureGeneration(`${path14}.1`) && secureGeneration(path14);
36077
+ return secureGeneration(`${path15}.1`) && secureGeneration(path15);
35980
36078
  },
35981
36079
  write(line) {
35982
36080
  try {
@@ -35996,7 +36094,7 @@ function createRotatingFileSink(path14, maxBytes, opts = {}) {
35996
36094
  const shouldRotate = maxBytes > 0 && (opts.hardMaxBytes ? currentBytes > 0 && currentBytes + serializedBytes > maxBytes : currentBytes >= maxBytes);
35997
36095
  if (shouldRotate && !rotate() && opts.hardMaxBytes)
35998
36096
  return;
35999
- appendFileSync(path14, serialized, opts.mode === undefined ? undefined : { mode: opts.mode });
36097
+ appendFileSync(path15, serialized, opts.mode === undefined ? undefined : { mode: opts.mode });
36000
36098
  } catch (error62) {
36001
36099
  report("append", error62);
36002
36100
  }
@@ -36004,7 +36102,7 @@ function createRotatingFileSink(path14, maxBytes, opts = {}) {
36004
36102
  openSnapshot() {
36005
36103
  const files = [];
36006
36104
  try {
36007
- for (const candidate of [`${path14}.1`, path14]) {
36105
+ for (const candidate of [`${path15}.1`, path15]) {
36008
36106
  if (!existsSync6(candidate))
36009
36107
  continue;
36010
36108
  if (!secureGeneration(candidate))
@@ -36165,11 +36263,11 @@ function createTraceSampler(emit, throttleMs = DEFAULT_TRACE_SAMPLE_MS) {
36165
36263
 
36166
36264
  // src/util/statusFile.ts
36167
36265
  import { writeFileSync as writeFileSync5, renameSync as renameSync4 } from "node:fs";
36168
- function writeStatusFile(path14, snapshot) {
36266
+ function writeStatusFile(path15, snapshot) {
36169
36267
  try {
36170
- const tmp = `${path14}.tmp`;
36268
+ const tmp = `${path15}.tmp`;
36171
36269
  writeFileSync5(tmp, JSON.stringify(snapshot));
36172
- renameSync4(tmp, path14);
36270
+ renameSync4(tmp, path15);
36173
36271
  } catch {}
36174
36272
  }
36175
36273
 
@@ -36851,7 +36949,7 @@ import * as fs7 from "fs";
36851
36949
  import * as http from "http";
36852
36950
  import * as https from "https";
36853
36951
  import * as os2 from "os";
36854
- import * as path14 from "path";
36952
+ import * as path15 from "path";
36855
36953
  import { URL as URL2 } from "url";
36856
36954
  var LOCAL_MESSAGE_REMINDER_PATH = "/__alook/local/message-reminder";
36857
36955
  var LOCAL_MESSAGE_REMINDER_BODY_MAX_BYTES = 4 * 1024;
@@ -36883,15 +36981,15 @@ class CredentialBroker {
36883
36981
  this.voucherPrefix = config2.voucherPrefix ?? "vch_";
36884
36982
  this.clientLabel = config2.clientLabel ?? "cli";
36885
36983
  this.headerNames = config2.headerNames ?? DEFAULT_HEADER_NAMES;
36886
- this.voucherDir = config2.voucherDir ?? path14.join(os2.tmpdir(), "agent-vouchers");
36984
+ this.voucherDir = config2.voucherDir ?? path15.join(os2.tmpdir(), "agent-vouchers");
36887
36985
  }
36888
36986
  mint(agentId, launchId, capabilities2, runnerKey) {
36889
36987
  if (!runnerKey)
36890
36988
  throw new Error("CredentialBroker.mint: runnerKey is required (per-agent tier-2 credential)");
36891
36989
  const voucher = randomVoucher(this.voucherPrefix);
36892
- const dir = path14.join(this.voucherDir, sanitizeIdSegment(agentId));
36990
+ const dir = path15.join(this.voucherDir, sanitizeIdSegment(agentId));
36893
36991
  fs7.mkdirSync(dir, { recursive: true });
36894
- const voucherFile = path14.join(dir, `${sanitizeIdSegment(launchId)}.token`);
36992
+ const voucherFile = path15.join(dir, `${sanitizeIdSegment(launchId)}.token`);
36895
36993
  fs7.writeFileSync(voucherFile, voucher, { mode: 384 });
36896
36994
  this.registrations.set(voucher, {
36897
36995
  agentId,
@@ -37019,20 +37117,20 @@ function parseLocalMessageReminderBody(body, agentId) {
37019
37117
  }
37020
37118
  if (!value || typeof value !== "object" || Array.isArray(value))
37021
37119
  return null;
37022
- const record6 = value;
37023
- if (Object.keys(record6).sort().join(",") !== "channel,remindAfterMs,sentSeq")
37120
+ const record7 = value;
37121
+ if (Object.keys(record7).sort().join(",") !== "channel,remindAfterMs,sentSeq")
37024
37122
  return null;
37025
- if (typeof record6.channel !== "string" || !isCanonicalChannelScope(record6.channel))
37123
+ if (typeof record7.channel !== "string" || !isCanonicalChannelScope(record7.channel))
37026
37124
  return null;
37027
- if (!Number.isSafeInteger(record6.sentSeq) || record6.sentSeq < 1)
37125
+ if (!Number.isSafeInteger(record7.sentSeq) || record7.sentSeq < 1)
37028
37126
  return null;
37029
- if (!Number.isSafeInteger(record6.remindAfterMs) || record6.remindAfterMs !== 0 && record6.remindAfterMs < LOCAL_MESSAGE_REMINDER_MIN_MS || record6.remindAfterMs > LOCAL_MESSAGE_REMINDER_MAX_MS)
37127
+ if (!Number.isSafeInteger(record7.remindAfterMs) || record7.remindAfterMs !== 0 && record7.remindAfterMs < LOCAL_MESSAGE_REMINDER_MIN_MS || record7.remindAfterMs > LOCAL_MESSAGE_REMINDER_MAX_MS)
37030
37128
  return null;
37031
37129
  return {
37032
37130
  agentId,
37033
- channel: record6.channel,
37034
- sentSeq: record6.sentSeq,
37035
- remindAfterMs: record6.remindAfterMs
37131
+ channel: record7.channel,
37132
+ sentSeq: record7.sentSeq,
37133
+ remindAfterMs: record7.remindAfterMs
37036
37134
  };
37037
37135
  }
37038
37136
  async function handleLocalMessageReminder(req, res, agentId, onArm) {
@@ -37434,13 +37532,13 @@ function reduceManager(state, event) {
37434
37532
  const existing = state.agents[event.agentId];
37435
37533
  if (!existing || existing.execution.sessionInstanceId !== event.sessionInstanceId)
37436
37534
  return { state, effects: [] };
37437
- const record6 = existing.pendingAdmissions.find((entry) => entry.sessionInstanceId === event.sessionInstanceId && entry.commandId === event.commandId);
37438
- if (!record6)
37535
+ const record7 = existing.pendingAdmissions.find((entry) => entry.sessionInstanceId === event.sessionInstanceId && entry.commandId === event.commandId);
37536
+ if (!record7)
37439
37537
  return { state, effects: [] };
37440
37538
  const agent2 = clone2(existing);
37441
37539
  agent2.pendingAdmissions = agent2.pendingAdmissions.filter((entry) => entry.sessionInstanceId !== event.sessionInstanceId || entry.commandId !== event.commandId);
37442
37540
  syncExecutionProjection(agent2);
37443
- return commit(state, agent2, event.outcome === "failed" ? recoveryEffects(agent2, [record6]) : []);
37541
+ return commit(state, agent2, event.outcome === "failed" ? recoveryEffects(agent2, [record7]) : []);
37444
37542
  }
37445
37543
  case "admission_acknowledged": {
37446
37544
  const existing = state.agents[event.agentId];
@@ -37963,11 +38061,11 @@ function syncExecutionProjection(agent2) {
37963
38061
  agent2.lastDeliverAt = agent2.pendingAdmissions.length > 0 ? Math.max(...agent2.pendingAdmissions.map((entry) => entry.admittedAt)) : null;
37964
38062
  }
37965
38063
  function recoveryEffects(agent2, records) {
37966
- return records.filter((record6) => record6.requeueOnFailure).map((record6) => ({
38064
+ return records.filter((record7) => record7.requeueOnFailure).map((record7) => ({
37967
38065
  type: "requeue_delivery",
37968
38066
  agentId: agent2.agentId,
37969
- message: record6.exactAgentMsg,
37970
- mode: record6.mode
38067
+ message: record7.exactAgentMsg,
38068
+ mode: record7.mode
37971
38069
  }));
37972
38070
  }
37973
38071
  function commit(state, agent2, effects) {
@@ -38008,7 +38106,7 @@ function runtimeModelName(config2) {
38008
38106
  // agent-driver/dist/adapters/antigravity/quota.js
38009
38107
  import { createHash as createHash4, randomBytes as randomBytes6 } from "node:crypto";
38010
38108
  import { readFile } from "node:fs/promises";
38011
- import { homedir as homedir7 } from "node:os";
38109
+ import { homedir as homedir9 } from "node:os";
38012
38110
  import { isAbsolute, join as join13 } from "node:path";
38013
38111
  var PROD = "https://cloudcode-pa.googleapis.com";
38014
38112
  var DAILY = "https://daily-cloudcode-pa.googleapis.com";
@@ -38080,10 +38178,10 @@ function parseAntigravityQuota(value) {
38080
38178
  }
38081
38179
  async function readAntigravityQuota(options = {}) {
38082
38180
  const env = options.env ?? process.env;
38083
- const home = options.home ?? homedir7();
38181
+ const home = options.home ?? homedir9();
38084
38182
  const configuredHome = env.GEMINI_HOME?.replace(/^~(?=[/\\]|$)/, home);
38085
38183
  const root = configuredHome ? isAbsolute(configuredHome) ? configuredHome : join13(process.cwd(), configuredHome) : join13(home, ".gemini");
38086
- const read = options.readCredentialsFile ?? ((path15) => readFile(path15, "utf8"));
38184
+ const read = options.readCredentialsFile ?? ((path16) => readFile(path16, "utf8"));
38087
38185
  let credentials = null;
38088
38186
  let authType;
38089
38187
  let storageUnavailable = false;
@@ -38202,7 +38300,7 @@ async function readAntigravityQuota(options = {}) {
38202
38300
  // agent-driver/dist/provider-quota.js
38203
38301
  import { execFile } from "node:child_process";
38204
38302
  import { readFile as readFile2 } from "node:fs/promises";
38205
- import { homedir as homedir8 } from "node:os";
38303
+ import { homedir as homedir10 } from "node:os";
38206
38304
  import { join as join14 } from "node:path";
38207
38305
  import { promisify } from "node:util";
38208
38306
  import { randomBytes as randomBytes7 } from "node:crypto";
@@ -38231,7 +38329,7 @@ async function claudeCredentials(options) {
38231
38329
  } catch {}
38232
38330
  }
38233
38331
  const env = options.env ?? process.env;
38234
- const root = env.CLAUDE_CONFIG_DIR || join14(options.home ?? homedir8(), ".claude");
38332
+ const root = env.CLAUDE_CONFIG_DIR || join14(options.home ?? homedir10(), ".claude");
38235
38333
  try {
38236
38334
  const value = options.readCredentialsFile ? await options.readCredentialsFile(join14(root, ".credentials.json")) : await readFile2(join14(root, ".credentials.json"), "utf8");
38237
38335
  return parseCredentials(value);
@@ -38320,8 +38418,8 @@ async function readClaudeQuota(options) {
38320
38418
  if (!body || typeof body !== "object") {
38321
38419
  return { status: "error", sourceEpoch: claudeSourceEpoch, code: "invalid_response", retryable: true };
38322
38420
  }
38323
- const record6 = body;
38324
- const limits = ["five_hour", "seven_day", "seven_day_sonnet", "seven_day_opus"].map((key) => claudeLimit(key, record6[key])).filter((limit) => limit !== null);
38421
+ const record7 = body;
38422
+ const limits = ["five_hour", "seven_day", "seven_day_sonnet", "seven_day_opus"].map((key) => claudeLimit(key, record7[key])).filter((limit) => limit !== null);
38325
38423
  if (limits.length === 0) {
38326
38424
  return { status: "error", sourceEpoch: claudeSourceEpoch, code: "invalid_response", retryable: true };
38327
38425
  }
@@ -41021,9 +41119,9 @@ function compactLines(input2) {
41021
41119
  }
41022
41120
  return suffix;
41023
41121
  }
41024
- function isRealDirectory(path15) {
41122
+ function isRealDirectory(path16) {
41025
41123
  try {
41026
- return fs9.lstatSync(path15).isDirectory();
41124
+ return fs9.lstatSync(path16).isDirectory();
41027
41125
  } catch {
41028
41126
  return false;
41029
41127
  }
@@ -42168,15 +42266,15 @@ class MessageReminderScheduler {
42168
42266
  const startedAt = this.now();
42169
42267
  const dueAt = startedAt + input2.remindAfterMs;
42170
42268
  const sentRef = `${input2.channel}#${input2.sentSeq}`;
42171
- const record6 = {
42269
+ const record7 = {
42172
42270
  ...input2,
42173
42271
  sentRef,
42174
42272
  startedAt,
42175
42273
  dueAt,
42176
42274
  timer: undefined
42177
42275
  };
42178
- record6.timer = this.setTimer(() => {
42179
- if (this.reminders.get(key) !== record6)
42276
+ record7.timer = this.setTimer(() => {
42277
+ if (this.reminders.get(key) !== record7)
42180
42278
  return;
42181
42279
  this.reminders.delete(key);
42182
42280
  try {
@@ -42187,8 +42285,8 @@ class MessageReminderScheduler {
42187
42285
  Promise.resolve(delivery).catch(() => {});
42188
42286
  } catch {}
42189
42287
  }, input2.remindAfterMs);
42190
- record6.timer.unref?.();
42191
- this.reminders.set(key, record6);
42288
+ record7.timer.unref?.();
42289
+ this.reminders.set(key, record7);
42192
42290
  return { armed: true, dueAt };
42193
42291
  }
42194
42292
  observe(agentId, channel2, latestSeq) {
@@ -42228,7 +42326,7 @@ class MessageReminderScheduler {
42228
42326
 
42229
42327
  // src/manager/agentDriverHost.ts
42230
42328
  import { randomUUID as randomUUID8 } from "node:crypto";
42231
- import { homedir as homedir9 } from "node:os";
42329
+ import { homedir as homedir11 } from "node:os";
42232
42330
  import { join as join16 } from "node:path";
42233
42331
 
42234
42332
  // src/drivers/gitIdentityEnv.ts
@@ -42354,7 +42452,7 @@ function createDaemonAgentDriverHost(ctx, onRawLine) {
42354
42452
  hostUser: readHostGitIdentity() ?? undefined
42355
42453
  }),
42356
42454
  platformProtected: {
42357
- ALOOK_HOME: process.env.ALOOK_HOME ?? join16(homedir9(), ".alook"),
42455
+ ALOOK_HOME: process.env.ALOOK_HOME ?? join16(homedir11(), ".alook"),
42358
42456
  ALOOK_ID: ctx.agentId,
42359
42457
  ALOOK_CLI: ctx.agentCliPath,
42360
42458
  ALOOK_SERVER_URL: ctx.config.serverUrl,
@@ -42460,7 +42558,7 @@ class DaemonSelfSleepScheduler {
42460
42558
  }
42461
42559
 
42462
42560
  // src/telemetry/dailyTokenUsage.ts
42463
- import { chmod, mkdir, open as open2, readFile as readFile3, rename, rm } from "node:fs/promises";
42561
+ import { chmod, mkdir, open as open3, readFile as readFile3, rename, rm } from "node:fs/promises";
42464
42562
  import { dirname as dirname6, join as join17 } from "node:path";
42465
42563
  import { randomUUID as randomUUID9 } from "node:crypto";
42466
42564
  var TOKEN_USAGE_WINDOW_DAYS = 30;
@@ -42713,7 +42811,7 @@ class DailyTokenUsageStore {
42713
42811
  await mkdir(directory, { recursive: true, mode: 448 });
42714
42812
  const temporary = `${this.filePath}.${randomUUID9()}.tmp`;
42715
42813
  try {
42716
- const file2 = await open2(temporary, "wx", 384);
42814
+ const file2 = await open3(temporary, "wx", 384);
42717
42815
  try {
42718
42816
  await file2.writeFile(JSON.stringify(this.data), { encoding: "utf8" });
42719
42817
  await file2.sync();
@@ -42723,7 +42821,7 @@ class DailyTokenUsageStore {
42723
42821
  await rename(temporary, this.filePath);
42724
42822
  await chmod(this.filePath, 384);
42725
42823
  try {
42726
- const directoryHandle = await open2(directory, "r");
42824
+ const directoryHandle = await open3(directory, "r");
42727
42825
  try {
42728
42826
  await directoryHandle.sync();
42729
42827
  } finally {
@@ -42818,13 +42916,13 @@ function createRuntimeRawLineTap(args) {
42818
42916
  const maxBytes = args.maxBytes ?? RUNTIME_RAW_TRACE_MAX_BYTES;
42819
42917
  const sinks = new Map;
42820
42918
  const warned = new Set;
42821
- const warnOnce = (agentId, path15, operation, error62) => {
42919
+ const warnOnce = (agentId, path16, operation, error62) => {
42822
42920
  if (warned.has(agentId))
42823
42921
  return;
42824
42922
  warned.add(agentId);
42825
42923
  args.logger.warn("runtime raw trace sink failed", {
42826
42924
  agentId,
42827
- path: path15,
42925
+ path: path16,
42828
42926
  operation,
42829
42927
  error: error62 instanceof Error ? error62.message : String(error62)
42830
42928
  });
@@ -42833,10 +42931,10 @@ function createRuntimeRawLineTap(args) {
42833
42931
  if (!args.enabledAgentIds.has(agentId))
42834
42932
  return;
42835
42933
  const encodedAgentId = encodeURIComponent(agentId).replace(/\./g, "%2E");
42836
- const path15 = `${traceDir}/runtime-raw-events-${encodedAgentId}.jsonl`;
42934
+ const path16 = `${traceDir}/runtime-raw-events-${encodedAgentId}.jsonl`;
42837
42935
  const serializedBytes = Buffer.byteLength(line, "utf8") + 1;
42838
42936
  if (serializedBytes > maxBytes) {
42839
- warnOnce(agentId, path15, "oversize", new Error(`raw line is ${serializedBytes} bytes; max is ${maxBytes}`));
42937
+ warnOnce(agentId, path16, "oversize", new Error(`raw line is ${serializedBytes} bytes; max is ${maxBytes}`));
42840
42938
  return;
42841
42939
  }
42842
42940
  let sink = sinks.get(agentId);
@@ -42844,12 +42942,12 @@ function createRuntimeRawLineTap(args) {
42844
42942
  try {
42845
42943
  mkdirSync9(traceDir, { recursive: true });
42846
42944
  } catch (error62) {
42847
- warnOnce(agentId, path15, "mkdir", error62);
42945
+ warnOnce(agentId, path16, "mkdir", error62);
42848
42946
  }
42849
- sink = createRotatingFileSink(path15, maxBytes, {
42947
+ sink = createRotatingFileSink(path16, maxBytes, {
42850
42948
  mode: 384,
42851
42949
  hardMaxBytes: true,
42852
- onError: ({ operation, error: error62 }) => warnOnce(agentId, path15, operation, error62)
42950
+ onError: ({ operation, error: error62 }) => warnOnce(agentId, path16, operation, error62)
42853
42951
  });
42854
42952
  sinks.set(agentId, sink);
42855
42953
  }
@@ -42943,7 +43041,7 @@ async function createDaemon(opts) {
42943
43041
  const log2 = opts.logger ?? createLogger2({ header: "@alook/daemon" });
42944
43042
  const recentContextSdk = createAgentDriverSdk();
42945
43043
  const appendRecentContext = createRecentContextPromptAppender((input2) => recentContextSdk.discoverRecentContext(input2));
42946
- const fallbackBase = (process.env.ALOOK_PROJECT_ROOT || `${homedir10()}/.alook`) + "/daemon";
43044
+ const fallbackBase = (process.env.ALOOK_PROJECT_ROOT || `${homedir12()}/.alook`) + "/daemon";
42947
43045
  const workingDirectoryBase = opts.workingDirectoryBase ?? fallbackBase;
42948
43046
  const workdirFor = (agentId) => `${workingDirectoryBase}/${agentId}`;
42949
43047
  const dailyTokenUsage2 = new DailyTokenUsageStore(workingDirectoryBase);
@@ -44334,7 +44432,7 @@ class CoordinatorError extends Error {
44334
44432
  function defaultFsOps() {
44335
44433
  return {
44336
44434
  randomSuffix: () => randomBytes9(12).toString("hex"),
44337
- open: (path15, flags, mode) => openSync4(path15, flags, mode),
44435
+ open: (path16, flags, mode) => openSync4(path16, flags, mode),
44338
44436
  write: (fd, bytes) => {
44339
44437
  writeSync(fd, bytes);
44340
44438
  },
@@ -44347,10 +44445,10 @@ function defaultFsOps() {
44347
44445
  rename: (from, to) => {
44348
44446
  renameSync6(from, to);
44349
44447
  },
44350
- fsyncDirectory: (path15) => {
44448
+ fsyncDirectory: (path16) => {
44351
44449
  if (process.platform === "win32")
44352
44450
  return;
44353
- const fd = openSync4(path15, "r");
44451
+ const fd = openSync4(path16, "r");
44354
44452
  try {
44355
44453
  fsyncSync2(fd);
44356
44454
  } finally {
@@ -44415,11 +44513,11 @@ function createDiagnosticReportCoordinator(args) {
44415
44513
  args.logger?.warn("diagnostic local artifact invalid", { reportId, code: "local_artifact_invalid" });
44416
44514
  } catch {}
44417
44515
  };
44418
- const removeExact = (path15) => {
44516
+ const removeExact = (path16) => {
44419
44517
  try {
44420
- const stat2 = lstatSync5(path15);
44518
+ const stat2 = lstatSync5(path16);
44421
44519
  if (stat2.isFile() && !stat2.isSymbolicLink())
44422
- unlinkSync6(path15);
44520
+ unlinkSync6(path16);
44423
44521
  } catch {}
44424
44522
  };
44425
44523
  const cleanup = (reportId) => {
@@ -44457,12 +44555,12 @@ function createDiagnosticReportCoordinator(args) {
44457
44555
  checkpoint(sidecar.phase === "collecting" ? "collecting_dir_fsynced" : "ready_dir_fsynced");
44458
44556
  };
44459
44557
  const committedArchive = (reportId) => {
44460
- const path15 = archivePath(reportId);
44558
+ const path16 = archivePath(reportId);
44461
44559
  try {
44462
- const stat2 = lstatSync5(path15);
44560
+ const stat2 = lstatSync5(path16);
44463
44561
  if (!stat2.isFile() || stat2.isSymbolicLink())
44464
44562
  return null;
44465
- const bytes = readFileSync7(path15);
44563
+ const bytes = readFileSync7(path16);
44466
44564
  return { sizeBytes: bytes.byteLength, sha256: createHash7("sha256").update(bytes).digest("hex") };
44467
44565
  } catch {
44468
44566
  return null;
@@ -44587,12 +44685,12 @@ function createDiagnosticReportCoordinator(args) {
44587
44685
  return uploadReady(ready);
44588
44686
  };
44589
44687
  const readSidecar = (reportId) => {
44590
- const path15 = sidecarPath(reportId);
44688
+ const path16 = sidecarPath(reportId);
44591
44689
  try {
44592
- const stat2 = lstatSync5(path15);
44690
+ const stat2 = lstatSync5(path16);
44593
44691
  if (!stat2.isFile() || stat2.isSymbolicLink())
44594
44692
  return null;
44595
- return parseSidecar(JSON.parse(readFileSync7(path15, "utf8")));
44693
+ return parseSidecar(JSON.parse(readFileSync7(path16, "utf8")));
44596
44694
  } catch {
44597
44695
  return null;
44598
44696
  }
@@ -44680,9 +44778,9 @@ function createDiagnosticReportCoordinator(args) {
44680
44778
  }
44681
44779
  // src/diagnostics/httpTransport.ts
44682
44780
  import { Readable as Readable2 } from "node:stream";
44683
- function endpoint(serverUrl, path15) {
44781
+ function endpoint(serverUrl, path16) {
44684
44782
  const base = serverUrl.endsWith("/") ? serverUrl : `${serverUrl}/`;
44685
- return new URL(path15.replace(/^\//, ""), base).toString();
44783
+ return new URL(path16.replace(/^\//, ""), base).toString();
44686
44784
  }
44687
44785
  async function strictOutcome(response, allowed) {
44688
44786
  try {
@@ -44690,11 +44788,11 @@ async function strictOutcome(response, allowed) {
44690
44788
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
44691
44789
  return { kind: "retryable" };
44692
44790
  }
44693
- const record6 = value;
44694
- if (Object.keys(record6).length !== 2 || record6.kind !== "terminal") {
44791
+ const record7 = value;
44792
+ if (Object.keys(record7).length !== 2 || record7.kind !== "terminal") {
44695
44793
  return { kind: "retryable" };
44696
44794
  }
44697
- const status = record6.status;
44795
+ const status = record7.status;
44698
44796
  if (status !== "uploaded" && status !== "failed" || allowed[status] !== response.status) {
44699
44797
  return { kind: "retryable" };
44700
44798
  }
@@ -44746,29 +44844,29 @@ function createDiagnosticHttpTransport(args) {
44746
44844
  // src/cli/daemonUpdate.ts
44747
44845
  import * as crypto4 from "node:crypto";
44748
44846
  import * as fs10 from "node:fs";
44749
- import * as path15 from "node:path";
44847
+ import * as path16 from "node:path";
44750
44848
  import { spawn as spawn2 } from "node:child_process";
44751
44849
  var UPDATE_INTENT_SCHEMA_VERSION = 1;
44752
44850
  var UPDATE_LOG_MAX_BYTES = 512 * 1024;
44753
44851
  var UPDATE_LOG_KEEP_BYTES = 256 * 1024;
44754
44852
  var REQUEST_ID_PATTERN = /^[A-Za-z0-9_-]{16,128}$/;
44755
44853
  function intentPath(baseDir, machineId) {
44756
- return path15.join(daemonDirById(baseDir, machineId), "update-intent.json");
44854
+ return path16.join(daemonDirById(baseDir, machineId), "update-intent.json");
44757
44855
  }
44758
44856
  function updateLogPath(baseDir, machineId) {
44759
- return path15.join(daemonDirById(baseDir, machineId), "update.log");
44857
+ return path16.join(daemonDirById(baseDir, machineId), "update.log");
44760
44858
  }
44761
44859
  function updatePackageMapPath(baseDir, machineId) {
44762
- return path15.join(daemonDirById(baseDir, machineId), "update-package-map.json");
44860
+ return path16.join(daemonDirById(baseDir, machineId), "update-package-map.json");
44763
44861
  }
44764
44862
  function ensurePrivateDir(dir) {
44765
44863
  fs10.mkdirSync(dir, { recursive: true, mode: 448 });
44766
44864
  fs10.chmodSync(dir, 448);
44767
44865
  }
44768
44866
  function writePrivateJsonAtomic(filePath, value) {
44769
- const dir = path15.dirname(filePath);
44867
+ const dir = path16.dirname(filePath);
44770
44868
  ensurePrivateDir(dir);
44771
- const tempPath = path15.join(dir, `.${path15.basename(filePath)}.${process.pid}.${crypto4.randomBytes(8).toString("hex")}.tmp`);
44869
+ const tempPath = path16.join(dir, `.${path16.basename(filePath)}.${process.pid}.${crypto4.randomBytes(8).toString("hex")}.tmp`);
44772
44870
  let fd = fs10.openSync(tempPath, "wx", 384);
44773
44871
  try {
44774
44872
  fs10.writeFileSync(fd, JSON.stringify(value));
@@ -44793,7 +44891,7 @@ function scrub(value) {
44793
44891
  }
44794
44892
  function appendUpdateLog(baseDir, machineId, event, fields2 = {}) {
44795
44893
  const filePath = updateLogPath(baseDir, machineId);
44796
- ensurePrivateDir(path15.dirname(filePath));
44894
+ ensurePrivateDir(path16.dirname(filePath));
44797
44895
  try {
44798
44896
  if (fs10.existsSync(filePath) && fs10.statSync(filePath).size > UPDATE_LOG_MAX_BYTES) {
44799
44897
  const data = fs10.readFileSync(filePath);
@@ -44860,7 +44958,7 @@ function pathEnvironment(env, platform) {
44860
44958
  return entry?.[1];
44861
44959
  }
44862
44960
  function launchFromNpmPath(args) {
44863
- const pathApi = args.platform === "win32" ? path15.win32 : path15.posix;
44961
+ const pathApi = args.platform === "win32" ? path16.win32 : path16.posix;
44864
44962
  if (!pathApi.isAbsolute(args.npmPath) || !args.probe.isFile(args.npmPath))
44865
44963
  return null;
44866
44964
  const extension = pathApi.extname(args.npmPath).toLowerCase();
@@ -44892,7 +44990,7 @@ function resolveNpmLaunchCommand(options = {}) {
44892
44990
  if (launch)
44893
44991
  return launch;
44894
44992
  }
44895
- const pathApi = platform === "win32" ? path15.win32 : path15.posix;
44993
+ const pathApi = platform === "win32" ? path16.win32 : path16.posix;
44896
44994
  const names = platform === "win32" ? ["npm.exe", "npm.cmd", "npm.bat", "npm"] : ["npm"];
44897
44995
  const pathValue = pathEnvironment(env, platform);
44898
44996
  for (const directory of pathValue?.split(pathApi.delimiter) ?? []) {
@@ -44931,7 +45029,7 @@ function readTestPackageMap(baseDir, machineId) {
44931
45029
  for (const [key, value] of Object.entries(parsed)) {
44932
45030
  if (key !== "latest" && !parseReleaseVersion(key))
44933
45031
  throw new Error("invalid daemon update package map key");
44934
- if (typeof value !== "string" || !path15.isAbsolute(value))
45032
+ if (typeof value !== "string" || !path16.isAbsolute(value))
44935
45033
  throw new Error("invalid daemon update package map value");
44936
45034
  result[key] = value;
44937
45035
  }
@@ -45240,7 +45338,7 @@ async function buildRunnerDiagnosticBundle(args) {
45240
45338
  function createDaemonProcessLogger(daemonDir, foreground) {
45241
45339
  fs11.mkdirSync(daemonDir, { recursive: true, mode: 448 });
45242
45340
  fs11.chmodSync(daemonDir, 448);
45243
- const logPath = path16.join(daemonDir, "daemon.log");
45341
+ const logPath = path17.join(daemonDir, "daemon.log");
45244
45342
  let warnedOversize = false;
45245
45343
  const sink = createRotatingFileSink(logPath, DAEMON_LOG_MAX_BYTES, {
45246
45344
  mode: 384,
@@ -45267,7 +45365,7 @@ function createDaemonProcessLogger(daemonDir, foreground) {
45267
45365
  `) : quiet,
45268
45366
  err: foreground ? (line2) => process.stderr.write(line2 + `
45269
45367
  `) : quiet,
45270
- record: (record6) => sink.write(JSON.stringify(record6))
45368
+ record: (record7) => sink.write(JSON.stringify(record7))
45271
45369
  });
45272
45370
  return { logger, logPath, sink };
45273
45371
  }
@@ -45476,16 +45574,16 @@ var LEGACY_DAEMON_ID_PATTERN = /^[a-f0-9]{12}$/;
45476
45574
  var DEFAULT_SERVER_URL = "https://alook.ai";
45477
45575
  var DEFAULT_WS_URL = "wss://alook.ai/api/ws/community-daemon";
45478
45576
  function resolveDefaultBaseDir() {
45479
- const root = process.env.ALOOK_PROJECT_ROOT || path17.join(homedir11(), ".alook");
45480
- return path17.join(root, "daemon");
45577
+ const root = process.env.ALOOK_PROJECT_ROOT || path18.join(homedir13(), ".alook");
45578
+ return path18.join(root, "daemon");
45481
45579
  }
45482
45580
  var DEFAULT_BASE_DIR = resolveDefaultBaseDir();
45483
45581
  var log2 = createLogger2({ header: "@alook/daemon" });
45484
45582
  function daemonsDir(baseDir) {
45485
- return path17.join(baseDir, "daemons");
45583
+ return path18.join(baseDir, "daemons");
45486
45584
  }
45487
45585
  function daemonDirById(baseDir, id3) {
45488
- return path17.join(daemonsDir(baseDir), validateDaemonId(id3));
45586
+ return path18.join(daemonsDir(baseDir), validateDaemonId(id3));
45489
45587
  }
45490
45588
  function validateMachineId(machineId) {
45491
45589
  if (!MACHINE_ID_PATTERN.test(machineId))
@@ -45501,10 +45599,10 @@ function validateDaemonId(id3) {
45501
45599
  return id3;
45502
45600
  }
45503
45601
  function pidfilePathById(baseDir, id3) {
45504
- return path17.join(daemonDirById(baseDir, id3), "daemon.pid");
45602
+ return path18.join(daemonDirById(baseDir, id3), "daemon.pid");
45505
45603
  }
45506
45604
  function statusFilePathById(baseDir, id3) {
45507
- return path17.join(daemonDirById(baseDir, id3), "status.json");
45605
+ return path18.join(daemonDirById(baseDir, id3), "status.json");
45508
45606
  }
45509
45607
  function isProcessAlive(pid) {
45510
45608
  try {
@@ -45564,9 +45662,9 @@ function syncDirectory(dir) {
45564
45662
  }
45565
45663
  }
45566
45664
  function writeExclusive(filePath, value) {
45567
- const dir = path17.dirname(filePath);
45665
+ const dir = path18.dirname(filePath);
45568
45666
  ensurePrivateDir2(dir);
45569
- const tempPath = path17.join(dir, `.${path17.basename(filePath)}.${process.pid}.${crypto5.randomBytes(12).toString("hex")}.tmp`);
45667
+ const tempPath = path18.join(dir, `.${path18.basename(filePath)}.${process.pid}.${crypto5.randomBytes(12).toString("hex")}.tmp`);
45570
45668
  let fd = fs12.openSync(tempPath, "wx", 384);
45571
45669
  try {
45572
45670
  fs12.writeFileSync(fd, JSON.stringify(value));
@@ -45588,9 +45686,9 @@ function writeExclusive(filePath, value) {
45588
45686
  }
45589
45687
  }
45590
45688
  function writePrivateJsonAtomic2(filePath, value) {
45591
- const dir = path17.dirname(filePath);
45689
+ const dir = path18.dirname(filePath);
45592
45690
  ensurePrivateDir2(dir);
45593
- const tempPath = path17.join(dir, `.${path17.basename(filePath)}.${process.pid}.${crypto5.randomBytes(12).toString("hex")}.tmp`);
45691
+ const tempPath = path18.join(dir, `.${path18.basename(filePath)}.${process.pid}.${crypto5.randomBytes(12).toString("hex")}.tmp`);
45594
45692
  let fd = fs12.openSync(tempPath, "wx", 384);
45595
45693
  try {
45596
45694
  fs12.writeFileSync(fd, JSON.stringify(value));
@@ -45677,7 +45775,7 @@ function clearStaleOwnership(filePath, liveError) {
45677
45775
  } catch {}
45678
45776
  }
45679
45777
  function replacementLockPathById(baseDir, machineId) {
45680
- return path17.join(daemonDirById(baseDir, machineId), "daemon.replace.lock");
45778
+ return path18.join(daemonDirById(baseDir, machineId), "daemon.replace.lock");
45681
45779
  }
45682
45780
  function readReplacementLock(filePath) {
45683
45781
  if (!fs12.existsSync(filePath))
@@ -45747,7 +45845,7 @@ function checkReplacementLock(baseDir, machineId, resumeRequestId) {
45747
45845
  }
45748
45846
  function acquireDaemonReplacementLock(args) {
45749
45847
  const lockPath = replacementLockPathById(args.baseDir, args.machineId);
45750
- ensurePrivateDir2(path17.dirname(lockPath));
45848
+ ensurePrivateDir2(path18.dirname(lockPath));
45751
45849
  checkReplacementLock(args.baseDir, args.machineId);
45752
45850
  const lock = {
45753
45851
  pid: process.pid,
@@ -45760,11 +45858,11 @@ function acquireDaemonReplacementLock(args) {
45760
45858
  return { path: lockPath, lock };
45761
45859
  }
45762
45860
  function coarseStartLockPath(baseDir) {
45763
- return path17.join(daemonsDir(baseDir), ".start.lock");
45861
+ return path18.join(daemonsDir(baseDir), ".start.lock");
45764
45862
  }
45765
45863
  function acquireCoarseLock(baseDir, ownerToken) {
45766
45864
  const lf = coarseStartLockPath(baseDir);
45767
- ensurePrivateDir2(path17.dirname(lf));
45865
+ ensurePrivateDir2(path18.dirname(lf));
45768
45866
  secureExistingFile(lf);
45769
45867
  clearStaleOwnership(lf, (pid) => new Error(`another daemon start is in progress on this machine (pid ${pid})`));
45770
45868
  writeExclusive(lf, { pid: process.pid, machineId: "coarse", startedAt: new Date().toISOString(), ownerToken });
@@ -45773,7 +45871,7 @@ function acquireCoarseLock(baseDir, ownerToken) {
45773
45871
  function acquireLaunchLock(baseDir, machineId, ownerToken, resumeRequestId) {
45774
45872
  const daemonDir = daemonDirById(baseDir, machineId);
45775
45873
  ensurePrivateDir2(daemonDir);
45776
- const lockPath = path17.join(daemonDir, "daemon.launch.lock");
45874
+ const lockPath = path18.join(daemonDir, "daemon.launch.lock");
45777
45875
  const finalPath = pidfilePathById(baseDir, machineId);
45778
45876
  checkReplacementLock(baseDir, machineId, resumeRequestId);
45779
45877
  secureExistingFile(lockPath);
@@ -45795,9 +45893,9 @@ function legacyPidfileCandidates(baseDir) {
45795
45893
  const candidates = [];
45796
45894
  for (const entry of fs12.readdirSync(dir, { withFileTypes: true })) {
45797
45895
  if (entry.isDirectory()) {
45798
- candidates.push(path17.join(dir, entry.name, "daemon.pid"));
45896
+ candidates.push(path18.join(dir, entry.name, "daemon.pid"));
45799
45897
  } else if (entry.isFile() && entry.name.endsWith(".pid")) {
45800
- candidates.push(path17.join(dir, entry.name));
45898
+ candidates.push(path18.join(dir, entry.name));
45801
45899
  }
45802
45900
  }
45803
45901
  return candidates;
@@ -45869,7 +45967,7 @@ function daemonList(opts) {
45869
45967
  for (const entry of fs12.readdirSync(dir, { withFileTypes: true })) {
45870
45968
  if (entry.isDirectory() && isDaemonId(entry.name)) {
45871
45969
  const id3 = entry.name;
45872
- pushRow(id3, path17.join(dir, id3, "daemon.pid"), path17.join(dir, id3, "status.json"));
45970
+ pushRow(id3, path18.join(dir, id3, "daemon.pid"), path18.join(dir, id3, "status.json"));
45873
45971
  }
45874
45972
  }
45875
45973
  return results;
@@ -45917,7 +46015,7 @@ function daemonIdsWithStatus(baseDir) {
45917
46015
  return [];
45918
46016
  const ids = [];
45919
46017
  for (const entry of fs12.readdirSync(dir, { withFileTypes: true })) {
45920
- if (entry.isDirectory() && isDaemonId(entry.name) && fs12.existsSync(path17.join(dir, entry.name, "status.json"))) {
46018
+ if (entry.isDirectory() && isDaemonId(entry.name) && fs12.existsSync(path18.join(dir, entry.name, "status.json"))) {
45921
46019
  ids.push(entry.name);
45922
46020
  }
45923
46021
  }
@@ -45980,10 +46078,10 @@ async function stopByPidfile(pf, notFoundHint) {
45980
46078
  }
45981
46079
  async function daemonStop(opts) {
45982
46080
  const baseDir = opts.baseDir || process.env.ALOOK_DATA_DIR || DEFAULT_BASE_DIR;
45983
- await stopByPidfile(path17.join(daemonDirById(baseDir, opts.id), "daemon.pid"), `no daemon with id '${opts.id}' (pidfile not found — check \`alook daemon list\`)`);
46081
+ await stopByPidfile(path18.join(daemonDirById(baseDir, opts.id), "daemon.pid"), `no daemon with id '${opts.id}' (pidfile not found — check \`alook daemon list\`)`);
45984
46082
  }
45985
46083
  function credentialFilePathByMachineId(baseDir, machineId) {
45986
- return path17.join(daemonsDir(baseDir), `${validateMachineId(machineId)}.credential.json`);
46084
+ return path18.join(daemonsDir(baseDir), `${validateMachineId(machineId)}.credential.json`);
45987
46085
  }
45988
46086
  function readCredentialFile(filePath) {
45989
46087
  if (!fs12.existsSync(filePath))
@@ -46010,18 +46108,18 @@ function readCredentialFile(filePath) {
46010
46108
  } catch {}
46011
46109
  return null;
46012
46110
  }
46013
- function writeCredentialFile(filePath, record6) {
46014
- writePrivateJsonAtomic2(filePath, record6);
46111
+ function writeCredentialFile(filePath, record7) {
46112
+ writePrivateJsonAtomic2(filePath, record7);
46015
46113
  }
46016
46114
  function readDaemonLaunchRecord(baseDir, machineId) {
46017
- const record6 = readCredentialFile(credentialFilePathByMachineId(baseDir, machineId));
46018
- if (!record6 || !("schemaVersion" in record6) || record6.schemaVersion !== 1 || !parseReleaseVersion(record6.daemonVersion)) {
46115
+ const record7 = readCredentialFile(credentialFilePathByMachineId(baseDir, machineId));
46116
+ if (!record7 || !("schemaVersion" in record7) || record7.schemaVersion !== 1 || !parseReleaseVersion(record7.daemonVersion)) {
46019
46117
  throw new Error("daemon launch record is missing or requires a manual start upgrade");
46020
46118
  }
46021
- validateMachineId(record6.machineId);
46022
- if (record6.machineId !== machineId)
46119
+ validateMachineId(record7.machineId);
46120
+ if (record7.machineId !== machineId)
46023
46121
  throw new Error("daemon launch record machine mismatch");
46024
- return record6;
46122
+ return record7;
46025
46123
  }
46026
46124
  function findExistingCredentialForBearer(baseDir, bearer) {
46027
46125
  const dir = daemonsDir(baseDir);
@@ -46030,7 +46128,7 @@ function findExistingCredentialForBearer(baseDir, bearer) {
46030
46128
  for (const file2 of fs12.readdirSync(dir)) {
46031
46129
  if (!file2.endsWith(".credential.json"))
46032
46130
  continue;
46033
- const parsed = readCredentialFile(path17.join(dir, file2));
46131
+ const parsed = readCredentialFile(path18.join(dir, file2));
46034
46132
  if (parsed && parsed.credential === bearer)
46035
46133
  return parsed;
46036
46134
  }
@@ -46186,23 +46284,23 @@ async function daemonResume(opts) {
46186
46284
  if (!/^[A-Za-z0-9_-]{16,128}$/.test(opts.requestId))
46187
46285
  throw new Error("invalid replacement request id");
46188
46286
  const baseDir = opts.baseDir || process.env.ALOOK_DATA_DIR || DEFAULT_BASE_DIR;
46189
- const record6 = readDaemonLaunchRecord(baseDir, opts.id);
46287
+ const record7 = readDaemonLaunchRecord(baseDir, opts.id);
46190
46288
  if (false) {}
46191
46289
  await daemonStart({
46192
- machineKey: record6.credential,
46193
- serverUrl: record6.serverUrl,
46194
- wsUrl: record6.wsUrl,
46290
+ machineKey: record7.credential,
46291
+ serverUrl: record7.serverUrl,
46292
+ wsUrl: record7.wsUrl,
46195
46293
  baseDir,
46196
46294
  resumeRequestId: opts.requestId
46197
46295
  });
46198
46296
  }
46199
46297
  async function daemonStartById(opts) {
46200
46298
  const baseDir = opts.baseDir || process.env.ALOOK_DATA_DIR || DEFAULT_BASE_DIR;
46201
- const record6 = readDaemonLaunchRecord(baseDir, opts.id);
46299
+ const record7 = readDaemonLaunchRecord(baseDir, opts.id);
46202
46300
  await daemonStart({
46203
- machineKey: record6.credential,
46204
- serverUrl: record6.serverUrl,
46205
- wsUrl: record6.wsUrl,
46301
+ machineKey: record7.credential,
46302
+ serverUrl: record7.serverUrl,
46303
+ wsUrl: record7.wsUrl,
46206
46304
  baseDir,
46207
46305
  foreground: opts.foreground
46208
46306
  });
@@ -46218,7 +46316,11 @@ async function daemonReconnect(opts, deps = {}) {
46218
46316
  }
46219
46317
  const machineId = validateMachineId(opts.id);
46220
46318
  const baseDir = opts.baseDir || process.env.ALOOK_DATA_DIR || DEFAULT_BASE_DIR;
46221
- const launch = readDaemonLaunchRecord(baseDir, machineId);
46319
+ const launch = readCredentialFile(credentialFilePathByMachineId(baseDir, machineId));
46320
+ if (launch && launch.machineId !== machineId)
46321
+ throw new Error("daemon launch record machine mismatch");
46322
+ const serverUrl = opts.serverUrl ?? (launch && "serverUrl" in launch ? launch.serverUrl : undefined);
46323
+ const wsUrl = opts.wsUrl ?? (launch && "wsUrl" in launch ? launch.wsUrl : undefined);
46222
46324
  const pidPath = pidfilePathById(baseDir, machineId);
46223
46325
  const before = readPidFile(pidPath);
46224
46326
  if (before && (before.machineId !== machineId || !before.startedAt || !before.ownerToken)) {
@@ -46234,6 +46336,9 @@ async function daemonReconnect(opts, deps = {}) {
46234
46336
  throw new Error("daemon ownership changed after reconnect lock acquisition");
46235
46337
  }
46236
46338
  if (owned && (deps.isProcessAlive ?? isProcessAlive)(owned.pid)) {
46339
+ if (!launch) {
46340
+ throw new Error(`cannot safely reconnect a running daemon without its saved credential; run daemon stop ${machineId}, then retry the reconnect command`);
46341
+ }
46237
46342
  await (deps.stopExactDaemonPid ?? stopExactDaemonPid)(owned.pid);
46238
46343
  oldStopped = true;
46239
46344
  removePidFileIfMatches(pidPath, owned);
@@ -46243,8 +46348,8 @@ async function daemonReconnect(opts, deps = {}) {
46243
46348
  try {
46244
46349
  await (deps.start ?? daemonStart)({
46245
46350
  machineKey: opts.machineKey,
46246
- serverUrl: opts.serverUrl ?? launch.serverUrl,
46247
- wsUrl: opts.wsUrl ?? launch.wsUrl,
46351
+ serverUrl,
46352
+ wsUrl,
46248
46353
  baseDir,
46249
46354
  resumeRequestId: requestId,
46250
46355
  expectedMachineId: machineId,
@@ -46256,7 +46361,17 @@ async function daemonReconnect(opts, deps = {}) {
46256
46361
  const canRestoreOldEpoch = !activationAttempted || error62 instanceof PairingActivationError && error62.sessionOutcome === "not_committed";
46257
46362
  if (oldStopped && canRestoreOldEpoch) {
46258
46363
  try {
46259
- await (deps.resume ?? daemonResume)({ id: machineId, baseDir, requestId });
46364
+ if (deps.resume || launch && "daemonVersion" in launch && parseReleaseVersion(launch.daemonVersion)) {
46365
+ await (deps.resume ?? daemonResume)({ id: machineId, baseDir, requestId });
46366
+ } else {
46367
+ await (deps.start ?? daemonStart)({
46368
+ machineKey: launch.credential,
46369
+ serverUrl,
46370
+ wsUrl,
46371
+ baseDir,
46372
+ resumeRequestId: requestId
46373
+ });
46374
+ }
46260
46375
  } catch (rollbackError) {
46261
46376
  throw new AggregateError([error62, rollbackError], "reconnect failed before rotation and the prior daemon could not be resumed");
46262
46377
  }
@@ -46311,7 +46426,7 @@ function waitForReceipt(child, prepared) {
46311
46426
  };
46312
46427
  const configuredTestTimeout = NaN;
46313
46428
  const receiptTimeoutMs = Number.isFinite(configuredTestTimeout) && configuredTestTimeout > 0 ? configuredTestTimeout : START_RECEIPT_TIMEOUT_MS;
46314
- const timeout = setTimeout(() => settle2(new Error(`daemon start timed out; inspect ${path17.join(prepared.daemonDir, "daemon.log")}`)), receiptTimeoutMs);
46429
+ const timeout = setTimeout(() => settle2(new Error(`daemon start timed out; inspect ${path18.join(prepared.daemonDir, "daemon.log")}`)), receiptTimeoutMs);
46315
46430
  child.on("message", (message2) => {
46316
46431
  const accepted = message2;
46317
46432
  if (accepted.type === "daemon:accepted") {
@@ -46330,7 +46445,7 @@ function waitForReceipt(child, prepared) {
46330
46445
  settle2(undefined, receipt);
46331
46446
  });
46332
46447
  child.once("exit", (code2, signal) => {
46333
- settle2(new Error(`daemon child exited before ready (${signal ?? code2}); inspect ${path17.join(prepared.daemonDir, "daemon.log")}`));
46448
+ settle2(new Error(`daemon child exited before ready (${signal ?? code2}); inspect ${path18.join(prepared.daemonDir, "daemon.log")}`));
46334
46449
  });
46335
46450
  child.once("error", (error62) => settle2(error62));
46336
46451
  });