@agentchatme/agent-core 0.1.0 → 0.2.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.
@@ -603,8 +603,8 @@ function getErrorMap() {
603
603
 
604
604
  // node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js
605
605
  var makeIssue = (params) => {
606
- const { data, path: path6, errorMaps, issueData } = params;
607
- const fullPath = [...path6, ...issueData.path || []];
606
+ const { data, path: path7, errorMaps, issueData } = params;
607
+ const fullPath = [...path7, ...issueData.path || []];
608
608
  const fullIssue = {
609
609
  ...issueData,
610
610
  path: fullPath
@@ -720,11 +720,11 @@ var errorUtil;
720
720
 
721
721
  // node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js
722
722
  var ParseInputLazyPath = class {
723
- constructor(parent, value, path6, key) {
723
+ constructor(parent, value, path7, key) {
724
724
  this._cachedPath = [];
725
725
  this.parent = parent;
726
726
  this.data = value;
727
- this._path = path6;
727
+ this._path = path7;
728
728
  this._key = key;
729
729
  }
730
730
  get path() {
@@ -4258,96 +4258,16 @@ function clearPending(home) {
4258
4258
  }
4259
4259
  }
4260
4260
 
4261
- // src/version.ts
4262
- var VERSION = "0.1.0";
4263
-
4264
4261
  // src/client-identity.ts
4265
- var CODING_AGENTS_CLIENT_IDENTITY = {
4266
- name: "coding_agents",
4267
- version: VERSION
4268
- };
4269
- var CODING_AGENTS_CLIENT_HEADERS = {
4270
- "X-AgentChat-Client": CODING_AGENTS_CLIENT_IDENTITY.name,
4271
- "X-AgentChat-Client-Version": CODING_AGENTS_CLIENT_IDENTITY.version
4272
- };
4273
-
4274
- // src/wire/index.ts
4275
- var DEFAULT_TIMEOUT_MS = 6e3;
4276
- var WireError = class extends Error {
4277
- status;
4278
- constructor(status, detail) {
4279
- super(`AgentChat API ${status}: ${detail}`);
4280
- this.name = "WireError";
4281
- this.status = status;
4282
- }
4283
- };
4284
- async function wireRequest(cfg, method, pathname, body) {
4285
- const url = cfg.apiBase.replace(/\/+$/, "") + pathname;
4286
- const res = await fetch(url, {
4287
- method,
4288
- headers: {
4289
- ...CODING_AGENTS_CLIENT_HEADERS,
4290
- authorization: `Bearer ${cfg.apiKey}`,
4291
- accept: "application/json",
4292
- ...body !== void 0 ? { "content-type": "application/json" } : {}
4293
- },
4294
- ...body !== void 0 ? { body: JSON.stringify(body) } : {},
4295
- signal: AbortSignal.timeout(cfg.timeoutMs ?? DEFAULT_TIMEOUT_MS)
4296
- });
4297
- if (!res.ok) {
4298
- const text = await res.text().catch(() => "");
4299
- throw new WireError(res.status, text.slice(0, 300));
4300
- }
4301
- return res.json();
4302
- }
4303
- async function getMeLite(cfg) {
4304
- try {
4305
- const data = await wireRequest(cfg, "GET", "/v1/agents/me");
4306
- const parsed = external_exports.object({ handle: external_exports.string() }).passthrough().safeParse(data);
4307
- return parsed.success ? { handle: parsed.data.handle } : null;
4308
- } catch {
4309
- return null;
4310
- }
4262
+ function clientIdentityOf(client) {
4263
+ return { name: client.runtime, version: client.version };
4311
4264
  }
4312
- var INBOX_MAX_LIMIT = 50;
4313
- async function traySummary(cfg) {
4314
- const data = await wireRequest(cfg, "GET", `/v1/inbox?wait_ms=0&limit=${INBOX_MAX_LIMIT}`);
4315
- const parsed = external_exports.object({
4316
- conversations: external_exports.array(external_exports.unknown()).optional(),
4317
- deferred: external_exports.number().optional(),
4318
- truncated: external_exports.boolean().optional()
4319
- }).passthrough().safeParse(data);
4320
- if (!parsed.success) throw new WireError(200, "GET /v1/inbox: unexpected shape");
4265
+ function clientHeadersOf(client) {
4321
4266
  return {
4322
- waiting: parsed.data.conversations?.length ?? 0,
4323
- deferred: parsed.data.deferred ?? 0,
4324
- truncated: parsed.data.truncated === true
4267
+ "X-AgentChat-Client": client.runtime,
4268
+ "X-AgentChat-Client-Version": client.version
4325
4269
  };
4326
4270
  }
4327
- async function trayHasWaiting(cfg) {
4328
- const data = await wireRequest(cfg, "GET", "/v1/inbox?wait_ms=0&limit=1");
4329
- const parsed = external_exports.object({ conversations: external_exports.array(external_exports.unknown()).optional(), truncated: external_exports.boolean().optional() }).passthrough().safeParse(data);
4330
- if (!parsed.success) throw new WireError(200, "GET /v1/inbox: unexpected shape");
4331
- return (parsed.data.conversations?.length ?? 0) > 0 || parsed.data.truncated === true;
4332
- }
4333
- async function listGroupInvites(cfg) {
4334
- const data = await wireRequest(cfg, "GET", "/v1/groups/invites");
4335
- const parsed = external_exports.array(
4336
- external_exports.object({
4337
- id: external_exports.string(),
4338
- group_id: external_exports.string().nullable().optional(),
4339
- group_name: external_exports.string().nullable().optional(),
4340
- inviter_handle: external_exports.string().nullable().optional()
4341
- }).passthrough()
4342
- ).safeParse(data);
4343
- if (!parsed.success) throw new WireError(200, "GET /v1/groups/invites: unexpected shape");
4344
- return parsed.data.map((row) => ({
4345
- inviteId: row.id,
4346
- groupId: row.group_id ?? null,
4347
- groupName: row.group_name ?? null,
4348
- inviterHandle: row.inviter_handle ?? null
4349
- }));
4350
- }
4351
4271
 
4352
4272
  // src/daemon/health.ts
4353
4273
  import * as fs4 from "fs";
@@ -4444,13 +4364,35 @@ function alwaysOnHealth(home) {
4444
4364
  return { wanted: state !== "off", healthy: state !== "down" };
4445
4365
  }
4446
4366
 
4447
- // src/doorbell/status.ts
4367
+ // src/skill/identity-line.ts
4368
+ function identityLineOf(texts) {
4369
+ return texts.identity_line;
4370
+ }
4371
+ function normalizeHandle(handle) {
4372
+ return handle.trim().replace(/^@/, "").toLowerCase();
4373
+ }
4374
+
4375
+ // src/integration/prompts.ts
4376
+ function buildRunPrompts(texts, manualPointer) {
4377
+ return {
4378
+ wake: `${texts.wake_instruction}
4379
+
4380
+ ${manualPointer}`,
4381
+ invite: `${texts.invite_prompt}
4382
+
4383
+ ${manualPointer}`
4384
+ };
4385
+ }
4386
+
4387
+ // src/integration/status.ts
4448
4388
  import * as fs5 from "fs";
4449
4389
  import * as path5 from "path";
4450
- var DOORBELL_STATUS_FILE = "doorbell.status.json";
4451
- var SOCKET_STATES = ["off", "idle", "connecting", "ready", "reconnecting", "terminal", "closed"];
4390
+ var INTEGRATION_STATUS_FILE = "integration.status.json";
4391
+ var LEGACY_STATUS_FILE = "doorbell.status.json";
4392
+ var SOCKET_STATES = ["off", "idle", "connecting", "ready", "reconnecting", "blocked", "closed"];
4393
+ var LEGACY_BLOCKED_STATE = "terminal";
4452
4394
  var LastRunSchema = external_exports.object({
4453
- kind: external_exports.enum(["knock", "invite"]),
4395
+ kind: external_exports.enum(["wake", "invite", "knock"]),
4454
4396
  started_at: external_exports.string(),
4455
4397
  ended_at: external_exports.string(),
4456
4398
  state: external_exports.enum(["ok", "failed", "timed_out", "not_started"]),
@@ -4458,53 +4400,95 @@ var LastRunSchema = external_exports.object({
4458
4400
  duration_ms: external_exports.number(),
4459
4401
  detail: external_exports.string().nullable()
4460
4402
  });
4403
+ var TextsStatusSchema = external_exports.object({
4404
+ source: external_exports.enum(["server", "cache", "none"]),
4405
+ fetched_at: external_exports.string().nullable(),
4406
+ version: external_exports.string().nullable(),
4407
+ manual_version: external_exports.string().nullable()
4408
+ });
4461
4409
  var StatusSchema = external_exports.object({
4462
- version: external_exports.literal(1),
4410
+ version: external_exports.union([external_exports.literal(1), external_exports.literal(2)]),
4463
4411
  updated_at: external_exports.string(),
4464
4412
  pid: external_exports.number(),
4465
4413
  runtime: external_exports.string().nullable(),
4466
4414
  handle: external_exports.string().nullable(),
4467
4415
  profile: external_exports.string(),
4468
- socket: external_exports.enum(SOCKET_STATES),
4469
- /** null until the server answered the capability negotiation. */
4470
- ack_negotiated: external_exports.boolean().nullable(),
4471
- knocks: external_exports.number(),
4472
- knocks_absorbed: external_exports.number(),
4416
+ socket: external_exports.enum([...SOCKET_STATES, LEGACY_BLOCKED_STATE]),
4417
+ wakes: external_exports.number().optional(),
4418
+ wakes_absorbed: external_exports.number().optional(),
4419
+ knocks: external_exports.number().optional(),
4420
+ knocks_absorbed: external_exports.number().optional(),
4473
4421
  invites: external_exports.number(),
4474
4422
  runs_started: external_exports.number(),
4475
4423
  runs_ok: external_exports.number(),
4476
4424
  runs_failed: external_exports.number(),
4477
4425
  runs_timed_out: external_exports.number(),
4478
4426
  runs_not_started: external_exports.number(),
4479
- /** Knocks whose tray count came back empty, so no run started. Absent in files from older daemons. */
4480
4427
  runs_skipped_empty: external_exports.number().default(0),
4481
4428
  last_run: LastRunSchema.nullable(),
4482
4429
  retry_rung: external_exports.number(),
4483
4430
  retry_due_at: external_exports.string().nullable(),
4484
- last_error: external_exports.string().nullable()
4485
- });
4486
- function doorbellStatusPath(home) {
4487
- return path5.join(home, DOORBELL_STATUS_FILE);
4431
+ last_error: external_exports.string().nullable(),
4432
+ texts: TextsStatusSchema.nullable().default(null)
4433
+ }).passthrough();
4434
+ function normalize(raw) {
4435
+ const lastRun = raw.last_run === null ? null : { ...raw.last_run, kind: raw.last_run.kind === "knock" ? "wake" : raw.last_run.kind };
4436
+ return {
4437
+ version: 2,
4438
+ updated_at: raw.updated_at,
4439
+ pid: raw.pid,
4440
+ runtime: raw.runtime,
4441
+ handle: raw.handle,
4442
+ profile: raw.profile,
4443
+ socket: raw.socket === LEGACY_BLOCKED_STATE ? "blocked" : raw.socket,
4444
+ wakes: raw.wakes ?? raw.knocks ?? 0,
4445
+ wakes_absorbed: raw.wakes_absorbed ?? raw.knocks_absorbed ?? 0,
4446
+ invites: raw.invites,
4447
+ runs_started: raw.runs_started,
4448
+ runs_ok: raw.runs_ok,
4449
+ runs_failed: raw.runs_failed,
4450
+ runs_timed_out: raw.runs_timed_out,
4451
+ runs_not_started: raw.runs_not_started,
4452
+ runs_skipped_empty: raw.runs_skipped_empty,
4453
+ last_run: lastRun,
4454
+ retry_rung: raw.retry_rung,
4455
+ retry_due_at: raw.retry_due_at,
4456
+ last_error: raw.last_error,
4457
+ texts: raw.texts
4458
+ };
4488
4459
  }
4489
- function writeDoorbellStatus(home, status) {
4460
+ function integrationStatusPath(home) {
4461
+ return path5.join(home, INTEGRATION_STATUS_FILE);
4462
+ }
4463
+ function legacyStatusPath(home) {
4464
+ return path5.join(home, LEGACY_STATUS_FILE);
4465
+ }
4466
+ function writeIntegrationStatus(home, status) {
4490
4467
  try {
4491
- atomicWriteFile(doorbellStatusPath(home), `${JSON.stringify(status, null, 2)}
4468
+ atomicWriteFile(integrationStatusPath(home), `${JSON.stringify(status, null, 2)}
4492
4469
  `, 384);
4493
4470
  } catch (err) {
4494
- log.debug(`doorbell status write failed: ${String(err)}`);
4471
+ log.debug(`integration status write failed: ${String(err)}`);
4495
4472
  }
4496
4473
  }
4497
- function readDoorbellStatus(home) {
4498
- const parsed = StatusSchema.safeParse(readJsonFile(doorbellStatusPath(home)));
4499
- return parsed.success ? parsed.data : null;
4474
+ function readIntegrationStatus(home) {
4475
+ for (const file of [integrationStatusPath(home), legacyStatusPath(home)]) {
4476
+ const raw = readJsonFile(file);
4477
+ if (raw === null) continue;
4478
+ const parsed = StatusSchema.safeParse(raw);
4479
+ if (parsed.success) return normalize(parsed.data);
4480
+ }
4481
+ return null;
4500
4482
  }
4501
- function clearDoorbellStatus(home) {
4502
- try {
4503
- fs5.rmSync(doorbellStatusPath(home), { force: true });
4504
- } catch {
4483
+ function clearIntegrationStatus(home) {
4484
+ for (const file of [integrationStatusPath(home), legacyStatusPath(home)]) {
4485
+ try {
4486
+ fs5.rmSync(file, { force: true });
4487
+ } catch {
4488
+ }
4505
4489
  }
4506
4490
  }
4507
- function doorbellStatusAge(status, now = Date.now()) {
4491
+ function integrationStatusAge(status, now = Date.now()) {
4508
4492
  if (status === null) return null;
4509
4493
  const t = Date.parse(status.updated_at);
4510
4494
  return Number.isNaN(t) ? null : Math.max(0, now - t);
@@ -4516,15 +4500,24 @@ function ago(ms) {
4516
4500
  if (ms < 36 * 36e5) return `${Math.round(ms / 36e5)} hour(s) ago`;
4517
4501
  return `${Math.round(ms / 864e5)} day(s) ago`;
4518
4502
  }
4519
- function formatDoorbellStatus(status, now = Date.now()) {
4520
- if (status === null) return ["Doorbell: no status recorded yet (the daemon has not run, or is still starting)"];
4521
- const age = doorbellStatusAge(status, now);
4503
+ function textsLine(texts, now) {
4504
+ if (texts === null || texts.source === "none") {
4505
+ return " texts: not fetched yet (GET /v1/texts unreachable and nothing cached \u2014 a run waits for them)";
4506
+ }
4507
+ const fetched = texts.fetched_at === null ? "" : `, fetched ${ago(Math.max(0, now - Date.parse(texts.fetched_at)))}`;
4508
+ const versions = `${texts.version !== null ? `v${texts.version}` : "unversioned"}${texts.manual_version !== null ? `, manual ${texts.manual_version}` : ""}`;
4509
+ return texts.source === "server" ? ` texts: served (${versions}${fetched}; refreshed daily)` : ` texts: from the identity-home cache (${versions}${fetched}; the server has not answered since the daemon started)`;
4510
+ }
4511
+ function formatIntegrationStatus(status, now = Date.now()) {
4512
+ if (status === null) return ["Integration: no status recorded yet (the daemon has not run, or is still starting)"];
4513
+ const age = integrationStatusAge(status, now);
4522
4514
  const stale = age !== null && age > 3 * 6e4;
4523
4515
  const lines = [
4524
- `Doorbell: socket ${status.socket}${stale ? ` (status last written ${ago(age)} \u2014 the daemon may be down)` : ""}`,
4525
- ` ack capability: ${status.ack_negotiated === null ? "not negotiated yet" : status.ack_negotiated ? "negotiated (the server keeps envelopes stored until the agent decides; this daemon never acknowledges)" : "NOT echoed by the server (legacy server marks on send)"}`,
4526
- ` knocks: ${status.knocks} (${status.knocks_absorbed} absorbed into a pending run), invites: ${status.invites}`,
4527
- ` 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} knock(s) found the tray empty (no run)`,
4516
+ `Integration: socket ${status.socket}${stale ? ` (status last written ${ago(age)} \u2014 the daemon may be down)` : ""}`,
4517
+ " delivery: acknowledged on receipt by the SDK socket (delivered = this machine received it; read is the agent\u2019s own verdict inside its run)",
4518
+ ` wakes: ${status.wakes} (${status.wakes_absorbed} absorbed into a pending run), invites: ${status.invites}`,
4519
+ ` 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)`,
4520
+ textsLine(status.texts, now),
4528
4521
  ` profile: ${status.profile}${status.runtime ? ` (${status.runtime})` : ""}`
4529
4522
  ];
4530
4523
  if (status.last_run) {
@@ -4537,13 +4530,238 @@ function formatDoorbellStatus(status, now = Date.now()) {
4537
4530
  }
4538
4531
  if (status.retry_due_at) {
4539
4532
  const due = Date.parse(status.retry_due_at) - now;
4540
- lines.push(` retry: rung ${status.retry_rung}, next knock ${due > 0 ? `in ${Math.round(due / 1e3)} s` : "due"}`);
4533
+ lines.push(` retry: rung ${status.retry_rung}, next wake ${due > 0 ? `in ${Math.round(due / 1e3)} s` : "due"}`);
4541
4534
  }
4542
4535
  if (status.last_error) lines.push(` last error: ${status.last_error}`);
4543
4536
  return lines;
4544
4537
  }
4545
4538
 
4546
- // src/doorbell/profile.ts
4539
+ // src/integration/texts.ts
4540
+ import * as path6 from "path";
4541
+ import { AgentChatClient } from "agentchatme";
4542
+ var TEXTS_CACHE_FILE = "texts.json";
4543
+ var TEXTS_REFRESH_MS = 24 * 36e5;
4544
+ var TEXTS_RETRY_MS = 36e5;
4545
+ var FETCH_TIMEOUT_MS = 5e3;
4546
+ var TextsSchema = external_exports.object({
4547
+ version: external_exports.string(),
4548
+ manual: external_exports.object({ url: external_exports.string(), version: external_exports.string() }).passthrough(),
4549
+ wake_instruction: external_exports.string().min(1),
4550
+ invite_prompt: external_exports.string().min(1),
4551
+ identity_line: external_exports.string().min(1),
4552
+ identity_line_template: external_exports.string().min(1)
4553
+ }).passthrough();
4554
+ var CacheSchema = external_exports.object({
4555
+ version: external_exports.literal(1),
4556
+ fetched_at: external_exports.string(),
4557
+ runtime: external_exports.string(),
4558
+ texts: TextsSchema
4559
+ });
4560
+ function textsCachePath(home) {
4561
+ return path6.join(home, TEXTS_CACHE_FILE);
4562
+ }
4563
+ function readCachedTexts(home, runtime) {
4564
+ const parsed = CacheSchema.safeParse(readJsonFile(textsCachePath(home)));
4565
+ if (!parsed.success || parsed.data.runtime !== runtime) return null;
4566
+ return { fetched_at: parsed.data.fetched_at, runtime: parsed.data.runtime, texts: parsed.data.texts };
4567
+ }
4568
+ function writeCachedTexts(home, runtime, texts, fetchedAt) {
4569
+ try {
4570
+ atomicWriteFile(
4571
+ textsCachePath(home),
4572
+ `${JSON.stringify({ version: 1, fetched_at: fetchedAt.toISOString(), runtime, texts }, null, 2)}
4573
+ `,
4574
+ 384
4575
+ );
4576
+ } catch (err) {
4577
+ log.debug(`texts cache write failed: ${String(err)}`);
4578
+ }
4579
+ }
4580
+ async function loadTexts(options) {
4581
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
4582
+ try {
4583
+ const texts = await fetchTexts(options.client, options.runtime, options.timeoutMs);
4584
+ const fetchedAt = now();
4585
+ writeCachedTexts(options.home, options.runtime, texts, fetchedAt);
4586
+ return { texts, source: "server", fetched_at: fetchedAt.toISOString() };
4587
+ } catch (err) {
4588
+ const cached = readCachedTexts(options.home, options.runtime);
4589
+ log.debug(`GET /v1/texts failed (${describe(err)}) \u2014 ${cached ? "using the cached texts" : "nothing cached"}`);
4590
+ return cached === null ? null : { texts: cached.texts, source: "cache", fetched_at: cached.fetched_at };
4591
+ }
4592
+ }
4593
+ async function fetchIdentityLine(options) {
4594
+ const client = new AgentChatClient({
4595
+ apiKey: options.apiKey,
4596
+ baseUrl: options.apiBase,
4597
+ clientIdentity: clientIdentityOf(options.client),
4598
+ timeoutMs: options.timeoutMs ?? FETCH_TIMEOUT_MS,
4599
+ retry: { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 }
4600
+ });
4601
+ const loaded = await loadTexts({ home: options.home, runtime: options.client.runtime, client, ...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {} });
4602
+ return loaded === null ? null : loaded.texts.identity_line;
4603
+ }
4604
+ async function fetchTexts(client, runtime, timeoutMs = FETCH_TIMEOUT_MS) {
4605
+ const raw = await client.texts.get({ runtime, timeoutMs });
4606
+ const parsed = TextsSchema.safeParse(raw);
4607
+ if (!parsed.success) throw new Error("GET /v1/texts: unexpected shape");
4608
+ return parsed.data;
4609
+ }
4610
+ var TextsStore = class {
4611
+ runtime;
4612
+ home;
4613
+ client;
4614
+ refreshMs;
4615
+ retryMs;
4616
+ timeoutMs;
4617
+ onChange;
4618
+ now;
4619
+ _setTimeout;
4620
+ _clearTimeout;
4621
+ texts = null;
4622
+ _source = "none";
4623
+ _fetchedAt = null;
4624
+ inFlight = null;
4625
+ timer = null;
4626
+ stopped = false;
4627
+ lastFailure = null;
4628
+ serverSeen = false;
4629
+ constructor(options) {
4630
+ this.home = options.home;
4631
+ this.runtime = options.runtime;
4632
+ this.client = options.client;
4633
+ this.refreshMs = options.refreshMs ?? TEXTS_REFRESH_MS;
4634
+ this.retryMs = options.retryMs ?? TEXTS_RETRY_MS;
4635
+ this.timeoutMs = options.timeoutMs;
4636
+ this.onChange = options.onChange ?? (() => void 0);
4637
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
4638
+ this._setTimeout = options.setTimeout ?? ((fn, ms) => setTimeout(fn, ms));
4639
+ this._clearTimeout = options.clearTimeout ?? ((handle) => clearTimeout(handle));
4640
+ const cached = readCachedTexts(this.home, this.runtime);
4641
+ if (cached !== null) {
4642
+ this.texts = cached.texts;
4643
+ this._source = "cache";
4644
+ this._fetchedAt = cached.fetched_at;
4645
+ }
4646
+ }
4647
+ /** Where the current texts came from: the server (this process), the on-disk cache, or nowhere yet. */
4648
+ get source() {
4649
+ return this._source;
4650
+ }
4651
+ /** When the current texts were fetched from the server (by this process or the one that cached them). */
4652
+ get fetchedAt() {
4653
+ return this._fetchedAt;
4654
+ }
4655
+ /** The texts in hand, without a network call. */
4656
+ current() {
4657
+ return this.texts;
4658
+ }
4659
+ /**
4660
+ * The start-time fetch, then the refresh timer. Returns once the first
4661
+ * attempt has settled, so a run that starts right after `start()` has the
4662
+ * freshest text available; a failure is logged once and does not throw —
4663
+ * the daemon starts anyway, on the cache if there is one.
4664
+ */
4665
+ async start() {
4666
+ this.stopped = false;
4667
+ const ok = await this.refresh();
4668
+ if (!ok && this.texts === null) {
4669
+ log.warn(
4670
+ "GET /v1/texts did not answer and nothing is cached in the identity home \u2014 starting anyway; a run waits for the texts (fetched again on first use, then hourly)"
4671
+ );
4672
+ }
4673
+ }
4674
+ stop() {
4675
+ this.stopped = true;
4676
+ if (this.timer !== null) {
4677
+ this._clearTimeout(this.timer);
4678
+ this.timer = null;
4679
+ }
4680
+ }
4681
+ /**
4682
+ * Fetch now (coalescing a fetch already in flight), cache on success, arm
4683
+ * the next refresh either way. Resolves whether the server answered.
4684
+ */
4685
+ refresh() {
4686
+ if (this.inFlight !== null) return this.inFlight;
4687
+ this.inFlight = this.fetchOnce().finally(() => {
4688
+ this.inFlight = null;
4689
+ });
4690
+ return this.inFlight;
4691
+ }
4692
+ /**
4693
+ * The texts for a run: what is in hand, after one more fetch attempt if the
4694
+ * server has not answered yet in this process. Null only when the server is
4695
+ * unreachable and nothing was ever cached — the run then does not start and
4696
+ * the wake retries on the ladder.
4697
+ */
4698
+ async ensure() {
4699
+ if (!this.serverSeen && !this.stopped) await this.refresh();
4700
+ return this.texts;
4701
+ }
4702
+ async fetchOnce() {
4703
+ try {
4704
+ const texts = await fetchTexts(this.client, this.runtime, this.timeoutMs);
4705
+ if (this.stopped) return true;
4706
+ const fetchedAt = this.now();
4707
+ this.texts = texts;
4708
+ this._source = "server";
4709
+ this._fetchedAt = fetchedAt.toISOString();
4710
+ this.serverSeen = true;
4711
+ writeCachedTexts(this.home, this.runtime, texts, fetchedAt);
4712
+ if (this.lastFailure !== null) {
4713
+ log.info(`GET /v1/texts answered again (texts v${texts.version}, manual ${texts.manual.version})`);
4714
+ this.lastFailure = null;
4715
+ } else {
4716
+ log.info(`texts fetched for ${this.runtime} (texts v${texts.version}, manual ${texts.manual.version})`);
4717
+ }
4718
+ this.arm(this.refreshMs);
4719
+ this.onChange();
4720
+ return true;
4721
+ } catch (err) {
4722
+ if (this.stopped) return false;
4723
+ const message = describe(err);
4724
+ if (message !== this.lastFailure) {
4725
+ log.warn(
4726
+ `GET /v1/texts failed (${message}) \u2014 ${this.texts === null ? "no texts yet" : `keeping the ${this._source === "server" ? "last fetched" : "cached"} texts from ${this._fetchedAt ?? "?"}`}; retrying in ${Math.round(this.retryMs / 6e4)} min`
4727
+ );
4728
+ this.lastFailure = message;
4729
+ }
4730
+ this.arm(this.retryMs);
4731
+ this.onChange();
4732
+ return false;
4733
+ }
4734
+ }
4735
+ arm(ms) {
4736
+ if (this.stopped) return;
4737
+ if (this.timer !== null) this._clearTimeout(this.timer);
4738
+ this.timer = this._setTimeout(() => {
4739
+ this.timer = null;
4740
+ void this.refresh();
4741
+ }, ms);
4742
+ this.timer.unref?.();
4743
+ }
4744
+ };
4745
+ function describe(err) {
4746
+ return err instanceof Error ? err.message : String(err);
4747
+ }
4748
+
4749
+ // src/integration/tray.ts
4750
+ import { INBOX_TRAY_MAX_LIMIT } from "agentchatme";
4751
+ async function traySummary(client) {
4752
+ const tray = await client.inbox.tray({ limit: INBOX_TRAY_MAX_LIMIT });
4753
+ return {
4754
+ waiting: Array.isArray(tray.conversations) ? tray.conversations.length : 0,
4755
+ deferred: typeof tray.deferred === "number" ? tray.deferred : 0,
4756
+ truncated: tray.truncated === true
4757
+ };
4758
+ }
4759
+ async function trayHasWaiting(client) {
4760
+ const tray = await client.inbox.tray({ limit: 1 });
4761
+ return Array.isArray(tray.conversations) && tray.conversations.length > 0 || tray.truncated === true;
4762
+ }
4763
+
4764
+ // src/integration/profile.ts
4547
4765
  var RUN_PROFILES = ["answer", "work", "full"];
4548
4766
  var RUN_PROFILE_ENV = "AGENTCHAT_RUN_PROFILE";
4549
4767
  var DEFAULT_RUN_PROFILE = "answer";
@@ -4554,10 +4772,20 @@ function resolveRunProfile(env = process.env) {
4554
4772
  const raw = env[RUN_PROFILE_ENV]?.trim().toLowerCase();
4555
4773
  return isRunProfile(raw) ? raw : DEFAULT_RUN_PROFILE;
4556
4774
  }
4557
- var DOORBELL_ENV = "AGENTCHAT_DOORBELL";
4558
- function doorbellDisabled(env = process.env) {
4559
- const raw = env[DOORBELL_ENV]?.trim().toLowerCase();
4560
- return raw === "off" || raw === "0" || raw === "false";
4775
+ var INTEGRATION_ENV = "AGENTCHAT_INTEGRATION";
4776
+ var INTEGRATION_ENV_LEGACY = "AGENTCHAT_DOORBELL";
4777
+ function isOff(raw) {
4778
+ const value = raw?.trim().toLowerCase();
4779
+ return value === "off" || value === "0" || value === "false";
4780
+ }
4781
+ function integrationDisabledBy(env = process.env) {
4782
+ if (env[INTEGRATION_ENV] !== void 0 && env[INTEGRATION_ENV].trim().length > 0) {
4783
+ return isOff(env[INTEGRATION_ENV]) ? INTEGRATION_ENV : null;
4784
+ }
4785
+ return isOff(env[INTEGRATION_ENV_LEGACY]) ? INTEGRATION_ENV_LEGACY : null;
4786
+ }
4787
+ function integrationDisabled(env = process.env) {
4788
+ return integrationDisabledBy(env) !== null;
4561
4789
  }
4562
4790
  var RUN_BUDGET_ENV = "AGENTCHAT_RUN_BUDGET_MS";
4563
4791
  var DEFAULT_RUN_BUDGET_MS = 10 * 6e4;
@@ -4591,16 +4819,8 @@ export {
4591
4819
  readPending,
4592
4820
  writePending,
4593
4821
  clearPending,
4594
- VERSION,
4595
- CODING_AGENTS_CLIENT_IDENTITY,
4596
- CODING_AGENTS_CLIENT_HEADERS,
4597
- WireError,
4598
- wireRequest,
4599
- getMeLite,
4600
- INBOX_MAX_LIMIT,
4601
- traySummary,
4602
- trayHasWaiting,
4603
- listGroupInvites,
4822
+ clientIdentityOf,
4823
+ clientHeadersOf,
4604
4824
  HEARTBEAT_FILE,
4605
4825
  markAlwaysOnWanted,
4606
4826
  clearAlwaysOnWanted,
@@ -4615,25 +4835,42 @@ export {
4615
4835
  idle,
4616
4836
  alwaysOnState,
4617
4837
  alwaysOnHealth,
4618
- DOORBELL_STATUS_FILE,
4838
+ identityLineOf,
4839
+ normalizeHandle,
4840
+ buildRunPrompts,
4841
+ INTEGRATION_STATUS_FILE,
4842
+ LEGACY_STATUS_FILE,
4619
4843
  SOCKET_STATES,
4620
- doorbellStatusPath,
4621
- writeDoorbellStatus,
4622
- readDoorbellStatus,
4623
- clearDoorbellStatus,
4624
- doorbellStatusAge,
4625
- formatDoorbellStatus,
4844
+ integrationStatusPath,
4845
+ writeIntegrationStatus,
4846
+ readIntegrationStatus,
4847
+ clearIntegrationStatus,
4848
+ integrationStatusAge,
4849
+ formatIntegrationStatus,
4850
+ TEXTS_CACHE_FILE,
4851
+ TEXTS_REFRESH_MS,
4852
+ TEXTS_RETRY_MS,
4853
+ textsCachePath,
4854
+ readCachedTexts,
4855
+ writeCachedTexts,
4856
+ loadTexts,
4857
+ fetchIdentityLine,
4858
+ TextsStore,
4859
+ traySummary,
4860
+ trayHasWaiting,
4626
4861
  RUN_PROFILES,
4627
4862
  RUN_PROFILE_ENV,
4628
4863
  DEFAULT_RUN_PROFILE,
4629
4864
  isRunProfile,
4630
4865
  resolveRunProfile,
4631
- DOORBELL_ENV,
4632
- doorbellDisabled,
4866
+ INTEGRATION_ENV,
4867
+ INTEGRATION_ENV_LEGACY,
4868
+ integrationDisabledBy,
4869
+ integrationDisabled,
4633
4870
  RUN_BUDGET_ENV,
4634
4871
  DEFAULT_RUN_BUDGET_MS,
4635
4872
  resolveRunBudgetMs,
4636
4873
  spawnCommand,
4637
4874
  spawnCommandSync
4638
4875
  };
4639
- //# sourceMappingURL=chunk-I4U4A7HO.js.map
4876
+ //# sourceMappingURL=chunk-GXAX47O6.js.map