@agentchatme/agent-core 0.4.1 → 0.5.0

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.
@@ -3,8 +3,10 @@ import {
3
3
  atomicWriteFile,
4
4
  clientIdentityOf,
5
5
  log,
6
- readJsonFile
7
- } from "./chunk-QDM4EFI7.js";
6
+ readJsonFile,
7
+ runProfileWarning,
8
+ workdirExposesHome
9
+ } from "./chunk-AFDD53DD.js";
8
10
 
9
11
  // src/integration/texts.ts
10
12
  import * as path from "path";
@@ -533,8 +535,8 @@ function getErrorMap() {
533
535
 
534
536
  // node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js
535
537
  var makeIssue = (params) => {
536
- const { data, path: path6, errorMaps, issueData } = params;
537
- const fullPath = [...path6, ...issueData.path || []];
538
+ const { data, path: path8, errorMaps, issueData } = params;
539
+ const fullPath = [...path8, ...issueData.path || []];
538
540
  const fullIssue = {
539
541
  ...issueData,
540
542
  path: fullPath
@@ -650,11 +652,11 @@ var errorUtil;
650
652
 
651
653
  // node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js
652
654
  var ParseInputLazyPath = class {
653
- constructor(parent, value, path6, key) {
655
+ constructor(parent, value, path8, key) {
654
656
  this._cachedPath = [];
655
657
  this.parent = parent;
656
658
  this.data = value;
657
- this._path = path6;
659
+ this._path = path8;
658
660
  this._key = key;
659
661
  }
660
662
  get path() {
@@ -4311,40 +4313,13 @@ function readLocal(file) {
4311
4313
  }
4312
4314
  }
4313
4315
 
4314
- // src/integration/profile.ts
4315
- var RUN_PROFILES = ["answer", "work", "full"];
4316
- var RUN_PROFILE_ENV = "AGENTCHAT_RUN_PROFILE";
4317
- var DEFAULT_RUN_PROFILE = "answer";
4318
- function isRunProfile(value) {
4319
- return typeof value === "string" && RUN_PROFILES.includes(value);
4316
+ // src/skill/identity-line.ts
4317
+ import { integration as kit3 } from "agentchatme";
4318
+ function identityLineOf(texts) {
4319
+ return texts.identity_line;
4320
4320
  }
4321
- function resolveRunProfile(env = process.env) {
4322
- const raw = env[RUN_PROFILE_ENV]?.trim().toLowerCase();
4323
- return isRunProfile(raw) ? raw : DEFAULT_RUN_PROFILE;
4324
- }
4325
- var INTEGRATION_ENV = "AGENTCHAT_INTEGRATION";
4326
- var INTEGRATION_ENV_LEGACY = "AGENTCHAT_DOORBELL";
4327
- var INTEGRATION_ENV_LEGACY_REMOVAL = "2027-02-01";
4328
- function isOff(raw) {
4329
- const value = raw?.trim().toLowerCase();
4330
- return value === "off" || value === "0" || value === "false";
4331
- }
4332
- function integrationDisabledBy(env = process.env) {
4333
- if (env[INTEGRATION_ENV] !== void 0 && env[INTEGRATION_ENV].trim().length > 0) {
4334
- return isOff(env[INTEGRATION_ENV]) ? INTEGRATION_ENV : null;
4335
- }
4336
- return isOff(env[INTEGRATION_ENV_LEGACY]) ? INTEGRATION_ENV_LEGACY : null;
4337
- }
4338
- function integrationDisabled(env = process.env) {
4339
- return integrationDisabledBy(env) !== null;
4340
- }
4341
- var RUN_BUDGET_ENV = "AGENTCHAT_RUN_BUDGET_MS";
4342
- var DEFAULT_RUN_BUDGET_MS = 10 * 6e4;
4343
- var MAX_RUN_BUDGET_MS = 2 * 60 * 6e4;
4344
- function resolveRunBudgetMs(env = process.env) {
4345
- const parsed = Number(env[RUN_BUDGET_ENV]);
4346
- if (!Number.isFinite(parsed) || parsed < 1e3) return DEFAULT_RUN_BUDGET_MS;
4347
- return Math.min(parsed, MAX_RUN_BUDGET_MS);
4321
+ function normalizeHandle(handle) {
4322
+ return kit3.anchor.normalizeHandle(handle);
4348
4323
  }
4349
4324
 
4350
4325
  // src/integration/status.ts
@@ -4397,6 +4372,7 @@ var StatusSchema = external_exports.object({
4397
4372
  runtime: external_exports.string().nullable(),
4398
4373
  handle: external_exports.string().nullable(),
4399
4374
  profile: external_exports.string(),
4375
+ workdir: external_exports.string().optional(),
4400
4376
  socket: external_exports.enum([...SOCKET_STATES, LEGACY_BLOCKED_STATE]),
4401
4377
  wakes: external_exports.number().optional(),
4402
4378
  wakes_absorbed: external_exports.number().optional(),
@@ -4415,6 +4391,10 @@ var StatusSchema = external_exports.object({
4415
4391
  last_error: external_exports.string().nullable(),
4416
4392
  texts: TextsStatusSchema.nullable().default(null),
4417
4393
  capabilities: external_exports.array(external_exports.string()).nullable().optional(),
4394
+ standby: external_exports.object({ home: external_exports.string().nullable(), pid: external_exports.number().nullable(), since: external_exports.string().nullable() }).nullable().optional(),
4395
+ runs_failing: external_exports.object({ reason: external_exports.string(), since: external_exports.string(), runs_missed: external_exports.number(), checked_at: external_exports.string() }).nullable().optional(),
4396
+ unservable: external_exports.object({ reason: external_exports.enum(["key_refused", "runs_failing"]), detail: external_exports.string(), since: external_exports.string(), retry_at: external_exports.string() }).nullable().optional(),
4397
+ lease_errors: external_exports.object({ count: external_exports.number(), last: external_exports.string().nullable() }).nullable().optional(),
4418
4398
  recent_cycles: external_exports.array(external_exports.object({ at: external_exports.string(), outcome: external_exports.string(), cards: external_exports.number(), invites: external_exports.number(), failure: external_exports.string().nullable() })).nullable().optional(),
4419
4399
  intake_paused: external_exports.boolean().nullable().optional()
4420
4400
  }).passthrough();
@@ -4427,6 +4407,7 @@ function normalize(raw) {
4427
4407
  runtime: raw.runtime,
4428
4408
  handle: raw.handle,
4429
4409
  profile: raw.profile,
4410
+ ...raw.workdir !== void 0 ? { workdir: raw.workdir } : {},
4430
4411
  socket: raw.socket === LEGACY_BLOCKED_STATE ? "blocked" : raw.socket,
4431
4412
  wakes: raw.wakes ?? raw.knocks ?? 0,
4432
4413
  wakes_absorbed: raw.wakes_absorbed ?? raw.knocks_absorbed ?? 0,
@@ -4444,7 +4425,11 @@ function normalize(raw) {
4444
4425
  texts: raw.texts,
4445
4426
  capabilities: raw.capabilities ?? null,
4446
4427
  recent_cycles: raw.recent_cycles ?? null,
4447
- intake_paused: raw.intake_paused ?? null
4428
+ intake_paused: raw.intake_paused ?? null,
4429
+ standby: raw.standby ?? null,
4430
+ runs_failing: raw.runs_failing ?? null,
4431
+ unservable: raw.unservable ?? null,
4432
+ lease_errors: raw.lease_errors ?? null
4448
4433
  };
4449
4434
  }
4450
4435
  function integrationStatusPath(home) {
@@ -4502,8 +4487,20 @@ function formatIntegrationStatus(status, now = Date.now()) {
4502
4487
  if (status === null) return ["Integration: no status recorded yet (the daemon has not run, or is still starting)"];
4503
4488
  const age = integrationStatusAge(status, now);
4504
4489
  const stale = age !== null && age > 3 * 6e4;
4490
+ const profileWarning = runProfileWarning(status.profile);
4491
+ const standby = status.standby ?? null;
4492
+ const failing = status.runs_failing ?? null;
4493
+ const unservable = status.unservable ?? null;
4505
4494
  const lines = [
4506
- `Integration: socket ${status.socket}${stale ? ` (status last written ${ago(age)} \u2014 the daemon may be down)` : ""}`,
4495
+ `Integration: socket ${status.socket}${stale ? ` (status last written ${ago(age)} \u2014 the daemon may be down)` : ""}${unservable !== null ? " \u2014 this home gave the agent up (below)" : standby !== null ? " \u2014 standing by: another listener serves this agent" : failing !== null ? " \u2014 but runs are failing (below)" : ""}`,
4496
+ ...unservable !== null ? [
4497
+ ` gave up: ${unservable.reason === "key_refused" ? "the server refuses this home's key" : "runs fail for a runtime reason, and another listener for the agent was waiting"} \u2014 ${unservable.detail} (since ${unservable.since}). No socket, no run here while another listener can serve it; looks again at ${unservable.retry_at}${unservable.reason === "runs_failing" ? " (the runtime checked first: a check that passes clears this)" : " (signing in again here clears this at once)"}, and takes the agent back whenever no other listener holds it.`
4498
+ ] : [],
4499
+ ...standby !== null ? [` standby: ${standby.home ?? "another identity home"}${standby.pid !== null ? ` (pid ${standby.pid})` : ""} serves this agent${standby.since !== null ? ` since ${standby.since}` : ""}; this one holds no socket and starts no run while it does (no message is answered twice), and takes over when it stops`] : [],
4500
+ ...failing !== null ? [
4501
+ ` runs failing: ${failing.reason} \u2014 since ${failing.since} (${ago(Math.max(0, now - Date.parse(failing.since)))}), ${failing.runs_missed} run(s) missed; checked ${ago(Math.max(0, now - Date.parse(failing.checked_at)))}. ${unservable !== null ? "The runtime recheck clears this." : "Wakes still arrive, are counted and start runs; the next run that succeeds clears this."}`
4502
+ ] : [],
4503
+ ...status.lease_errors !== void 0 && status.lease_errors !== null && status.lease_errors.count > 0 ? [` lock: ${status.lease_errors.count} renewal(s) failed${status.lease_errors.last ? ` (last: ${status.lease_errors.last})` : ""}; a lock that cannot be renewed for 45 s is given up`] : [],
4507
4504
  " delivery: acknowledged on receipt by the SDK socket (delivered = this machine received it; read is the agent\u2019s own verdict inside its run)",
4508
4505
  ` wakes: ${status.wakes} (${status.wakes_absorbed} absorbed into a pending run), invites: ${status.invites}`,
4509
4506
  ` runs: ${status.runs_started} started, ${status.runs_ok} ok, ${status.runs_failed} failed, ${status.runs_timed_out} timed out, ${status.runs_not_started} did not start; ${status.runs_skipped_empty} wake(s) found the tray empty (no run)`,
@@ -4511,7 +4508,10 @@ function formatIntegrationStatus(status, now = Date.now()) {
4511
4508
  ...status.capabilities === null || status.capabilities === void 0 ? [] : [
4512
4509
  status.capabilities.includes("rewake") ? " re-wake: the server wakes this agent again for cards it has not answered (+1 m, +5 m, +30 m, +3 h)" : " re-wake: not offered by this server \u2014 an unanswered card waits for the next message"
4513
4510
  ],
4514
- ` profile: ${status.profile}${status.runtime ? ` (${status.runtime})` : ""}`
4511
+ ` profile: ${status.profile}${status.runtime ? ` (${status.runtime})` : ""}${profileWarning !== null ? ` \u2014 ${profileWarning}` : ""}`,
4512
+ ...status.workdir !== void 0 && workdirExposesHome(status.workdir) ? [
4513
+ ` workdir: ${status.workdir} is your home folder or contains it \u2014 a run started by a peer's message there can see everything under it${status.profile === "answer" ? " (the presets' answer runs use their own empty folder instead)" : ""}; point the workdir at a folder of its own`
4514
+ ] : []
4515
4515
  ];
4516
4516
  if (status.last_run) {
4517
4517
  const r = status.last_run;
@@ -4528,9 +4528,9 @@ function formatIntegrationStatus(status, now = Date.now()) {
4528
4528
  if (cycles.length > 0) {
4529
4529
  const last = cycles[cycles.length - 1];
4530
4530
  lines.push(` cycles: ${cycles.length} recent; the last one ${last.outcome} (${last.cards} card(s), ${last.invites} invite(s)) ${ago(Math.max(0, now - Date.parse(last.at)))}`);
4531
- const failing = failedCyclesInARow(status);
4532
- if (failing !== null && failing.count >= REPEATED_FAILED_CYCLES) {
4533
- lines.push(` WARNING: the last ${failing.count} wake cycles did not get done (latest: ${failing.latest.outcome}${failing.latest.failure ? ` \u2014 ${failing.latest.failure}` : ""})`);
4531
+ const failing2 = failedCyclesInARow(status);
4532
+ if (failing2 !== null && failing2.count >= REPEATED_FAILED_CYCLES) {
4533
+ lines.push(` WARNING: the last ${failing2.count} wake cycles did not get done (latest: ${failing2.latest.outcome}${failing2.latest.failure ? ` \u2014 ${failing2.latest.failure}` : ""})`);
4534
4534
  }
4535
4535
  }
4536
4536
  if (status.retry_due_at) {
@@ -4641,62 +4641,424 @@ function alwaysOnHealth(home) {
4641
4641
  return { wanted: state !== "off", healthy: state !== "down" };
4642
4642
  }
4643
4643
 
4644
- // src/daemon/leader-lock.ts
4644
+ // src/util/lease.ts
4645
+ import * as crypto from "crypto";
4645
4646
  import * as fs5 from "fs";
4647
+ import * as os from "os";
4646
4648
  import * as path5 from "path";
4647
- function acquireLeaderLock(home) {
4648
- const lockPath = path5.join(home, "daemon.lock");
4649
- fs5.mkdirSync(home, { recursive: true });
4650
- const tryWrite = () => {
4651
- try {
4652
- const fd = fs5.openSync(lockPath, "wx");
4653
- fs5.writeSync(fd, String(process.pid));
4654
- fs5.closeSync(fd);
4655
- return true;
4656
- } catch {
4657
- return false;
4658
- }
4659
- };
4660
- if (tryWrite()) return makeHandle(lockPath);
4661
- let holderPid = 0;
4649
+ var LEASE_RENEW_MS = 1e4;
4650
+ var LEASE_STALE_MS = 45e3;
4651
+ var WRITE_GRACE_MS = 5e3;
4652
+ var GUARD_STALE_MS = 1e4;
4653
+ var BOOT_MARGIN_MS = 6e4;
4654
+ var ATTEMPTS = 40;
4655
+ var BACKOFF_MS = 25;
4656
+ var sleep = (ms) => new Promise((resolve3) => setTimeout(resolve3, ms));
4657
+ function pause(ms, signal) {
4658
+ if (signal?.aborted === true) return Promise.resolve();
4659
+ return new Promise((resolve3) => {
4660
+ const done = () => {
4661
+ clearTimeout(timer);
4662
+ signal?.removeEventListener("abort", done);
4663
+ resolve3();
4664
+ };
4665
+ const timer = setTimeout(done, ms);
4666
+ signal?.addEventListener("abort", done, { once: true });
4667
+ });
4668
+ }
4669
+ function leaseConfirmMs(renewMs = LEASE_RENEW_MS) {
4670
+ return Math.round(renewMs * 1.5);
4671
+ }
4672
+ function leaseStartupObserveMs(options = {}) {
4673
+ return (options.staleMs ?? LEASE_STALE_MS) + (options.renewMs ?? LEASE_RENEW_MS);
4674
+ }
4675
+ function hostname2() {
4676
+ try {
4677
+ return os.hostname();
4678
+ } catch {
4679
+ return "";
4680
+ }
4681
+ }
4682
+ function bootedAt(now = Date.now()) {
4683
+ return now - os.uptime() * 1e3;
4684
+ }
4685
+ function pidAlive(pid) {
4686
+ if (!Number.isInteger(pid) || pid <= 0) return false;
4687
+ try {
4688
+ process.kill(pid, 0);
4689
+ return true;
4690
+ } catch (err) {
4691
+ return err.code === "EPERM";
4692
+ }
4693
+ }
4694
+ function parseLease(raw) {
4695
+ const text = raw.trim();
4696
+ const firstLine = text.split(/\r?\n/, 1)[0]?.trim() ?? "";
4697
+ if (!/^\d+$/.test(firstLine)) return null;
4698
+ const pid = Number(firstLine);
4699
+ const rest = text.slice(firstLine.length).trim();
4700
+ if (rest.length === 0) return { pid, token: null, host: null, renewed_at: null };
4701
+ try {
4702
+ const j = JSON.parse(rest);
4703
+ return {
4704
+ pid,
4705
+ token: typeof j["token"] === "string" ? j["token"] : null,
4706
+ host: typeof j["host"] === "string" ? j["host"] : null,
4707
+ ...typeof j["home"] === "string" ? { home: j["home"] } : {},
4708
+ ...typeof j["label"] === "string" ? { label: j["label"] } : {},
4709
+ ...typeof j["acquired_at"] === "string" ? { acquired_at: j["acquired_at"] } : {},
4710
+ renewed_at: typeof j["renewed_at"] === "number" && Number.isFinite(j["renewed_at"]) ? j["renewed_at"] : null
4711
+ };
4712
+ } catch {
4713
+ return null;
4714
+ }
4715
+ }
4716
+ var sameHost = (holder) => holder.host === null || holder.host === hostname2();
4717
+ function legacyLive(holder, mtimeMs, booted) {
4718
+ if (!pidAlive(holder.pid)) return false;
4719
+ return mtimeMs === null || mtimeMs >= booted - BOOT_MARGIN_MS;
4720
+ }
4721
+ function holderLive(holder, at = {}) {
4722
+ const now = at.now ?? Date.now();
4723
+ if (holder.renewed_at === null) return legacyLive(holder, at.mtimeMs ?? null, at.bootedAt ?? bootedAt(now));
4724
+ if (sameHost(holder) && !pidAlive(holder.pid)) return false;
4725
+ return Math.abs(now - holder.renewed_at) < (at.staleMs ?? LEASE_STALE_MS);
4726
+ }
4727
+ var observations = /* @__PURE__ */ new Map();
4728
+ function judge(file, holder, ctx) {
4729
+ if (holder === null) return mtimeOf(file) !== null && ctx.now - (mtimeOf(file) ?? 0) < WRITE_GRACE_MS ? "writing" : "stale";
4730
+ if (holder.renewed_at === null) return legacyLive(holder, mtimeOf(file), ctx.booted) ? "held" : "stale";
4731
+ if (sameHost(holder)) {
4732
+ if (!pidAlive(holder.pid)) return "stale";
4733
+ const mtime = mtimeOf(file);
4734
+ if (mtime !== null && mtime < ctx.booted - BOOT_MARGIN_MS && holder.renewed_at < ctx.booted - BOOT_MARGIN_MS) return "stale";
4735
+ }
4736
+ const signature = `${holder.token ?? ""}\0${holder.renewed_at}`;
4737
+ const seen = observations.get(file);
4738
+ if (seen === void 0 || seen.signature !== signature) {
4739
+ observations.set(file, { signature, firstSeen: ctx.mono });
4740
+ return "held";
4741
+ }
4742
+ return ctx.mono - seen.firstSeen >= ctx.staleMs ? "observed" : "held";
4743
+ }
4744
+ function signatureOf(holder) {
4745
+ return holder === null || holder.renewed_at === null ? null : `${holder.token ?? ""}\0${holder.renewed_at}`;
4746
+ }
4747
+ function readRaw(file) {
4662
4748
  try {
4663
- holderPid = Number.parseInt(fs5.readFileSync(lockPath, "utf-8").trim(), 10);
4749
+ return fs5.readFileSync(file, "utf-8");
4664
4750
  } catch {
4751
+ return null;
4665
4752
  }
4666
- if (holderPid && isAlive(holderPid)) {
4667
- log.error(`another agentchatd already holds ${lockPath} (pid ${holderPid})`);
4753
+ }
4754
+ function mtimeOf(file) {
4755
+ try {
4756
+ return fs5.statSync(file).mtimeMs;
4757
+ } catch {
4668
4758
  return null;
4669
4759
  }
4670
- log.warn(`stealing stale lock ${lockPath} (dead pid ${holderPid || "?"})`);
4760
+ }
4761
+ function createExclusive(file, content) {
4762
+ let fd;
4671
4763
  try {
4672
- fs5.writeFileSync(lockPath, String(process.pid));
4673
- return makeHandle(lockPath);
4764
+ fd = fs5.openSync(file, "wx", 384);
4674
4765
  } catch (err) {
4675
- log.error(`could not steal stale lock: ${String(err)}`);
4676
- return null;
4766
+ if (err.code === "EEXIST") return false;
4767
+ throw err;
4677
4768
  }
4769
+ try {
4770
+ fs5.writeSync(fd, content);
4771
+ fs5.fsyncSync(fd);
4772
+ } finally {
4773
+ fs5.closeSync(fd);
4774
+ }
4775
+ return true;
4678
4776
  }
4679
- function isAlive(pid) {
4777
+ function removeIfStill(file, content) {
4778
+ if (readRaw(file) !== content) return;
4779
+ const aside = `${file}.gone-${crypto.randomUUID()}`;
4680
4780
  try {
4681
- process.kill(pid, 0);
4682
- return true;
4781
+ fs5.renameSync(file, aside);
4683
4782
  } catch {
4783
+ return;
4784
+ }
4785
+ if (readRaw(aside) === content) fs5.rmSync(aside, { force: true });
4786
+ else {
4787
+ try {
4788
+ fs5.linkSync(aside, file);
4789
+ } catch {
4790
+ }
4791
+ fs5.rmSync(aside, { force: true });
4792
+ }
4793
+ }
4794
+ function replaceContent(file, content) {
4795
+ const temp = `${file}.renew-${crypto.randomUUID()}`;
4796
+ try {
4797
+ fs5.writeFileSync(temp, content, { mode: 384 });
4798
+ fs5.renameSync(temp, file);
4799
+ } catch {
4800
+ fs5.rmSync(temp, { force: true });
4801
+ fs5.writeFileSync(file, content, { mode: 384 });
4802
+ }
4803
+ }
4804
+ function withGuard(file, now, fn) {
4805
+ const guard = `${file}.takeover`;
4806
+ const mine = `${process.pid}
4807
+ ${JSON.stringify({ pid: process.pid, token: crypto.randomUUID(), host: hostname2(), renewed_at: now })}
4808
+ `;
4809
+ if (!createExclusive(guard, mine)) {
4810
+ const raw = readRaw(guard);
4811
+ const g = raw === null ? null : parseLease(raw);
4812
+ const dead = g !== null && sameHost(g) && !pidAlive(g.pid);
4813
+ if (raw !== null && (dead || now - (mtimeOf(guard) ?? now) > GUARD_STALE_MS)) removeIfStill(guard, raw);
4684
4814
  return false;
4685
4815
  }
4816
+ try {
4817
+ fn();
4818
+ } finally {
4819
+ removeIfStill(guard, mine);
4820
+ }
4821
+ return true;
4822
+ }
4823
+ async function acquireLease(file, info = {}, options = {}) {
4824
+ const now = options.now ?? Date.now;
4825
+ const mono = options.monotonic ?? (() => performance.now());
4826
+ const staleMs = options.staleMs ?? LEASE_STALE_MS;
4827
+ const renewMs = options.renewMs ?? LEASE_RENEW_MS;
4828
+ const booted = (options.bootedAt ?? (() => bootedAt(now())))();
4829
+ const signal = options.signal;
4830
+ const observeUntil = performance.now() + (options.observeMs ?? 0);
4831
+ const pollMs = Math.max(50, Math.min(1e3, Math.round(renewMs / 4)));
4832
+ let firstSignature = null;
4833
+ let confirmed = null;
4834
+ fs5.mkdirSync(path5.dirname(file), { recursive: true, mode: 448 });
4835
+ const token = crypto.randomUUID();
4836
+ const acquiredAt = new Date(now()).toISOString();
4837
+ const render = (renewedAt) => `${process.pid}
4838
+ ${JSON.stringify({ pid: process.pid, token, host: hostname2(), ...info, acquired_at: acquiredAt, renewed_at: renewedAt })}
4839
+ `;
4840
+ let attempt = 0;
4841
+ while (attempt < ATTEMPTS) {
4842
+ if (createExclusive(file, render(now()))) {
4843
+ observations.delete(file);
4844
+ return { ok: true, lease: startLease(file, token, render, options) };
4845
+ }
4846
+ const raw2 = readRaw(file);
4847
+ if (raw2 === null) {
4848
+ attempt += 1;
4849
+ continue;
4850
+ }
4851
+ const holder2 = parseLease(raw2);
4852
+ const verdict = judge(file, holder2, { now: now(), mono: mono(), staleMs, booted });
4853
+ if (verdict === "writing") {
4854
+ attempt += 1;
4855
+ await sleep(BACKOFF_MS);
4856
+ continue;
4857
+ }
4858
+ if (verdict === "observed" && raw2 !== confirmed) {
4859
+ await pause(leaseConfirmMs(renewMs), signal);
4860
+ if (signal?.aborted === true) return { ok: false, path: file, holder: holder2 };
4861
+ if (readRaw(file) !== raw2) continue;
4862
+ confirmed = raw2;
4863
+ } else if (verdict === "held") {
4864
+ const signature = signatureOf(holder2);
4865
+ if (firstSignature !== null && signature !== firstSignature) return { ok: false, path: file, holder: holder2 };
4866
+ firstSignature ??= signature;
4867
+ if (signature === null || performance.now() >= observeUntil || signal?.aborted === true) return { ok: false, path: file, holder: holder2 };
4868
+ await pause(pollMs, signal);
4869
+ continue;
4870
+ }
4871
+ attempt += 1;
4872
+ if (!withGuard(file, now(), () => removeIfStill(file, raw2))) await sleep(BACKOFF_MS);
4873
+ }
4874
+ const raw = readRaw(file);
4875
+ const holder = raw === null ? null : parseLease(raw);
4876
+ return { ok: false, path: file, holder: holder !== null && holderLive(holder, { now: now(), staleMs, mtimeMs: mtimeOf(file), bootedAt: booted }) ? holder : null };
4686
4877
  }
4687
- function makeHandle(lockPath) {
4688
- let released = false;
4689
- const release = () => {
4690
- if (released) return;
4691
- released = true;
4878
+ function startLease(file, token, render, options) {
4879
+ const now = options.now ?? Date.now;
4880
+ const mono = options.monotonic ?? (() => performance.now());
4881
+ const staleMs = options.staleMs ?? LEASE_STALE_MS;
4882
+ const listeners = [];
4883
+ let lost = false;
4884
+ let renewErrors = 0;
4885
+ let lastRenewError = null;
4886
+ let lastRenewedMono = mono();
4887
+ let content = readRaw(file) ?? "";
4888
+ const loseIt = (why) => {
4889
+ if (lost) return;
4890
+ lost = true;
4891
+ clearInterval(timer);
4892
+ for (const l of listeners) {
4893
+ try {
4894
+ l(why);
4895
+ } catch {
4896
+ }
4897
+ }
4898
+ };
4899
+ const renew = () => {
4900
+ if (lost) return;
4692
4901
  try {
4693
- if (fs5.readFileSync(lockPath, "utf-8").trim() === String(process.pid)) {
4694
- fs5.unlinkSync(lockPath);
4902
+ const done = withGuard(file, now(), () => {
4903
+ const raw = readRaw(file);
4904
+ const holder = raw === null ? null : parseLease(raw);
4905
+ if (holder?.token !== token) {
4906
+ loseIt(raw === null ? `${file} was removed` : `${file} now names another holder (pid ${holder?.pid ?? "?"})`);
4907
+ return;
4908
+ }
4909
+ const next = render(now());
4910
+ replaceContent(file, next);
4911
+ content = next;
4912
+ lastRenewedMono = mono();
4913
+ });
4914
+ if (!done && mono() - lastRenewedMono >= staleMs) loseIt(`could not renew ${file} for ${Math.round(staleMs / 1e3)} s (its guard stayed taken)`);
4915
+ } catch (err) {
4916
+ renewErrors += 1;
4917
+ lastRenewError = err instanceof Error ? err.message : String(err);
4918
+ if (readRaw(file) === null) loseIt(`${file} is gone (${lastRenewError})`);
4919
+ else if (mono() - lastRenewedMono >= staleMs) loseIt(`could not renew ${file} for ${Math.round(staleMs / 1e3)} s (${lastRenewError})`);
4920
+ }
4921
+ };
4922
+ const timer = setInterval(renew, options.renewMs ?? LEASE_RENEW_MS);
4923
+ timer.unref();
4924
+ return {
4925
+ path: file,
4926
+ get lost() {
4927
+ return lost;
4928
+ },
4929
+ get renewErrors() {
4930
+ return renewErrors;
4931
+ },
4932
+ get lastRenewError() {
4933
+ return lastRenewError;
4934
+ },
4935
+ onLost(listener) {
4936
+ listeners.push(listener);
4937
+ },
4938
+ release() {
4939
+ if (lost) return;
4940
+ lost = true;
4941
+ clearInterval(timer);
4942
+ try {
4943
+ const done = withGuard(file, now(), () => {
4944
+ const raw = readRaw(file);
4945
+ if (raw !== null && parseLease(raw)?.token === token) removeIfStill(file, raw);
4946
+ });
4947
+ if (!done) removeIfStill(file, readRaw(file) === content ? content : "\0");
4948
+ } catch {
4695
4949
  }
4696
- } catch {
4697
4950
  }
4698
4951
  };
4699
- return { release };
4952
+ }
4953
+ function leaseHolder(file, staleMs = LEASE_STALE_MS) {
4954
+ const raw = readRaw(file);
4955
+ const holder = raw === null ? null : parseLease(raw);
4956
+ return holder !== null && holderLive(holder, { staleMs, mtimeMs: mtimeOf(file) }) ? holder : null;
4957
+ }
4958
+ function resetLeaseObservations() {
4959
+ observations.clear();
4960
+ }
4961
+
4962
+ // src/daemon/leader-lock.ts
4963
+ import * as path6 from "path";
4964
+ var DAEMON_LOCK_FILE = "daemon.lock";
4965
+ async function acquireLeaderLock(home, options = {}) {
4966
+ const lockPath = path6.join(home, DAEMON_LOCK_FILE);
4967
+ const attempt = await acquireLease(lockPath, { home: path6.resolve(home) }, { observeMs: leaseStartupObserveMs(options), ...options });
4968
+ if (attempt.ok) return attempt.lease;
4969
+ log.error(`another agentchat daemon already holds ${lockPath}${attempt.holder !== null ? ` (pid ${attempt.holder.pid})` : ""}`);
4970
+ return null;
4971
+ }
4972
+
4973
+ // src/daemon/agent-lock.ts
4974
+ import * as crypto2 from "crypto";
4975
+ import * as fs6 from "fs";
4976
+ import * as os2 from "os";
4977
+ import * as path7 from "path";
4978
+ var AGENT_LOCK_DIR_ENV = "AGENTCHAT_LOCK_DIR";
4979
+ function agentLockDir(env = process.env, system = process.platform, home = os2.homedir()) {
4980
+ const override = env[AGENT_LOCK_DIR_ENV]?.trim();
4981
+ if (override !== void 0 && override.length > 0) return path7.resolve(override);
4982
+ const p = system === "win32" ? path7.win32 : path7.posix;
4983
+ if (system === "darwin") return p.join(home, "Library", "Application Support", "AgentChat", "locks");
4984
+ if (system === "win32") return p.join(home, "AppData", "Local", "AgentChat", "locks");
4985
+ return p.join(home, ".local", "state", "agentchat", "locks");
4986
+ }
4987
+ function originOf(apiBase) {
4988
+ try {
4989
+ return new URL(apiBase).origin.toLowerCase();
4990
+ } catch {
4991
+ return apiBase.trim().toLowerCase();
4992
+ }
4993
+ }
4994
+ function agentLockPath(agent, env = process.env) {
4995
+ const id = crypto2.createHash("sha256").update(`${originOf(agent.apiBase)}
4996
+ ${normalizeHandle(agent.handle)}`).digest("hex").slice(0, 32);
4997
+ return path7.join(agentLockDir(env), `agent-${id}.lock`);
4998
+ }
4999
+ function acquireAgentLock(agent, env = process.env, options = {}) {
5000
+ return acquireLease(agentLockPath(agent, env), { home: path7.resolve(agent.home), label: `@${normalizeHandle(agent.handle)}` }, options);
5001
+ }
5002
+ function agentLockRefusal(agent, holder, file) {
5003
+ const who = holder === null ? `another listener (its lock ${file} is being taken over right now)` : `${holder.home !== void 0 ? holder.home : "another identity home"} (pid ${holder.pid}${holder.host !== null ? ` on ${holder.host}` : ""}${holder.acquired_at !== void 0 ? `, since ${holder.acquired_at}` : ""})`;
5004
+ return `@${normalizeHandle(agent.handle)} is served by ${who}: this one (${path7.resolve(agent.home)}) holds no socket and starts no run while it does, so no message is answered twice. Stop that one, or log out here; this one takes over when it stops.`;
5005
+ }
5006
+ var STANDBY_MARKER_FRESH_MS = 9e4;
5007
+ function hostnameOf() {
5008
+ try {
5009
+ return os2.hostname();
5010
+ } catch {
5011
+ return "";
5012
+ }
5013
+ }
5014
+ function standbyMarkerPath(lockFile, home) {
5015
+ return `${lockFile}.standby-${crypto2.createHash("sha256").update(path7.resolve(home)).digest("hex").slice(0, 16)}`;
5016
+ }
5017
+ function markStandby(lockFile, home) {
5018
+ const file = standbyMarkerPath(lockFile, home);
5019
+ const content = `${process.pid}
5020
+ ${JSON.stringify({ pid: process.pid, host: hostnameOf(), home: path7.resolve(home), at: Date.now() })}
5021
+ `;
5022
+ try {
5023
+ fs6.mkdirSync(path7.dirname(file), { recursive: true, mode: 448 });
5024
+ const temp = `${file}.${crypto2.randomUUID()}`;
5025
+ fs6.writeFileSync(temp, content, { mode: 384 });
5026
+ fs6.renameSync(temp, file);
5027
+ } catch {
5028
+ }
5029
+ }
5030
+ function clearStandby(lockFile, home) {
5031
+ try {
5032
+ fs6.rmSync(standbyMarkerPath(lockFile, home), { force: true });
5033
+ } catch {
5034
+ }
5035
+ }
5036
+ function standbyWaiting(lockFile, home, now = Date.now()) {
5037
+ const own = standbyMarkerPath(lockFile, home);
5038
+ const prefix = `${path7.basename(lockFile)}.standby-`;
5039
+ let names;
5040
+ try {
5041
+ names = fs6.readdirSync(path7.dirname(lockFile));
5042
+ } catch {
5043
+ return false;
5044
+ }
5045
+ for (const name of names) {
5046
+ if (!name.startsWith(prefix) || name.includes(".", prefix.length)) continue;
5047
+ const file = path7.join(path7.dirname(lockFile), name);
5048
+ if (file === own) continue;
5049
+ try {
5050
+ const st = fs6.statSync(file);
5051
+ if (Math.abs(now - st.mtimeMs) >= STANDBY_MARKER_FRESH_MS) continue;
5052
+ const marker = parseLease(fs6.readFileSync(file, "utf-8"));
5053
+ if (marker === null) continue;
5054
+ const sameHost2 = marker.host === null || marker.host === hostnameOf();
5055
+ if (sameHost2 && !pidAlive(marker.pid)) continue;
5056
+ return true;
5057
+ } catch {
5058
+ continue;
5059
+ }
5060
+ }
5061
+ return false;
4700
5062
  }
4701
5063
 
4702
5064
  export {
@@ -4734,19 +5096,8 @@ export {
4734
5096
  syncManual,
4735
5097
  describeManualSync,
4736
5098
  checkManual,
4737
- RUN_PROFILES,
4738
- RUN_PROFILE_ENV,
4739
- DEFAULT_RUN_PROFILE,
4740
- isRunProfile,
4741
- resolveRunProfile,
4742
- INTEGRATION_ENV,
4743
- INTEGRATION_ENV_LEGACY,
4744
- INTEGRATION_ENV_LEGACY_REMOVAL,
4745
- integrationDisabledBy,
4746
- integrationDisabled,
4747
- RUN_BUDGET_ENV,
4748
- DEFAULT_RUN_BUDGET_MS,
4749
- resolveRunBudgetMs,
5099
+ identityLineOf,
5100
+ normalizeHandle,
4750
5101
  INTEGRATION_STATUS_FILE,
4751
5102
  LEGACY_STATUS_FILE,
4752
5103
  SOCKET_STATES,
@@ -4774,6 +5125,26 @@ export {
4774
5125
  idle,
4775
5126
  alwaysOnState,
4776
5127
  alwaysOnHealth,
4777
- acquireLeaderLock
5128
+ LEASE_RENEW_MS,
5129
+ LEASE_STALE_MS,
5130
+ bootedAt,
5131
+ pidAlive,
5132
+ parseLease,
5133
+ holderLive,
5134
+ acquireLease,
5135
+ leaseHolder,
5136
+ resetLeaseObservations,
5137
+ DAEMON_LOCK_FILE,
5138
+ acquireLeaderLock,
5139
+ AGENT_LOCK_DIR_ENV,
5140
+ agentLockDir,
5141
+ agentLockPath,
5142
+ acquireAgentLock,
5143
+ agentLockRefusal,
5144
+ STANDBY_MARKER_FRESH_MS,
5145
+ standbyMarkerPath,
5146
+ markStandby,
5147
+ clearStandby,
5148
+ standbyWaiting
4778
5149
  };
4779
- //# sourceMappingURL=chunk-7LAAAXUO.js.map
5150
+ //# sourceMappingURL=chunk-NAAHIK7Z.js.map