@sjawhar/claude-envoy 1.32.1 → 1.32.3

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.
@@ -39777,6 +39777,14 @@ function projectedToken(path) {
39777
39777
  };
39778
39778
  }
39779
39779
 
39780
+ // ../contracts/src/trailing-slash.ts
39781
+ function withoutTrailingSlashes(url) {
39782
+ let end = url.length;
39783
+ while (end > 0 && url[end - 1] === "/")
39784
+ end -= 1;
39785
+ return url.slice(0, end);
39786
+ }
39787
+
39780
39788
  // ../../node_modules/.bun/oauth4webapi@3.8.8/node_modules/oauth4webapi/build/index.js
39781
39789
  var USER_AGENT;
39782
39790
  if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) {
@@ -40867,12 +40875,6 @@ function statusOf(error) {
40867
40875
  }
40868
40876
  return 0;
40869
40877
  }
40870
- function withoutTrailingSlashes(url) {
40871
- let end = url.length;
40872
- while (end > 0 && url[end - 1] === "/")
40873
- end -= 1;
40874
- return url.slice(0, end);
40875
- }
40876
40878
 
40877
40879
  class BrokerTokenClient {
40878
40880
  #brokerUrl;
@@ -42518,7 +42520,7 @@ class DispatchClient {
42518
42520
  this.fetchImpl = fetchImpl;
42519
42521
  this.writeRetry = writeRetry;
42520
42522
  this.#credential = credential;
42521
- this.#baseUrl = baseUrl.replace(/\/+$/, "");
42523
+ this.#baseUrl = withoutTrailingSlashes(baseUrl);
42522
42524
  this.#signal = requestSignal(signal);
42523
42525
  this.#madeAt = this.#now();
42524
42526
  }
@@ -44255,2355 +44257,2219 @@ function streamStores(topic) {
44255
44257
  return STREAM_SUBJECT_PREFIXES.some((prefix) => topic.length > prefix.length && topic.startsWith(prefix));
44256
44258
  }
44257
44259
 
44258
- // ../envoy-client/src/envoy-config.ts
44259
- import {
44260
- chmodSync,
44261
- closeSync,
44262
- existsSync,
44263
- lstatSync,
44264
- mkdtempSync,
44265
- openSync,
44266
- readFileSync as readFileSync2,
44267
- readlinkSync,
44268
- rmSync,
44269
- statSync
44270
- } from "fs";
44271
- import { homedir, tmpdir } from "os";
44272
- import * as path from "path";
44273
-
44274
- // ../envoy-client/src/json-position.ts
44275
- function jsonErrorPosition(text) {
44276
- let at = 0;
44277
- const fail = () => {
44278
- throw new RangeError("not JSON");
44279
- };
44280
- const space = () => {
44281
- while (at < text.length && `
44282
- \r`.includes(text.charAt(at)))
44283
- at += 1;
44284
- };
44285
- const expect = (char) => {
44286
- if (text.charAt(at) !== char)
44287
- fail();
44288
- at += 1;
44289
- };
44290
- const string = () => {
44291
- expect('"');
44292
- while (at < text.length) {
44293
- const char = text.charAt(at);
44294
- if (char === '"') {
44295
- at += 1;
44296
- return;
44297
- }
44298
- if (char < " ")
44299
- fail();
44300
- at += char === "\\" ? 2 : 1;
44301
- }
44302
- fail();
44303
- };
44304
- const value = () => {
44305
- space();
44306
- const char = text.charAt(at);
44307
- if (char === "{" || char === "[") {
44308
- const close = char === "{" ? "}" : "]";
44309
- at += 1;
44310
- space();
44311
- if (text.charAt(at) === close) {
44312
- at += 1;
44313
- return;
44314
- }
44315
- for (;; ) {
44316
- if (close === "}") {
44317
- space();
44318
- string();
44319
- space();
44320
- expect(":");
44321
- }
44322
- value();
44323
- space();
44324
- if (text.charAt(at) === ",") {
44325
- at += 1;
44326
- continue;
44327
- }
44328
- expect(close);
44329
- return;
44330
- }
44331
- }
44332
- if (char === '"') {
44333
- string();
44334
- return;
44335
- }
44336
- for (const word of ["true", "false", "null"]) {
44337
- if (text.startsWith(word, at)) {
44338
- at += word.length;
44339
- return;
44340
- }
44341
- }
44342
- const number = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/.exec(text.slice(at));
44343
- if (number === null)
44344
- fail();
44345
- at += number?.[0].length ?? 0;
44346
- };
44347
- try {
44348
- value();
44349
- space();
44350
- if (at < text.length)
44351
- fail();
44352
- return;
44353
- } catch {
44354
- const before = text.slice(0, at).split(`
44355
- `);
44356
- return `line ${before.length}, column ${(before.at(-1)?.length ?? 0) + 1}`;
44357
- }
44260
+ // ../envoy-client/src/machine.ts
44261
+ import { hostname as hostname3 } from "os";
44262
+ function machineID() {
44263
+ return process.env["ENVOY_MACHINE_ID"] || process.env["AGENTBOX_HOST"] || hostname3();
44358
44264
  }
44359
44265
 
44360
- // ../envoy-client/src/secret-file.ts
44361
- import { readFileSync } from "fs";
44362
- function sendable(value) {
44363
- return !/[\s\p{Cc}]/u.test(value);
44266
+ // ../envoy-client/src/transport.ts
44267
+ var REPLAY_TIMEOUT_MS = 1e4;
44268
+ var REPLAY_UNAVAILABLE_CODE = "REPLAY_UNAVAILABLE";
44269
+ var SessionStateSchema = _enum2(["live", "unresponsive", "gone"]);
44270
+ var UNRESPONSIVE_RULE = "An unresponsive session is not dead: it keeps its role claims and its issue claims, and a " + "message sent to it is stored until it answers. Start no replacement for it and take no claim " + `from it until it is gone, or until ${ISSUE_CLAIM_UNRESPONSIVE_GRACE_MS / 60000} minutes ` + "have passed since its last_seen, the time of its last registration.";
44271
+ var WireStateSchema = SessionStateSchema.default("live");
44272
+ var InterestWireSchema = object({
44273
+ session_id: string2(),
44274
+ machine_id: string2(),
44275
+ dir: string2(),
44276
+ topics: array(string2()),
44277
+ updated_at: number2().int().optional(),
44278
+ warnings: array(string2()).optional()
44279
+ });
44280
+ var DeliveryAnswerWireSchema = discriminatedUnion("mode", [
44281
+ object({
44282
+ mode: literal("consumer"),
44283
+ subject: string2().min(1),
44284
+ stream_id: string2(),
44285
+ gap: boolean2(),
44286
+ consumer_start: number2().int().nonnegative().optional()
44287
+ }),
44288
+ object({ mode: literal("core"), reason: string2() })
44289
+ ]);
44290
+ var SessionWireSchema = object({
44291
+ session_id: string2(),
44292
+ machine_id: string2(),
44293
+ host: string2().optional(),
44294
+ dir: string2(),
44295
+ port: number2().int(),
44296
+ title: string2(),
44297
+ topics: array(string2()),
44298
+ roles: array(string2()).optional(),
44299
+ capabilities: array(string2()).optional(),
44300
+ self_subscribed: boolean2(),
44301
+ last_seen: number2().int().optional(),
44302
+ state: WireStateSchema,
44303
+ plugin: string2().optional(),
44304
+ plugin_version: string2().optional()
44305
+ });
44306
+ var RoleWireSchema = object({
44307
+ role: string2(),
44308
+ holder: string2(),
44309
+ host: string2().optional(),
44310
+ last_seen: number2().int(),
44311
+ state: WireStateSchema,
44312
+ holder_state: SessionStateSchema.optional(),
44313
+ client_instance_id: string2().optional(),
44314
+ handed_back: boolean2().optional()
44315
+ });
44316
+ var RoleHeldWireSchema = object({
44317
+ error: string2(),
44318
+ role: string2(),
44319
+ holder: string2()
44320
+ });
44321
+ var ErrorWireSchema = object({
44322
+ error: string2(),
44323
+ code: string2().optional(),
44324
+ expected: array(string2()).optional(),
44325
+ state: SessionStateSchema.optional(),
44326
+ holder: string2().optional(),
44327
+ holder_state: SessionStateSchema.optional(),
44328
+ last_seen: number2().int().optional(),
44329
+ claim_released: boolean2().optional(),
44330
+ unresponsive: array(string2()).optional()
44331
+ });
44332
+ var EnvelopeResponseSchema = EnvelopeSchema.extend({
44333
+ recipient: string2().optional(),
44334
+ holder: string2().optional(),
44335
+ holder_state: SessionStateSchema.optional(),
44336
+ recipient_state: SessionStateSchema.optional(),
44337
+ last_seen: number2().int().optional(),
44338
+ unresponsive: array(string2()).optional(),
44339
+ duplicate: boolean2().optional()
44340
+ });
44341
+ var PublishResponseSchema = EnvelopeResponseSchema.extend({
44342
+ kept: boolean2().optional(),
44343
+ kept_reason: _enum2(["unclaimed", "holder_lapsed"]).optional()
44344
+ });
44345
+ var ReplayWireSchema = object({
44346
+ stream: object({
44347
+ id: string2().min(1).optional(),
44348
+ created: string2(),
44349
+ first_seq: number2().int().nonnegative(),
44350
+ last_seq: number2().int().nonnegative()
44351
+ }),
44352
+ subjects: array(object({
44353
+ subject: string2(),
44354
+ messages: array(object({
44355
+ seq: number2().int().positive(),
44356
+ subject: string2(),
44357
+ time: string2(),
44358
+ data: string2()
44359
+ })),
44360
+ next_after: number2().int().nonnegative(),
44361
+ more: boolean2(),
44362
+ refused: string2().optional()
44363
+ }))
44364
+ });
44365
+ var DELIVERY_NOT_ANSWERED = "not_answered";
44366
+ var DELIVERY_UNREADABLE = "unreadable_answer";
44367
+ function parseSubscribeAnswer(body) {
44368
+ const interest = InterestWireSchema.parse(body);
44369
+ const raw = typeof body === "object" && body !== null && "delivery" in body ? body.delivery : undefined;
44370
+ if (raw === undefined || raw === null) {
44371
+ return { ...interest, delivery: { mode: "core", reason: DELIVERY_NOT_ANSWERED } };
44372
+ }
44373
+ const delivery = DeliveryAnswerWireSchema.safeParse(raw);
44374
+ return {
44375
+ ...interest,
44376
+ delivery: delivery.success ? delivery.data : { mode: "core", reason: DELIVERY_UNREADABLE }
44377
+ };
44364
44378
  }
44365
- function readSecretFile(variable, filePath) {
44366
- let contents;
44367
- try {
44368
- contents = readFileSync(filePath, "utf8");
44369
- } catch (error) {
44370
- throw new Error(`${variable} names ${filePath}, which could not be read: ${messageFor(error)}`);
44379
+ function mergeInterestSources(registryTopics, liveTopics) {
44380
+ const interests = new Map;
44381
+ for (const topic of registryTopics) {
44382
+ interests.set(topic, liveTopics.includes(topic) ? "both" : "registry");
44371
44383
  }
44372
- const value = contents.trim();
44373
- if (value.length === 0)
44374
- throw new Error(`${variable} names ${filePath}, which is empty`);
44375
- if (!sendable(value)) {
44376
- throw new Error(`${variable} names ${filePath}, which holds whitespace or a control character`);
44384
+ for (const topic of liveTopics) {
44385
+ if (!interests.has(topic))
44386
+ interests.set(topic, "live");
44377
44387
  }
44378
- return value;
44388
+ return interests;
44379
44389
  }
44380
-
44381
- // ../envoy-client/src/envoy-config.ts
44382
- var COMMAND_TIMEOUT_MS = 1e4;
44383
- function nonEmpty(value) {
44384
- return value === undefined || value === "" ? undefined : value;
44390
+ function holderStateOf(role) {
44391
+ return role.holder_state ?? role.state;
44385
44392
  }
44386
- function absolute(name, value) {
44387
- if (value !== undefined && !path.isAbsolute(value)) {
44388
- throw new Error(`${name} is ${value}, which is not an absolute path`);
44389
- }
44390
- return value;
44393
+ function namedProcess(id) {
44394
+ return id === "" ? undefined : id;
44391
44395
  }
44392
- function neutralConfig(env) {
44393
- const xdgConfigHome = nonEmpty(env.XDG_CONFIG_HOME);
44394
- if (xdgConfigHome !== undefined && !path.isAbsolute(xdgConfigHome)) {
44395
- return { error: `XDG_CONFIG_HOME is ${xdgConfigHome}, which is not an absolute path` };
44396
- }
44397
- const configHome = xdgConfigHome ?? path.join(nonEmpty(env.HOME) ?? homedir(), ".config");
44398
- return { path: path.resolve(configHome, "legion", "envoy.json") };
44396
+ function roleHeldBy(info, sessionID, clientInstanceID) {
44397
+ if (info === undefined || info.holder !== sessionID || info.handed_back === true)
44398
+ return false;
44399
+ const holding = namedProcess(info.client_instance_id);
44400
+ return holding === undefined || holding === namedProcess(clientInstanceID);
44399
44401
  }
44400
- var HARNESS_DIRECTORY_VARIABLE = {
44401
- omp: "PI_CODING_AGENT_DIR",
44402
- claude: "CLAUDE_CONFIG_DIR"
44403
- };
44404
- var PLUGIN_HARNESSES = Object.keys(HARNESS_DIRECTORY_VARIABLE);
44405
- function namedDirectory(harness, env) {
44406
- if (harness === "omp") {
44407
- const profile = nonEmpty(env.OMP_PROFILE);
44408
- if (profile === undefined || profile === "default")
44409
- return;
44410
- }
44411
- return nonEmpty(env[HARNESS_DIRECTORY_VARIABLE[harness]]);
44402
+ function mayActOnRoleRecord(writer, clientInstanceID, holdsRole) {
44403
+ const wrote = namedProcess(writer);
44404
+ if (wrote === undefined || wrote === namedProcess(clientInstanceID))
44405
+ return true;
44406
+ return !holdsRole;
44412
44407
  }
44413
- function harnessDirectory(harness, env) {
44414
- for (const plugin of harness === "command" ? PLUGIN_HARNESSES : [harness]) {
44415
- if (harness === "command" && plugin === "claude" && env.CLAUDE_CODE_CHILD_SESSION !== "1") {
44408
+ function newClientInstanceID() {
44409
+ return Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join("");
44410
+ }
44411
+ function expandSubscriptionTopics(topics) {
44412
+ const expanded = new Set;
44413
+ for (const topic of topics) {
44414
+ const base = topic.endsWith(".>") ? topic.slice(0, -2) : undefined;
44415
+ if (base === undefined || base.includes("*") || base.includes(">")) {
44416
+ expanded.add(topic);
44416
44417
  continue;
44417
44418
  }
44418
- const directory = namedDirectory(plugin, env);
44419
- if (directory !== undefined)
44420
- return absolute(HARNESS_DIRECTORY_VARIABLE[plugin], directory);
44419
+ const segments = base.split(".");
44420
+ if (segments.length < 2 || segments.some((segment) => segment.length === 0)) {
44421
+ throw new TypeError(`cannot expand Envoy wildcard topic "${topic}": its concrete base must have at least two non-empty segments`);
44422
+ }
44423
+ expanded.add(base);
44424
+ expanded.add(topic);
44421
44425
  }
44422
- return;
44423
- }
44424
- function handedConfigPath(env) {
44425
- const handed = nonEmpty(env.ENVOY_CONFIG_FILE);
44426
- return handed === undefined ? undefined : path.resolve(absolute("ENVOY_CONFIG_FILE", handed));
44427
- }
44428
- function envoyConfigPath(harness, env) {
44429
- const handedFirst = harness === "command" ? handedConfigPath(env) : undefined;
44430
- if (handedFirst !== undefined)
44431
- return handedFirst;
44432
- const directory = harnessDirectory(harness, env);
44433
- if (directory !== undefined)
44434
- return path.resolve(directory, "envoy.json");
44435
- const handed = handedConfigPath(env);
44436
- if (handed !== undefined)
44437
- return handed;
44438
- const neutral = neutralConfig(env);
44439
- if ("error" in neutral)
44440
- throw new Error(neutral.error);
44441
- return neutral.path;
44442
- }
44443
- var httpUrlSchema = url({ protocol: /^https?$/, error: "must be an http or https URL" });
44444
- var DispatchSectionSchema = strictObject({
44445
- enabled: boolean2().optional(),
44446
- serverUrl: httpUrlSchema.optional(),
44447
- token: string2().optional()
44448
- });
44449
- var EnvoySectionSchema = strictObject({
44450
- enabled: boolean2().optional(),
44451
- url: httpUrlSchema.optional(),
44452
- natsUrls: array(string2().trim().min(1, "must not be empty")).optional(),
44453
- token: string2().optional(),
44454
- natsSeed: string2().optional()
44455
- });
44456
- var EnvoyFileSchema = looseObject({
44457
- $schema: string2().optional(),
44458
- dispatch: DispatchSectionSchema.optional(),
44459
- envoy: EnvoySectionSchema.optional()
44460
- });
44461
- var CheckoutFileSchema = looseObject({
44462
- $schema: string2().optional(),
44463
- dispatch: DispatchSectionSchema.optional()
44464
- });
44465
- var AskgateSectionSchema = strictObject({ enabled: boolean2().optional() });
44466
- function offWithNotice(notice) {
44467
- return { enabled: false, notice, error: null };
44468
- }
44469
- function offWithError(error) {
44470
- return { enabled: false, notice: null, error };
44426
+ return [...expanded];
44471
44427
  }
44472
- function httpUrl2(value) {
44473
- let url2;
44474
- try {
44475
- url2 = new URL(value);
44476
- } catch {
44477
- return;
44428
+ function refusalStateText(parsed) {
44429
+ const sentences = [];
44430
+ const state = parsed.holder_state ?? parsed.state;
44431
+ if (state !== undefined) {
44432
+ const who = parsed.holder === undefined ? "That session" : `Holder ${parsed.holder}`;
44433
+ const seen = parsed.last_seen === undefined || parsed.last_seen <= 0 ? "" : `, last seen ${new Date(parsed.last_seen).toISOString()}`;
44434
+ sentences.push(`${who} is ${state}${seen}.`);
44478
44435
  }
44479
- return url2.protocol === "http:" || url2.protocol === "https:" ? url2 : undefined;
44480
- }
44481
- function describeSchemaIssue(filePath, error) {
44482
- const issue = error.issues[0];
44483
- if (!issue)
44484
- return `${filePath}: invalid envoy.json`;
44485
- if (issue.code === "unrecognized_keys") {
44486
- const section = issue.path.join(".");
44487
- const keys = issue.keys.map((key) => `${section}.${key}`).join(", ");
44488
- return `${filePath}: unrecognized ${section} key(s): ${keys}`;
44436
+ const stored = parsed.unresponsive ?? [];
44437
+ if (stored.length > 0) {
44438
+ const one = stored.length === 1;
44439
+ sentences.push(`Envoy stored the message for ${stored.join(", ")}.`, `${one ? "That session" : "Those sessions"} stopped answering, so ${one ? "it" : "they"} did not fail this send.`);
44489
44440
  }
44490
- return `${filePath}: ${issue.path.join(".")}: ${issue.message}`;
44441
+ if (sentences.length === 0)
44442
+ return "";
44443
+ if (state === "unresponsive" || stored.length > 0)
44444
+ sentences.push(UNRESPONSIVE_RULE);
44445
+ return ` ${sentences.join(" ")}`;
44491
44446
  }
44492
- function danglingLink(filePath) {
44493
- try {
44494
- return lstatSync(filePath).isSymbolicLink() ? readlinkSync(filePath) : null;
44495
- } catch {
44496
- return null;
44447
+
44448
+ class EnvoyApiError extends Error {
44449
+ details;
44450
+ name = "EnvoyApiError";
44451
+ expected;
44452
+ code;
44453
+ holder;
44454
+ sessionState;
44455
+ lastSeen;
44456
+ claimReleased;
44457
+ unresponsive;
44458
+ constructor(details) {
44459
+ let parsed;
44460
+ try {
44461
+ const result = ErrorWireSchema.safeParse(JSON.parse(details.responseBody));
44462
+ if (result.success)
44463
+ parsed = result.data;
44464
+ } catch {}
44465
+ super(parsed === undefined ? `${details.method} ${details.url} failed with ${details.status}: ${details.responseBody}` : `${parsed.error}${parsed.expected === undefined ? "" : ` (expected: ${parsed.expected.join(", ")})`}${refusalStateText(parsed)}`);
44466
+ this.details = details;
44467
+ this.expected = parsed?.expected;
44468
+ this.code = parsed?.code;
44469
+ this.holder = parsed?.holder;
44470
+ this.sessionState = parsed?.holder_state ?? parsed?.state;
44471
+ this.lastSeen = parsed?.last_seen;
44472
+ this.claimReleased = parsed?.claim_released;
44473
+ this.unresponsive = parsed?.unresponsive;
44497
44474
  }
44498
44475
  }
44499
- function parseFile(filePath, schema, checkout) {
44500
- let raw;
44501
- try {
44502
- raw = readFileSync2(filePath, "utf-8");
44503
- } catch (error) {
44504
- if (hasErrnoCode(error, "ENOENT") || hasErrnoCode(error, "ENOTDIR")) {
44505
- return { kind: "absent", link: danglingLink(filePath) };
44506
- }
44507
- return { kind: "invalid", reason: `${filePath}: could not be read (${messageFor(error)})` };
44508
- }
44509
- let parsedJson;
44510
- try {
44511
- parsedJson = JSON.parse(raw);
44512
- } catch {
44513
- const position = jsonErrorPosition(raw);
44514
- return {
44515
- kind: "invalid",
44516
- reason: `${filePath}: invalid JSON${position === undefined ? "" : ` at ${position}`}`
44517
- };
44518
- }
44519
- if (typeof parsedJson === "object" && parsedJson !== null && "natsUrls" in parsedJson) {
44520
- return {
44521
- kind: "invalid",
44522
- reason: checkout ? `${filePath}: the top-level natsUrls is not read, and a checkout's envoy.json holds only a dispatch section` : `${filePath}: the top-level natsUrls is not read; move it to envoy.natsUrls`
44523
- };
44524
- }
44525
- const parsed = schema.safeParse(parsedJson);
44526
- if (!parsed.success) {
44527
- return { kind: "invalid", reason: describeSchemaIssue(filePath, parsed.error) };
44476
+ var mintedDedupeKey2 = new RegExp(MINTED_DEDUPE_KEY_PATTERN);
44477
+
44478
+ class EnvoySendUnconfirmedError extends Error {
44479
+ targetSessionID;
44480
+ idempotencyKey;
44481
+ attempts;
44482
+ last;
44483
+ name = "EnvoySendUnconfirmedError";
44484
+ resendSafe;
44485
+ constructor(targetSessionID, idempotencyKey, attempts, last) {
44486
+ const got = last instanceof EnvoyApiError ? `the listener answered ${last.details.status} (${last.message})` : `the listener did not answer (${last instanceof Error ? last.message : String(last)})`;
44487
+ const tried = attempts === 1 ? "on its only attempt" : `on the last of ${attempts} attempts`;
44488
+ const resendSafe = mintedDedupeKey2.test(`agent.${targetSessionID.trim()}.${idempotencyKey}`);
44489
+ const resend = resendSafe ? `Sending it again with idempotency_key ${idempotencyKey} within ` + `${DELIVERY_DUPLICATE_WINDOW_MS / 3600000} hours is the safe resend: Envoy drops it as ` + "a repeat if the first copy arrived (a recipient that restarted in between can rarely " + "see it twice)." : `Envoy cannot recognise a resend under idempotency_key ${idempotencyKey} as a repeat ` + "(the key is not a lower-case UUID, or the session id holds a dot): ask the recipient " + "whether it arrived before sending it again.";
44490
+ super(`The send to ${targetSessionID} is not confirmed delivered: ${got} ${tried}. It may or may ` + `not have arrived. ${resend}`, { cause: last });
44491
+ this.targetSessionID = targetSessionID;
44492
+ this.idempotencyKey = idempotencyKey;
44493
+ this.attempts = attempts;
44494
+ this.last = last;
44495
+ this.resendSafe = resendSafe;
44528
44496
  }
44529
- return { kind: "valid", settings: parsed.data };
44530
44497
  }
44531
- var FAILURE_KEPT_MS = 60000;
44532
- var COMMAND_OUTCOMES = Symbol.for("legion.envoy-config.commands.v1");
44533
- var processGlobal = globalThis;
44534
- var commandOutcomes = processGlobal[COMMAND_OUTCOMES] ?? new Map;
44535
- processGlobal[COMMAND_OUTCOMES] = commandOutcomes;
44536
- function runCommand(command, env, cwd) {
44537
- const childEnv = {};
44538
- for (const [name, variable] of Object.entries(env)) {
44539
- if (variable !== undefined)
44540
- childEnv[name] = variable;
44541
- }
44542
- const directory = mkdtempSync(path.join(tmpdir(), "envoy-command-"));
44543
- try {
44544
- chmodSync(directory, 448);
44545
- const output = path.join(directory, "stdout");
44546
- const fd = openSync(output, "wx", 384);
44547
- let result;
44498
+ function resolveCallTiming(config) {
44499
+ return {
44500
+ timeoutMs: config.timeoutMs ?? LISTENER_CALL_TIMEOUT_MS,
44501
+ attempts: config.retry === false ? 1 : LISTENER_CALL_ATTEMPTS,
44502
+ retryDelayMs: LISTENER_CALL_RETRY_DELAY_MS
44503
+ };
44504
+ }
44505
+ function createEnvoyClient(config) {
44506
+ const baseUrl = withoutTrailingSlashes(config.baseUrl);
44507
+ const { timeoutMs, attempts, retryDelayMs } = resolveCallTiming(config);
44508
+ const credential = config.credential;
44509
+ const attemptOnce = async (url, init, deadlineMs, actingSession) => {
44510
+ let response;
44511
+ let unminted;
44548
44512
  try {
44549
- result = Bun.spawnSync(["/bin/sh", "-c", command], {
44550
- cwd,
44551
- env: childEnv,
44552
- stdin: "ignore",
44553
- stdout: fd,
44554
- stderr: "ignore",
44555
- timeout: COMMAND_TIMEOUT_MS,
44556
- detached: true
44513
+ const headers = new Headers(init.headers);
44514
+ let presented;
44515
+ try {
44516
+ const ready = credential?.headers(init.method ?? "GET", url, actingSession);
44517
+ presented = ready instanceof Promise ? await ready : ready;
44518
+ } catch (error) {
44519
+ unminted = error;
44520
+ }
44521
+ for (const [name, value] of Object.entries(presented ?? {}))
44522
+ headers.set(name, value);
44523
+ response = await config.fetch(url, {
44524
+ ...init,
44525
+ headers,
44526
+ signal: AbortSignal.timeout(deadlineMs)
44557
44527
  });
44558
44528
  } catch (error) {
44559
- return { failure: `could not start: ${messageFor(error)}`, timedOut: false };
44560
- } finally {
44561
- closeSync(fd);
44529
+ return { unanswered: error };
44562
44530
  }
44563
- try {
44564
- process.kill(-result.pid, "SIGKILL");
44565
- } catch {}
44566
- if (result.exitedDueToTimeout) {
44531
+ if (unminted !== undefined && (response.status === 401 || response.status === 403)) {
44567
44532
  return {
44568
- failure: `did not finish within ${COMMAND_TIMEOUT_MS / 1000} s, and does not run again in this process`,
44569
- timedOut: true
44533
+ unanswered: new Error(`${init.method ?? "GET"} ${url} answered ${response.status}, and this machine's Envoy credential could not be minted: ${messageFor(unminted)}`, { cause: unminted })
44570
44534
  };
44571
44535
  }
44572
- if (!result.success) {
44536
+ try {
44537
+ return { response, body: await response.text() };
44538
+ } catch (error) {
44539
+ if (response.status >= 400 && response.status < 500) {
44540
+ return { response, body: `(its body did not arrive: ${String(error)})` };
44541
+ }
44542
+ return { unanswered: error };
44543
+ }
44544
+ };
44545
+ const request = async (path, init, options = {}) => {
44546
+ const url = `${baseUrl}${path}`;
44547
+ const tries = options.retry === false ? 1 : attempts;
44548
+ for (let attempt = 0;attempt < tries; attempt += 1) {
44549
+ const outcome = await attemptOnce(url, init, options.timeoutMs ?? timeoutMs, options.actingSession);
44550
+ if ("unanswered" in outcome) {
44551
+ options.onUnanswered?.();
44552
+ if (attempt + 1 < tries) {
44553
+ await waitForRetry(retryDelayMs);
44554
+ continue;
44555
+ }
44556
+ throw outcome.unanswered;
44557
+ }
44558
+ const { response, body } = outcome;
44559
+ if (response.ok)
44560
+ return body;
44561
+ const error = new EnvoyApiError({
44562
+ method: init.method ?? "GET",
44563
+ url,
44564
+ status: response.status,
44565
+ responseBody: body
44566
+ });
44567
+ if (response.status >= 500) {
44568
+ options.onUnanswered?.();
44569
+ if (attempt + 1 < tries) {
44570
+ await waitForRetry(retryDelayMs);
44571
+ continue;
44572
+ }
44573
+ }
44574
+ throw error;
44575
+ }
44576
+ throw new Error("Envoy request exhausted retries");
44577
+ };
44578
+ const post = (path, body, options) => request(path, {
44579
+ method: "POST",
44580
+ headers: { "Content-Type": "application/json" },
44581
+ body: JSON.stringify(body)
44582
+ }, options);
44583
+ return {
44584
+ subscribe: async (input) => parseSubscribeAnswer(JSON.parse(await post("/v1/interests/subscribe", {
44585
+ session_id: input.sessionID,
44586
+ dir: input.directory,
44587
+ topics: expandSubscriptionTopics(input.topics),
44588
+ port: input.port,
44589
+ title: input.title,
44590
+ ...input.capabilities === undefined ? {} : { capabilities: input.capabilities },
44591
+ driving: input.driving,
44592
+ ...input.selfSubscribed === undefined ? {} : { self_subscribed: input.selfSubscribed },
44593
+ ...input.delivery === undefined ? {} : { delivery: input.delivery },
44594
+ ...input.clientInstanceID === undefined ? {} : { client_instance_id: input.clientInstanceID },
44595
+ host: machineID(),
44596
+ ...input.place === undefined ? {} : { tmux_place: input.place },
44597
+ plugin: input.plugin.name,
44598
+ plugin_version: input.plugin.version
44599
+ }, { actingSession: input.sessionID }))),
44600
+ unsubscribe: async (input) => {
44601
+ await post("/v1/interests/unsubscribe", {
44602
+ session_id: input.sessionID,
44603
+ topics: expandSubscriptionTopics(input.topics),
44604
+ ...input.clientInstanceID === undefined ? {} : { client_instance_id: input.clientInstanceID }
44605
+ }, { actingSession: input.sessionID });
44606
+ },
44607
+ getInterest: async (sessionID) => InterestWireSchema.parse(JSON.parse(await request(`/v1/interests/${sessionID}`, {}))),
44608
+ send: async (input) => {
44609
+ const idempotencyKey = input.idempotencyKey ?? crypto.randomUUID();
44610
+ let unanswered = false;
44611
+ let response;
44612
+ try {
44613
+ const answer = await post("/v1/messages/send", {
44614
+ source: input.source ?? "agent",
44615
+ ...sourceSession(input.sourceSessionID),
44616
+ target_session: input.targetSessionID,
44617
+ message: input.message,
44618
+ idempotency_key: idempotencyKey,
44619
+ ...messageMetadata(input)
44620
+ }, {
44621
+ onUnanswered: () => {
44622
+ unanswered = true;
44623
+ },
44624
+ ...input.sourceSessionID === undefined || input.sourceSessionID === "" ? {} : { actingSession: input.sourceSessionID }
44625
+ });
44626
+ response = EnvelopeResponseSchema.parse(JSON.parse(answer));
44627
+ } catch (error) {
44628
+ if (error instanceof EnvoyApiError && error.details.status < 500 && !unanswered) {
44629
+ throw error;
44630
+ }
44631
+ throw new EnvoySendUnconfirmedError(input.targetSessionID, idempotencyKey, attempts, error);
44632
+ }
44573
44633
  return {
44574
- failure: `exited with ${result.signalCode ?? `status ${result.exitCode}`}`,
44575
- timedOut: false
44634
+ envelope: response,
44635
+ recipient: response.recipient ?? input.targetSessionID,
44636
+ confirmed: response.recipient !== undefined,
44637
+ recipientState: response.recipient_state ?? "live",
44638
+ ...response.last_seen === undefined || response.last_seen <= 0 ? {} : { lastSeen: response.last_seen },
44639
+ duplicate: response.duplicate === true
44576
44640
  };
44577
- }
44578
- const value = readFileSync2(output, "utf-8").trim();
44579
- if (value.length === 0)
44580
- return { failure: "printed nothing", timedOut: false };
44581
- if (!sendable(value)) {
44641
+ },
44642
+ publish: async (input) => {
44643
+ const idempotencyKey = input.idempotencyKey ?? crypto.randomUUID();
44644
+ const response = PublishResponseSchema.parse(JSON.parse(await post("/v1/messages/publish", {
44645
+ source: input.source ?? "agent",
44646
+ ...sourceSession(input.sourceSessionID),
44647
+ topic: input.topic,
44648
+ message: input.message,
44649
+ ...input.payload === undefined ? {} : { payload: input.payload },
44650
+ idempotency_key: idempotencyKey,
44651
+ ...messageMetadata(input),
44652
+ ...input.keep === undefined ? {} : { keep: input.keep }
44653
+ }, input.sourceSessionID === undefined || input.sourceSessionID === "" ? {} : { actingSession: input.sourceSessionID })));
44582
44654
  return {
44583
- failure: "printed more than one line, or whitespace inside its value",
44584
- timedOut: false
44655
+ envelope: response,
44656
+ ...response.holder === undefined ? {} : { holder: response.holder },
44657
+ ...response.holder_state === undefined ? {} : { holderState: response.holder_state },
44658
+ unresponsive: response.unresponsive ?? [],
44659
+ ...response.kept === undefined ? {} : { kept: response.kept },
44660
+ ...response.kept_reason === undefined ? {} : { keptReason: response.kept_reason }
44585
44661
  };
44586
- }
44587
- return { value };
44588
- } finally {
44589
- rmSync(directory, { recursive: true, force: true });
44590
- }
44662
+ },
44663
+ unregisterSession: async (input) => {
44664
+ const query = input.clientInstanceID === undefined ? "" : `?client_instance_id=${encodeURIComponent(input.clientInstanceID)}`;
44665
+ await request(`/v1/sessions/${encodeURIComponent(input.sessionID)}${query}`, { method: "DELETE" }, { actingSession: input.sessionID });
44666
+ },
44667
+ setRole: async (input) => {
44668
+ const soft = input.soft === true;
44669
+ const previous = soft ? input.previousSessionID ?? "" : "";
44670
+ const body = {
44671
+ session_id: input.sessionID,
44672
+ role: input.role,
44673
+ ...soft ? { soft: true } : {},
44674
+ ...previous === "" ? {} : { previous_session_id: previous },
44675
+ ...input.clientInstanceID === undefined ? {} : { client_instance_id: input.clientInstanceID }
44676
+ };
44677
+ let raw;
44678
+ try {
44679
+ raw = await post("/v1/roles/set", body, { actingSession: input.sessionID });
44680
+ } catch (error) {
44681
+ if (error instanceof EnvoyApiError && error.details.status === 409) {
44682
+ let answer;
44683
+ try {
44684
+ answer = JSON.parse(error.details.responseBody);
44685
+ } catch {
44686
+ throw error;
44687
+ }
44688
+ const held = RoleHeldWireSchema.safeParse(answer);
44689
+ if (held.success)
44690
+ return { claimed: false, holder: held.data.holder };
44691
+ }
44692
+ throw error;
44693
+ }
44694
+ return { claimed: true, interest: InterestWireSchema.parse(JSON.parse(raw)) };
44695
+ },
44696
+ getRole: async (role) => RoleWireSchema.parse(JSON.parse(await request(`/v1/roles/${encodeURIComponent(role)}`, { method: "GET" }))),
44697
+ listSessions: async (input = {}) => {
44698
+ const search = new URLSearchParams;
44699
+ if (input.directory !== undefined)
44700
+ search.set("dir", input.directory);
44701
+ if (input.title !== undefined)
44702
+ search.set("title", input.title);
44703
+ if (input.include !== undefined)
44704
+ search.set("include", input.include);
44705
+ const query = search.size === 0 ? "" : `?${search.toString()}`;
44706
+ return SessionWireSchema.array().parse(JSON.parse(await request(`/v1/sessions${query}`, {})));
44707
+ },
44708
+ replay: async (input) => ReplayWireSchema.parse(JSON.parse(await post("/v1/replay", {
44709
+ session_id: input.sessionID,
44710
+ subjects: input.subjects.map((cursor) => cursor.after === undefined ? { subject: cursor.subject } : { subject: cursor.subject, after: cursor.after }),
44711
+ ...input.maxMessages === undefined ? {} : { max_messages: input.maxMessages }
44712
+ }, {
44713
+ timeoutMs: input.timeoutMs ?? REPLAY_TIMEOUT_MS,
44714
+ retry: false,
44715
+ actingSession: input.sessionID
44716
+ })))
44717
+ };
44591
44718
  }
44592
- function fileValue(value, field, filePath, env, commands = "run") {
44593
- if (!value.startsWith("!")) {
44594
- if (!sendable(value)) {
44595
- throw new Error(`${filePath}: ${field} holds whitespace or a control character`);
44596
- }
44597
- return value;
44598
- }
44599
- const command = value.slice(1);
44600
- const cwd = path.dirname(path.resolve(filePath));
44601
- const key = JSON.stringify([command, filePath, cwd]);
44602
- let outcome = commandOutcomes.get(key);
44603
- if (commands === "kept") {
44604
- if (outcome === undefined) {
44605
- throw new Error(`${filePath}: ${field}'s command has not run in this process yet, and this read does not run it`);
44606
- }
44607
- } else if (outcome === undefined || "failure" in outcome && !outcome.timedOut && Date.now() - outcome.at >= FAILURE_KEPT_MS) {
44608
- outcome = { ...runCommand(command, env, cwd), at: Date.now() };
44609
- commandOutcomes.set(key, outcome);
44610
- }
44611
- if ("failure" in outcome)
44612
- throw new Error(`${filePath}: ${field}'s command ${outcome.failure}`);
44613
- return outcome.value;
44719
+ function waitForRetry(delayMs) {
44720
+ const { promise, resolve } = Promise.withResolvers();
44721
+ setTimeout(resolve, delayMs);
44722
+ return promise;
44614
44723
  }
44615
- function statDevice(directory) {
44616
- try {
44617
- return statSync(directory).dev;
44618
- } catch {
44619
- return;
44620
- }
44621
- }
44622
- function moveNotice(oldFile, newFile, move, deviceOf) {
44623
- const oldDevice = deviceOf(path.dirname(oldFile));
44624
- let ancestor = path.dirname(newFile);
44625
- let newDevice = deviceOf(ancestor);
44626
- while (newDevice === undefined && path.dirname(ancestor) !== ancestor) {
44627
- ancestor = path.dirname(ancestor);
44628
- newDevice = deviceOf(ancestor);
44629
- }
44630
- if (oldDevice !== undefined && newDevice !== undefined && oldDevice !== newDevice) {
44631
- return `${oldFile} is not read, and is on another filesystem than ${newFile} (a mount): create ${newFile}, and move ${oldFile} on the machine that owns it`;
44632
- }
44633
- return `${oldFile} is not read: ${move}`;
44634
- }
44635
- function oldUserFileNotice(filePath, env, deviceOf) {
44636
- const home = nonEmpty(env.HOME) ?? homedir();
44637
- const old = path.join(home, ".config", "opencode", "envoy.json");
44638
- if (!existsSync(old))
44639
- return;
44640
- const selected = path.resolve(filePath);
44641
- const userFile = path.resolve(home, ".config", "legion", "envoy.json");
44642
- if (selected === userFile) {
44643
- return moveNotice(old, userFile, "mkdir -p ~/.config/legion && mv ~/.config/opencode/envoy.json ~/.config/legion/", deviceOf);
44644
- }
44645
- const profileFile = PLUGIN_HARNESSES.map((harness) => namedDirectory(harness, env)).some((directory) => directory !== undefined && path.isAbsolute(directory) && selected === path.resolve(directory, "envoy.json"));
44646
- if (profileFile) {
44647
- return `${old} is not read for this profile; copy or link it to ${filePath}, or write that file`;
44648
- }
44649
- const configHome = nonEmpty(env.XDG_CONFIG_HOME);
44650
- const neutral = neutralConfig(env);
44651
- if (configHome !== undefined && path.isAbsolute(configHome) && "path" in neutral && selected === neutral.path) {
44652
- return `${old} is not read under XDG_CONFIG_HOME=${configHome}`;
44653
- }
44654
- return;
44655
- }
44656
- function missingConfigNotice(filePath, missing, off) {
44657
- const link = missing.link === null ? "" : ` (a link to ${missing.link}, which does not exist)`;
44658
- const old = missing.oldUserFileNotice === undefined ? "" : `; ${missing.oldUserFileNotice}`;
44659
- return `no envoy.json at ${filePath}${link}: ${off}${old}`;
44660
- }
44661
- function readEnvoyConfig(filePath, env, options) {
44662
- const deviceOf = options.deviceOf ?? statDevice;
44663
- const chosen = parseFile(filePath, EnvoyFileSchema, false);
44664
- if (chosen.kind === "invalid")
44665
- return { kind: "failed", path: filePath, error: chosen.reason };
44666
- const resolvedChosen = path.resolve(filePath);
44667
- const checkoutPath = path.resolve(options.cwd, ".envoy", "envoy.json");
44668
- const checkoutFile = checkoutPath === resolvedChosen ? { kind: "absent", link: null } : parseFile(checkoutPath, CheckoutFileSchema, true);
44669
- const own = chosen.kind === "valid" ? chosen.settings : {};
44670
- let checkout = null;
44671
- if (checkoutFile.kind === "invalid") {
44672
- checkout = { kind: "invalid", path: checkoutPath, error: checkoutFile.reason };
44673
- } else if (checkoutFile.kind === "valid") {
44674
- checkout = {
44675
- kind: "valid",
44676
- path: checkoutPath,
44677
- dispatch: checkoutFile.settings.dispatch ?? {},
44678
- envoyError: Object.hasOwn(checkoutFile.settings, "envoy") ? `${checkoutPath}: envoy is not read from a checkout's envoy.json; put it in ${filePath}` : null,
44679
- askgateError: Object.hasOwn(checkoutFile.settings, "askgate") ? `askgate in ${checkoutPath} is not read; set it in ${filePath}` : null
44680
- };
44681
- }
44682
- const oldCheckout = path.resolve(options.cwd, ".opencode", "envoy.json");
44683
- const warnings = oldCheckout !== resolvedChosen && !existsSync(checkoutPath) && existsSync(oldCheckout) ? [
44684
- moveNotice(oldCheckout, checkoutPath, `mkdir -p ${path.dirname(checkoutPath)} && mv ${oldCheckout} ${checkoutPath}`, deviceOf)
44685
- ] : [];
44686
- const unreadOldUserFile = chosen.kind === "absent" ? oldUserFileNotice(filePath, env, deviceOf) : undefined;
44687
- return {
44688
- kind: "read",
44689
- path: filePath,
44690
- dispatch: own.dispatch ?? {},
44691
- envoy: own.envoy ?? {},
44692
- checkout,
44693
- missing: chosen.kind === "absent" ? {
44694
- link: chosen.link,
44695
- ...unreadOldUserFile === undefined ? {} : { oldUserFileNotice: unreadOldUserFile }
44696
- } : null,
44697
- warnings
44698
- };
44699
- }
44700
-
44701
- // ../envoy-client/src/bearer.ts
44702
- function bearerCredential(token) {
44724
+ function messageMetadata(input) {
44703
44725
  return {
44704
- scheme: "Bearer",
44705
- headers: () => ({ Authorization: `Bearer ${token}` }),
44706
- secret: () => token
44726
+ ...input.inReplyTo === undefined ? {} : { in_reply_to: input.inReplyTo },
44727
+ ...input.supersedes === undefined ? {} : { supersedes: input.supersedes },
44728
+ ...input.urgency === undefined ? {} : { urgency: input.urgency },
44729
+ ...input.expectsReply === undefined ? {} : { expects_reply: input.expectsReply },
44730
+ ...input.expiresAt === undefined ? {} : { expires_at: input.expiresAt }
44707
44731
  };
44708
44732
  }
44709
- function bearerSource(env, section, written) {
44710
- const pointer = nonEmpty(env[`${section}_TOKEN_FILE`]);
44711
- if (pointer !== undefined) {
44712
- return { kind: "variable", token: readSecretFile(`${section}_TOKEN_FILE`, pointer) };
44713
- }
44714
- const plain = nonEmpty(env[`${section}_TOKEN`]);
44715
- if (plain !== undefined) {
44716
- if (!sendable(plain)) {
44717
- throw new Error(`${section}_TOKEN holds whitespace or a control character`);
44718
- }
44719
- return { kind: "variable", token: plain };
44720
- }
44721
- const bearer = written();
44722
- return bearer === undefined ? { kind: "none" } : { kind: "file", ...bearer };
44723
- }
44724
- function fileBearer(bearer, url, section, env, commands = "run") {
44725
- const named = httpUrl2(url)?.origin;
44726
- const paired = httpUrl2(bearer.server)?.origin;
44727
- if (named !== paired) {
44728
- throw new Error(`${section}_URL names ${named}, but ${bearer.path}'s ${bearer.field} is for ${paired}; set ${section}_TOKEN or ${section}_TOKEN_FILE for it`);
44729
- }
44730
- if (bearer.checkout && bearer.token.startsWith("!")) {
44731
- throw new Error(`${bearer.path}: ${bearer.field} is a command, which a checkout's envoy.json cannot run`);
44732
- }
44733
- if (bearer.token === "") {
44734
- throw new Error(`${bearer.field} in ${bearer.path} must be a non-empty bearer token`);
44735
- }
44736
- return fileValue(bearer.token, bearer.field, bearer.path, env, commands);
44733
+ function sourceSession(sessionID) {
44734
+ return sessionID === undefined || sessionID === "" ? {} : { source_session: sessionID };
44737
44735
  }
44738
44736
 
44739
- // ../envoy-client/src/envoy-settings.ts
44740
- var DEFAULT_ENVOY_URL = "http://127.0.0.1:9020";
44741
- var DEFAULT_HEARTBEAT_MS = SESSION_HEARTBEAT_MS;
44742
- var MIN_PASS_DEADLINE_MS = 30000;
44743
- var DEFAULT_TMUX_PLACE_CACHE_MS = 30000;
44744
- var MIN_INTERVAL_MS = 25;
44745
- var MAX_INTERVAL_MS = 2147483647;
44746
- var REGISTRATION_SETTLE_MS = 5000;
44747
- var SHUTDOWN_SETTLE_MS = 250;
44748
- var HEARTBEAT_RETRY_MIN_MS = 20000;
44749
- var HEARTBEAT_RETRY_MAX_MS = 40000;
44750
- function heartbeatRetryDelayMs(draw = Math.random) {
44751
- return Math.round(HEARTBEAT_RETRY_MIN_MS + draw() * (HEARTBEAT_RETRY_MAX_MS - HEARTBEAT_RETRY_MIN_MS));
44752
- }
44753
- function namedInterval(raw) {
44754
- const parsed = Number(raw);
44755
- return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
44756
- }
44757
- function resolvedInterval(raw, fallback) {
44758
- const named = namedInterval(raw);
44759
- return named === undefined ? fallback : Math.min(Math.max(named, MIN_INTERVAL_MS), MAX_INTERVAL_MS);
44760
- }
44761
- function natsSeedFromEnvironment(env) {
44762
- const { NATS_NKEY_SEED_FILE: file, NATS_NKEY_SEED: plain } = env;
44763
- if (file !== undefined) {
44764
- if (file === "")
44765
- throw new Error("NATS_NKEY_SEED_FILE is set but empty");
44766
- return {
44767
- value: readSecretFile("NATS_NKEY_SEED_FILE", file),
44768
- source: `NATS_NKEY_SEED_FILE (${file})`
44769
- };
44770
- }
44771
- if (plain === undefined)
44772
- return;
44773
- const value = plain.trim();
44774
- if (value.length === 0)
44775
- throw new Error("NATS_NKEY_SEED is set but empty");
44776
- return { value, source: "NATS_NKEY_SEED" };
44777
- }
44778
- var NO_NATS_SERVER = "Envoy has no NATS server (envoy.natsUrls, ENVOY_NATS_URL)";
44779
- var NO_NATS_CONNECTION = "this session opens no NATS connection";
44780
- function natsServerKey(url) {
44781
- const match = /^([a-z][a-z0-9+.-]*):\/\/([^@/]*@)?(\[[^\]]*\]|[^:/]*)(?::(\d+))?(\/.*)?$/i.exec(url);
44782
- if (match === null)
44783
- return url;
44784
- const [, scheme = "", userinfo = "", host = "", port = "4222", rest = ""] = match;
44785
- return `${scheme.toLowerCase()}://${userinfo}${host.toLowerCase()}:${port}${rest.replace(/\/+$/, "")}`;
44786
- }
44787
- function natsCredential(env, section, namedNatsUrls, filePath) {
44788
- const fromEnvironment = natsSeedFromEnvironment(env);
44789
- if (fromEnvironment !== undefined || section.natsSeed === undefined)
44790
- return fromEnvironment;
44791
- if (namedNatsUrls.length > 0) {
44792
- const servers = new Set((section.natsUrls ?? []).map(natsServerKey));
44793
- const named = new Set(namedNatsUrls.map(natsServerKey));
44794
- if (named.size !== servers.size || ![...named].every((server) => servers.has(server))) {
44795
- throw new Error(`ENVOY_NATS_URL names other servers than ${filePath}'s envoy.natsUrls; set NATS_NKEY_SEED_FILE for them`);
44737
+ // ../envoy-client/src/replay.ts
44738
+ var REPLAY_LEDGER_TTL_MS = DELIVERY_DUPLICATE_WINDOW_MS;
44739
+ var REPLAY_LEDGER_LIMIT = 20000;
44740
+ var REPLAY_PAGES_PER_SWEEP = 20;
44741
+ var REPLAY_FAILURES_BEFORE_NOTICE = 3;
44742
+ var REPLAY_STATE_REFRESH_MS = 60 * 60 * 1000;
44743
+ var REPLAY_MAX_SUBJECTS = 32;
44744
+ var START_CURSORS_TIMEOUT_MS = 2000;
44745
+ var ROLE_FORWARD_KEY_PREFIX = "envoy.role.forward.";
44746
+ var ReplayLedgerEntrySchema = object({
44747
+ event_id: string2().min(1).optional(),
44748
+ dedupe_key: string2().min(1).optional(),
44749
+ at: number2()
44750
+ });
44751
+ var ReplayCursorSchema = object({
44752
+ since: number2().int().nonnegative().optional(),
44753
+ after: number2().int().nonnegative().optional(),
44754
+ from_start: number2().int().nonnegative().optional()
44755
+ });
44756
+ var ReplayPendingNoticeSchema = _enum2([
44757
+ "retention_gap",
44758
+ "stream_moved_back",
44759
+ "stream_recreated"
44760
+ ]);
44761
+ var PENDING_NOTICE_MESSAGES = {
44762
+ stream_recreated: "Envoy's notification stream was recreated, so messages published to this session while its connection was down before that may be lost.",
44763
+ stream_moved_back: "Envoy's notification stream was restored to an earlier point, so messages published to this session while its connection was down may be shown again, and any published between that point and the restore are missing.",
44764
+ retention_gap: "The notification stream no longer holds some messages published to this session while its connection was down: messages older than 72 hours may be missing."
44765
+ };
44766
+ var ReplayStateSchema = object({
44767
+ stream_id: string2().optional(),
44768
+ stream_created: string2().optional(),
44769
+ subjects: record(string2(), ReplayCursorSchema),
44770
+ notices: array(string2()).optional()
44771
+ });
44772
+ var ReplaySnapshotSchema = object({
44773
+ state: ReplayStateSchema.optional(),
44774
+ ledger: array(ReplayLedgerEntrySchema)
44775
+ });
44776
+ function createReplayEngine(options) {
44777
+ const { host, transport, dedupe } = options;
44778
+ const now = options.now ?? Date.now;
44779
+ const ledger = createLedger(now);
44780
+ const cursors = new Map;
44781
+ const cursorStarts = new Map;
44782
+ let streamID;
44783
+ let streamCreated;
44784
+ const pending = new Set;
44785
+ const failures = new Map;
44786
+ let unwritten = [];
44787
+ let writtenState;
44788
+ let writtenShape;
44789
+ let writtenAt;
44790
+ let writes = Promise.resolve();
44791
+ let epoch = 0;
44792
+ let listenerNoticed;
44793
+ const answered = new Set;
44794
+ let running;
44795
+ let rerun;
44796
+ let consumerMode = false;
44797
+ const safely = (what, call) => {
44798
+ try {
44799
+ call();
44800
+ } catch (error) {
44801
+ try {
44802
+ host.log(`replay: ${what} failed`, error);
44803
+ } catch {}
44796
44804
  }
44797
- }
44798
- return {
44799
- value: fileValue(section.natsSeed, "envoy.natsSeed", filePath, env),
44800
- source: `envoy.natsSeed in ${filePath}`
44801
44805
  };
44802
- }
44803
- function envoySettings(env, config, options = {}) {
44804
- if (config.kind === "failed")
44805
- return offWithError(config.error);
44806
- const section = config.envoy;
44807
- if (section.enabled === false) {
44808
- return offWithNotice(`${config.path} sets envoy.enabled to false: Envoy is off`);
44809
- }
44810
- const namedUrl = nonEmpty(env.ENVOY_URL);
44811
- const namedNatsUrls = (env.ENVOY_NATS_URL ?? "").split(",").map((url) => url.trim()).filter((url) => url.length > 0);
44812
- const addressed = namedUrl !== undefined || namedNatsUrls.length > 0 || section.url !== undefined || (section.natsUrls ?? []).length > 0 || section.enabled === true;
44813
- if (!addressed) {
44814
- return offWithNotice(config.missing === null ? `${config.path} names no Envoy listener or NATS server, and neither ENVOY_URL nor ENVOY_NATS_URL is set: Envoy is off` : missingConfigNotice(config.path, config.missing, "Envoy is off"));
44815
- }
44816
- if (namedUrl !== undefined && httpUrl2(namedUrl) === undefined) {
44817
- return offWithError("ENVOY_URL must be an http or https URL");
44818
- }
44819
- const listener = section.url ?? DEFAULT_ENVOY_URL;
44820
- const url = namedUrl ?? listener;
44821
- let credential;
44822
- try {
44823
- const source = bearerSource(env, "ENVOY", () => section.token === undefined ? undefined : {
44824
- token: section.token,
44825
- field: "envoy.token",
44826
- path: config.path,
44827
- server: listener,
44828
- checkout: false
44806
+ const log = (message, error) => safely("log", () => host.log(message, error));
44807
+ const notify = (notice) => safely("notice", () => host.notify(notice));
44808
+ const tell = (kind) => {
44809
+ pending.delete(kind);
44810
+ notify({ kind, message: PENDING_NOTICE_MESSAGES[kind] });
44811
+ };
44812
+ const sessionRead = (read) => () => {
44813
+ try {
44814
+ return read();
44815
+ } catch {
44816
+ return;
44817
+ }
44818
+ };
44819
+ const currentSession = sessionRead(() => host.sessionID());
44820
+ const writeSession = sessionRead(() => host.writeSessionID === undefined ? host.sessionID() : host.writeSessionID());
44821
+ const bindTo = (sessionID, read) => {
44822
+ if (sessionID === undefined || sessionID === "" || read() !== sessionID)
44823
+ return;
44824
+ const bound = epoch;
44825
+ return { sessionID, alive: () => bound === epoch && read() === sessionID };
44826
+ };
44827
+ const bind = () => bindTo(currentSession(), currentSession);
44828
+ const stateJSON = (afters = true) => {
44829
+ const subjects = {};
44830
+ for (const subject of [...cursors.keys()].sort()) {
44831
+ const cursor = cursors.get(subject) ?? {};
44832
+ subjects[subject] = {
44833
+ ...cursor.since === undefined ? {} : { since: cursor.since },
44834
+ ...!afters || cursor.after === undefined ? {} : { after: cursor.after },
44835
+ ...cursor.from_start === undefined ? {} : { from_start: cursor.from_start }
44836
+ };
44837
+ }
44838
+ return JSON.stringify({
44839
+ ...streamID === undefined ? {} : { stream_id: streamID },
44840
+ ...streamCreated === undefined ? {} : { stream_created: streamCreated },
44841
+ subjects,
44842
+ ...pending.size === 0 ? {} : { notices: [...pending].sort() }
44829
44843
  });
44830
- if (source.kind === "none") {
44831
- credential = brokerRouteConfigured(env).traded ? brokerCredential(env, options.session) : undefined;
44832
- } else {
44833
- credential = bearerCredential(source.kind === "variable" ? source.token : fileBearer(source, url, "ENVOY", env));
44844
+ };
44845
+ const record2 = (identity) => {
44846
+ const entry = ledger.record(identity);
44847
+ if (entry !== undefined)
44848
+ unwritten.push(entry);
44849
+ };
44850
+ const flush = (alive, atOnce = false) => {
44851
+ writes = writes.then(async () => {
44852
+ if (!alive())
44853
+ return;
44854
+ const json = stateJSON();
44855
+ const delivered = unwritten;
44856
+ if (json === writtenState && delivered.length === 0)
44857
+ return;
44858
+ const shape = stateJSON(false);
44859
+ if (delivered.length === 0 && !atOnce && shape === writtenShape && writtenAt !== undefined && now() - writtenAt < REPLAY_STATE_REFRESH_MS) {
44860
+ return;
44861
+ }
44862
+ unwritten = [];
44863
+ const state = json === writtenState ? undefined : JSON.parse(json);
44864
+ try {
44865
+ await host.write({
44866
+ delivered,
44867
+ state,
44868
+ snapshot: () => ({ state: JSON.parse(json), ledger: ledger.list() })
44869
+ });
44870
+ if (state !== undefined) {
44871
+ writtenState = json;
44872
+ writtenShape = shape;
44873
+ writtenAt = now();
44874
+ }
44875
+ } catch (error) {
44876
+ unwritten = [...delivered, ...unwritten];
44877
+ log("replay: could not persist the replay state; the next write carries it", error);
44878
+ }
44879
+ });
44880
+ return writes;
44881
+ };
44882
+ const syncFollowed = () => {
44883
+ const followed = new Set(host.followedSubjects());
44884
+ for (const subject of [...cursors.keys()]) {
44885
+ if (!followed.has(subject)) {
44886
+ cursors.delete(subject);
44887
+ cursorStarts.delete(subject);
44888
+ }
44834
44889
  }
44835
- } catch (error) {
44836
- return offWithError(messageFor(error));
44837
- }
44838
- const natsUrls = namedNatsUrls.length > 0 ? namedNatsUrls : section.natsUrls ?? [];
44839
- let inbound;
44840
- if (options.nats === false)
44841
- inbound = { off: NO_NATS_CONNECTION };
44842
- else if (natsUrls.length === 0)
44843
- inbound = { off: NO_NATS_SERVER };
44844
- else {
44890
+ for (const subject of followed) {
44891
+ if (!cursors.has(subject))
44892
+ cursors.set(subject, {});
44893
+ }
44894
+ };
44895
+ const failureNotice = (envelope, publishedAt, error, subject) => ({
44896
+ eventId: envelope.event_id ?? "unknown",
44897
+ sender: senderLabel(envelope),
44898
+ summary: envelope.payload_summary ?? "unknown",
44899
+ publishedAt,
44900
+ error,
44901
+ readWith: envelope.source === "dispatch" ? "dispatch read" : "envoy_inbox",
44902
+ ...subject === undefined ? {} : { subject },
44903
+ envelope
44904
+ });
44905
+ const showFailureNotice = async (notice, alive) => {
44906
+ let queued;
44845
44907
  try {
44846
- inbound = { natsUrls, natsSeed: natsCredential(env, section, namedNatsUrls, config.path) };
44908
+ queued = await host.showFailureNotice(notice) === "queued";
44847
44909
  } catch (error) {
44848
- inbound = { off: messageFor(error) };
44910
+ if (!alive())
44911
+ return "stopped";
44912
+ safely("failure notice warning", () => host.failureNoticeFailed(notice, error));
44913
+ return "hole";
44849
44914
  }
44850
- }
44851
- const heartbeatMs = resolvedInterval(env.ENVOY_HEARTBEAT_MS, DEFAULT_HEARTBEAT_MS);
44852
- const tmuxPlaceCacheMs = resolvedInterval(env.ENVOY_TMUX_PLACE_CACHE_MS, DEFAULT_TMUX_PLACE_CACHE_MS);
44853
- const namedPassDeadlineMs = namedInterval(env.ENVOY_PASS_DEADLINE_MS);
44854
- return {
44855
- enabled: true,
44856
- url: normalizeEnvoyUrl(url),
44857
- credential,
44858
- inbound,
44859
- heartbeatMs,
44860
- tmuxPlaceCacheMs,
44861
- passDeadlineMs: Math.min(Math.max(namedPassDeadlineMs ?? MIN_PASS_DEADLINE_MS, heartbeatMs), MAX_INTERVAL_MS),
44862
- passDeadlineRaisedFrom: namedPassDeadlineMs !== undefined && namedPassDeadlineMs < heartbeatMs ? namedPassDeadlineMs : undefined
44915
+ if (!alive())
44916
+ return "stopped";
44917
+ if (queued)
44918
+ return "hole";
44919
+ record2(replayLedgerIdentity(notice.envelope));
44920
+ await flush(alive);
44921
+ return "done";
44863
44922
  };
44864
- }
44865
- function normalizeEnvoyUrl(value) {
44866
- return value.replace(/\/+$/, "");
44867
- }
44868
-
44869
- // ../envoy-client/src/machine.ts
44870
- import { hostname as hostname3 } from "os";
44871
- function machineID() {
44872
- return process.env["ENVOY_MACHINE_ID"] || process.env["AGENTBOX_HOST"] || hostname3();
44873
- }
44874
-
44875
- // ../envoy-client/src/transport.ts
44876
- var REPLAY_TIMEOUT_MS = 1e4;
44877
- var REPLAY_UNAVAILABLE_CODE = "REPLAY_UNAVAILABLE";
44878
- var SessionStateSchema = _enum2(["live", "unresponsive", "gone"]);
44879
- var UNRESPONSIVE_RULE = "An unresponsive session is not dead: it keeps its role claims and its issue claims, and a " + "message sent to it is stored until it answers. Start no replacement for it and take no claim " + `from it until it is gone, or until ${ISSUE_CLAIM_UNRESPONSIVE_GRACE_MS / 60000} minutes ` + "have passed since its last_seen, the time of its last registration.";
44880
- var WireStateSchema = SessionStateSchema.default("live");
44881
- var InterestWireSchema = object({
44882
- session_id: string2(),
44883
- machine_id: string2(),
44884
- dir: string2(),
44885
- topics: array(string2()),
44886
- updated_at: number2().int().optional(),
44887
- warnings: array(string2()).optional()
44888
- });
44889
- var DeliveryAnswerWireSchema = discriminatedUnion("mode", [
44890
- object({
44891
- mode: literal("consumer"),
44892
- subject: string2().min(1),
44893
- stream_id: string2(),
44894
- gap: boolean2(),
44895
- consumer_start: number2().int().nonnegative().optional()
44896
- }),
44897
- object({ mode: literal("core"), reason: string2() })
44898
- ]);
44899
- var SessionWireSchema = object({
44900
- session_id: string2(),
44901
- machine_id: string2(),
44902
- host: string2().optional(),
44903
- dir: string2(),
44904
- port: number2().int(),
44905
- title: string2(),
44906
- topics: array(string2()),
44907
- roles: array(string2()).optional(),
44908
- capabilities: array(string2()).optional(),
44909
- self_subscribed: boolean2(),
44910
- last_seen: number2().int().optional(),
44911
- state: WireStateSchema,
44912
- plugin: string2().optional(),
44913
- plugin_version: string2().optional()
44914
- });
44915
- var RoleWireSchema = object({
44916
- role: string2(),
44917
- holder: string2(),
44918
- host: string2().optional(),
44919
- last_seen: number2().int(),
44920
- state: WireStateSchema,
44921
- holder_state: SessionStateSchema.optional(),
44922
- client_instance_id: string2().optional(),
44923
- handed_back: boolean2().optional()
44924
- });
44925
- var RoleHeldWireSchema = object({
44926
- error: string2(),
44927
- role: string2(),
44928
- holder: string2()
44929
- });
44930
- var ErrorWireSchema = object({
44931
- error: string2(),
44932
- code: string2().optional(),
44933
- expected: array(string2()).optional(),
44934
- state: SessionStateSchema.optional(),
44935
- holder: string2().optional(),
44936
- holder_state: SessionStateSchema.optional(),
44937
- last_seen: number2().int().optional(),
44938
- claim_released: boolean2().optional(),
44939
- unresponsive: array(string2()).optional()
44940
- });
44941
- var EnvelopeResponseSchema = EnvelopeSchema.extend({
44942
- recipient: string2().optional(),
44943
- holder: string2().optional(),
44944
- holder_state: SessionStateSchema.optional(),
44945
- recipient_state: SessionStateSchema.optional(),
44946
- last_seen: number2().int().optional(),
44947
- unresponsive: array(string2()).optional(),
44948
- duplicate: boolean2().optional()
44949
- });
44950
- var PublishResponseSchema = EnvelopeResponseSchema.extend({
44951
- kept: boolean2().optional(),
44952
- kept_reason: _enum2(["unclaimed", "holder_lapsed"]).optional()
44953
- });
44954
- var ReplayWireSchema = object({
44955
- stream: object({
44956
- id: string2().min(1).optional(),
44957
- created: string2(),
44958
- first_seq: number2().int().nonnegative(),
44959
- last_seq: number2().int().nonnegative()
44960
- }),
44961
- subjects: array(object({
44962
- subject: string2(),
44963
- messages: array(object({
44964
- seq: number2().int().positive(),
44965
- subject: string2(),
44966
- time: string2(),
44967
- data: string2()
44968
- })),
44969
- next_after: number2().int().nonnegative(),
44970
- more: boolean2(),
44971
- refused: string2().optional()
44972
- }))
44973
- });
44974
- var DELIVERY_NOT_ANSWERED = "not_answered";
44975
- var DELIVERY_UNREADABLE = "unreadable_answer";
44976
- function parseSubscribeAnswer(body) {
44977
- const interest = InterestWireSchema.parse(body);
44978
- const raw = typeof body === "object" && body !== null && "delivery" in body ? body.delivery : undefined;
44979
- if (raw === undefined || raw === null) {
44980
- return { ...interest, delivery: { mode: "core", reason: DELIVERY_NOT_ANSWERED } };
44981
- }
44982
- const delivery = DeliveryAnswerWireSchema.safeParse(raw);
44983
- return {
44984
- ...interest,
44985
- delivery: delivery.success ? delivery.data : { mode: "core", reason: DELIVERY_UNREADABLE }
44986
- };
44987
- }
44988
- function mergeInterestSources(registryTopics, liveTopics) {
44989
- const interests = new Map;
44990
- for (const topic of registryTopics) {
44991
- interests.set(topic, liveTopics.includes(topic) ? "both" : "registry");
44992
- }
44993
- for (const topic of liveTopics) {
44994
- if (!interests.has(topic))
44995
- interests.set(topic, "live");
44996
- }
44997
- return interests;
44998
- }
44999
- function holderStateOf(role) {
45000
- return role.holder_state ?? role.state;
45001
- }
45002
- function namedProcess(id) {
45003
- return id === "" ? undefined : id;
45004
- }
45005
- function roleHeldBy(info, sessionID, clientInstanceID) {
45006
- if (info === undefined || info.holder !== sessionID || info.handed_back === true)
45007
- return false;
45008
- const holding = namedProcess(info.client_instance_id);
45009
- return holding === undefined || holding === namedProcess(clientInstanceID);
45010
- }
45011
- function mayActOnRoleRecord(writer, clientInstanceID, holdsRole) {
45012
- const wrote = namedProcess(writer);
45013
- if (wrote === undefined || wrote === namedProcess(clientInstanceID))
45014
- return true;
45015
- return !holdsRole;
45016
- }
45017
- function newClientInstanceID() {
45018
- return Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join("");
45019
- }
45020
- function expandSubscriptionTopics(topics) {
45021
- const expanded = new Set;
45022
- for (const topic of topics) {
45023
- const base = topic.endsWith(".>") ? topic.slice(0, -2) : undefined;
45024
- if (base === undefined || base.includes("*") || base.includes(">")) {
45025
- expanded.add(topic);
45026
- continue;
44923
+ const handle = async (seq, buffered, alive) => {
44924
+ const { message } = buffered;
44925
+ const envelope = parseEnvelope(message.data);
44926
+ if (envelope === undefined) {
44927
+ log(`replay: skipping stored message ${seq} on ${message.subject}: not an Envoy envelope`);
44928
+ return "done";
45027
44929
  }
45028
- const segments = base.split(".");
45029
- if (segments.length < 2 || segments.some((segment) => segment.length === 0)) {
45030
- throw new TypeError(`cannot expand Envoy wildcard topic "${topic}": its concrete base must have at least two non-empty segments`);
44930
+ if (isRoleForward(envelope))
44931
+ return "done";
44932
+ const identity = replayLedgerIdentity(envelope);
44933
+ if (ledger.has(identity)) {
44934
+ failures.delete(seq);
44935
+ return "done";
45031
44936
  }
45032
- expanded.add(base);
45033
- expanded.add(topic);
45034
- }
45035
- return [...expanded];
45036
- }
45037
- function refusalStateText(parsed) {
45038
- const sentences = [];
45039
- const state = parsed.holder_state ?? parsed.state;
45040
- if (state !== undefined) {
45041
- const who = parsed.holder === undefined ? "That session" : `Holder ${parsed.holder}`;
45042
- const seen = parsed.last_seen === undefined || parsed.last_seen <= 0 ? "" : `, last seen ${new Date(parsed.last_seen).toISOString()}`;
45043
- sentences.push(`${who} is ${state}${seen}.`);
45044
- }
45045
- const stored = parsed.unresponsive ?? [];
45046
- if (stored.length > 0) {
45047
- const one = stored.length === 1;
45048
- sentences.push(`Envoy stored the message for ${stored.join(", ")}.`, `${one ? "That session" : "Those sessions"} stopped answering, so ${one ? "it" : "they"} did not fail this send.`);
45049
- }
45050
- if (sentences.length === 0)
45051
- return "";
45052
- if (state === "unresponsive" || stored.length > 0)
45053
- sentences.push(UNRESPONSIVE_RULE);
45054
- return ` ${sentences.join(" ")}`;
45055
- }
45056
-
45057
- class EnvoyApiError extends Error {
45058
- details;
45059
- name = "EnvoyApiError";
45060
- expected;
45061
- code;
45062
- holder;
45063
- sessionState;
45064
- lastSeen;
45065
- claimReleased;
45066
- unresponsive;
45067
- constructor(details) {
45068
- let parsed;
45069
- try {
45070
- const result = ErrorWireSchema.safeParse(JSON.parse(details.responseBody));
45071
- if (result.success)
45072
- parsed = result.data;
45073
- } catch {}
45074
- super(parsed === undefined ? `${details.method} ${details.url} failed with ${details.status}: ${details.responseBody}` : `${parsed.error}${parsed.expected === undefined ? "" : ` (expected: ${parsed.expected.join(", ")})`}${refusalStateText(parsed)}`);
45075
- this.details = details;
45076
- this.expected = parsed?.expected;
45077
- this.code = parsed?.code;
45078
- this.holder = parsed?.holder;
45079
- this.sessionState = parsed?.holder_state ?? parsed?.state;
45080
- this.lastSeen = parsed?.last_seen;
45081
- this.claimReleased = parsed?.claim_released;
45082
- this.unresponsive = parsed?.unresponsive;
45083
- }
45084
- }
45085
- var mintedDedupeKey2 = new RegExp(MINTED_DEDUPE_KEY_PATTERN);
45086
-
45087
- class EnvoySendUnconfirmedError extends Error {
45088
- targetSessionID;
45089
- idempotencyKey;
45090
- attempts;
45091
- last;
45092
- name = "EnvoySendUnconfirmedError";
45093
- resendSafe;
45094
- constructor(targetSessionID, idempotencyKey, attempts, last) {
45095
- const got = last instanceof EnvoyApiError ? `the listener answered ${last.details.status} (${last.message})` : `the listener did not answer (${last instanceof Error ? last.message : String(last)})`;
45096
- const tried = attempts === 1 ? "on its only attempt" : `on the last of ${attempts} attempts`;
45097
- const resendSafe = mintedDedupeKey2.test(`agent.${targetSessionID.trim()}.${idempotencyKey}`);
45098
- const resend = resendSafe ? `Sending it again with idempotency_key ${idempotencyKey} within ` + `${DELIVERY_DUPLICATE_WINDOW_MS / 3600000} hours is the safe resend: Envoy drops it as ` + "a repeat if the first copy arrived (a recipient that restarted in between can rarely " + "see it twice)." : `Envoy cannot recognise a resend under idempotency_key ${idempotencyKey} as a repeat ` + "(the key is not a lower-case UUID, or the session id holds a dot): ask the recipient " + "whether it arrived before sending it again.";
45099
- super(`The send to ${targetSessionID} is not confirmed delivered: ${got} ${tried}. It may or may ` + `not have arrived. ${resend}`, { cause: last });
45100
- this.targetSessionID = targetSessionID;
45101
- this.idempotencyKey = idempotencyKey;
45102
- this.attempts = attempts;
45103
- this.last = last;
45104
- this.resendSafe = resendSafe;
45105
- }
45106
- }
45107
- function resolveCallTiming(config) {
45108
- return {
45109
- timeoutMs: config.timeoutMs ?? LISTENER_CALL_TIMEOUT_MS,
45110
- attempts: config.retry === false ? 1 : LISTENER_CALL_ATTEMPTS,
45111
- retryDelayMs: LISTENER_CALL_RETRY_DELAY_MS
45112
- };
45113
- }
45114
- function createEnvoyClient(config) {
45115
- const baseUrl = normalizeEnvoyUrl(config.baseUrl);
45116
- const { timeoutMs, attempts, retryDelayMs } = resolveCallTiming(config);
45117
- const credential = config.credential;
45118
- const attemptOnce = async (url, init, deadlineMs, actingSession) => {
45119
- let response;
45120
- let unminted;
44937
+ if (dedupe?.pending(envelope) === true)
44938
+ return "hole";
44939
+ if (!alive())
44940
+ return "stopped";
44941
+ const giveUp = async (error) => {
44942
+ const handled = await showFailureNotice(failureNotice(envelope, message.time, error, message.subject), alive);
44943
+ if (handled === "done")
44944
+ failures.delete(seq);
44945
+ return handled;
44946
+ };
44947
+ const failure = failures.get(seq);
44948
+ if (failure !== undefined && failure.count >= REPLAY_FAILURES_BEFORE_NOTICE) {
44949
+ return giveUp(failure.error);
44950
+ }
44951
+ const followed = buffered.subjects[0] ?? message.subject;
44952
+ let outcome;
44953
+ let error = "the host could not show it";
45121
44954
  try {
45122
- const headers = new Headers(init.headers);
45123
- let presented;
45124
- try {
45125
- const ready = credential?.headers(init.method ?? "GET", url, actingSession);
45126
- presented = ready instanceof Promise ? await ready : ready;
45127
- } catch (error) {
45128
- unminted = error;
45129
- }
45130
- for (const [name, value] of Object.entries(presented ?? {}))
45131
- headers.set(name, value);
45132
- response = await config.fetch(url, {
45133
- ...init,
45134
- headers,
45135
- signal: AbortSignal.timeout(deadlineMs)
44955
+ outcome = await host.deliver({
44956
+ envelope,
44957
+ data: message.data,
44958
+ seq,
44959
+ subject: message.subject,
44960
+ followed,
44961
+ time: message.time,
44962
+ since: cursors.get(followed)?.since
45136
44963
  });
45137
- } catch (error) {
45138
- return { unanswered: error };
44964
+ } catch (thrown) {
44965
+ outcome = "failed";
44966
+ error = messageFor(thrown);
45139
44967
  }
45140
- if (unminted !== undefined && (response.status === 401 || response.status === 403)) {
45141
- return {
45142
- unanswered: new Error(`${init.method ?? "GET"} ${url} answered ${response.status}, and this machine's Envoy credential could not be minted: ${messageFor(unminted)}`, { cause: unminted })
45143
- };
44968
+ if (!alive())
44969
+ return "stopped";
44970
+ if (outcome === "shown") {
44971
+ failures.delete(seq);
44972
+ record2(identity);
44973
+ await flush(alive);
44974
+ return "done";
45144
44975
  }
45145
- try {
45146
- return { response, body: await response.text() };
45147
- } catch (error) {
45148
- if (response.status >= 400 && response.status < 500) {
45149
- return { response, body: `(its body did not arrive: ${String(error)})` };
45150
- }
45151
- return { unanswered: error };
44976
+ if (outcome === "suppressed") {
44977
+ failures.delete(seq);
44978
+ return "done";
44979
+ }
44980
+ if (outcome === "queued") {
44981
+ failures.delete(seq);
44982
+ return "hole";
45152
44983
  }
44984
+ const count = (failure?.count ?? 0) + 1;
44985
+ failures.set(seq, { count, error });
44986
+ if (count >= REPLAY_FAILURES_BEFORE_NOTICE)
44987
+ return giveUp(error);
44988
+ log(`replay: could not show stored message ${seq} (${envelope.event_id}): ${error}`);
44989
+ return "hole";
45153
44990
  };
45154
- const request = async (path, init, options = {}) => {
45155
- const url = `${baseUrl}${path}`;
45156
- const tries = options.retry === false ? 1 : attempts;
45157
- for (let attempt = 0;attempt < tries; attempt += 1) {
45158
- const outcome = await attemptOnce(url, init, options.timeoutMs ?? timeoutMs, options.actingSession);
45159
- if ("unanswered" in outcome) {
45160
- options.onUnanswered?.();
45161
- if (attempt + 1 < tries) {
45162
- await waitForRetry(retryDelayMs);
45163
- continue;
45164
- }
45165
- throw outcome.unanswered;
44991
+ const listenerFailed = (error) => {
44992
+ if (error instanceof EnvoyApiError) {
44993
+ const status = error.details.status;
44994
+ if (status === 404) {
44995
+ if (listenerNoticed === "not_served")
44996
+ return;
44997
+ listenerNoticed = "not_served";
44998
+ notify({
44999
+ kind: "not_served",
45000
+ message: "This session's Envoy listener does not serve replay (POST /v1/replay answered 404), so messages published while its connection is down are not recovered."
45001
+ });
45002
+ return;
45166
45003
  }
45167
- const { response, body } = outcome;
45168
- if (response.ok)
45169
- return body;
45170
- const error = new EnvoyApiError({
45171
- method: init.method ?? "GET",
45172
- url,
45173
- status: response.status,
45174
- responseBody: body
45175
- });
45176
- if (response.status >= 500) {
45177
- options.onUnanswered?.();
45178
- if (attempt + 1 < tries) {
45179
- await waitForRetry(retryDelayMs);
45180
- continue;
45181
- }
45004
+ if (status === 503 && error.code === REPLAY_UNAVAILABLE_CODE || status === 401 || status === 403) {
45005
+ const key = `unavailable:${status}:${error.message}`;
45006
+ if (listenerNoticed === key)
45007
+ return;
45008
+ listenerNoticed = key;
45009
+ notify({
45010
+ kind: "unavailable",
45011
+ status,
45012
+ error: error.message,
45013
+ message: `Envoy replay is unavailable (${status}: ${error.message}), so messages published while this session's connection is down are not recovered until it answers.`
45014
+ });
45015
+ return;
45182
45016
  }
45183
- throw error;
45184
45017
  }
45185
- throw new Error("Envoy request exhausted retries");
45018
+ log("replay: the listener's replay failed; the next trigger tries again", error);
45186
45019
  };
45187
- const post = (path, body, options) => request(path, {
45188
- method: "POST",
45189
- headers: { "Content-Type": "application/json" },
45190
- body: JSON.stringify(body)
45191
- }, options);
45192
- return {
45193
- subscribe: async (input) => parseSubscribeAnswer(JSON.parse(await post("/v1/interests/subscribe", {
45194
- session_id: input.sessionID,
45195
- dir: input.directory,
45196
- topics: expandSubscriptionTopics(input.topics),
45197
- port: input.port,
45198
- title: input.title,
45199
- ...input.capabilities === undefined ? {} : { capabilities: input.capabilities },
45200
- driving: input.driving,
45201
- ...input.selfSubscribed === undefined ? {} : { self_subscribed: input.selfSubscribed },
45202
- ...input.delivery === undefined ? {} : { delivery: input.delivery },
45203
- ...input.clientInstanceID === undefined ? {} : { client_instance_id: input.clientInstanceID },
45204
- host: machineID(),
45205
- ...input.place === undefined ? {} : { tmux_place: input.place },
45206
- plugin: input.plugin.name,
45207
- plugin_version: input.plugin.version
45208
- }, { actingSession: input.sessionID }))),
45209
- unsubscribe: async (input) => {
45210
- await post("/v1/interests/unsubscribe", {
45211
- session_id: input.sessionID,
45212
- topics: expandSubscriptionTopics(input.topics),
45213
- ...input.clientInstanceID === undefined ? {} : { client_instance_id: input.clientInstanceID }
45214
- }, { actingSession: input.sessionID });
45215
- },
45216
- getInterest: async (sessionID) => InterestWireSchema.parse(JSON.parse(await request(`/v1/interests/${sessionID}`, {}))),
45217
- send: async (input) => {
45218
- const idempotencyKey = input.idempotencyKey ?? crypto.randomUUID();
45219
- let unanswered = false;
45020
+ const streamReplaced = (stream) => {
45021
+ if (stream.id === undefined) {
45022
+ return streamCreated !== undefined && streamCreated !== "" && stream.created !== streamCreated;
45023
+ }
45024
+ return streamID !== undefined && streamID !== "" && stream.id !== streamID;
45025
+ };
45026
+ const streamMovedBack = (stream) => {
45027
+ for (const cursor of cursors.values()) {
45028
+ if (cursor.after !== undefined && cursor.after > stream.last_seq)
45029
+ return true;
45030
+ }
45031
+ return false;
45032
+ };
45033
+ const sweepOnce = async () => {
45034
+ const binding = bind();
45035
+ if (binding === undefined)
45036
+ return;
45037
+ const { sessionID, alive } = binding;
45038
+ syncFollowed();
45039
+ const readings = new Map;
45040
+ for (const [subject, cursor] of cursors) {
45041
+ readings.set(subject, {
45042
+ read: cursor.from_start === undefined ? cursor.after : 0,
45043
+ more: true
45044
+ });
45045
+ }
45046
+ const buffer = new Map;
45047
+ const holes = new Map;
45048
+ let gapNoticed = false;
45049
+ if (pending.size > 0) {
45050
+ for (const kind of [...pending].sort()) {
45051
+ if (kind === "retention_gap")
45052
+ gapNoticed = true;
45053
+ tell(kind);
45054
+ }
45055
+ await flush(alive);
45056
+ if (!alive())
45057
+ return;
45058
+ }
45059
+ if (consumerMode)
45060
+ return;
45061
+ for (let page = 0;page < REPLAY_PAGES_PER_SWEEP; page += 1) {
45062
+ let handledAny = false;
45063
+ const asking = [...readings].filter(([, reading]) => reading.more).sort(([, a], [, b]) => (a.read ?? -1) - (b.read ?? -1)).slice(0, REPLAY_MAX_SUBJECTS);
45064
+ if (asking.length === 0)
45065
+ break;
45220
45066
  let response;
45221
45067
  try {
45222
- const answer = await post("/v1/messages/send", {
45223
- source: input.source ?? "agent",
45224
- ...sourceSession(input.sourceSessionID),
45225
- target_session: input.targetSessionID,
45226
- message: input.message,
45227
- idempotency_key: idempotencyKey,
45228
- ...messageMetadata(input)
45229
- }, {
45230
- onUnanswered: () => {
45231
- unanswered = true;
45232
- },
45233
- ...input.sourceSessionID === undefined || input.sourceSessionID === "" ? {} : { actingSession: input.sourceSessionID }
45068
+ response = await transport.replay({
45069
+ sessionID,
45070
+ subjects: asking.map(([subject, reading]) => reading.read === undefined ? { subject } : { subject, after: reading.read }),
45071
+ ...options.maxMessages === undefined ? {} : { maxMessages: options.maxMessages }
45234
45072
  });
45235
- response = EnvelopeResponseSchema.parse(JSON.parse(answer));
45236
45073
  } catch (error) {
45237
- if (error instanceof EnvoyApiError && error.details.status < 500 && !unanswered) {
45238
- throw error;
45074
+ if (alive()) {
45075
+ answered.clear();
45076
+ listenerFailed(error);
45239
45077
  }
45240
- throw new EnvoySendUnconfirmedError(input.targetSessionID, idempotencyKey, attempts, error);
45078
+ return;
45241
45079
  }
45242
- return {
45243
- envelope: response,
45244
- recipient: response.recipient ?? input.targetSessionID,
45245
- confirmed: response.recipient !== undefined,
45246
- recipientState: response.recipient_state ?? "live",
45247
- ...response.last_seen === undefined || response.last_seen <= 0 ? {} : { lastSeen: response.last_seen },
45248
- duplicate: response.duplicate === true
45249
- };
45250
- },
45251
- publish: async (input) => {
45252
- const idempotencyKey = input.idempotencyKey ?? crypto.randomUUID();
45253
- const response = PublishResponseSchema.parse(JSON.parse(await post("/v1/messages/publish", {
45254
- source: input.source ?? "agent",
45255
- ...sourceSession(input.sourceSessionID),
45256
- topic: input.topic,
45257
- message: input.message,
45258
- ...input.payload === undefined ? {} : { payload: input.payload },
45259
- idempotency_key: idempotencyKey,
45260
- ...messageMetadata(input),
45261
- ...input.keep === undefined ? {} : { keep: input.keep }
45262
- }, input.sourceSessionID === undefined || input.sourceSessionID === "" ? {} : { actingSession: input.sourceSessionID })));
45263
- return {
45264
- envelope: response,
45265
- ...response.holder === undefined ? {} : { holder: response.holder },
45266
- ...response.holder_state === undefined ? {} : { holderState: response.holder_state },
45267
- unresponsive: response.unresponsive ?? [],
45268
- ...response.kept === undefined ? {} : { kept: response.kept },
45269
- ...response.kept_reason === undefined ? {} : { keptReason: response.kept_reason }
45270
- };
45271
- },
45272
- unregisterSession: async (input) => {
45273
- const query = input.clientInstanceID === undefined ? "" : `?client_instance_id=${encodeURIComponent(input.clientInstanceID)}`;
45274
- await request(`/v1/sessions/${encodeURIComponent(input.sessionID)}${query}`, { method: "DELETE" }, { actingSession: input.sessionID });
45275
- },
45276
- setRole: async (input) => {
45277
- const soft = input.soft === true;
45278
- const previous = soft ? input.previousSessionID ?? "" : "";
45279
- const body = {
45280
- session_id: input.sessionID,
45281
- role: input.role,
45282
- ...soft ? { soft: true } : {},
45283
- ...previous === "" ? {} : { previous_session_id: previous },
45284
- ...input.clientInstanceID === undefined ? {} : { client_instance_id: input.clientInstanceID }
45285
- };
45286
- let raw;
45287
- try {
45288
- raw = await post("/v1/roles/set", body, { actingSession: input.sessionID });
45289
- } catch (error) {
45290
- if (error instanceof EnvoyApiError && error.details.status === 409) {
45291
- let answer;
45292
- try {
45293
- answer = JSON.parse(error.details.responseBody);
45294
- } catch {
45295
- throw error;
45080
+ if (!alive())
45081
+ return;
45082
+ listenerNoticed = undefined;
45083
+ for (const result of response.subjects) {
45084
+ if (result.refused === undefined)
45085
+ answered.add(result.subject);
45086
+ else
45087
+ answered.delete(result.subject);
45088
+ }
45089
+ const { stream } = response;
45090
+ const replaced = streamReplaced(stream);
45091
+ streamID = stream.id ?? (replaced ? undefined : streamID);
45092
+ streamCreated = stream.created;
45093
+ if (replaced) {
45094
+ const at = now();
45095
+ for (const subject of cursors.keys()) {
45096
+ cursors.set(subject, { since: stream.last_seq, after: stream.last_seq });
45097
+ cursorStarts.set(subject, at);
45098
+ }
45099
+ failures.clear();
45100
+ pending.add("stream_recreated");
45101
+ await flush(alive);
45102
+ if (!alive())
45103
+ return;
45104
+ tell("stream_recreated");
45105
+ await flush(alive);
45106
+ return;
45107
+ }
45108
+ if (streamMovedBack(stream)) {
45109
+ const from = Math.max(0, stream.first_seq - 1);
45110
+ for (const [subject, cursor] of cursors) {
45111
+ if (cursor.after === undefined)
45112
+ continue;
45113
+ cursors.set(subject, { ...cursor, after: from });
45114
+ const reading = readings.get(subject);
45115
+ if (reading !== undefined) {
45116
+ reading.read = from;
45117
+ reading.more = true;
45296
45118
  }
45297
- const held = RoleHeldWireSchema.safeParse(answer);
45298
- if (held.success)
45299
- return { claimed: false, holder: held.data.holder };
45300
45119
  }
45301
- throw error;
45120
+ buffer.clear();
45121
+ holes.clear();
45122
+ failures.clear();
45123
+ pending.add("stream_moved_back");
45124
+ await flush(alive, true);
45125
+ if (!alive())
45126
+ return;
45127
+ tell("stream_moved_back");
45128
+ await flush(alive);
45129
+ if (!alive())
45130
+ return;
45131
+ continue;
45302
45132
  }
45303
- return { claimed: true, interest: InterestWireSchema.parse(JSON.parse(raw)) };
45304
- },
45305
- getRole: async (role) => RoleWireSchema.parse(JSON.parse(await request(`/v1/roles/${encodeURIComponent(role)}`, { method: "GET" }))),
45306
- listSessions: async (input = {}) => {
45307
- const search = new URLSearchParams;
45308
- if (input.directory !== undefined)
45309
- search.set("dir", input.directory);
45310
- if (input.title !== undefined)
45311
- search.set("title", input.title);
45312
- if (input.include !== undefined)
45313
- search.set("include", input.include);
45314
- const query = search.size === 0 ? "" : `?${search.toString()}`;
45315
- return SessionWireSchema.array().parse(JSON.parse(await request(`/v1/sessions${query}`, {})));
45316
- },
45317
- replay: async (input) => ReplayWireSchema.parse(JSON.parse(await post("/v1/replay", {
45318
- session_id: input.sessionID,
45319
- subjects: input.subjects.map((cursor) => cursor.after === undefined ? { subject: cursor.subject } : { subject: cursor.subject, after: cursor.after }),
45320
- ...input.maxMessages === undefined ? {} : { max_messages: input.maxMessages }
45321
- }, {
45322
- timeoutMs: input.timeoutMs ?? REPLAY_TIMEOUT_MS,
45323
- retry: false,
45324
- actingSession: input.sessionID
45325
- })))
45326
- };
45327
- }
45328
- function waitForRetry(delayMs) {
45329
- const { promise, resolve } = Promise.withResolvers();
45330
- setTimeout(resolve, delayMs);
45331
- return promise;
45332
- }
45333
- function messageMetadata(input) {
45334
- return {
45335
- ...input.inReplyTo === undefined ? {} : { in_reply_to: input.inReplyTo },
45336
- ...input.supersedes === undefined ? {} : { supersedes: input.supersedes },
45337
- ...input.urgency === undefined ? {} : { urgency: input.urgency },
45338
- ...input.expectsReply === undefined ? {} : { expects_reply: input.expectsReply },
45339
- ...input.expiresAt === undefined ? {} : { expires_at: input.expiresAt }
45133
+ for (const [, reading] of asking)
45134
+ reading.more = false;
45135
+ for (const result of response.subjects) {
45136
+ const reading = readings.get(result.subject);
45137
+ const markedAt = cursors.get(result.subject)?.from_start;
45138
+ if (reading === undefined || markedAt === undefined || result.refused !== undefined) {
45139
+ continue;
45140
+ }
45141
+ const start = Math.max(0, stream.first_seq - 1);
45142
+ cursors.set(result.subject, { since: start, after: start });
45143
+ cursorStarts.set(result.subject, now());
45144
+ if (now() - markedAt < DELIVERY_DUPLICATE_WINDOW_MS)
45145
+ reading.read = start;
45146
+ }
45147
+ let gapped = false;
45148
+ for (const result of response.subjects) {
45149
+ const reading = readings.get(result.subject);
45150
+ if (reading?.read === undefined || result.refused !== undefined)
45151
+ continue;
45152
+ if (reading.read >= stream.first_seq - 1)
45153
+ continue;
45154
+ gapped = true;
45155
+ reading.read = stream.first_seq - 1;
45156
+ const cursor = cursors.get(result.subject);
45157
+ if (cursor?.after !== undefined && cursor.after < reading.read) {
45158
+ cursors.set(result.subject, { ...cursor, after: reading.read });
45159
+ }
45160
+ }
45161
+ if (gapped) {
45162
+ if (!gapNoticed)
45163
+ pending.add("retention_gap");
45164
+ await flush(alive, true);
45165
+ if (!alive())
45166
+ return;
45167
+ if (pending.has("retention_gap")) {
45168
+ gapNoticed = true;
45169
+ tell("retention_gap");
45170
+ await flush(alive);
45171
+ }
45172
+ }
45173
+ for (const result of response.subjects) {
45174
+ const reading = readings.get(result.subject);
45175
+ if (reading === undefined || result.refused !== undefined)
45176
+ continue;
45177
+ if (reading.read === undefined) {
45178
+ const cursor = cursors.get(result.subject);
45179
+ if (cursor !== undefined && cursor.after === undefined) {
45180
+ cursors.set(result.subject, { since: result.next_after, after: result.next_after });
45181
+ cursorStarts.set(result.subject, now());
45182
+ }
45183
+ reading.read = result.next_after;
45184
+ continue;
45185
+ }
45186
+ for (const message of result.messages) {
45187
+ if (message.seq <= reading.read)
45188
+ continue;
45189
+ const buffered = buffer.get(message.seq);
45190
+ if (buffered === undefined) {
45191
+ buffer.set(message.seq, { message, subjects: [result.subject] });
45192
+ } else if (!buffered.subjects.includes(result.subject)) {
45193
+ buffered.subjects.push(result.subject);
45194
+ }
45195
+ }
45196
+ reading.read = Math.max(reading.read, result.next_after);
45197
+ reading.more = result.more;
45198
+ }
45199
+ let bound = Number.POSITIVE_INFINITY;
45200
+ for (const reading of readings.values()) {
45201
+ if (reading.more && reading.read !== undefined)
45202
+ bound = Math.min(bound, reading.read);
45203
+ }
45204
+ const ready = [...buffer.keys()].filter((seq) => seq <= bound).sort((a, b) => a - b);
45205
+ for (const seq of ready) {
45206
+ const buffered = buffer.get(seq);
45207
+ if (buffered === undefined)
45208
+ continue;
45209
+ buffer.delete(seq);
45210
+ if (!buffered.subjects.some((subject) => cursors.has(subject)))
45211
+ continue;
45212
+ const handled = await handle(seq, buffered, alive);
45213
+ if (handled === "stopped")
45214
+ return;
45215
+ if (handled === "done")
45216
+ handledAny = true;
45217
+ if (handled === "hole") {
45218
+ for (const subject of buffered.subjects) {
45219
+ if (!holes.has(subject))
45220
+ holes.set(subject, seq);
45221
+ }
45222
+ }
45223
+ }
45224
+ if (!alive())
45225
+ return;
45226
+ for (const [subject, reading] of readings) {
45227
+ const cursor = cursors.get(subject);
45228
+ if (cursor?.after === undefined || reading.read === undefined)
45229
+ continue;
45230
+ let after = Math.min(reading.read, bound);
45231
+ const hole = holes.get(subject);
45232
+ if (hole !== undefined)
45233
+ after = Math.min(after, hole - 1);
45234
+ if (after > cursor.after)
45235
+ cursors.set(subject, { ...cursor, after });
45236
+ }
45237
+ await flush(alive, handledAny);
45238
+ if (![...readings.values()].some((reading) => reading.more))
45239
+ break;
45240
+ }
45340
45241
  };
45341
- }
45342
- function sourceSession(sessionID) {
45343
- return sessionID === undefined || sessionID === "" ? {} : { source_session: sessionID };
45344
- }
45345
-
45346
- // ../envoy-client/src/replay.ts
45347
- var REPLAY_LEDGER_TTL_MS = DELIVERY_DUPLICATE_WINDOW_MS;
45348
- var REPLAY_LEDGER_LIMIT = 20000;
45349
- var REPLAY_PAGES_PER_SWEEP = 20;
45350
- var REPLAY_FAILURES_BEFORE_NOTICE = 3;
45351
- var REPLAY_STATE_REFRESH_MS = 60 * 60 * 1000;
45352
- var REPLAY_MAX_SUBJECTS = 32;
45353
- var START_CURSORS_TIMEOUT_MS = 2000;
45354
- var ROLE_FORWARD_KEY_PREFIX = "envoy.role.forward.";
45355
- var ReplayLedgerEntrySchema = object({
45356
- event_id: string2().min(1).optional(),
45357
- dedupe_key: string2().min(1).optional(),
45358
- at: number2()
45359
- });
45360
- var ReplayCursorSchema = object({
45361
- since: number2().int().nonnegative().optional(),
45362
- after: number2().int().nonnegative().optional(),
45363
- from_start: number2().int().nonnegative().optional()
45364
- });
45365
- var ReplayPendingNoticeSchema = _enum2([
45366
- "retention_gap",
45367
- "stream_moved_back",
45368
- "stream_recreated"
45369
- ]);
45370
- var PENDING_NOTICE_MESSAGES = {
45371
- stream_recreated: "Envoy's notification stream was recreated, so messages published to this session while its connection was down before that may be lost.",
45372
- stream_moved_back: "Envoy's notification stream was restored to an earlier point, so messages published to this session while its connection was down may be shown again, and any published between that point and the restore are missing.",
45373
- retention_gap: "The notification stream no longer holds some messages published to this session while its connection was down: messages older than 72 hours may be missing."
45374
- };
45375
- var ReplayStateSchema = object({
45376
- stream_id: string2().optional(),
45377
- stream_created: string2().optional(),
45378
- subjects: record(string2(), ReplayCursorSchema),
45379
- notices: array(string2()).optional()
45380
- });
45381
- var ReplaySnapshotSchema = object({
45382
- state: ReplayStateSchema.optional(),
45383
- ledger: array(ReplayLedgerEntrySchema)
45384
- });
45385
- function createReplayEngine(options) {
45386
- const { host, transport, dedupe } = options;
45387
- const now = options.now ?? Date.now;
45388
- const ledger = createLedger(now);
45389
- const cursors = new Map;
45390
- const cursorStarts = new Map;
45391
- let streamID;
45392
- let streamCreated;
45393
- const pending = new Set;
45394
- const failures = new Map;
45395
- let unwritten = [];
45396
- let writtenState;
45397
- let writtenShape;
45398
- let writtenAt;
45399
- let writes = Promise.resolve();
45400
- let epoch = 0;
45401
- let listenerNoticed;
45402
- const answered = new Set;
45403
- let running;
45404
- let rerun;
45405
- let consumerMode = false;
45406
- const safely = (what, call) => {
45242
+ const runSweep = async () => {
45407
45243
  try {
45408
- call();
45244
+ await sweepOnce();
45409
45245
  } catch (error) {
45410
- try {
45411
- host.log(`replay: ${what} failed`, error);
45412
- } catch {}
45246
+ log("replay: a sweep failed", error);
45413
45247
  }
45414
45248
  };
45415
- const log = (message, error) => safely("log", () => host.log(message, error));
45416
- const notify = (notice) => safely("notice", () => host.notify(notice));
45417
- const tell = (kind) => {
45418
- pending.delete(kind);
45419
- notify({ kind, message: PENDING_NOTICE_MESSAGES[kind] });
45420
- };
45421
- const sessionRead = (read) => () => {
45422
- try {
45423
- return read();
45424
- } catch {
45425
- return;
45249
+ const sweep = () => {
45250
+ if (running === undefined) {
45251
+ running = runSweep().finally(() => {
45252
+ running = undefined;
45253
+ });
45254
+ return running;
45426
45255
  }
45256
+ rerun ??= running.then(() => {
45257
+ rerun = undefined;
45258
+ return sweep();
45259
+ });
45260
+ return rerun;
45427
45261
  };
45428
- const currentSession = sessionRead(() => host.sessionID());
45429
- const writeSession = sessionRead(() => host.writeSessionID === undefined ? host.sessionID() : host.writeSessionID());
45430
- const bindTo = (sessionID, read) => {
45431
- if (sessionID === undefined || sessionID === "" || read() !== sessionID)
45262
+ const started = (cursor) => cursor?.after !== undefined || cursor?.from_start !== undefined;
45263
+ const startOnce = async () => {
45264
+ const binding = bind();
45265
+ if (binding === undefined)
45432
45266
  return;
45433
- const bound = epoch;
45434
- return { sessionID, alive: () => bound === epoch && read() === sessionID };
45435
- };
45436
- const bind = () => bindTo(currentSession(), currentSession);
45437
- const stateJSON = (afters = true) => {
45438
- const subjects = {};
45439
- for (const subject of [...cursors.keys()].sort()) {
45440
- const cursor = cursors.get(subject) ?? {};
45441
- subjects[subject] = {
45442
- ...cursor.since === undefined ? {} : { since: cursor.since },
45443
- ...!afters || cursor.after === undefined ? {} : { after: cursor.after },
45444
- ...cursor.from_start === undefined ? {} : { from_start: cursor.from_start }
45445
- };
45446
- }
45447
- return JSON.stringify({
45448
- ...streamID === undefined ? {} : { stream_id: streamID },
45449
- ...streamCreated === undefined ? {} : { stream_created: streamCreated },
45450
- subjects,
45451
- ...pending.size === 0 ? {} : { notices: [...pending].sort() }
45452
- });
45453
- };
45454
- const record2 = (identity) => {
45455
- const entry = ledger.record(identity);
45456
- if (entry !== undefined)
45457
- unwritten.push(entry);
45458
- };
45459
- const flush = (alive, atOnce = false) => {
45460
- writes = writes.then(async () => {
45461
- if (!alive())
45462
- return;
45463
- const json = stateJSON();
45464
- const delivered = unwritten;
45465
- if (json === writtenState && delivered.length === 0)
45466
- return;
45467
- const shape = stateJSON(false);
45468
- if (delivered.length === 0 && !atOnce && shape === writtenShape && writtenAt !== undefined && now() - writtenAt < REPLAY_STATE_REFRESH_MS) {
45469
- return;
45470
- }
45471
- unwritten = [];
45472
- const state = json === writtenState ? undefined : JSON.parse(json);
45267
+ const { sessionID, alive } = binding;
45268
+ const unstarted = [...new Set(host.followedSubjects())].filter((subject) => !started(cursors.get(subject)));
45269
+ let changed = false;
45270
+ for (let index = 0;index < unstarted.length; index += REPLAY_MAX_SUBJECTS) {
45271
+ let response;
45473
45272
  try {
45474
- await host.write({
45475
- delivered,
45476
- state,
45477
- snapshot: () => ({ state: JSON.parse(json), ledger: ledger.list() })
45273
+ response = await transport.replay({
45274
+ sessionID,
45275
+ subjects: unstarted.slice(index, index + REPLAY_MAX_SUBJECTS).map((subject) => ({ subject })),
45276
+ timeoutMs: START_CURSORS_TIMEOUT_MS
45478
45277
  });
45479
- if (state !== undefined) {
45480
- writtenState = json;
45481
- writtenShape = shape;
45482
- writtenAt = now();
45483
- }
45484
45278
  } catch (error) {
45485
- unwritten = [...delivered, ...unwritten];
45486
- log("replay: could not persist the replay state; the next write carries it", error);
45279
+ if (!alive())
45280
+ return;
45281
+ const own = `${AGENT_TOPIC_PREFIX}${sessionID}`;
45282
+ const marked = unstarted.includes(own) && !started(cursors.get(own));
45283
+ if (marked) {
45284
+ cursors.set(own, { from_start: now() });
45285
+ changed = true;
45286
+ }
45287
+ log(marked ? `replay: could not read the stream's position for ${own} before registering while the session's NATS connection is down; its first sweep once the connection is back reads it from the stream's oldest message, so what is stored for it meanwhile is shown` : "replay: could not read the stream's position before registering while the session's NATS connection is down; the first sweep starts the cursors instead", error);
45288
+ break;
45487
45289
  }
45488
- });
45489
- return writes;
45490
- };
45491
- const syncFollowed = () => {
45492
- const followed = new Set(host.followedSubjects());
45493
- for (const subject of [...cursors.keys()]) {
45494
- if (!followed.has(subject)) {
45495
- cursors.delete(subject);
45496
- cursorStarts.delete(subject);
45290
+ if (!alive())
45291
+ return;
45292
+ const { stream } = response;
45293
+ if (streamReplaced(stream))
45294
+ break;
45295
+ streamID = stream.id ?? streamID;
45296
+ streamCreated = stream.created;
45297
+ const at = now();
45298
+ for (const result of response.subjects) {
45299
+ if (result.refused !== undefined || started(cursors.get(result.subject)))
45300
+ continue;
45301
+ cursors.set(result.subject, { since: result.next_after, after: result.next_after });
45302
+ cursorStarts.set(result.subject, at);
45303
+ changed = true;
45497
45304
  }
45498
45305
  }
45499
- for (const subject of followed) {
45500
- if (!cursors.has(subject))
45501
- cursors.set(subject, {});
45502
- }
45306
+ if (changed)
45307
+ await flush(alive, true);
45503
45308
  };
45504
- const failureNotice = (envelope, publishedAt, error, subject) => ({
45505
- eventId: envelope.event_id ?? "unknown",
45506
- sender: senderLabel(envelope),
45507
- summary: envelope.payload_summary ?? "unknown",
45508
- publishedAt,
45509
- error,
45510
- readWith: envelope.source === "dispatch" ? "dispatch read" : "envoy_inbox",
45511
- ...subject === undefined ? {} : { subject },
45512
- envelope
45513
- });
45514
- const showFailureNotice = async (notice, alive) => {
45515
- let queued;
45516
- try {
45517
- queued = await host.showFailureNotice(notice) === "queued";
45518
- } catch (error) {
45519
- if (!alive())
45520
- return "stopped";
45521
- safely("failure notice warning", () => host.failureNoticeFailed(notice, error));
45522
- return "hole";
45523
- }
45524
- if (!alive())
45525
- return "stopped";
45526
- if (queued)
45527
- return "hole";
45528
- record2(replayLedgerIdentity(notice.envelope));
45529
- await flush(alive);
45530
- return "done";
45309
+ const startCursors = async () => {
45310
+ while (running !== undefined)
45311
+ await running;
45312
+ running = startOnce().catch((error) => log("replay: starting the cursors failed", error)).finally(() => {
45313
+ running = undefined;
45314
+ });
45315
+ await running;
45531
45316
  };
45532
- const handle = async (seq, buffered, alive) => {
45533
- const { message } = buffered;
45534
- const envelope = parseEnvelope(message.data);
45535
- if (envelope === undefined) {
45536
- log(`replay: skipping stored message ${seq} on ${message.subject}: not an Envoy envelope`);
45537
- return "done";
45538
- }
45539
- if (isRoleForward(envelope))
45540
- return "done";
45541
- const identity = replayLedgerIdentity(envelope);
45542
- if (ledger.has(identity)) {
45543
- failures.delete(seq);
45544
- return "done";
45545
- }
45546
- if (dedupe?.pending(envelope) === true)
45547
- return "hole";
45548
- if (!alive())
45549
- return "stopped";
45550
- const giveUp = async (error) => {
45551
- const handled = await showFailureNotice(failureNotice(envelope, message.time, error, message.subject), alive);
45552
- if (handled === "done")
45553
- failures.delete(seq);
45554
- return handled;
45555
- };
45556
- const failure = failures.get(seq);
45557
- if (failure !== undefined && failure.count >= REPLAY_FAILURES_BEFORE_NOTICE) {
45558
- return giveUp(failure.error);
45559
- }
45560
- const followed = buffered.subjects[0] ?? message.subject;
45561
- let outcome;
45562
- let error = "the host could not show it";
45563
- try {
45564
- outcome = await host.deliver({
45565
- envelope,
45566
- data: message.data,
45567
- seq,
45568
- subject: message.subject,
45569
- followed,
45570
- time: message.time,
45571
- since: cursors.get(followed)?.since
45572
- });
45573
- } catch (thrown) {
45574
- outcome = "failed";
45575
- error = messageFor(thrown);
45576
- }
45577
- if (!alive())
45578
- return "stopped";
45579
- if (outcome === "shown") {
45580
- failures.delete(seq);
45581
- record2(identity);
45317
+ return {
45318
+ sweep,
45319
+ startCursors,
45320
+ startPending: () => [...cursors.values()].some((cursor) => cursor.from_start !== undefined),
45321
+ setConsumerMode(on) {
45322
+ consumerMode = on;
45323
+ },
45324
+ async followedChanged() {
45325
+ const alive = bind()?.alive;
45326
+ if (alive === undefined)
45327
+ return;
45328
+ try {
45329
+ syncFollowed();
45330
+ await flush(alive);
45331
+ } catch (error) {
45332
+ log("replay: could not take the followed subjects", error);
45333
+ }
45334
+ },
45335
+ delivered: (frame) => ledger.has(replayLedgerIdentity(frame)),
45336
+ async recordDelivered(frame) {
45337
+ const alive = bind()?.alive;
45338
+ if (alive === undefined)
45339
+ return;
45340
+ record2(replayLedgerIdentity(frame));
45582
45341
  await flush(alive);
45583
- return "done";
45584
- }
45585
- if (outcome === "suppressed") {
45586
- failures.delete(seq);
45587
- return "done";
45588
- }
45589
- if (outcome === "queued") {
45590
- failures.delete(seq);
45591
- return "hole";
45592
- }
45593
- const count = (failure?.count ?? 0) + 1;
45594
- failures.set(seq, { count, error });
45595
- if (count >= REPLAY_FAILURES_BEFORE_NOTICE)
45596
- return giveUp(error);
45597
- log(`replay: could not show stored message ${seq} (${envelope.event_id}): ${error}`);
45598
- return "hole";
45599
- };
45600
- const listenerFailed = (error) => {
45601
- if (error instanceof EnvoyApiError) {
45602
- const status = error.details.status;
45603
- if (status === 404) {
45604
- if (listenerNoticed === "not_served")
45605
- return;
45606
- listenerNoticed = "not_served";
45607
- notify({
45608
- kind: "not_served",
45609
- message: "This session's Envoy listener does not serve replay (POST /v1/replay answered 404), so messages published while its connection is down are not recovered."
45610
- });
45342
+ },
45343
+ async recordDeliveredFor(sessionID, frame) {
45344
+ const alive = bindTo(sessionID, writeSession)?.alive;
45345
+ if (alive === undefined)
45346
+ return;
45347
+ record2(replayLedgerIdentity(frame));
45348
+ await flush(alive);
45349
+ },
45350
+ async liveFailed(followed, envelope, error, receivedAt) {
45351
+ const started = cursorStarts.get(followed);
45352
+ if (!isRoleForward(envelope) && answered.has(followed) && cursors.get(followed)?.after !== undefined && (started === undefined || started <= receivedAt)) {
45611
45353
  return;
45612
45354
  }
45613
- if (status === 503 && error.code === REPLAY_UNAVAILABLE_CODE || status === 401 || status === 403) {
45614
- const key = `unavailable:${status}:${error.message}`;
45615
- if (listenerNoticed === key)
45616
- return;
45617
- listenerNoticed = key;
45618
- notify({
45619
- kind: "unavailable",
45620
- status,
45621
- error: error.message,
45622
- message: `Envoy replay is unavailable (${status}: ${error.message}), so messages published while this session's connection is down are not recovered until it answers.`
45623
- });
45355
+ const alive = bind()?.alive;
45356
+ if (alive === undefined)
45624
45357
  return;
45358
+ try {
45359
+ await showFailureNotice(failureNotice(envelope, inboundTimestamp(envelope.issued_at), messageFor(error)), alive);
45360
+ } catch (thrown) {
45361
+ log("replay: could not report a failed live frame", thrown);
45625
45362
  }
45626
- }
45627
- log("replay: the listener's replay failed; the next trigger tries again", error);
45628
- };
45629
- const streamReplaced = (stream) => {
45630
- if (stream.id === undefined) {
45631
- return streamCreated !== undefined && streamCreated !== "" && stream.created !== streamCreated;
45632
- }
45633
- return streamID !== undefined && streamID !== "" && stream.id !== streamID;
45363
+ },
45364
+ followedBefore: (topic, seq) => {
45365
+ const since = cursors.get(topic)?.since;
45366
+ return since !== undefined && seq > since;
45367
+ },
45368
+ restore(snapshot) {
45369
+ epoch += 1;
45370
+ ledger.restore(snapshot.ledger);
45371
+ cursors.clear();
45372
+ cursorStarts.clear();
45373
+ streamID = snapshot.state?.stream_id;
45374
+ streamCreated = snapshot.state?.stream_created;
45375
+ pending.clear();
45376
+ for (const kind of snapshot.state?.notices ?? []) {
45377
+ const known = ReplayPendingNoticeSchema.safeParse(kind);
45378
+ if (known.success)
45379
+ pending.add(known.data);
45380
+ }
45381
+ for (const [subject, cursor] of Object.entries(snapshot.state?.subjects ?? {})) {
45382
+ cursors.set(subject, { ...cursor });
45383
+ }
45384
+ writtenState = snapshot.state === undefined ? undefined : stateJSON();
45385
+ writtenShape = snapshot.state === undefined ? undefined : stateJSON(false);
45386
+ writtenAt = undefined;
45387
+ unwritten = [];
45388
+ failures.clear();
45389
+ listenerNoticed = undefined;
45390
+ answered.clear();
45391
+ },
45392
+ state: () => JSON.parse(stateJSON())
45634
45393
  };
45635
- const streamMovedBack = (stream) => {
45636
- for (const cursor of cursors.values()) {
45637
- if (cursor.after !== undefined && cursor.after > stream.last_seq)
45638
- return true;
45639
- }
45394
+ }
45395
+ function replaySuppressed(rendered) {
45396
+ return rendered.skip || rendered.malformedDelivery === true;
45397
+ }
45398
+ var REPLAYED_SUFFIX = "while this session's connection was down.";
45399
+ function replayedText(content, publishedAt) {
45400
+ return `${content}
45401
+ Published at ${publishedAt} ${REPLAYED_SUFFIX}`;
45402
+ }
45403
+ function failureNoticeFields(notice) {
45404
+ const readWith = notice.readWith === "dispatch read" ? "Read it with the `dispatch read` command on the issue or ask it concerns." : "Read it with the envoy_inbox tool.";
45405
+ return {
45406
+ notice: "message not shown",
45407
+ event_id: notice.eventId,
45408
+ from: notice.sender,
45409
+ summary: notice.summary,
45410
+ published_at: notice.publishedAt,
45411
+ ...notice.subject === undefined ? {} : { subject: notice.subject },
45412
+ error: notice.error,
45413
+ detail: `This session could not be shown this message, so it is not coming back on its own. ${readWith}`
45414
+ };
45415
+ }
45416
+ var REPLAY_NOTICE_NAMES = {
45417
+ stream_recreated: "stream recreated",
45418
+ stream_moved_back: "stream moved back"
45419
+ };
45420
+ function replayNoticeFields(notice) {
45421
+ return {
45422
+ notice: REPLAY_NOTICE_NAMES[notice.kind] ?? "messages may be missing",
45423
+ detail: notice.message
45424
+ };
45425
+ }
45426
+ function envoyNoticeText(fields) {
45427
+ return encode5({ envoy: fields });
45428
+ }
45429
+ var PRIVATE_STREAM_SUBJECTS = [
45430
+ `${AGENT_TOPIC_PREFIX}>`,
45431
+ `${LEGION_NOTICE_TOPIC_PREFIX}>`,
45432
+ `${EXCEPTION_TOPIC_PREFIX}${AGENT_TOPIC_PREFIX}>`
45433
+ ];
45434
+ function subjectsOverlap(a, b) {
45435
+ const aTokens = a.split(".");
45436
+ const bTokens = b.split(".");
45437
+ for (let index = 0;index < aTokens.length && index < bTokens.length; index += 1) {
45438
+ const aToken = aTokens[index];
45439
+ const bToken = bTokens[index];
45440
+ if (aToken === ">" || bToken === ">")
45441
+ return true;
45442
+ if (aToken !== "*" && bToken !== "*" && aToken !== bToken)
45443
+ return false;
45444
+ }
45445
+ return aTokens.length === bTokens.length;
45446
+ }
45447
+ function reachesPrivateStreamSubject(ownAgentSubject, topic) {
45448
+ if (!PRIVATE_STREAM_SUBJECTS.some((subject) => subjectsOverlap(topic, subject)))
45640
45449
  return false;
45450
+ return topic !== ownAgentSubject || /[*>]/.test(ownAgentSubject);
45451
+ }
45452
+ function replayFollowedSubjects(ownAgentSubject, topics, heldForRole = () => false) {
45453
+ const followed = [...topics].filter((topic) => !topic.startsWith(ROLE_TOPIC_PREFIX) && !reachesPrivateStreamSubject(ownAgentSubject, topic) && !heldForRole(topic));
45454
+ return [...new Set([ownAgentSubject, ...followed])];
45455
+ }
45456
+ function rememberedTopics(state) {
45457
+ return Object.keys(state?.subjects ?? {}).filter((topic) => !topic.startsWith(AGENT_TOPIC_PREFIX) && !topic.startsWith(ROLE_TOPIC_PREFIX));
45458
+ }
45459
+ async function closeReplayedRemoval(frame, host) {
45460
+ const closed = (subscriptionRemovedTopics(frame.data, host.sessionID) ?? []).filter((topic) => host.engine.followedBefore(topic, frame.seq) && host.close(topic));
45461
+ if (closed.length === 0)
45462
+ return closed;
45463
+ const unregistering = host.unregister(closed);
45464
+ await host.followedChanged();
45465
+ await unregistering;
45466
+ return closed;
45467
+ }
45468
+ function routeReplayNotice(notice, routes) {
45469
+ if (notice.kind === "not_served" || notice.kind === "unavailable") {
45470
+ routes.warn(notice.message);
45471
+ return;
45472
+ }
45473
+ routes.card(envoyNoticeText(replayNoticeFields(notice)));
45474
+ }
45475
+ function isRoleForward(envelope) {
45476
+ return envelope.dedupe_key?.startsWith(ROLE_FORWARD_KEY_PREFIX) === true || envelope.topic?.startsWith(ROLE_TOPIC_PREFIX) === true;
45477
+ }
45478
+ function replayLedgerIdentity(frame) {
45479
+ return {
45480
+ ...frame.event_id === undefined || frame.event_id === "" ? {} : { event_id: frame.event_id },
45481
+ ...frame.dedupe_key === undefined || !dedupeKeyNamesItsEvent(frame) ? {} : { dedupe_key: frame.dedupe_key }
45641
45482
  };
45642
- const sweepOnce = async () => {
45643
- const binding = bind();
45644
- if (binding === undefined)
45645
- return;
45646
- const { sessionID, alive } = binding;
45647
- syncFollowed();
45648
- const readings = new Map;
45649
- for (const [subject, cursor] of cursors) {
45650
- readings.set(subject, {
45651
- read: cursor.from_start === undefined ? cursor.after : 0,
45652
- more: true
45653
- });
45483
+ }
45484
+ var StoredEnvelopeSchema = EnvelopeSchema.extend({
45485
+ expects_reply: InboundExpectsReplySchema.optional()
45486
+ });
45487
+ function parseEnvelope(data) {
45488
+ let parsed;
45489
+ try {
45490
+ parsed = JSON.parse(data);
45491
+ } catch {
45492
+ return;
45493
+ }
45494
+ const result = StoredEnvelopeSchema.safeParse(parsed);
45495
+ return result.success ? result.data : undefined;
45496
+ }
45497
+ function createLedger(now) {
45498
+ let entries = new Set;
45499
+ const byEvent = new Map;
45500
+ const byKey = new Map;
45501
+ const drop = (entry) => {
45502
+ entries.delete(entry);
45503
+ if (entry.event_id !== undefined && byEvent.get(entry.event_id) === entry) {
45504
+ byEvent.delete(entry.event_id);
45654
45505
  }
45655
- const buffer = new Map;
45656
- const holes = new Map;
45657
- let gapNoticed = false;
45658
- if (pending.size > 0) {
45659
- for (const kind of [...pending].sort()) {
45660
- if (kind === "retention_gap")
45661
- gapNoticed = true;
45662
- tell(kind);
45663
- }
45664
- await flush(alive);
45665
- if (!alive())
45666
- return;
45506
+ if (entry.dedupe_key !== undefined && byKey.get(entry.dedupe_key) === entry) {
45507
+ byKey.delete(entry.dedupe_key);
45667
45508
  }
45668
- if (consumerMode)
45669
- return;
45670
- for (let page = 0;page < REPLAY_PAGES_PER_SWEEP; page += 1) {
45671
- let handledAny = false;
45672
- const asking = [...readings].filter(([, reading]) => reading.more).sort(([, a], [, b]) => (a.read ?? -1) - (b.read ?? -1)).slice(0, REPLAY_MAX_SUBJECTS);
45673
- if (asking.length === 0)
45509
+ };
45510
+ const add = (entry) => {
45511
+ if (entries.size >= REPLAY_LEDGER_LIMIT) {
45512
+ const oldest = entries.values().next();
45513
+ if (oldest.done !== true)
45514
+ drop(oldest.value);
45515
+ }
45516
+ entries.add(entry);
45517
+ if (entry.event_id !== undefined)
45518
+ byEvent.set(entry.event_id, entry);
45519
+ if (entry.dedupe_key !== undefined)
45520
+ byKey.set(entry.dedupe_key, entry);
45521
+ };
45522
+ const expire = () => {
45523
+ const at = now();
45524
+ for (const entry of entries) {
45525
+ if (at - entry.at < REPLAY_LEDGER_TTL_MS)
45674
45526
  break;
45675
- let response;
45676
- try {
45677
- response = await transport.replay({
45678
- sessionID,
45679
- subjects: asking.map(([subject, reading]) => reading.read === undefined ? { subject } : { subject, after: reading.read }),
45680
- ...options.maxMessages === undefined ? {} : { maxMessages: options.maxMessages }
45681
- });
45682
- } catch (error) {
45683
- if (alive()) {
45684
- answered.clear();
45685
- listenerFailed(error);
45686
- }
45687
- return;
45688
- }
45689
- if (!alive())
45527
+ drop(entry);
45528
+ }
45529
+ };
45530
+ const has = (identity) => {
45531
+ expire();
45532
+ return identity.event_id !== undefined && byEvent.has(identity.event_id) || identity.dedupe_key !== undefined && byKey.has(identity.dedupe_key);
45533
+ };
45534
+ return {
45535
+ has,
45536
+ record(identity) {
45537
+ if (identity.event_id === undefined && identity.dedupe_key === undefined)
45690
45538
  return;
45691
- listenerNoticed = undefined;
45692
- for (const result of response.subjects) {
45693
- if (result.refused === undefined)
45694
- answered.add(result.subject);
45695
- else
45696
- answered.delete(result.subject);
45697
- }
45698
- const { stream } = response;
45699
- const replaced = streamReplaced(stream);
45700
- streamID = stream.id ?? (replaced ? undefined : streamID);
45701
- streamCreated = stream.created;
45702
- if (replaced) {
45703
- const at = now();
45704
- for (const subject of cursors.keys()) {
45705
- cursors.set(subject, { since: stream.last_seq, after: stream.last_seq });
45706
- cursorStarts.set(subject, at);
45707
- }
45708
- failures.clear();
45709
- pending.add("stream_recreated");
45710
- await flush(alive);
45711
- if (!alive())
45712
- return;
45713
- tell("stream_recreated");
45714
- await flush(alive);
45539
+ if (has(identity))
45715
45540
  return;
45716
- }
45717
- if (streamMovedBack(stream)) {
45718
- const from = Math.max(0, stream.first_seq - 1);
45719
- for (const [subject, cursor] of cursors) {
45720
- if (cursor.after === undefined)
45721
- continue;
45722
- cursors.set(subject, { ...cursor, after: from });
45723
- const reading = readings.get(subject);
45724
- if (reading !== undefined) {
45725
- reading.read = from;
45726
- reading.more = true;
45727
- }
45728
- }
45729
- buffer.clear();
45730
- holes.clear();
45731
- failures.clear();
45732
- pending.add("stream_moved_back");
45733
- await flush(alive, true);
45734
- if (!alive())
45735
- return;
45736
- tell("stream_moved_back");
45737
- await flush(alive);
45738
- if (!alive())
45739
- return;
45740
- continue;
45741
- }
45742
- for (const [, reading] of asking)
45743
- reading.more = false;
45744
- for (const result of response.subjects) {
45745
- const reading = readings.get(result.subject);
45746
- const markedAt = cursors.get(result.subject)?.from_start;
45747
- if (reading === undefined || markedAt === undefined || result.refused !== undefined) {
45748
- continue;
45749
- }
45750
- const start = Math.max(0, stream.first_seq - 1);
45751
- cursors.set(result.subject, { since: start, after: start });
45752
- cursorStarts.set(result.subject, now());
45753
- if (now() - markedAt < DELIVERY_DUPLICATE_WINDOW_MS)
45754
- reading.read = start;
45755
- }
45756
- let gapped = false;
45757
- for (const result of response.subjects) {
45758
- const reading = readings.get(result.subject);
45759
- if (reading?.read === undefined || result.refused !== undefined)
45760
- continue;
45761
- if (reading.read >= stream.first_seq - 1)
45762
- continue;
45763
- gapped = true;
45764
- reading.read = stream.first_seq - 1;
45765
- const cursor = cursors.get(result.subject);
45766
- if (cursor?.after !== undefined && cursor.after < reading.read) {
45767
- cursors.set(result.subject, { ...cursor, after: reading.read });
45768
- }
45769
- }
45770
- if (gapped) {
45771
- if (!gapNoticed)
45772
- pending.add("retention_gap");
45773
- await flush(alive, true);
45774
- if (!alive())
45775
- return;
45776
- if (pending.has("retention_gap")) {
45777
- gapNoticed = true;
45778
- tell("retention_gap");
45779
- await flush(alive);
45780
- }
45781
- }
45782
- for (const result of response.subjects) {
45783
- const reading = readings.get(result.subject);
45784
- if (reading === undefined || result.refused !== undefined)
45785
- continue;
45786
- if (reading.read === undefined) {
45787
- const cursor = cursors.get(result.subject);
45788
- if (cursor !== undefined && cursor.after === undefined) {
45789
- cursors.set(result.subject, { since: result.next_after, after: result.next_after });
45790
- cursorStarts.set(result.subject, now());
45791
- }
45792
- reading.read = result.next_after;
45793
- continue;
45794
- }
45795
- for (const message of result.messages) {
45796
- if (message.seq <= reading.read)
45797
- continue;
45798
- const buffered = buffer.get(message.seq);
45799
- if (buffered === undefined) {
45800
- buffer.set(message.seq, { message, subjects: [result.subject] });
45801
- } else if (!buffered.subjects.includes(result.subject)) {
45802
- buffered.subjects.push(result.subject);
45803
- }
45804
- }
45805
- reading.read = Math.max(reading.read, result.next_after);
45806
- reading.more = result.more;
45807
- }
45808
- let bound = Number.POSITIVE_INFINITY;
45809
- for (const reading of readings.values()) {
45810
- if (reading.more && reading.read !== undefined)
45811
- bound = Math.min(bound, reading.read);
45812
- }
45813
- const ready = [...buffer.keys()].filter((seq) => seq <= bound).sort((a, b) => a - b);
45814
- for (const seq of ready) {
45815
- const buffered = buffer.get(seq);
45816
- if (buffered === undefined)
45817
- continue;
45818
- buffer.delete(seq);
45819
- if (!buffered.subjects.some((subject) => cursors.has(subject)))
45820
- continue;
45821
- const handled = await handle(seq, buffered, alive);
45822
- if (handled === "stopped")
45823
- return;
45824
- if (handled === "done")
45825
- handledAny = true;
45826
- if (handled === "hole") {
45827
- for (const subject of buffered.subjects) {
45828
- if (!holes.has(subject))
45829
- holes.set(subject, seq);
45830
- }
45831
- }
45832
- }
45833
- if (!alive())
45834
- return;
45835
- for (const [subject, reading] of readings) {
45836
- const cursor = cursors.get(subject);
45837
- if (cursor?.after === undefined || reading.read === undefined)
45838
- continue;
45839
- let after = Math.min(reading.read, bound);
45840
- const hole = holes.get(subject);
45841
- if (hole !== undefined)
45842
- after = Math.min(after, hole - 1);
45843
- if (after > cursor.after)
45844
- cursors.set(subject, { ...cursor, after });
45845
- }
45846
- await flush(alive, handledAny);
45847
- if (![...readings.values()].some((reading) => reading.more))
45848
- break;
45541
+ const entry = { ...identity, at: now() };
45542
+ add(entry);
45543
+ return entry;
45544
+ },
45545
+ restore(restored) {
45546
+ entries = new Set;
45547
+ byEvent.clear();
45548
+ byKey.clear();
45549
+ const at = now();
45550
+ const kept = restored.filter((entry) => at - entry.at < REPLAY_LEDGER_TTL_MS && (entry.event_id !== undefined || entry.dedupe_key !== undefined)).sort((a, b) => a.at - b.at);
45551
+ for (const entry of kept)
45552
+ add({ ...entry });
45553
+ },
45554
+ list() {
45555
+ expire();
45556
+ return [...entries];
45557
+ }
45558
+ };
45559
+ }
45560
+
45561
+ // ../envoy-client/src/consumer-delivery.ts
45562
+ var DELIVER_SUBJECT_PREFIX = "notifications.envoy.deliver.";
45563
+ function deliverSubject(sessionID) {
45564
+ return `${DELIVER_SUBJECT_PREFIX}${sessionID}`;
45565
+ }
45566
+ var RelayHeader = {
45567
+ subject: "Envoy-Subject",
45568
+ streamSeq: "Envoy-Stream-Seq",
45569
+ streamID: "Envoy-Stream-Id",
45570
+ delivered: "Envoy-Delivered",
45571
+ storedAt: "Envoy-Stored-At",
45572
+ gap: "Envoy-Gap"
45573
+ };
45574
+ var RELAY_PROGRESS_INTERVAL_MS = 20000;
45575
+ var FOLLOW_CLOCK_ALLOWANCE_MS = 2000;
45576
+ var RELAY_ATTEMPTS_BEFORE_FAILED = 3;
45577
+ var decoder4 = new TextDecoder;
45578
+ var DECIMAL = /^[0-9]+$/;
45579
+ var RFC3339 = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})$/;
45580
+ function positiveInteger(text) {
45581
+ if (text === null || text === undefined || !DECIMAL.test(text))
45582
+ return;
45583
+ const value = Number(text);
45584
+ return Number.isSafeInteger(value) && value > 0 ? value : undefined;
45585
+ }
45586
+ function parseStoredAt(text) {
45587
+ const match = RFC3339.exec(text);
45588
+ if (match === null)
45589
+ return;
45590
+ const fraction = (match[2] ?? "").padEnd(3, "0").slice(0, 3);
45591
+ const ms = Date.parse(`${match[1]}.${fraction}${match[3]}`);
45592
+ return Number.isNaN(ms) ? undefined : ms;
45593
+ }
45594
+ function decodeRelayFrame(message) {
45595
+ const reply = message.reply ?? "";
45596
+ if (reply === "")
45597
+ return { error: "no reply subject" };
45598
+ const headers = message.headers;
45599
+ if (headers === undefined)
45600
+ return { error: "no headers" };
45601
+ const subject = headers.get(RelayHeader.subject) ?? "";
45602
+ if (subject === "")
45603
+ return { error: `no ${RelayHeader.subject}` };
45604
+ const streamSeq = positiveInteger(headers.get(RelayHeader.streamSeq));
45605
+ if (streamSeq === undefined)
45606
+ return { error: `bad ${RelayHeader.streamSeq}` };
45607
+ const streamID = headers.get(RelayHeader.streamID) ?? "";
45608
+ if (streamID === "")
45609
+ return { error: `no ${RelayHeader.streamID}` };
45610
+ const delivered = positiveInteger(headers.get(RelayHeader.delivered));
45611
+ if (delivered === undefined)
45612
+ return { error: `bad ${RelayHeader.delivered}` };
45613
+ const storedAt = headers.get(RelayHeader.storedAt) ?? "";
45614
+ const storedAtMs = parseStoredAt(storedAt);
45615
+ if (storedAtMs === undefined)
45616
+ return { error: `bad ${RelayHeader.storedAt}` };
45617
+ return {
45618
+ frame: {
45619
+ subject,
45620
+ streamSeq,
45621
+ streamID,
45622
+ delivered,
45623
+ storedAt,
45624
+ storedAtMs,
45625
+ gap: headers.get(RelayHeader.gap) === "true",
45626
+ data: typeof message.data === "string" ? message.data : decoder4.decode(message.data),
45627
+ reply
45628
+ }
45629
+ };
45630
+ }
45631
+ function newEpoch() {
45632
+ return crypto.randomUUID();
45633
+ }
45634
+ var GAP_MESSAGES = {
45635
+ retention_gap: "The notification stream no longer holds some messages published to this session while it was away: messages older than 72 hours may be missing.",
45636
+ stream_recreated: "Envoy's notification stream was recreated, so messages published to this session before that may be lost."
45637
+ };
45638
+ var ConsumerDeliverySnapshotSchema = object({
45639
+ resume: object({ stream_id: string2().min(1), seq: number2().int().nonnegative() }).optional(),
45640
+ follows: record(string2(), number2()).default({})
45641
+ });
45642
+ function parseIdentity(data) {
45643
+ let parsed;
45644
+ try {
45645
+ parsed = JSON.parse(data);
45646
+ } catch {
45647
+ return;
45648
+ }
45649
+ const identity = DedupeIdentitySchema.safeParse(parsed);
45650
+ if (!identity.success)
45651
+ return;
45652
+ const { event_id, dedupe_key } = identity.data;
45653
+ return event_id === undefined && dedupe_key === undefined ? undefined : identity.data;
45654
+ }
45655
+ function reaches(topic, subject) {
45656
+ return expandSubscriptionTopics([topic]).some((pattern) => subjectsOverlap(pattern, subject));
45657
+ }
45658
+ function every(ms, callback) {
45659
+ const timer = setInterval(callback, ms);
45660
+ return () => clearInterval(timer);
45661
+ }
45662
+ function createConsumerDelivery(options) {
45663
+ const { host, ledger, sessionID } = options;
45664
+ const now = options.now ?? Date.now;
45665
+ const repeat = options.every ?? every;
45666
+ const ownSubject = agentSubject(sessionID);
45667
+ let currentEpoch = { id: newEpoch(), startedAt: now() };
45668
+ let follows = new Map;
45669
+ let streamID;
45670
+ let held = new Set;
45671
+ let written;
45672
+ let registeredResume;
45673
+ let gapTold = false;
45674
+ let closed = false;
45675
+ let relayed;
45676
+ let persisted = JSON.stringify({ follows: {} });
45677
+ const entries = new Map;
45678
+ const queue = [];
45679
+ let blocking;
45680
+ let pumping = false;
45681
+ const safely = (what, call) => {
45682
+ try {
45683
+ call();
45684
+ } catch (error) {
45685
+ try {
45686
+ host.log(`consumer delivery: ${what} failed`, error);
45687
+ } catch {}
45849
45688
  }
45850
45689
  };
45851
- const runSweep = async () => {
45690
+ const log = (message, error) => safely("log", () => host.log(`consumer delivery: ${message}`, error));
45691
+ const send = (reply, body) => safely(`reply ${body}`, () => options.publish(reply, body));
45692
+ const tellGap = (kind) => safely("gap notice", () => host.gap({ kind, message: GAP_MESSAGES[kind] }));
45693
+ const switchStream = (id) => {
45694
+ if (streamID === id)
45695
+ return;
45696
+ streamID = id;
45697
+ held = new Set;
45698
+ written = undefined;
45699
+ };
45700
+ const tellReplacedResume = (id) => {
45701
+ const asked = resumePoint() ?? registeredResume;
45702
+ if (asked === undefined || asked.stream_id === id)
45703
+ return;
45704
+ registeredResume = undefined;
45705
+ tellGap("stream_recreated");
45706
+ };
45707
+ const followedAt = (subject) => {
45708
+ if (subject === ownSubject)
45709
+ return Number.NEGATIVE_INFINITY;
45710
+ let earliest;
45711
+ for (const [topic, at] of follows) {
45712
+ if (!reaches(topic, subject))
45713
+ continue;
45714
+ if (earliest === undefined || at < earliest)
45715
+ earliest = at;
45716
+ }
45717
+ return earliest;
45718
+ };
45719
+ const followedOnCorePath = (frame) => {
45720
+ const state = ledger.state();
45721
+ if (state.stream_id !== frame.streamID)
45722
+ return false;
45723
+ for (const [topic, cursor] of Object.entries(state.subjects)) {
45724
+ if (cursor.since === undefined || frame.streamSeq <= cursor.since)
45725
+ continue;
45726
+ if (reaches(topic, frame.subject))
45727
+ return true;
45728
+ }
45729
+ return false;
45730
+ };
45731
+ const settle = (entry, body) => {
45732
+ if (entry.settled)
45733
+ return;
45734
+ entry.settled = true;
45735
+ entry.stopProgress();
45736
+ entries.delete(entry.key);
45737
+ for (const reply of entry.replies)
45738
+ send(reply, body);
45739
+ if (body === "done" && entry.frame.streamID === streamID) {
45740
+ held.delete(entry.frame.streamSeq);
45741
+ written = Math.max(written ?? 0, entry.frame.streamSeq);
45742
+ }
45743
+ release(entry);
45744
+ };
45745
+ const release = (entry) => {
45746
+ if (blocking !== entry)
45747
+ return;
45748
+ blocking = undefined;
45749
+ pump();
45750
+ };
45751
+ const alreadyWritten = (identity) => identity !== undefined && ledger.delivered(identity);
45752
+ const failed = (entry, error) => {
45753
+ if (entry.settled)
45754
+ return;
45755
+ if (entry.frame.delivered < RELAY_ATTEMPTS_BEFORE_FAILED) {
45756
+ log(`frame ${entry.frame.streamSeq} failed; it comes again`, error);
45757
+ settle(entry, "nak");
45758
+ return;
45759
+ }
45760
+ safely("failure notice", () => {
45761
+ const { subject, data } = entry.frame;
45762
+ const { envelope } = renderInbound(data, sessionID, subject);
45763
+ if (envelope !== undefined)
45764
+ ledger.liveFailed(subject, envelope, error, now());
45765
+ });
45766
+ settle(entry, "done");
45767
+ };
45768
+ const handOff = (entry) => {
45769
+ const handle = {
45770
+ ...entry.frame,
45771
+ late: entry.late,
45772
+ done: () => settle(entry, "done"),
45773
+ nak: () => settle(entry, "nak"),
45774
+ release: () => release(entry)
45775
+ };
45776
+ blocking = entry;
45777
+ let result;
45852
45778
  try {
45853
- await sweepOnce();
45779
+ result = host.deliver(handle);
45854
45780
  } catch (error) {
45855
- log("replay: a sweep failed", error);
45781
+ failed(entry, error);
45782
+ release(entry);
45783
+ return;
45856
45784
  }
45857
- };
45858
- const sweep = () => {
45859
- if (running === undefined) {
45860
- running = runSweep().finally(() => {
45861
- running = undefined;
45862
- });
45863
- return running;
45785
+ if (!(result instanceof Promise)) {
45786
+ release(entry);
45787
+ return;
45864
45788
  }
45865
- rerun ??= running.then(() => {
45866
- rerun = undefined;
45867
- return sweep();
45789
+ result.then(() => release(entry), (error) => {
45790
+ failed(entry, error);
45791
+ release(entry);
45868
45792
  });
45869
- return rerun;
45870
45793
  };
45871
- const started = (cursor) => cursor?.after !== undefined || cursor?.from_start !== undefined;
45872
- const startOnce = async () => {
45873
- const binding = bind();
45874
- if (binding === undefined)
45794
+ function pump() {
45795
+ if (pumping)
45875
45796
  return;
45876
- const { sessionID, alive } = binding;
45877
- const unstarted = [...new Set(host.followedSubjects())].filter((subject) => !started(cursors.get(subject)));
45878
- let changed = false;
45879
- for (let index = 0;index < unstarted.length; index += REPLAY_MAX_SUBJECTS) {
45880
- let response;
45881
- try {
45882
- response = await transport.replay({
45883
- sessionID,
45884
- subjects: unstarted.slice(index, index + REPLAY_MAX_SUBJECTS).map((subject) => ({ subject })),
45885
- timeoutMs: START_CURSORS_TIMEOUT_MS
45886
- });
45887
- } catch (error) {
45888
- if (!alive())
45797
+ pumping = true;
45798
+ try {
45799
+ while (blocking === undefined && !closed) {
45800
+ const entry = queue.shift();
45801
+ if (entry === undefined)
45889
45802
  return;
45890
- const own = `${AGENT_TOPIC_PREFIX}${sessionID}`;
45891
- const marked = unstarted.includes(own) && !started(cursors.get(own));
45892
- if (marked) {
45893
- cursors.set(own, { from_start: now() });
45894
- changed = true;
45803
+ if (entry.settled)
45804
+ continue;
45805
+ if (alreadyWritten(entry.identity)) {
45806
+ settle(entry, "done");
45807
+ continue;
45895
45808
  }
45896
- log(marked ? `replay: could not read the stream's position for ${own} before registering while the session's NATS connection is down; its first sweep once the connection is back reads it from the stream's oldest message, so what is stored for it meanwhile is shown` : "replay: could not read the stream's position before registering while the session's NATS connection is down; the first sweep starts the cursors instead", error);
45897
- break;
45809
+ handOff(entry);
45898
45810
  }
45899
- if (!alive())
45900
- return;
45901
- const { stream } = response;
45902
- if (streamReplaced(stream))
45903
- break;
45904
- streamID = stream.id ?? streamID;
45905
- streamCreated = stream.created;
45906
- const at = now();
45907
- for (const result of response.subjects) {
45908
- if (result.refused !== undefined || started(cursors.get(result.subject)))
45909
- continue;
45910
- cursors.set(result.subject, { since: result.next_after, after: result.next_after });
45911
- cursorStarts.set(result.subject, at);
45912
- changed = true;
45811
+ } finally {
45812
+ pumping = false;
45813
+ }
45814
+ }
45815
+ const receive = (message) => {
45816
+ const decoded = decodeRelayFrame(message);
45817
+ if ("error" in decoded) {
45818
+ log(`dropping an undecodable relay frame: ${decoded.error}`);
45819
+ if (message.reply !== undefined && message.reply !== "")
45820
+ send(message.reply, "done");
45821
+ return;
45822
+ }
45823
+ const { frame } = decoded;
45824
+ if (closed) {
45825
+ send(frame.reply, "nak");
45826
+ return;
45827
+ }
45828
+ send(frame.reply, "received");
45829
+ if (frame.gap && !gapTold)
45830
+ tellGap("retention_gap");
45831
+ gapTold = false;
45832
+ if (frame.streamID !== streamID) {
45833
+ if (streamID !== undefined && (written !== undefined || held.size > 0)) {
45834
+ tellGap("stream_recreated");
45835
+ } else if (streamID === undefined) {
45836
+ tellReplacedResume(frame.streamID);
45913
45837
  }
45838
+ switchStream(frame.streamID);
45914
45839
  }
45915
- if (changed)
45916
- await flush(alive, true);
45840
+ const key = `${frame.streamID}:${frame.streamSeq}`;
45841
+ const first = entries.get(key);
45842
+ if (first !== undefined) {
45843
+ first.replies.push(frame.reply);
45844
+ return;
45845
+ }
45846
+ const since = followedAt(frame.subject);
45847
+ const unfollowed = (since === undefined || frame.storedAtMs < since - FOLLOW_CLOCK_ALLOWANCE_MS) && !followedOnCorePath(frame);
45848
+ const identity = unfollowed ? undefined : parseIdentity(frame.data);
45849
+ if (unfollowed || alreadyWritten(identity)) {
45850
+ send(frame.reply, "done");
45851
+ written = Math.max(written ?? 0, frame.streamSeq);
45852
+ return;
45853
+ }
45854
+ held.add(frame.streamSeq);
45855
+ const entry = {
45856
+ frame,
45857
+ identity,
45858
+ late: frame.delivered > 1 || frame.storedAtMs < currentEpoch.startedAt,
45859
+ replies: [frame.reply],
45860
+ key,
45861
+ stopProgress: () => {
45862
+ return;
45863
+ },
45864
+ settled: false
45865
+ };
45866
+ entry.stopProgress = repeat(RELAY_PROGRESS_INTERVAL_MS, () => {
45867
+ if (entry.settled)
45868
+ return;
45869
+ for (const reply of entry.replies)
45870
+ send(reply, "progress");
45871
+ });
45872
+ entries.set(key, entry);
45873
+ queue.push(entry);
45874
+ pump();
45875
+ };
45876
+ const resumePoint = () => {
45877
+ if (streamID === undefined)
45878
+ return;
45879
+ if (held.size > 0)
45880
+ return { stream_id: streamID, seq: Math.min(...held) - 1 };
45881
+ return written === undefined ? undefined : { stream_id: streamID, seq: written };
45882
+ };
45883
+ const seededResume = () => {
45884
+ const state = ledger.state();
45885
+ const stream = state.stream_id;
45886
+ if (stream === undefined)
45887
+ return;
45888
+ let lowest;
45889
+ for (const [subject, cursor] of Object.entries(state.subjects)) {
45890
+ if (cursor.after === undefined || !streamStores(subject))
45891
+ continue;
45892
+ if (lowest === undefined || cursor.after < lowest)
45893
+ lowest = cursor.after;
45894
+ }
45895
+ return lowest === undefined ? undefined : { stream_id: stream, seq: lowest };
45896
+ };
45897
+ const snapshot = () => {
45898
+ const resume = resumePoint();
45899
+ return {
45900
+ ...resume === undefined ? {} : { resume },
45901
+ follows: Object.fromEntries(follows)
45902
+ };
45917
45903
  };
45918
- const startCursors = async () => {
45919
- while (running !== undefined)
45920
- await running;
45921
- running = startOnce().catch((error) => log("replay: starting the cursors failed", error)).finally(() => {
45922
- running = undefined;
45923
- });
45924
- await running;
45904
+ const persist = () => {
45905
+ const current = snapshot();
45906
+ const serialized = JSON.stringify(current);
45907
+ if (serialized === persisted)
45908
+ return;
45909
+ if (!options.persist(current))
45910
+ return;
45911
+ persisted = serialized;
45925
45912
  };
45926
45913
  return {
45927
- sweep,
45928
- startCursors,
45929
- startPending: () => [...cursors.values()].some((cursor) => cursor.from_start !== undefined),
45930
- setConsumerMode(on) {
45931
- consumerMode = on;
45932
- },
45933
- async followedChanged() {
45934
- const alive = bind()?.alive;
45935
- if (alive === undefined)
45936
- return;
45937
- try {
45938
- syncFollowed();
45939
- await flush(alive);
45940
- } catch (error) {
45941
- log("replay: could not take the followed subjects", error);
45942
- }
45943
- },
45944
- delivered: (frame) => ledger.has(replayLedgerIdentity(frame)),
45945
- async recordDelivered(frame) {
45946
- const alive = bind()?.alive;
45947
- if (alive === undefined)
45948
- return;
45949
- record2(replayLedgerIdentity(frame));
45950
- await flush(alive);
45914
+ subject: deliverSubject(sessionID),
45915
+ receive,
45916
+ epoch: () => currentEpoch,
45917
+ beginEpoch() {
45918
+ currentEpoch = { id: newEpoch(), startedAt: now() };
45919
+ return currentEpoch;
45951
45920
  },
45952
- async recordDeliveredFor(sessionID, frame) {
45953
- const alive = bindTo(sessionID, writeSession)?.alive;
45954
- if (alive === undefined)
45955
- return;
45956
- record2(replayLedgerIdentity(frame));
45957
- await flush(alive);
45921
+ registration() {
45922
+ const resume = resumePoint() ?? seededResume();
45923
+ registeredResume = resume;
45924
+ return {
45925
+ consumer: true,
45926
+ epoch: currentEpoch.id,
45927
+ ...resume === undefined ? {} : { resume }
45928
+ };
45958
45929
  },
45959
- async liveFailed(followed, envelope, error, receivedAt) {
45960
- const started = cursorStarts.get(followed);
45961
- if (!isRoleForward(envelope) && answered.has(followed) && cursors.get(followed)?.after !== undefined && (started === undefined || started <= receivedAt)) {
45962
- return;
45963
- }
45964
- const alive = bind()?.alive;
45965
- if (alive === undefined)
45966
- return;
45967
- try {
45968
- await showFailureNotice(failureNotice(envelope, inboundTimestamp(envelope.issued_at), messageFor(error)), alive);
45969
- } catch (thrown) {
45970
- log("replay: could not report a failed live frame", thrown);
45930
+ answered(answer, topics) {
45931
+ if (answer.mode === "consumer") {
45932
+ if (answer.stream_id !== "" && answer.stream_id !== streamID) {
45933
+ tellReplacedResume(answer.stream_id);
45934
+ switchStream(answer.stream_id);
45935
+ }
45936
+ const floor = (answer.consumer_start ?? 0) - 1;
45937
+ if (answer.stream_id === streamID && floor > (written ?? -1))
45938
+ written = floor;
45939
+ if (answer.gap) {
45940
+ tellGap("retention_gap");
45941
+ gapTold = true;
45942
+ }
45943
+ relayed = new Set([...topics].filter(streamStores));
45944
+ } else {
45945
+ relayed = undefined;
45971
45946
  }
45947
+ ledger.setConsumerMode(relayed !== undefined);
45948
+ persist();
45949
+ return answer.mode;
45972
45950
  },
45973
- followedBefore: (topic, seq) => {
45974
- const since = cursors.get(topic)?.since;
45975
- return since !== undefined && seq > since;
45976
- },
45977
- restore(snapshot) {
45978
- epoch += 1;
45979
- ledger.restore(snapshot.ledger);
45980
- cursors.clear();
45981
- cursorStarts.clear();
45982
- streamID = snapshot.state?.stream_id;
45983
- streamCreated = snapshot.state?.stream_created;
45984
- pending.clear();
45985
- for (const kind of snapshot.state?.notices ?? []) {
45986
- const known = ReplayPendingNoticeSchema.safeParse(kind);
45987
- if (known.success)
45988
- pending.add(known.data);
45989
- }
45990
- for (const [subject, cursor] of Object.entries(snapshot.state?.subjects ?? {})) {
45991
- cursors.set(subject, { ...cursor });
45951
+ relays: (topic) => relayed?.has(topic) === true,
45952
+ relaying: () => relayed !== undefined,
45953
+ setFollowed(topics) {
45954
+ const at = now();
45955
+ const next = new Map;
45956
+ for (const topic of topics) {
45957
+ if (topic === ownSubject)
45958
+ continue;
45959
+ next.set(topic, follows.get(topic) ?? at);
45992
45960
  }
45993
- writtenState = snapshot.state === undefined ? undefined : stateJSON();
45994
- writtenShape = snapshot.state === undefined ? undefined : stateJSON(false);
45995
- writtenAt = undefined;
45996
- unwritten = [];
45997
- failures.clear();
45998
- listenerNoticed = undefined;
45999
- answered.clear();
45961
+ follows = next;
45962
+ persist();
46000
45963
  },
46001
- state: () => JSON.parse(stateJSON())
46002
- };
46003
- }
46004
- function replaySuppressed(rendered) {
46005
- return rendered.skip || rendered.malformedDelivery === true;
46006
- }
46007
- var REPLAYED_SUFFIX = "while this session's connection was down.";
46008
- function replayedText(content, publishedAt) {
46009
- return `${content}
46010
- Published at ${publishedAt} ${REPLAYED_SUFFIX}`;
46011
- }
46012
- function failureNoticeFields(notice) {
46013
- const readWith = notice.readWith === "dispatch read" ? "Read it with the `dispatch read` command on the issue or ask it concerns." : "Read it with the envoy_inbox tool.";
46014
- return {
46015
- notice: "message not shown",
46016
- event_id: notice.eventId,
46017
- from: notice.sender,
46018
- summary: notice.summary,
46019
- published_at: notice.publishedAt,
46020
- ...notice.subject === undefined ? {} : { subject: notice.subject },
46021
- error: notice.error,
46022
- detail: `This session could not be shown this message, so it is not coming back on its own. ${readWith}`
46023
- };
46024
- }
46025
- var REPLAY_NOTICE_NAMES = {
46026
- stream_recreated: "stream recreated",
46027
- stream_moved_back: "stream moved back"
46028
- };
46029
- function replayNoticeFields(notice) {
46030
- return {
46031
- notice: REPLAY_NOTICE_NAMES[notice.kind] ?? "messages may be missing",
46032
- detail: notice.message
46033
- };
46034
- }
46035
- function envoyNoticeText(fields) {
46036
- return encode5({ envoy: fields });
46037
- }
46038
- var PRIVATE_STREAM_SUBJECTS = [
46039
- `${AGENT_TOPIC_PREFIX}>`,
46040
- `${LEGION_NOTICE_TOPIC_PREFIX}>`,
46041
- `${EXCEPTION_TOPIC_PREFIX}${AGENT_TOPIC_PREFIX}>`
46042
- ];
46043
- function subjectsOverlap(a, b) {
46044
- const aTokens = a.split(".");
46045
- const bTokens = b.split(".");
46046
- for (let index = 0;index < aTokens.length && index < bTokens.length; index += 1) {
46047
- const aToken = aTokens[index];
46048
- const bToken = bTokens[index];
46049
- if (aToken === ">" || bToken === ">")
46050
- return true;
46051
- if (aToken !== "*" && bToken !== "*" && aToken !== bToken)
46052
- return false;
46053
- }
46054
- return aTokens.length === bTokens.length;
46055
- }
46056
- function reachesPrivateStreamSubject(ownAgentSubject, topic) {
46057
- if (!PRIVATE_STREAM_SUBJECTS.some((subject) => subjectsOverlap(topic, subject)))
46058
- return false;
46059
- return topic !== ownAgentSubject || /[*>]/.test(ownAgentSubject);
46060
- }
46061
- function replayFollowedSubjects(ownAgentSubject, topics, heldForRole = () => false) {
46062
- const followed = [...topics].filter((topic) => !topic.startsWith(ROLE_TOPIC_PREFIX) && !reachesPrivateStreamSubject(ownAgentSubject, topic) && !heldForRole(topic));
46063
- return [...new Set([ownAgentSubject, ...followed])];
46064
- }
46065
- function rememberedTopics(state) {
46066
- return Object.keys(state?.subjects ?? {}).filter((topic) => !topic.startsWith(AGENT_TOPIC_PREFIX) && !topic.startsWith(ROLE_TOPIC_PREFIX));
46067
- }
46068
- async function closeReplayedRemoval(frame, host) {
46069
- const closed = (subscriptionRemovedTopics(frame.data, host.sessionID) ?? []).filter((topic) => host.engine.followedBefore(topic, frame.seq) && host.close(topic));
46070
- if (closed.length === 0)
46071
- return closed;
46072
- const unregistering = host.unregister(closed);
46073
- await host.followedChanged();
46074
- await unregistering;
46075
- return closed;
46076
- }
46077
- function routeReplayNotice(notice, routes) {
46078
- if (notice.kind === "not_served" || notice.kind === "unavailable") {
46079
- routes.warn(notice.message);
46080
- return;
46081
- }
46082
- routes.card(envoyNoticeText(replayNoticeFields(notice)));
46083
- }
46084
- function isRoleForward(envelope) {
46085
- return envelope.dedupe_key?.startsWith(ROLE_FORWARD_KEY_PREFIX) === true || envelope.topic?.startsWith(ROLE_TOPIC_PREFIX) === true;
46086
- }
46087
- function replayLedgerIdentity(frame) {
46088
- return {
46089
- ...frame.event_id === undefined || frame.event_id === "" ? {} : { event_id: frame.event_id },
46090
- ...frame.dedupe_key === undefined || !dedupeKeyNamesItsEvent(frame) ? {} : { dedupe_key: frame.dedupe_key }
46091
- };
46092
- }
46093
- var StoredEnvelopeSchema = EnvelopeSchema.extend({
46094
- expects_reply: InboundExpectsReplySchema.optional()
46095
- });
46096
- function parseEnvelope(data) {
46097
- let parsed;
46098
- try {
46099
- parsed = JSON.parse(data);
46100
- } catch {
46101
- return;
46102
- }
46103
- const result = StoredEnvelopeSchema.safeParse(parsed);
46104
- return result.success ? result.data : undefined;
46105
- }
46106
- function createLedger(now) {
46107
- let entries = new Set;
46108
- const byEvent = new Map;
46109
- const byKey = new Map;
46110
- const drop = (entry) => {
46111
- entries.delete(entry);
46112
- if (entry.event_id !== undefined && byEvent.get(entry.event_id) === entry) {
46113
- byEvent.delete(entry.event_id);
46114
- }
46115
- if (entry.dedupe_key !== undefined && byKey.get(entry.dedupe_key) === entry) {
46116
- byKey.delete(entry.dedupe_key);
45964
+ persist,
45965
+ resumePoint,
45966
+ snapshot,
45967
+ restore(restored) {
45968
+ const merged = new Map(Object.entries(restored.follows));
45969
+ for (const [topic, at] of follows)
45970
+ if (!merged.has(topic))
45971
+ merged.set(topic, at);
45972
+ follows = merged;
45973
+ streamID = restored.resume?.stream_id;
45974
+ held = new Set;
45975
+ written = restored.resume?.seq;
45976
+ persisted = JSON.stringify(snapshot());
45977
+ },
45978
+ close() {
45979
+ closed = true;
45980
+ relayed = undefined;
45981
+ ledger.setConsumerMode(false);
45982
+ queue.length = 0;
45983
+ for (const entry of [...entries.values()])
45984
+ settle(entry, "nak");
45985
+ blocking = undefined;
46117
45986
  }
46118
45987
  };
46119
- const add = (entry) => {
46120
- if (entries.size >= REPLAY_LEDGER_LIMIT) {
46121
- const oldest = entries.values().next();
46122
- if (oldest.done !== true)
46123
- drop(oldest.value);
46124
- }
46125
- entries.add(entry);
46126
- if (entry.event_id !== undefined)
46127
- byEvent.set(entry.event_id, entry);
46128
- if (entry.dedupe_key !== undefined)
46129
- byKey.set(entry.dedupe_key, entry);
45988
+ }
45989
+
45990
+ // ../envoy-client/src/envoy-config.ts
45991
+ import {
45992
+ chmodSync,
45993
+ closeSync,
45994
+ existsSync,
45995
+ lstatSync,
45996
+ mkdtempSync,
45997
+ openSync,
45998
+ readFileSync as readFileSync2,
45999
+ readlinkSync,
46000
+ rmSync,
46001
+ statSync
46002
+ } from "fs";
46003
+ import { homedir, tmpdir } from "os";
46004
+ import * as path from "path";
46005
+
46006
+ // ../envoy-client/src/json-position.ts
46007
+ function jsonErrorPosition(text) {
46008
+ let at = 0;
46009
+ const fail = () => {
46010
+ throw new RangeError("not JSON");
46130
46011
  };
46131
- const expire = () => {
46132
- const at = now();
46133
- for (const entry of entries) {
46134
- if (at - entry.at < REPLAY_LEDGER_TTL_MS)
46135
- break;
46136
- drop(entry);
46137
- }
46012
+ const space = () => {
46013
+ while (at < text.length && `
46014
+ \r`.includes(text.charAt(at)))
46015
+ at += 1;
46138
46016
  };
46139
- const has = (identity) => {
46140
- expire();
46141
- return identity.event_id !== undefined && byEvent.has(identity.event_id) || identity.dedupe_key !== undefined && byKey.has(identity.dedupe_key);
46017
+ const expect = (char) => {
46018
+ if (text.charAt(at) !== char)
46019
+ fail();
46020
+ at += 1;
46142
46021
  };
46143
- return {
46144
- has,
46145
- record(identity) {
46146
- if (identity.event_id === undefined && identity.dedupe_key === undefined)
46022
+ const string = () => {
46023
+ expect('"');
46024
+ while (at < text.length) {
46025
+ const char = text.charAt(at);
46026
+ if (char === '"') {
46027
+ at += 1;
46147
46028
  return;
46148
- if (has(identity))
46029
+ }
46030
+ if (char < " ")
46031
+ fail();
46032
+ at += char === "\\" ? 2 : 1;
46033
+ }
46034
+ fail();
46035
+ };
46036
+ const value = () => {
46037
+ space();
46038
+ const char = text.charAt(at);
46039
+ if (char === "{" || char === "[") {
46040
+ const close = char === "{" ? "}" : "]";
46041
+ at += 1;
46042
+ space();
46043
+ if (text.charAt(at) === close) {
46044
+ at += 1;
46149
46045
  return;
46150
- const entry = { ...identity, at: now() };
46151
- add(entry);
46152
- return entry;
46153
- },
46154
- restore(restored) {
46155
- entries = new Set;
46156
- byEvent.clear();
46157
- byKey.clear();
46158
- const at = now();
46159
- const kept = restored.filter((entry) => at - entry.at < REPLAY_LEDGER_TTL_MS && (entry.event_id !== undefined || entry.dedupe_key !== undefined)).sort((a, b) => a.at - b.at);
46160
- for (const entry of kept)
46161
- add({ ...entry });
46162
- },
46163
- list() {
46164
- expire();
46165
- return [...entries];
46046
+ }
46047
+ for (;; ) {
46048
+ if (close === "}") {
46049
+ space();
46050
+ string();
46051
+ space();
46052
+ expect(":");
46053
+ }
46054
+ value();
46055
+ space();
46056
+ if (text.charAt(at) === ",") {
46057
+ at += 1;
46058
+ continue;
46059
+ }
46060
+ expect(close);
46061
+ return;
46062
+ }
46063
+ }
46064
+ if (char === '"') {
46065
+ string();
46066
+ return;
46067
+ }
46068
+ for (const word of ["true", "false", "null"]) {
46069
+ if (text.startsWith(word, at)) {
46070
+ at += word.length;
46071
+ return;
46072
+ }
46166
46073
  }
46074
+ const number = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/.exec(text.slice(at));
46075
+ if (number === null)
46076
+ fail();
46077
+ at += number?.[0].length ?? 0;
46167
46078
  };
46079
+ try {
46080
+ value();
46081
+ space();
46082
+ if (at < text.length)
46083
+ fail();
46084
+ return;
46085
+ } catch {
46086
+ const before = text.slice(0, at).split(`
46087
+ `);
46088
+ return `line ${before.length}, column ${(before.at(-1)?.length ?? 0) + 1}`;
46089
+ }
46168
46090
  }
46169
46091
 
46170
- // ../envoy-client/src/consumer-delivery.ts
46171
- var DELIVER_SUBJECT_PREFIX = "notifications.envoy.deliver.";
46172
- function deliverSubject(sessionID) {
46173
- return `${DELIVER_SUBJECT_PREFIX}${sessionID}`;
46092
+ // ../envoy-client/src/secret-file.ts
46093
+ import { readFileSync } from "fs";
46094
+ function sendable(value) {
46095
+ return !/[\s\p{Cc}]/u.test(value);
46174
46096
  }
46175
- var RelayHeader = {
46176
- subject: "Envoy-Subject",
46177
- streamSeq: "Envoy-Stream-Seq",
46178
- streamID: "Envoy-Stream-Id",
46179
- delivered: "Envoy-Delivered",
46180
- storedAt: "Envoy-Stored-At",
46181
- gap: "Envoy-Gap"
46182
- };
46183
- var RELAY_PROGRESS_INTERVAL_MS = 20000;
46184
- var FOLLOW_CLOCK_ALLOWANCE_MS = 2000;
46185
- var RELAY_ATTEMPTS_BEFORE_FAILED = 3;
46186
- var decoder4 = new TextDecoder;
46187
- var DECIMAL = /^[0-9]+$/;
46188
- var RFC3339 = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})$/;
46189
- function positiveInteger(text) {
46190
- if (text === null || text === undefined || !DECIMAL.test(text))
46191
- return;
46192
- const value = Number(text);
46193
- return Number.isSafeInteger(value) && value > 0 ? value : undefined;
46097
+ function readSecretFile(variable, filePath) {
46098
+ let contents;
46099
+ try {
46100
+ contents = readFileSync(filePath, "utf8");
46101
+ } catch (error) {
46102
+ throw new Error(`${variable} names ${filePath}, which could not be read: ${messageFor(error)}`);
46103
+ }
46104
+ const value = contents.trim();
46105
+ if (value.length === 0)
46106
+ throw new Error(`${variable} names ${filePath}, which is empty`);
46107
+ if (!sendable(value)) {
46108
+ throw new Error(`${variable} names ${filePath}, which holds whitespace or a control character`);
46109
+ }
46110
+ return value;
46194
46111
  }
46195
- function parseStoredAt(text) {
46196
- const match = RFC3339.exec(text);
46197
- if (match === null)
46198
- return;
46199
- const fraction = (match[2] ?? "").padEnd(3, "0").slice(0, 3);
46200
- const ms = Date.parse(`${match[1]}.${fraction}${match[3]}`);
46201
- return Number.isNaN(ms) ? undefined : ms;
46112
+
46113
+ // ../envoy-client/src/envoy-config.ts
46114
+ var COMMAND_TIMEOUT_MS = 1e4;
46115
+ function nonEmpty(value) {
46116
+ return value === undefined || value === "" ? undefined : value;
46202
46117
  }
46203
- function decodeRelayFrame(message) {
46204
- const reply = message.reply ?? "";
46205
- if (reply === "")
46206
- return { error: "no reply subject" };
46207
- const headers = message.headers;
46208
- if (headers === undefined)
46209
- return { error: "no headers" };
46210
- const subject = headers.get(RelayHeader.subject) ?? "";
46211
- if (subject === "")
46212
- return { error: `no ${RelayHeader.subject}` };
46213
- const streamSeq = positiveInteger(headers.get(RelayHeader.streamSeq));
46214
- if (streamSeq === undefined)
46215
- return { error: `bad ${RelayHeader.streamSeq}` };
46216
- const streamID = headers.get(RelayHeader.streamID) ?? "";
46217
- if (streamID === "")
46218
- return { error: `no ${RelayHeader.streamID}` };
46219
- const delivered = positiveInteger(headers.get(RelayHeader.delivered));
46220
- if (delivered === undefined)
46221
- return { error: `bad ${RelayHeader.delivered}` };
46222
- const storedAt = headers.get(RelayHeader.storedAt) ?? "";
46223
- const storedAtMs = parseStoredAt(storedAt);
46224
- if (storedAtMs === undefined)
46225
- return { error: `bad ${RelayHeader.storedAt}` };
46226
- return {
46227
- frame: {
46228
- subject,
46229
- streamSeq,
46230
- streamID,
46231
- delivered,
46232
- storedAt,
46233
- storedAtMs,
46234
- gap: headers.get(RelayHeader.gap) === "true",
46235
- data: typeof message.data === "string" ? message.data : decoder4.decode(message.data),
46236
- reply
46118
+ function absolute(name, value) {
46119
+ if (value !== undefined && !path.isAbsolute(value)) {
46120
+ throw new Error(`${name} is ${value}, which is not an absolute path`);
46121
+ }
46122
+ return value;
46123
+ }
46124
+ function neutralConfig(env) {
46125
+ const xdgConfigHome = nonEmpty(env.XDG_CONFIG_HOME);
46126
+ if (xdgConfigHome !== undefined && !path.isAbsolute(xdgConfigHome)) {
46127
+ return { error: `XDG_CONFIG_HOME is ${xdgConfigHome}, which is not an absolute path` };
46128
+ }
46129
+ const configHome = xdgConfigHome ?? path.join(nonEmpty(env.HOME) ?? homedir(), ".config");
46130
+ return { path: path.resolve(configHome, "legion", "envoy.json") };
46131
+ }
46132
+ var HARNESS_DIRECTORY_VARIABLE = {
46133
+ omp: "PI_CODING_AGENT_DIR",
46134
+ claude: "CLAUDE_CONFIG_DIR"
46135
+ };
46136
+ var PLUGIN_HARNESSES = Object.keys(HARNESS_DIRECTORY_VARIABLE);
46137
+ function namedDirectory(harness, env) {
46138
+ if (harness === "omp") {
46139
+ const profile = nonEmpty(env.OMP_PROFILE);
46140
+ if (profile === undefined || profile === "default")
46141
+ return;
46142
+ }
46143
+ return nonEmpty(env[HARNESS_DIRECTORY_VARIABLE[harness]]);
46144
+ }
46145
+ function harnessDirectory(harness, env) {
46146
+ for (const plugin of harness === "command" ? PLUGIN_HARNESSES : [harness]) {
46147
+ if (harness === "command" && plugin === "claude" && env.CLAUDE_CODE_CHILD_SESSION !== "1") {
46148
+ continue;
46237
46149
  }
46238
- };
46150
+ const directory = namedDirectory(plugin, env);
46151
+ if (directory !== undefined)
46152
+ return absolute(HARNESS_DIRECTORY_VARIABLE[plugin], directory);
46153
+ }
46154
+ return;
46239
46155
  }
46240
- function newEpoch() {
46241
- return crypto.randomUUID();
46156
+ function handedConfigPath(env) {
46157
+ const handed = nonEmpty(env.ENVOY_CONFIG_FILE);
46158
+ return handed === undefined ? undefined : path.resolve(absolute("ENVOY_CONFIG_FILE", handed));
46242
46159
  }
46243
- var GAP_MESSAGES = {
46244
- retention_gap: "The notification stream no longer holds some messages published to this session while it was away: messages older than 72 hours may be missing.",
46245
- stream_recreated: "Envoy's notification stream was recreated, so messages published to this session before that may be lost."
46246
- };
46247
- var ConsumerDeliverySnapshotSchema = object({
46248
- resume: object({ stream_id: string2().min(1), seq: number2().int().nonnegative() }).optional(),
46249
- follows: record(string2(), number2()).default({})
46160
+ function envoyConfigPath(harness, env) {
46161
+ const handedFirst = harness === "command" ? handedConfigPath(env) : undefined;
46162
+ if (handedFirst !== undefined)
46163
+ return handedFirst;
46164
+ const directory = harnessDirectory(harness, env);
46165
+ if (directory !== undefined)
46166
+ return path.resolve(directory, "envoy.json");
46167
+ const handed = handedConfigPath(env);
46168
+ if (handed !== undefined)
46169
+ return handed;
46170
+ const neutral = neutralConfig(env);
46171
+ if ("error" in neutral)
46172
+ throw new Error(neutral.error);
46173
+ return neutral.path;
46174
+ }
46175
+ var httpUrlSchema = url({ protocol: /^https?$/, error: "must be an http or https URL" });
46176
+ var DispatchSectionSchema = strictObject({
46177
+ enabled: boolean2().optional(),
46178
+ serverUrl: httpUrlSchema.optional(),
46179
+ token: string2().optional()
46250
46180
  });
46251
- function parseIdentity(data) {
46252
- let parsed;
46181
+ var EnvoySectionSchema = strictObject({
46182
+ enabled: boolean2().optional(),
46183
+ url: httpUrlSchema.optional(),
46184
+ natsUrls: array(string2().trim().min(1, "must not be empty")).optional(),
46185
+ token: string2().optional(),
46186
+ natsSeed: string2().optional()
46187
+ });
46188
+ var EnvoyFileSchema = looseObject({
46189
+ $schema: string2().optional(),
46190
+ dispatch: DispatchSectionSchema.optional(),
46191
+ envoy: EnvoySectionSchema.optional()
46192
+ });
46193
+ var CheckoutFileSchema = looseObject({
46194
+ $schema: string2().optional(),
46195
+ dispatch: DispatchSectionSchema.optional()
46196
+ });
46197
+ var AskgateSectionSchema = strictObject({ enabled: boolean2().optional() });
46198
+ function offWithNotice(notice) {
46199
+ return { enabled: false, notice, error: null };
46200
+ }
46201
+ function offWithError(error) {
46202
+ return { enabled: false, notice: null, error };
46203
+ }
46204
+ function httpUrl2(value) {
46205
+ let url2;
46253
46206
  try {
46254
- parsed = JSON.parse(data);
46207
+ url2 = new URL(value);
46255
46208
  } catch {
46256
46209
  return;
46257
46210
  }
46258
- const identity = DedupeIdentitySchema.safeParse(parsed);
46259
- if (!identity.success)
46260
- return;
46261
- const { event_id, dedupe_key } = identity.data;
46262
- return event_id === undefined && dedupe_key === undefined ? undefined : identity.data;
46211
+ return url2.protocol === "http:" || url2.protocol === "https:" ? url2 : undefined;
46263
46212
  }
46264
- function reaches(topic, subject) {
46265
- return expandSubscriptionTopics([topic]).some((pattern) => subjectsOverlap(pattern, subject));
46213
+ function describeSchemaIssue(filePath, error) {
46214
+ const issue = error.issues[0];
46215
+ if (!issue)
46216
+ return `${filePath}: invalid envoy.json`;
46217
+ if (issue.code === "unrecognized_keys") {
46218
+ const section = issue.path.join(".");
46219
+ const keys = issue.keys.map((key) => `${section}.${key}`).join(", ");
46220
+ return `${filePath}: unrecognized ${section} key(s): ${keys}`;
46221
+ }
46222
+ return `${filePath}: ${issue.path.join(".")}: ${issue.message}`;
46266
46223
  }
46267
- function every(ms, callback) {
46268
- const timer = setInterval(callback, ms);
46269
- return () => clearInterval(timer);
46224
+ function danglingLink(filePath) {
46225
+ try {
46226
+ return lstatSync(filePath).isSymbolicLink() ? readlinkSync(filePath) : null;
46227
+ } catch {
46228
+ return null;
46229
+ }
46270
46230
  }
46271
- function createConsumerDelivery(options) {
46272
- const { host, ledger, sessionID } = options;
46273
- const now = options.now ?? Date.now;
46274
- const repeat = options.every ?? every;
46275
- const ownSubject = agentSubject(sessionID);
46276
- let currentEpoch = { id: newEpoch(), startedAt: now() };
46277
- let follows = new Map;
46278
- let streamID;
46279
- let held = new Set;
46280
- let written;
46281
- let registeredResume;
46282
- let gapTold = false;
46283
- let closed = false;
46284
- let relayed;
46285
- let persisted = JSON.stringify({ follows: {} });
46286
- const entries = new Map;
46287
- const queue = [];
46288
- let blocking;
46289
- let pumping = false;
46290
- const safely = (what, call) => {
46291
- try {
46292
- call();
46293
- } catch (error) {
46294
- try {
46295
- host.log(`consumer delivery: ${what} failed`, error);
46296
- } catch {}
46297
- }
46298
- };
46299
- const log = (message, error) => safely("log", () => host.log(`consumer delivery: ${message}`, error));
46300
- const send = (reply, body) => safely(`reply ${body}`, () => options.publish(reply, body));
46301
- const tellGap = (kind) => safely("gap notice", () => host.gap({ kind, message: GAP_MESSAGES[kind] }));
46302
- const switchStream = (id) => {
46303
- if (streamID === id)
46304
- return;
46305
- streamID = id;
46306
- held = new Set;
46307
- written = undefined;
46308
- };
46309
- const tellReplacedResume = (id) => {
46310
- const asked = resumePoint() ?? registeredResume;
46311
- if (asked === undefined || asked.stream_id === id)
46312
- return;
46313
- registeredResume = undefined;
46314
- tellGap("stream_recreated");
46315
- };
46316
- const followedAt = (subject) => {
46317
- if (subject === ownSubject)
46318
- return Number.NEGATIVE_INFINITY;
46319
- let earliest;
46320
- for (const [topic, at] of follows) {
46321
- if (!reaches(topic, subject))
46322
- continue;
46323
- if (earliest === undefined || at < earliest)
46324
- earliest = at;
46325
- }
46326
- return earliest;
46327
- };
46328
- const followedOnCorePath = (frame) => {
46329
- const state = ledger.state();
46330
- if (state.stream_id !== frame.streamID)
46331
- return false;
46332
- for (const [topic, cursor] of Object.entries(state.subjects)) {
46333
- if (cursor.since === undefined || frame.streamSeq <= cursor.since)
46334
- continue;
46335
- if (reaches(topic, frame.subject))
46336
- return true;
46337
- }
46338
- return false;
46339
- };
46340
- const settle = (entry, body) => {
46341
- if (entry.settled)
46342
- return;
46343
- entry.settled = true;
46344
- entry.stopProgress();
46345
- entries.delete(entry.key);
46346
- for (const reply of entry.replies)
46347
- send(reply, body);
46348
- if (body === "done" && entry.frame.streamID === streamID) {
46349
- held.delete(entry.frame.streamSeq);
46350
- written = Math.max(written ?? 0, entry.frame.streamSeq);
46351
- }
46352
- release(entry);
46353
- };
46354
- const release = (entry) => {
46355
- if (blocking !== entry)
46356
- return;
46357
- blocking = undefined;
46358
- pump();
46359
- };
46360
- const alreadyWritten = (identity) => identity !== undefined && ledger.delivered(identity);
46361
- const failed = (entry, error) => {
46362
- if (entry.settled)
46363
- return;
46364
- if (entry.frame.delivered < RELAY_ATTEMPTS_BEFORE_FAILED) {
46365
- log(`frame ${entry.frame.streamSeq} failed; it comes again`, error);
46366
- settle(entry, "nak");
46367
- return;
46231
+ function parseFile(filePath, schema, checkout) {
46232
+ let raw;
46233
+ try {
46234
+ raw = readFileSync2(filePath, "utf-8");
46235
+ } catch (error) {
46236
+ if (hasErrnoCode(error, "ENOENT") || hasErrnoCode(error, "ENOTDIR")) {
46237
+ return { kind: "absent", link: danglingLink(filePath) };
46368
46238
  }
46369
- safely("failure notice", () => {
46370
- const { subject, data } = entry.frame;
46371
- const { envelope } = renderInbound(data, sessionID, subject);
46372
- if (envelope !== undefined)
46373
- ledger.liveFailed(subject, envelope, error, now());
46374
- });
46375
- settle(entry, "done");
46376
- };
46377
- const handOff = (entry) => {
46378
- const handle = {
46379
- ...entry.frame,
46380
- late: entry.late,
46381
- done: () => settle(entry, "done"),
46382
- nak: () => settle(entry, "nak"),
46383
- release: () => release(entry)
46239
+ return { kind: "invalid", reason: `${filePath}: could not be read (${messageFor(error)})` };
46240
+ }
46241
+ let parsedJson;
46242
+ try {
46243
+ parsedJson = JSON.parse(raw);
46244
+ } catch {
46245
+ const position = jsonErrorPosition(raw);
46246
+ return {
46247
+ kind: "invalid",
46248
+ reason: `${filePath}: invalid JSON${position === undefined ? "" : ` at ${position}`}`
46384
46249
  };
46385
- blocking = entry;
46250
+ }
46251
+ if (typeof parsedJson === "object" && parsedJson !== null && "natsUrls" in parsedJson) {
46252
+ return {
46253
+ kind: "invalid",
46254
+ reason: checkout ? `${filePath}: the top-level natsUrls is not read, and a checkout's envoy.json holds only a dispatch section` : `${filePath}: the top-level natsUrls is not read; move it to envoy.natsUrls`
46255
+ };
46256
+ }
46257
+ const parsed = schema.safeParse(parsedJson);
46258
+ if (!parsed.success) {
46259
+ return { kind: "invalid", reason: describeSchemaIssue(filePath, parsed.error) };
46260
+ }
46261
+ return { kind: "valid", settings: parsed.data };
46262
+ }
46263
+ var FAILURE_KEPT_MS = 60000;
46264
+ var COMMAND_OUTCOMES = Symbol.for("legion.envoy-config.commands.v1");
46265
+ var processGlobal = globalThis;
46266
+ var commandOutcomes = processGlobal[COMMAND_OUTCOMES] ?? new Map;
46267
+ processGlobal[COMMAND_OUTCOMES] = commandOutcomes;
46268
+ function runCommand(command, env, cwd) {
46269
+ const childEnv = {};
46270
+ for (const [name, variable] of Object.entries(env)) {
46271
+ if (variable !== undefined)
46272
+ childEnv[name] = variable;
46273
+ }
46274
+ const directory = mkdtempSync(path.join(tmpdir(), "envoy-command-"));
46275
+ try {
46276
+ chmodSync(directory, 448);
46277
+ const output = path.join(directory, "stdout");
46278
+ const fd = openSync(output, "wx", 384);
46386
46279
  let result;
46387
46280
  try {
46388
- result = host.deliver(handle);
46281
+ result = Bun.spawnSync(["/bin/sh", "-c", command], {
46282
+ cwd,
46283
+ env: childEnv,
46284
+ stdin: "ignore",
46285
+ stdout: fd,
46286
+ stderr: "ignore",
46287
+ timeout: COMMAND_TIMEOUT_MS,
46288
+ detached: true
46289
+ });
46389
46290
  } catch (error) {
46390
- failed(entry, error);
46391
- release(entry);
46392
- return;
46393
- }
46394
- if (!(result instanceof Promise)) {
46395
- release(entry);
46396
- return;
46397
- }
46398
- result.then(() => release(entry), (error) => {
46399
- failed(entry, error);
46400
- release(entry);
46401
- });
46402
- };
46403
- function pump() {
46404
- if (pumping)
46405
- return;
46406
- pumping = true;
46407
- try {
46408
- while (blocking === undefined && !closed) {
46409
- const entry = queue.shift();
46410
- if (entry === undefined)
46411
- return;
46412
- if (entry.settled)
46413
- continue;
46414
- if (alreadyWritten(entry.identity)) {
46415
- settle(entry, "done");
46416
- continue;
46417
- }
46418
- handOff(entry);
46419
- }
46291
+ return { failure: `could not start: ${messageFor(error)}`, timedOut: false };
46420
46292
  } finally {
46421
- pumping = false;
46422
- }
46423
- }
46424
- const receive = (message) => {
46425
- const decoded = decodeRelayFrame(message);
46426
- if ("error" in decoded) {
46427
- log(`dropping an undecodable relay frame: ${decoded.error}`);
46428
- if (message.reply !== undefined && message.reply !== "")
46429
- send(message.reply, "done");
46430
- return;
46293
+ closeSync(fd);
46431
46294
  }
46432
- const { frame } = decoded;
46433
- if (closed) {
46434
- send(frame.reply, "nak");
46435
- return;
46295
+ try {
46296
+ process.kill(-result.pid, "SIGKILL");
46297
+ } catch {}
46298
+ if (result.exitedDueToTimeout) {
46299
+ return {
46300
+ failure: `did not finish within ${COMMAND_TIMEOUT_MS / 1000} s, and does not run again in this process`,
46301
+ timedOut: true
46302
+ };
46436
46303
  }
46437
- send(frame.reply, "received");
46438
- if (frame.gap && !gapTold)
46439
- tellGap("retention_gap");
46440
- gapTold = false;
46441
- if (frame.streamID !== streamID) {
46442
- if (streamID !== undefined && (written !== undefined || held.size > 0)) {
46443
- tellGap("stream_recreated");
46444
- } else if (streamID === undefined) {
46445
- tellReplacedResume(frame.streamID);
46446
- }
46447
- switchStream(frame.streamID);
46304
+ if (!result.success) {
46305
+ return {
46306
+ failure: `exited with ${result.signalCode ?? `status ${result.exitCode}`}`,
46307
+ timedOut: false
46308
+ };
46448
46309
  }
46449
- const key = `${frame.streamID}:${frame.streamSeq}`;
46450
- const first = entries.get(key);
46451
- if (first !== undefined) {
46452
- first.replies.push(frame.reply);
46453
- return;
46310
+ const value = readFileSync2(output, "utf-8").trim();
46311
+ if (value.length === 0)
46312
+ return { failure: "printed nothing", timedOut: false };
46313
+ if (!sendable(value)) {
46314
+ return {
46315
+ failure: "printed more than one line, or whitespace inside its value",
46316
+ timedOut: false
46317
+ };
46454
46318
  }
46455
- const since = followedAt(frame.subject);
46456
- const unfollowed = (since === undefined || frame.storedAtMs < since - FOLLOW_CLOCK_ALLOWANCE_MS) && !followedOnCorePath(frame);
46457
- const identity = unfollowed ? undefined : parseIdentity(frame.data);
46458
- if (unfollowed || alreadyWritten(identity)) {
46459
- send(frame.reply, "done");
46460
- written = Math.max(written ?? 0, frame.streamSeq);
46461
- return;
46319
+ return { value };
46320
+ } finally {
46321
+ rmSync(directory, { recursive: true, force: true });
46322
+ }
46323
+ }
46324
+ function fileValue(value, field, filePath, env, commands = "run") {
46325
+ if (!value.startsWith("!")) {
46326
+ if (!sendable(value)) {
46327
+ throw new Error(`${filePath}: ${field} holds whitespace or a control character`);
46462
46328
  }
46463
- held.add(frame.streamSeq);
46464
- const entry = {
46465
- frame,
46466
- identity,
46467
- late: frame.delivered > 1 || frame.storedAtMs < currentEpoch.startedAt,
46468
- replies: [frame.reply],
46469
- key,
46470
- stopProgress: () => {
46471
- return;
46472
- },
46473
- settled: false
46474
- };
46475
- entry.stopProgress = repeat(RELAY_PROGRESS_INTERVAL_MS, () => {
46476
- if (entry.settled)
46477
- return;
46478
- for (const reply of entry.replies)
46479
- send(reply, "progress");
46480
- });
46481
- entries.set(key, entry);
46482
- queue.push(entry);
46483
- pump();
46484
- };
46485
- const resumePoint = () => {
46486
- if (streamID === undefined)
46487
- return;
46488
- if (held.size > 0)
46489
- return { stream_id: streamID, seq: Math.min(...held) - 1 };
46490
- return written === undefined ? undefined : { stream_id: streamID, seq: written };
46491
- };
46492
- const seededResume = () => {
46493
- const state = ledger.state();
46494
- const stream = state.stream_id;
46495
- if (stream === undefined)
46496
- return;
46497
- let lowest;
46498
- for (const [subject, cursor] of Object.entries(state.subjects)) {
46499
- if (cursor.after === undefined || !streamStores(subject))
46500
- continue;
46501
- if (lowest === undefined || cursor.after < lowest)
46502
- lowest = cursor.after;
46329
+ return value;
46330
+ }
46331
+ const command = value.slice(1);
46332
+ const cwd = path.dirname(path.resolve(filePath));
46333
+ const key = JSON.stringify([command, filePath, cwd]);
46334
+ let outcome = commandOutcomes.get(key);
46335
+ if (commands === "kept") {
46336
+ if (outcome === undefined) {
46337
+ throw new Error(`${filePath}: ${field}'s command has not run in this process yet, and this read does not run it`);
46503
46338
  }
46504
- return lowest === undefined ? undefined : { stream_id: stream, seq: lowest };
46505
- };
46506
- const snapshot = () => {
46507
- const resume = resumePoint();
46508
- return {
46509
- ...resume === undefined ? {} : { resume },
46510
- follows: Object.fromEntries(follows)
46339
+ } else if (outcome === undefined || "failure" in outcome && !outcome.timedOut && Date.now() - outcome.at >= FAILURE_KEPT_MS) {
46340
+ outcome = { ...runCommand(command, env, cwd), at: Date.now() };
46341
+ commandOutcomes.set(key, outcome);
46342
+ }
46343
+ if ("failure" in outcome)
46344
+ throw new Error(`${filePath}: ${field}'s command ${outcome.failure}`);
46345
+ return outcome.value;
46346
+ }
46347
+ function statDevice(directory) {
46348
+ try {
46349
+ return statSync(directory).dev;
46350
+ } catch {
46351
+ return;
46352
+ }
46353
+ }
46354
+ function moveNotice(oldFile, newFile, move, deviceOf) {
46355
+ const oldDevice = deviceOf(path.dirname(oldFile));
46356
+ let ancestor = path.dirname(newFile);
46357
+ let newDevice = deviceOf(ancestor);
46358
+ while (newDevice === undefined && path.dirname(ancestor) !== ancestor) {
46359
+ ancestor = path.dirname(ancestor);
46360
+ newDevice = deviceOf(ancestor);
46361
+ }
46362
+ if (oldDevice !== undefined && newDevice !== undefined && oldDevice !== newDevice) {
46363
+ return `${oldFile} is not read, and is on another filesystem than ${newFile} (a mount): create ${newFile}, and move ${oldFile} on the machine that owns it`;
46364
+ }
46365
+ return `${oldFile} is not read: ${move}`;
46366
+ }
46367
+ function oldUserFileNotice(filePath, env, deviceOf) {
46368
+ const home = nonEmpty(env.HOME) ?? homedir();
46369
+ const old = path.join(home, ".config", "opencode", "envoy.json");
46370
+ if (!existsSync(old))
46371
+ return;
46372
+ const selected = path.resolve(filePath);
46373
+ const userFile = path.resolve(home, ".config", "legion", "envoy.json");
46374
+ if (selected === userFile) {
46375
+ return moveNotice(old, userFile, "mkdir -p ~/.config/legion && mv ~/.config/opencode/envoy.json ~/.config/legion/", deviceOf);
46376
+ }
46377
+ const profileFile = PLUGIN_HARNESSES.map((harness) => namedDirectory(harness, env)).some((directory) => directory !== undefined && path.isAbsolute(directory) && selected === path.resolve(directory, "envoy.json"));
46378
+ if (profileFile) {
46379
+ return `${old} is not read for this profile; copy or link it to ${filePath}, or write that file`;
46380
+ }
46381
+ const configHome = nonEmpty(env.XDG_CONFIG_HOME);
46382
+ const neutral = neutralConfig(env);
46383
+ if (configHome !== undefined && path.isAbsolute(configHome) && "path" in neutral && selected === neutral.path) {
46384
+ return `${old} is not read under XDG_CONFIG_HOME=${configHome}`;
46385
+ }
46386
+ return;
46387
+ }
46388
+ function missingConfigNotice(filePath, missing, off) {
46389
+ const link = missing.link === null ? "" : ` (a link to ${missing.link}, which does not exist)`;
46390
+ const old = missing.oldUserFileNotice === undefined ? "" : `; ${missing.oldUserFileNotice}`;
46391
+ return `no envoy.json at ${filePath}${link}: ${off}${old}`;
46392
+ }
46393
+ function readEnvoyConfig(filePath, env, options) {
46394
+ const deviceOf = options.deviceOf ?? statDevice;
46395
+ const chosen = parseFile(filePath, EnvoyFileSchema, false);
46396
+ if (chosen.kind === "invalid")
46397
+ return { kind: "failed", path: filePath, error: chosen.reason };
46398
+ const resolvedChosen = path.resolve(filePath);
46399
+ const checkoutPath = path.resolve(options.cwd, ".envoy", "envoy.json");
46400
+ const checkoutFile = checkoutPath === resolvedChosen ? { kind: "absent", link: null } : parseFile(checkoutPath, CheckoutFileSchema, true);
46401
+ const own = chosen.kind === "valid" ? chosen.settings : {};
46402
+ let checkout = null;
46403
+ if (checkoutFile.kind === "invalid") {
46404
+ checkout = { kind: "invalid", path: checkoutPath, error: checkoutFile.reason };
46405
+ } else if (checkoutFile.kind === "valid") {
46406
+ checkout = {
46407
+ kind: "valid",
46408
+ path: checkoutPath,
46409
+ dispatch: checkoutFile.settings.dispatch ?? {},
46410
+ envoyError: Object.hasOwn(checkoutFile.settings, "envoy") ? `${checkoutPath}: envoy is not read from a checkout's envoy.json; put it in ${filePath}` : null,
46411
+ askgateError: Object.hasOwn(checkoutFile.settings, "askgate") ? `askgate in ${checkoutPath} is not read; set it in ${filePath}` : null
46511
46412
  };
46413
+ }
46414
+ const oldCheckout = path.resolve(options.cwd, ".opencode", "envoy.json");
46415
+ const warnings = oldCheckout !== resolvedChosen && !existsSync(checkoutPath) && existsSync(oldCheckout) ? [
46416
+ moveNotice(oldCheckout, checkoutPath, `mkdir -p ${path.dirname(checkoutPath)} && mv ${oldCheckout} ${checkoutPath}`, deviceOf)
46417
+ ] : [];
46418
+ const unreadOldUserFile = chosen.kind === "absent" ? oldUserFileNotice(filePath, env, deviceOf) : undefined;
46419
+ return {
46420
+ kind: "read",
46421
+ path: filePath,
46422
+ dispatch: own.dispatch ?? {},
46423
+ envoy: own.envoy ?? {},
46424
+ checkout,
46425
+ missing: chosen.kind === "absent" ? {
46426
+ link: chosen.link,
46427
+ ...unreadOldUserFile === undefined ? {} : { oldUserFileNotice: unreadOldUserFile }
46428
+ } : null,
46429
+ warnings
46512
46430
  };
46513
- const persist = () => {
46514
- const current = snapshot();
46515
- const serialized = JSON.stringify(current);
46516
- if (serialized === persisted)
46517
- return;
46518
- if (!options.persist(current))
46519
- return;
46520
- persisted = serialized;
46521
- };
46431
+ }
46432
+
46433
+ // ../envoy-client/src/bearer.ts
46434
+ function bearerCredential(token) {
46522
46435
  return {
46523
- subject: deliverSubject(sessionID),
46524
- receive,
46525
- epoch: () => currentEpoch,
46526
- beginEpoch() {
46527
- currentEpoch = { id: newEpoch(), startedAt: now() };
46528
- return currentEpoch;
46529
- },
46530
- registration() {
46531
- const resume = resumePoint() ?? seededResume();
46532
- registeredResume = resume;
46533
- return {
46534
- consumer: true,
46535
- epoch: currentEpoch.id,
46536
- ...resume === undefined ? {} : { resume }
46537
- };
46538
- },
46539
- answered(answer, topics) {
46540
- if (answer.mode === "consumer") {
46541
- if (answer.stream_id !== "" && answer.stream_id !== streamID) {
46542
- tellReplacedResume(answer.stream_id);
46543
- switchStream(answer.stream_id);
46544
- }
46545
- const floor = (answer.consumer_start ?? 0) - 1;
46546
- if (answer.stream_id === streamID && floor > (written ?? -1))
46547
- written = floor;
46548
- if (answer.gap) {
46549
- tellGap("retention_gap");
46550
- gapTold = true;
46551
- }
46552
- relayed = new Set([...topics].filter(streamStores));
46553
- } else {
46554
- relayed = undefined;
46555
- }
46556
- ledger.setConsumerMode(relayed !== undefined);
46557
- persist();
46558
- return answer.mode;
46559
- },
46560
- relays: (topic) => relayed?.has(topic) === true,
46561
- relaying: () => relayed !== undefined,
46562
- setFollowed(topics) {
46563
- const at = now();
46564
- const next = new Map;
46565
- for (const topic of topics) {
46566
- if (topic === ownSubject)
46567
- continue;
46568
- next.set(topic, follows.get(topic) ?? at);
46569
- }
46570
- follows = next;
46571
- persist();
46572
- },
46573
- persist,
46574
- resumePoint,
46575
- snapshot,
46576
- restore(restored) {
46577
- const merged = new Map(Object.entries(restored.follows));
46578
- for (const [topic, at] of follows)
46579
- if (!merged.has(topic))
46580
- merged.set(topic, at);
46581
- follows = merged;
46582
- streamID = restored.resume?.stream_id;
46583
- held = new Set;
46584
- written = restored.resume?.seq;
46585
- persisted = JSON.stringify(snapshot());
46586
- },
46587
- close() {
46588
- closed = true;
46589
- relayed = undefined;
46590
- ledger.setConsumerMode(false);
46591
- queue.length = 0;
46592
- for (const entry of [...entries.values()])
46593
- settle(entry, "nak");
46594
- blocking = undefined;
46595
- }
46436
+ scheme: "Bearer",
46437
+ headers: () => ({ Authorization: `Bearer ${token}` }),
46438
+ secret: () => token
46596
46439
  };
46597
46440
  }
46441
+ function bearerSource(env, section, written) {
46442
+ const pointer = nonEmpty(env[`${section}_TOKEN_FILE`]);
46443
+ if (pointer !== undefined) {
46444
+ return { kind: "variable", token: readSecretFile(`${section}_TOKEN_FILE`, pointer) };
46445
+ }
46446
+ const plain = nonEmpty(env[`${section}_TOKEN`]);
46447
+ if (plain !== undefined) {
46448
+ if (!sendable(plain)) {
46449
+ throw new Error(`${section}_TOKEN holds whitespace or a control character`);
46450
+ }
46451
+ return { kind: "variable", token: plain };
46452
+ }
46453
+ const bearer = written();
46454
+ return bearer === undefined ? { kind: "none" } : { kind: "file", ...bearer };
46455
+ }
46456
+ function fileBearer(bearer, url, section, env, commands = "run") {
46457
+ const named = httpUrl2(url)?.origin;
46458
+ const paired = httpUrl2(bearer.server)?.origin;
46459
+ if (named !== paired) {
46460
+ throw new Error(`${section}_URL names ${named}, but ${bearer.path}'s ${bearer.field} is for ${paired}; set ${section}_TOKEN or ${section}_TOKEN_FILE for it`);
46461
+ }
46462
+ if (bearer.checkout && bearer.token.startsWith("!")) {
46463
+ throw new Error(`${bearer.path}: ${bearer.field} is a command, which a checkout's envoy.json cannot run`);
46464
+ }
46465
+ if (bearer.token === "") {
46466
+ throw new Error(`${bearer.field} in ${bearer.path} must be a non-empty bearer token`);
46467
+ }
46468
+ return fileValue(bearer.token, bearer.field, bearer.path, env, commands);
46469
+ }
46598
46470
 
46599
46471
  // ../envoy-client/src/dispatch-config.ts
46600
46472
  var DEFAULT_SERVER_URL = "http://localhost:8766";
46601
- function withoutTrailingSlashes2(url) {
46602
- let end = url.length;
46603
- while (end > 0 && url[end - 1] === "/")
46604
- end -= 1;
46605
- return url.slice(0, end);
46606
- }
46607
46473
  function checkoutPair(checkout, serverUrl) {
46608
46474
  const { token } = checkout.dispatch;
46609
46475
  if (token === undefined) {
@@ -46665,7 +46531,7 @@ function dispatchSettings(env, config, options = {}) {
46665
46531
  enabled: true,
46666
46532
  url,
46667
46533
  credential,
46668
- ...publicUrl === undefined ? {} : { publicUrl: publicUrl.replace(/\/+$/, "") }
46534
+ ...publicUrl === undefined ? {} : { publicUrl: withoutTrailingSlashes(publicUrl) }
46669
46535
  };
46670
46536
  }
46671
46537
  function dispatchUrl(env, config) {
@@ -46725,7 +46591,7 @@ function dispatchTarget(env, config) {
46725
46591
  return offWithError(messageFor(error));
46726
46592
  }
46727
46593
  if (route.traded) {
46728
- const brokered = withoutTrailingSlashes2(explicitUrl ?? own.serverUrl ?? DEFAULT_SERVER_URL);
46594
+ const brokered = withoutTrailingSlashes(explicitUrl ?? own.serverUrl ?? DEFAULT_SERVER_URL);
46729
46595
  return { enabled: true, url: brokered, source: { kind: "broker" } };
46730
46596
  }
46731
46597
  if (forced) {
@@ -46733,7 +46599,7 @@ function dispatchTarget(env, config) {
46733
46599
  }
46734
46600
  return offWithError(explicitUrl === undefined ? `${config.path}: dispatch is enabled and no token is: set dispatch.token, or DISPATCH_TOKEN or DISPATCH_TOKEN_FILE` : `DISPATCH_URL is set and no token is: set DISPATCH_TOKEN or DISPATCH_TOKEN_FILE, or dispatch.token in ${config.path}`);
46735
46601
  }
46736
- const url = (explicitUrl ?? (source.kind === "file" ? source.server : own.serverUrl ?? DEFAULT_SERVER_URL)).replace(/\/+$/, "");
46602
+ const url = withoutTrailingSlashes(explicitUrl ?? (source.kind === "file" ? source.server : own.serverUrl ?? DEFAULT_SERVER_URL));
46737
46603
  return { enabled: true, url, source };
46738
46604
  }
46739
46605
  function activeDispatchSettings(resolution) {
@@ -51608,6 +51474,133 @@ function pruneSessions(root, now) {
51608
51474
  writeFileSync3(stamp, "", { mode: PRIVATE_FILE2 });
51609
51475
  }
51610
51476
 
51477
+ // ../envoy-client/src/envoy-settings.ts
51478
+ var DEFAULT_ENVOY_URL = "http://127.0.0.1:9020";
51479
+ var DEFAULT_HEARTBEAT_MS = SESSION_HEARTBEAT_MS;
51480
+ var MIN_PASS_DEADLINE_MS = 30000;
51481
+ var DEFAULT_TMUX_PLACE_CACHE_MS = 30000;
51482
+ var MIN_INTERVAL_MS = 25;
51483
+ var MAX_INTERVAL_MS = 2147483647;
51484
+ var REGISTRATION_SETTLE_MS = 5000;
51485
+ var SHUTDOWN_SETTLE_MS = 250;
51486
+ var HEARTBEAT_RETRY_MIN_MS = 20000;
51487
+ var HEARTBEAT_RETRY_MAX_MS = 40000;
51488
+ function heartbeatRetryDelayMs(draw = Math.random) {
51489
+ return Math.round(HEARTBEAT_RETRY_MIN_MS + draw() * (HEARTBEAT_RETRY_MAX_MS - HEARTBEAT_RETRY_MIN_MS));
51490
+ }
51491
+ function namedInterval(raw) {
51492
+ const parsed = Number(raw);
51493
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
51494
+ }
51495
+ function resolvedInterval(raw, fallback) {
51496
+ const named = namedInterval(raw);
51497
+ return named === undefined ? fallback : Math.min(Math.max(named, MIN_INTERVAL_MS), MAX_INTERVAL_MS);
51498
+ }
51499
+ function natsSeedFromEnvironment(env) {
51500
+ const { NATS_NKEY_SEED_FILE: file, NATS_NKEY_SEED: plain } = env;
51501
+ if (file !== undefined) {
51502
+ if (file === "")
51503
+ throw new Error("NATS_NKEY_SEED_FILE is set but empty");
51504
+ return {
51505
+ value: readSecretFile("NATS_NKEY_SEED_FILE", file),
51506
+ source: `NATS_NKEY_SEED_FILE (${file})`
51507
+ };
51508
+ }
51509
+ if (plain === undefined)
51510
+ return;
51511
+ const value = plain.trim();
51512
+ if (value.length === 0)
51513
+ throw new Error("NATS_NKEY_SEED is set but empty");
51514
+ return { value, source: "NATS_NKEY_SEED" };
51515
+ }
51516
+ var NO_NATS_SERVER = "Envoy has no NATS server (envoy.natsUrls, ENVOY_NATS_URL)";
51517
+ var NO_NATS_CONNECTION = "this session opens no NATS connection";
51518
+ function natsServerKey(url) {
51519
+ const match = /^([a-z][a-z0-9+.-]*):\/\/([^@/]*@)?(\[[^\]]*\]|[^:/]*)(?::(\d+))?(\/.*)?$/i.exec(url);
51520
+ if (match === null)
51521
+ return url;
51522
+ const [, scheme = "", userinfo = "", host = "", port = "4222", rest = ""] = match;
51523
+ return `${scheme.toLowerCase()}://${userinfo}${host.toLowerCase()}:${port}${withoutTrailingSlashes(rest)}`;
51524
+ }
51525
+ function natsCredential(env, section, namedNatsUrls, filePath) {
51526
+ const fromEnvironment = natsSeedFromEnvironment(env);
51527
+ if (fromEnvironment !== undefined || section.natsSeed === undefined)
51528
+ return fromEnvironment;
51529
+ if (namedNatsUrls.length > 0) {
51530
+ const servers = new Set((section.natsUrls ?? []).map(natsServerKey));
51531
+ const named = new Set(namedNatsUrls.map(natsServerKey));
51532
+ if (named.size !== servers.size || ![...named].every((server) => servers.has(server))) {
51533
+ throw new Error(`ENVOY_NATS_URL names other servers than ${filePath}'s envoy.natsUrls; set NATS_NKEY_SEED_FILE for them`);
51534
+ }
51535
+ }
51536
+ return {
51537
+ value: fileValue(section.natsSeed, "envoy.natsSeed", filePath, env),
51538
+ source: `envoy.natsSeed in ${filePath}`
51539
+ };
51540
+ }
51541
+ function envoySettings(env, config, options = {}) {
51542
+ if (config.kind === "failed")
51543
+ return offWithError(config.error);
51544
+ const section = config.envoy;
51545
+ if (section.enabled === false) {
51546
+ return offWithNotice(`${config.path} sets envoy.enabled to false: Envoy is off`);
51547
+ }
51548
+ const namedUrl = nonEmpty(env.ENVOY_URL);
51549
+ const namedNatsUrls = (env.ENVOY_NATS_URL ?? "").split(",").map((url) => url.trim()).filter((url) => url.length > 0);
51550
+ const addressed = namedUrl !== undefined || namedNatsUrls.length > 0 || section.url !== undefined || (section.natsUrls ?? []).length > 0 || section.enabled === true;
51551
+ if (!addressed) {
51552
+ return offWithNotice(config.missing === null ? `${config.path} names no Envoy listener or NATS server, and neither ENVOY_URL nor ENVOY_NATS_URL is set: Envoy is off` : missingConfigNotice(config.path, config.missing, "Envoy is off"));
51553
+ }
51554
+ if (namedUrl !== undefined && httpUrl2(namedUrl) === undefined) {
51555
+ return offWithError("ENVOY_URL must be an http or https URL");
51556
+ }
51557
+ const listener = section.url ?? DEFAULT_ENVOY_URL;
51558
+ const url = namedUrl ?? listener;
51559
+ let credential;
51560
+ try {
51561
+ const source = bearerSource(env, "ENVOY", () => section.token === undefined ? undefined : {
51562
+ token: section.token,
51563
+ field: "envoy.token",
51564
+ path: config.path,
51565
+ server: listener,
51566
+ checkout: false
51567
+ });
51568
+ if (source.kind === "none") {
51569
+ credential = brokerRouteConfigured(env).traded ? brokerCredential(env, options.session) : undefined;
51570
+ } else {
51571
+ credential = bearerCredential(source.kind === "variable" ? source.token : fileBearer(source, url, "ENVOY", env));
51572
+ }
51573
+ } catch (error) {
51574
+ return offWithError(messageFor(error));
51575
+ }
51576
+ const natsUrls = namedNatsUrls.length > 0 ? namedNatsUrls : section.natsUrls ?? [];
51577
+ let inbound;
51578
+ if (options.nats === false)
51579
+ inbound = { off: NO_NATS_CONNECTION };
51580
+ else if (natsUrls.length === 0)
51581
+ inbound = { off: NO_NATS_SERVER };
51582
+ else {
51583
+ try {
51584
+ inbound = { natsUrls, natsSeed: natsCredential(env, section, namedNatsUrls, config.path) };
51585
+ } catch (error) {
51586
+ inbound = { off: messageFor(error) };
51587
+ }
51588
+ }
51589
+ const heartbeatMs = resolvedInterval(env.ENVOY_HEARTBEAT_MS, DEFAULT_HEARTBEAT_MS);
51590
+ const tmuxPlaceCacheMs = resolvedInterval(env.ENVOY_TMUX_PLACE_CACHE_MS, DEFAULT_TMUX_PLACE_CACHE_MS);
51591
+ const namedPassDeadlineMs = namedInterval(env.ENVOY_PASS_DEADLINE_MS);
51592
+ return {
51593
+ enabled: true,
51594
+ url: withoutTrailingSlashes(url),
51595
+ credential,
51596
+ inbound,
51597
+ heartbeatMs,
51598
+ tmuxPlaceCacheMs,
51599
+ passDeadlineMs: Math.min(Math.max(namedPassDeadlineMs ?? MIN_PASS_DEADLINE_MS, heartbeatMs), MAX_INTERVAL_MS),
51600
+ passDeadlineRaisedFrom: namedPassDeadlineMs !== undefined && namedPassDeadlineMs < heartbeatMs ? namedPassDeadlineMs : undefined
51601
+ };
51602
+ }
51603
+
51611
51604
  // ../envoy-client/src/nats-auth.ts
51612
51605
  var import_nats = __toESM(require_mod4(), 1);
51613
51606
  var seedKeys = import_nats.nkeys;
@@ -52885,7 +52878,7 @@ function parseBody(schema, body) {
52885
52878
  };
52886
52879
  }
52887
52880
  function createLegionDaemonClient(baseUrl, fetchFn = fetch) {
52888
- const endpoint = baseUrl.replace(/\/+$/, "");
52881
+ const endpoint = withoutTrailingSlashes(baseUrl);
52889
52882
  const call = async (method, path, body, signal) => {
52890
52883
  const response = await fetchFn(`${endpoint}${path}`, {
52891
52884
  ...body === undefined ? {} : {
@@ -55439,7 +55432,7 @@ var import_nats2 = __toESM(require_mod4(), 1);
55439
55432
 
55440
55433
  // package.json
55441
55434
  var name = "@sjawhar/claude-envoy";
55442
- var version2 = "1.32.1";
55435
+ var version2 = "1.32.3";
55443
55436
  var legion = {
55444
55437
  daemonApiVersion: 59
55445
55438
  };