@sjawhar/pi-envoy 13.13.0 → 14.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -382,8 +382,8 @@ gated write only when it consumes one, so a write sent any other way is refused
382
382
  it when the ledger cannot take that line, and then posts it with a `dispatch: warning:` line.
383
383
  Either way pi-envoy records an `advisor-gate` entry with outcome `unmarked`. A record that cannot
384
384
  be read, or that names a store that is gone, is a refusal. A session no live record names needs
385
- no marker: a terminal, CI, Claude Code, OpenCode, a pod without pi-envoy, a session with no
386
- Dispatch and one with `askgate.enabled: false`.
385
+ no marker: a terminal, CI, Claude Code, a pod without pi-envoy, a session with no Dispatch and
386
+ one with `askgate.enabled: false`.
387
387
  - **The cause note.** When a `bash` call outside the literal form holds a `dispatch` word and a
388
388
  gated subcommand, and its result holds the CLI's refusal (or warn-mode warning) of a write with
389
389
  no marker, the gate appends an `AskGate note:` to that result. It names the first cause it found
package/dist/dispatch.js CHANGED
@@ -21023,8 +21023,7 @@ function neutralConfig(env) {
21023
21023
  }
21024
21024
  var HARNESS_DIRECTORY_VARIABLE = {
21025
21025
  omp: "PI_CODING_AGENT_DIR",
21026
- claude: "CLAUDE_CONFIG_DIR",
21027
- opencode: "OPENCODE_CONFIG_DIR"
21026
+ claude: "CLAUDE_CONFIG_DIR"
21028
21027
  };
21029
21028
  var PLUGIN_HARNESSES = Object.keys(HARNESS_DIRECTORY_VARIABLE);
21030
21029
  function namedDirectory(harness, env) {
@@ -21876,7 +21875,7 @@ function sourceSession(sessionID) {
21876
21875
  var OK = 0;
21877
21876
  var REFUSED = 1;
21878
21877
  var USAGE = 2;
21879
- var HOSTS = ["omp", "claude", "opencode"];
21878
+ var HOSTS = ["omp", "claude"];
21880
21879
  var CLAUDE_OUTPUT_MAX = 25000;
21881
21880
  var SAME_MESSAGE = "AskGate reviews the calls of a message before any of them runs, so it did not review that change.";
21882
21881
  var STATE_WRITE_FAILED = "dispatch: Dispatch took the call, but this session's state";
@@ -21958,7 +21957,7 @@ async function runDispatchCli(argv, rawEnv, io) {
21958
21957
  const hostName = env.DISPATCH_HOST ?? (env.CLAUDE_CODE_CHILD_SESSION === "1" ? "claude" : undefined);
21959
21958
  const host = HOSTS.find((name) => name === hostName);
21960
21959
  if (host === undefined) {
21961
- return refuse(hostName === undefined ? "dispatch: DISPATCH_HOST is not set. The host plugin sets it in an agent's shell. From an agent's session, send the command as a bash call. To run dispatch by hand, set DISPATCH_HOST, and set DISPATCH_SESSION_ID to the id of your own session." : `dispatch: DISPATCH_HOST is ${JSON.stringify(hostName)}, not omp, claude or opencode.`, USAGE, parsed.tool);
21960
+ return refuse(hostName === undefined ? "dispatch: DISPATCH_HOST is not set. The host plugin sets it in an agent's shell. From an agent's session, send the command as a bash call. To run dispatch by hand, set DISPATCH_HOST, and set DISPATCH_SESSION_ID to the id of your own session." : `dispatch: DISPATCH_HOST is ${JSON.stringify(hostName)}, not omp or claude.`, USAGE, parsed.tool);
21962
21961
  }
21963
21962
  const sessionVariable = host === "claude" ? "CLAUDE_CODE_SESSION_ID" : "DISPATCH_SESSION_ID";
21964
21963
  const sessionId = env[sessionVariable];
package/dist/envoy.js CHANGED
@@ -33602,8 +33602,7 @@ function neutralConfig(env) {
33602
33602
  }
33603
33603
  var HARNESS_DIRECTORY_VARIABLE = {
33604
33604
  omp: "PI_CODING_AGENT_DIR",
33605
- claude: "CLAUDE_CONFIG_DIR",
33606
- opencode: "OPENCODE_CONFIG_DIR"
33605
+ claude: "CLAUDE_CONFIG_DIR"
33607
33606
  };
33608
33607
  var PLUGIN_HARNESSES = Object.keys(HARNESS_DIRECTORY_VARIABLE);
33609
33608
  function namedDirectory(harness, env) {
@@ -36854,7 +36853,7 @@ function messageMetadataShape(schema) {
36854
36853
  return {
36855
36854
  in_reply_to: schema.string().optional(),
36856
36855
  supersedes: schema.string().optional(),
36857
- urgency: schema.enum(URGENCY_VALUES).describe("low | med | high | blocking").optional(),
36856
+ urgency: schema.enum(URGENCY_VALUES).describe("low | med | high | blocking: how soon the recipient should act, shown on its card. It does not deliver the message sooner or ahead of others.").optional(),
36858
36857
  expects_reply: schema.enum(EXPECTS_REPLY_VALUES).describe("none | optional | required").optional(),
36859
36858
  expires_at: schema.number({ int: true }).optional()
36860
36859
  };
@@ -36923,7 +36922,7 @@ var envoyToolSpecs = [
36923
36922
  },
36924
36923
  {
36925
36924
  name: "envoy_publish",
36926
- description: `Publish an Envoy message to a notifications. topic. A role or built-in topic is delivered as its guide says; a role message errs when its holder did not confirm it within the listener's window. Any other notifications. topic you name (a team topic such as notifications.team.deploy-squad.all) reaches every session subscribed to it when you publish, and is not kept for a session that subscribes later. The listener confirms it with each other session that holds its own NATS connection and registered the topic, and errs naming each session that did not confirm; a session that stopped without unregistering stays registered for up to 5 minutes and is named in that time, and a named session is not a failed delivery to the other sessions. A session that holds its own NATS connection receives it directly, yours included; a session the listener delivers to over a serve port, such as an OpenCode agent, is not confirmed and receives it through its machine's listener when that listener subscribes to every topic (ENVOY_SUBSCRIBE_ALL_TOPICS=1; the shared hub's listener does not). ${DELIVERY_CONTRACT}`,
36925
+ description: `Publish an Envoy message to a notifications. topic. A role or built-in topic is delivered as its guide says; a role message errs when its holder did not confirm it within the listener's window. Any other notifications. topic you name (a team topic such as notifications.team.deploy-squad.all) reaches every session subscribed to it when you publish, and is not kept for a session that subscribes later. The listener confirms it with each other session that holds its own NATS connection and registered the topic, and errs naming each session that did not confirm; a session that stopped without unregistering stays registered for up to 5 minutes and is named in that time, and a named session is not a failed delivery to the other sessions. A session that holds its own NATS connection receives it directly, yours included; a session the listener delivers to over a serve port is not confirmed and receives it through its machine's listener when that listener subscribes to every topic (ENVOY_SUBSCRIBE_ALL_TOPICS=1; the shared hub's listener does not). ${DELIVERY_CONTRACT}`,
36927
36926
  arguments: (schema) => ({ topic: schema.string(), ...messageArguments(schema) }),
36928
36927
  operation: EnvoyToolOperation.publish
36929
36928
  },
@@ -37276,7 +37275,7 @@ var import_nats2 = __toESM(require_mod4(), 1);
37276
37275
 
37277
37276
  // package.json
37278
37277
  var name = "@sjawhar/pi-envoy";
37279
- var version2 = "13.13.0";
37278
+ var version2 = "14.0.0";
37280
37279
  var package_default = {
37281
37280
  name,
37282
37281
  version: version2,
@@ -37640,6 +37639,362 @@ class AgentStreamPublisher {
37640
37639
  }
37641
37640
  }
37642
37641
 
37642
+ // src/missed-messages.ts
37643
+ var ENVOY_MESSAGE = "envoy-message";
37644
+ var REPLAY_DELIVERED_ENTRY = "envoy-replay-delivered";
37645
+ var REPLAY_STATE_ENTRY = "envoy-replay-state";
37646
+ var REPLAY_NOTICE_ENTRY = "envoy-replay-notice";
37647
+ function customEntries(entries, customType) {
37648
+ const found = [];
37649
+ for (const entry of entries) {
37650
+ if (typeof entry !== "object" || entry === null)
37651
+ continue;
37652
+ if (!("type" in entry) || entry.type !== "custom")
37653
+ continue;
37654
+ if (!("customType" in entry) || entry.customType !== customType)
37655
+ continue;
37656
+ if (!("data" in entry))
37657
+ continue;
37658
+ found.push(entry.data);
37659
+ }
37660
+ return found;
37661
+ }
37662
+ function newestState(entries) {
37663
+ const states = customEntries(entries, REPLAY_STATE_ENTRY);
37664
+ for (let index = states.length - 1;index >= 0; index -= 1) {
37665
+ const parsed = ReplayStateSchema.safeParse(states[index]);
37666
+ if (parsed.success)
37667
+ return parsed.data;
37668
+ }
37669
+ return;
37670
+ }
37671
+ function replaySnapshot(entries, now = Date.now()) {
37672
+ const ledger = [];
37673
+ for (const data of customEntries(entries, REPLAY_DELIVERED_ENTRY)) {
37674
+ const parsed = ReplayLedgerEntrySchema.safeParse(data);
37675
+ if (parsed.success)
37676
+ ledger.push(parsed.data);
37677
+ }
37678
+ ledger.push(...writtenCards(entries, ledger, now));
37679
+ const state = newestState(entries);
37680
+ return state === undefined ? { ledger } : { state, ledger };
37681
+ }
37682
+ function stringField(value, field) {
37683
+ const found = field in value ? Reflect.get(value, field) : undefined;
37684
+ return typeof found === "string" && found !== "" ? found : undefined;
37685
+ }
37686
+ function cardText(content) {
37687
+ if (typeof content === "string")
37688
+ return content;
37689
+ if (!Array.isArray(content))
37690
+ return "";
37691
+ const texts = [];
37692
+ for (const block of content) {
37693
+ if (typeof block !== "object" || block === null)
37694
+ continue;
37695
+ if (stringField(block, "type") !== "text")
37696
+ continue;
37697
+ const text = stringField(block, "text");
37698
+ if (text !== undefined)
37699
+ texts.push(text);
37700
+ }
37701
+ return texts.join(`
37702
+ `);
37703
+ }
37704
+ function cardEventID(text) {
37705
+ const lines = text.split(`
37706
+ `);
37707
+ if (lines[0] !== "envoy:")
37708
+ return;
37709
+ for (const line of lines.slice(1)) {
37710
+ const match = /^ {2}(id|event_id): (.+)$/.exec(line);
37711
+ const raw = match?.[2];
37712
+ if (raw === undefined)
37713
+ continue;
37714
+ let value = raw;
37715
+ if (raw.startsWith('"')) {
37716
+ try {
37717
+ value = JSON.parse(raw);
37718
+ } catch {
37719
+ return;
37720
+ }
37721
+ }
37722
+ return typeof value === "string" && value !== "" && value !== "unknown" ? value : undefined;
37723
+ }
37724
+ return;
37725
+ }
37726
+ function writtenCardIdentity(message) {
37727
+ if (typeof message !== "object" || message === null)
37728
+ return;
37729
+ if (stringField(message, "customType") !== ENVOY_MESSAGE)
37730
+ return;
37731
+ const details = "details" in message ? message.details : undefined;
37732
+ if (typeof details === "object" && details !== null) {
37733
+ const eventID = stringField(details, "event_id");
37734
+ const key = stringField(details, "dedupe_key");
37735
+ if (eventID !== undefined || key !== undefined) {
37736
+ return {
37737
+ ...eventID === undefined ? {} : { event_id: eventID },
37738
+ ...key === undefined ? {} : { dedupe_key: key }
37739
+ };
37740
+ }
37741
+ }
37742
+ const eventID = cardEventID(cardText("content" in message ? message.content : undefined));
37743
+ return eventID === undefined ? undefined : { event_id: eventID };
37744
+ }
37745
+ function writtenCards(entries, recorded, now) {
37746
+ const events = new Set;
37747
+ const keys = new Set;
37748
+ const note = (identity) => {
37749
+ if (identity.event_id !== undefined)
37750
+ events.add(identity.event_id);
37751
+ if (identity.dedupe_key !== undefined)
37752
+ keys.add(identity.dedupe_key);
37753
+ };
37754
+ for (const entry of recorded)
37755
+ note(entry);
37756
+ const found = [];
37757
+ for (const entry of entries) {
37758
+ if (typeof entry !== "object" || entry === null)
37759
+ continue;
37760
+ if (stringField(entry, "type") !== "custom_message")
37761
+ continue;
37762
+ const identity = writtenCardIdentity(entry);
37763
+ if (identity === undefined)
37764
+ continue;
37765
+ if (identity.event_id !== undefined && events.has(identity.event_id) || identity.dedupe_key !== undefined && keys.has(identity.dedupe_key)) {
37766
+ continue;
37767
+ }
37768
+ note(identity);
37769
+ const written = Date.parse(stringField(entry, "timestamp") ?? "");
37770
+ found.push({ ...identity, at: Number.isNaN(written) ? now : written });
37771
+ }
37772
+ return found;
37773
+ }
37774
+ function rememberedSubjects(entries) {
37775
+ return rememberedTopics(newestState(entries));
37776
+ }
37777
+ function heldReplayNotices(entries) {
37778
+ const held = new Map;
37779
+ const handed = new Set;
37780
+ for (const data of customEntries(entries, REPLAY_NOTICE_ENTRY)) {
37781
+ if (typeof data !== "object" || data === null)
37782
+ continue;
37783
+ const id = stringField(data, "id");
37784
+ if (id === undefined)
37785
+ continue;
37786
+ if (Reflect.get(data, "handed") === true) {
37787
+ handed.add(id);
37788
+ continue;
37789
+ }
37790
+ const content = stringField(data, "content");
37791
+ if (content !== undefined && !held.has(id))
37792
+ held.set(id, content);
37793
+ }
37794
+ const notices = [];
37795
+ for (const [id, content] of held) {
37796
+ if (!handed.has(id))
37797
+ notices.push({ id, content });
37798
+ }
37799
+ return notices;
37800
+ }
37801
+
37802
+ // src/card-age.ts
37803
+ var MATERIAL_WAIT_MS = 15 * 60000;
37804
+ var CARD_AGES_LIMIT = 20000;
37805
+
37806
+ class CardAges {
37807
+ #deps;
37808
+ #startedAt;
37809
+ #delivered = new Map;
37810
+ constructor(deps) {
37811
+ this.#deps = deps;
37812
+ this.#startedAt = deps.now();
37813
+ }
37814
+ written(message, sessionID) {
37815
+ const eventID = writtenCardIdentity(message)?.event_id;
37816
+ if (eventID === undefined)
37817
+ return;
37818
+ const key = deliveryKey(sessionID, eventID);
37819
+ if (this.#delivered.has(key))
37820
+ return;
37821
+ this.#remember(key, this.#deps.now());
37822
+ }
37823
+ annotate(messages, branch, sessionID) {
37824
+ let recorded;
37825
+ let changed = false;
37826
+ const annotated = messages.map((message) => {
37827
+ const card = cardText2(message);
37828
+ if (card === undefined)
37829
+ return message;
37830
+ const key = deliveryKey(sessionID, card.eventID);
37831
+ let delivered = this.#delivered.get(key);
37832
+ if (delivered === undefined) {
37833
+ recorded ??= branchTimes(branch());
37834
+ const at = recorded.get(card.eventID) ?? this.#handedHere(message);
37835
+ if (at === undefined)
37836
+ return message;
37837
+ delivered = this.#remember(key, at);
37838
+ } else if (delivered.clockOffset === undefined) {
37839
+ const clockOffset = this.#deps.clockOffset?.();
37840
+ if (clockOffset !== undefined) {
37841
+ delivered = { at: delivered.at, clockOffset };
37842
+ this.#delivered.set(key, delivered);
37843
+ }
37844
+ }
37845
+ const text = withDelivery(card.text, delivered.at, delivered.clockOffset);
37846
+ if (text === undefined)
37847
+ return message;
37848
+ changed = true;
37849
+ return card.withText(text);
37850
+ });
37851
+ return changed ? annotated : undefined;
37852
+ }
37853
+ #handedHere(message) {
37854
+ const handed = typeof message === "object" && message !== null && "timestamp" in message ? message.timestamp : undefined;
37855
+ return typeof handed === "number" && handed >= this.#startedAt ? this.#deps.now() : undefined;
37856
+ }
37857
+ #remember(key, at) {
37858
+ const delivery = { at, clockOffset: this.#deps.clockOffset?.() };
37859
+ this.#delivered.set(key, delivery);
37860
+ if (this.#delivered.size > CARD_AGES_LIMIT) {
37861
+ const oldest = this.#delivered.keys().next();
37862
+ if (oldest.done !== true)
37863
+ this.#delivered.delete(oldest.value);
37864
+ }
37865
+ return delivery;
37866
+ }
37867
+ }
37868
+ function deliveryKey(sessionID, eventID) {
37869
+ return `${sessionID}
37870
+ ${eventID}`;
37871
+ }
37872
+ function branchTimes(entries) {
37873
+ const ledger = new Map;
37874
+ const positions = new Map;
37875
+ let newest = Number.NEGATIVE_INFINITY;
37876
+ for (const entry of entries) {
37877
+ if (typeof entry !== "object" || entry === null)
37878
+ continue;
37879
+ const stamp = Date.parse("timestamp" in entry && typeof entry.timestamp === "string" ? entry.timestamp : "");
37880
+ if (!Number.isNaN(stamp))
37881
+ newest = Math.max(newest, stamp);
37882
+ if (!("type" in entry))
37883
+ continue;
37884
+ if (entry.type === "custom_message") {
37885
+ const eventID = writtenCardIdentity(entry)?.event_id;
37886
+ if (eventID !== undefined && !positions.has(eventID) && Number.isFinite(newest)) {
37887
+ positions.set(eventID, newest);
37888
+ }
37889
+ continue;
37890
+ }
37891
+ if (entry.type !== "custom")
37892
+ continue;
37893
+ if (!("customType" in entry) || entry.customType !== REPLAY_DELIVERED_ENTRY)
37894
+ continue;
37895
+ const data = "data" in entry ? entry.data : undefined;
37896
+ if (typeof data !== "object" || data === null)
37897
+ continue;
37898
+ const eventID = "event_id" in data ? data.event_id : undefined;
37899
+ const at = "at" in data ? data.at : undefined;
37900
+ if (typeof eventID !== "string" || typeof at !== "number" || ledger.has(eventID))
37901
+ continue;
37902
+ ledger.set(eventID, at);
37903
+ }
37904
+ for (const [eventID, at] of positions)
37905
+ if (!ledger.has(eventID))
37906
+ ledger.set(eventID, at);
37907
+ return ledger;
37908
+ }
37909
+ function cardText2(message) {
37910
+ if (typeof message !== "object" || message === null)
37911
+ return;
37912
+ if (!("role" in message) || message.role !== "custom")
37913
+ return;
37914
+ const eventID = writtenCardIdentity(message)?.event_id;
37915
+ if (eventID === undefined)
37916
+ return;
37917
+ const content = "content" in message ? message.content : undefined;
37918
+ if (typeof content === "string") {
37919
+ if (!content.startsWith(`envoy:
37920
+ `))
37921
+ return;
37922
+ return { eventID, text: content, withText: (text) => ({ ...message, content: text }) };
37923
+ }
37924
+ if (!Array.isArray(content))
37925
+ return;
37926
+ for (const [block, part] of content.entries()) {
37927
+ if (typeof part !== "object" || part === null)
37928
+ continue;
37929
+ const text = "text" in part ? part.text : undefined;
37930
+ if (typeof text !== "string" || !text.startsWith(`envoy:
37931
+ `))
37932
+ continue;
37933
+ return {
37934
+ eventID,
37935
+ text,
37936
+ withText: (replaced) => ({
37937
+ ...message,
37938
+ content: content.map((other, index) => index === block ? { ...part, text: replaced } : other)
37939
+ })
37940
+ };
37941
+ }
37942
+ return;
37943
+ }
37944
+ var SENT_LINE = /^ {2}(at|published_at): (.+)$/;
37945
+ var DELIVERED_LINE = /^ {2}delivered: /;
37946
+ function withDelivery(text, delivered, clockOffset) {
37947
+ const lines = text.split(`
37948
+ `);
37949
+ const sentIndex = lines.findIndex((line) => SENT_LINE.test(line));
37950
+ if (sentIndex < 0 || lines.some((line) => DELIVERED_LINE.test(line)))
37951
+ return;
37952
+ const matched = SENT_LINE.exec(lines[sentIndex] ?? "");
37953
+ const field = matched?.[1] ?? "at";
37954
+ const sent = Date.parse(toonString(matched?.[2] ?? ""));
37955
+ const fields = { delivered: inboundTimestamp(delivered) };
37956
+ if (!Number.isNaN(sent)) {
37957
+ const gap = delivered - sent;
37958
+ const skew = clockOffset !== undefined && Math.abs(clockOffset) >= MATERIAL_WAIT_MS ? clockOffset : 0;
37959
+ const waitedMs = gap - skew;
37960
+ const whose = `delivered is this machine's clock and ${field} the sending server's`;
37961
+ if (waitedMs >= MATERIAL_WAIT_MS) {
37962
+ const less = skew === 0 ? "" : ", less the difference in clocks";
37963
+ fields.waited = `${duration3(waitedMs)} between ${field} and delivered${less}; ${whose}, and ${field} is when it was sent, not the present time`;
37964
+ }
37965
+ const said = [];
37966
+ if (skew !== 0) {
37967
+ const way = skew > 0 ? "ahead of" : "behind";
37968
+ said.push(`this machine's clock runs ${duration3(Math.abs(skew))} ${way} the Envoy listener's, read from the listener's replies`);
37969
+ }
37970
+ if (waitedMs <= -MATERIAL_WAIT_MS) {
37971
+ const early = duration3(-waitedMs);
37972
+ said.push(skew === 0 ? `delivered is ${early} before ${field}, so this machine's clock runs at least ${early} behind the sending server's` : `delivered is still ${early} before ${field} less that difference, so the sending server's clock runs at least ${early} ahead of the Envoy listener's`);
37973
+ }
37974
+ if (said.length > 0)
37975
+ fields.clocks = `${said.join("; ")}; ${whose}`;
37976
+ }
37977
+ const added = encode3(fields).split(`
37978
+ `).map((line) => ` ${line}`);
37979
+ return [...lines.slice(0, sentIndex + 1), ...added, ...lines.slice(sentIndex + 1)].join(`
37980
+ `);
37981
+ }
37982
+ function toonString(raw) {
37983
+ if (!raw.startsWith('"'))
37984
+ return raw;
37985
+ try {
37986
+ const value = JSON.parse(raw);
37987
+ return typeof value === "string" ? value : raw;
37988
+ } catch {
37989
+ return raw;
37990
+ }
37991
+ }
37992
+ function duration3(ms) {
37993
+ const minutes = Math.floor(ms / 60000);
37994
+ const hours = Math.floor(minutes / 60);
37995
+ return hours === 0 ? `${minutes} min` : `${hours} h ${minutes % 60} min`;
37996
+ }
37997
+
37643
37998
  // src/card-wake.ts
37644
37999
  import { randomUUID as randomUUID2 } from "crypto";
37645
38000
  var STARTUP_CARD_CAP_MS = 30000;
@@ -37721,11 +38076,7 @@ class CardWake {
37721
38076
  this.#unseenStartup.set(details.envoyCard, this.#deps.now());
37722
38077
  return { deliverAs: "followUp", triggerTurn: false, details };
37723
38078
  }
37724
- return {
37725
- deliverAs: targetedAside || idle === false ? "aside" : "steer",
37726
- triggerTurn: true,
37727
- details
37728
- };
38079
+ return { deliverAs: "aside", triggerTurn: true, details };
37729
38080
  }
37730
38081
  messageEnd(message, context) {
37731
38082
  if (typeof message !== "object" || message === null || !("role" in message))
@@ -38072,166 +38423,6 @@ function resolveEnvoySession(sessionFile) {
38072
38423
  return [...sessions.values()][0] ?? "";
38073
38424
  }
38074
38425
 
38075
- // src/missed-messages.ts
38076
- var ENVOY_MESSAGE = "envoy-message";
38077
- var REPLAY_DELIVERED_ENTRY = "envoy-replay-delivered";
38078
- var REPLAY_STATE_ENTRY = "envoy-replay-state";
38079
- var REPLAY_NOTICE_ENTRY = "envoy-replay-notice";
38080
- function customEntries(entries, customType) {
38081
- const found = [];
38082
- for (const entry of entries) {
38083
- if (typeof entry !== "object" || entry === null)
38084
- continue;
38085
- if (!("type" in entry) || entry.type !== "custom")
38086
- continue;
38087
- if (!("customType" in entry) || entry.customType !== customType)
38088
- continue;
38089
- if (!("data" in entry))
38090
- continue;
38091
- found.push(entry.data);
38092
- }
38093
- return found;
38094
- }
38095
- function newestState(entries) {
38096
- const states = customEntries(entries, REPLAY_STATE_ENTRY);
38097
- for (let index = states.length - 1;index >= 0; index -= 1) {
38098
- const parsed = ReplayStateSchema.safeParse(states[index]);
38099
- if (parsed.success)
38100
- return parsed.data;
38101
- }
38102
- return;
38103
- }
38104
- function replaySnapshot(entries, now = Date.now()) {
38105
- const ledger = [];
38106
- for (const data of customEntries(entries, REPLAY_DELIVERED_ENTRY)) {
38107
- const parsed = ReplayLedgerEntrySchema.safeParse(data);
38108
- if (parsed.success)
38109
- ledger.push(parsed.data);
38110
- }
38111
- ledger.push(...writtenCards(entries, ledger, now));
38112
- const state = newestState(entries);
38113
- return state === undefined ? { ledger } : { state, ledger };
38114
- }
38115
- function stringField(value, field) {
38116
- const found = field in value ? Reflect.get(value, field) : undefined;
38117
- return typeof found === "string" && found !== "" ? found : undefined;
38118
- }
38119
- function cardText(content) {
38120
- if (typeof content === "string")
38121
- return content;
38122
- if (!Array.isArray(content))
38123
- return "";
38124
- const texts = [];
38125
- for (const block of content) {
38126
- if (typeof block !== "object" || block === null)
38127
- continue;
38128
- if (stringField(block, "type") !== "text")
38129
- continue;
38130
- const text = stringField(block, "text");
38131
- if (text !== undefined)
38132
- texts.push(text);
38133
- }
38134
- return texts.join(`
38135
- `);
38136
- }
38137
- function cardEventID(text) {
38138
- const lines = text.split(`
38139
- `);
38140
- if (lines[0] !== "envoy:")
38141
- return;
38142
- for (const line of lines.slice(1)) {
38143
- const match = /^ {2}(id|event_id): (.+)$/.exec(line);
38144
- const raw = match?.[2];
38145
- if (raw === undefined)
38146
- continue;
38147
- let value = raw;
38148
- if (raw.startsWith('"')) {
38149
- try {
38150
- value = JSON.parse(raw);
38151
- } catch {
38152
- return;
38153
- }
38154
- }
38155
- return typeof value === "string" && value !== "" && value !== "unknown" ? value : undefined;
38156
- }
38157
- return;
38158
- }
38159
- function writtenCardIdentity(message) {
38160
- if (typeof message !== "object" || message === null)
38161
- return;
38162
- if (stringField(message, "customType") !== ENVOY_MESSAGE)
38163
- return;
38164
- const details = "details" in message ? message.details : undefined;
38165
- if (typeof details === "object" && details !== null) {
38166
- const eventID = stringField(details, "event_id");
38167
- const key = stringField(details, "dedupe_key");
38168
- if (eventID !== undefined || key !== undefined) {
38169
- return {
38170
- ...eventID === undefined ? {} : { event_id: eventID },
38171
- ...key === undefined ? {} : { dedupe_key: key }
38172
- };
38173
- }
38174
- }
38175
- const eventID = cardEventID(cardText("content" in message ? message.content : undefined));
38176
- return eventID === undefined ? undefined : { event_id: eventID };
38177
- }
38178
- function writtenCards(entries, recorded, now) {
38179
- const events = new Set;
38180
- const keys = new Set;
38181
- const note = (identity) => {
38182
- if (identity.event_id !== undefined)
38183
- events.add(identity.event_id);
38184
- if (identity.dedupe_key !== undefined)
38185
- keys.add(identity.dedupe_key);
38186
- };
38187
- for (const entry of recorded)
38188
- note(entry);
38189
- const found = [];
38190
- for (const entry of entries) {
38191
- if (typeof entry !== "object" || entry === null)
38192
- continue;
38193
- if (stringField(entry, "type") !== "custom_message")
38194
- continue;
38195
- const identity = writtenCardIdentity(entry);
38196
- if (identity === undefined)
38197
- continue;
38198
- if (identity.event_id !== undefined && events.has(identity.event_id) || identity.dedupe_key !== undefined && keys.has(identity.dedupe_key)) {
38199
- continue;
38200
- }
38201
- note(identity);
38202
- const written = Date.parse(stringField(entry, "timestamp") ?? "");
38203
- found.push({ ...identity, at: Number.isNaN(written) ? now : written });
38204
- }
38205
- return found;
38206
- }
38207
- function rememberedSubjects(entries) {
38208
- return rememberedTopics(newestState(entries));
38209
- }
38210
- function heldReplayNotices(entries) {
38211
- const held = new Map;
38212
- const handed = new Set;
38213
- for (const data of customEntries(entries, REPLAY_NOTICE_ENTRY)) {
38214
- if (typeof data !== "object" || data === null)
38215
- continue;
38216
- const id = stringField(data, "id");
38217
- if (id === undefined)
38218
- continue;
38219
- if (Reflect.get(data, "handed") === true) {
38220
- handed.add(id);
38221
- continue;
38222
- }
38223
- const content = stringField(data, "content");
38224
- if (content !== undefined && !held.has(id))
38225
- held.set(id, content);
38226
- }
38227
- const notices = [];
38228
- for (const [id, content] of held) {
38229
- if (!handed.has(id))
38230
- notices.push({ id, content });
38231
- }
38232
- return notices;
38233
- }
38234
-
38235
38426
  // src/opens-ask.ts
38236
38427
  function adviceCount(details, key) {
38237
38428
  const count = asObject(asObject(details)?.advice)?.[key];
@@ -38697,6 +38888,33 @@ function createRegistrationState(deps) {
38697
38888
  };
38698
38889
  }
38699
38890
 
38891
+ // src/server-clock.ts
38892
+ class ServerClock {
38893
+ #now;
38894
+ #offset;
38895
+ constructor(now) {
38896
+ this.#now = now;
38897
+ }
38898
+ observing(fetch2) {
38899
+ return async (input, init) => {
38900
+ const response = await fetch2(input, init);
38901
+ this.observe(response.headers.get("date"));
38902
+ return response;
38903
+ };
38904
+ }
38905
+ observe(date) {
38906
+ if (date === null)
38907
+ return;
38908
+ const server = Date.parse(date);
38909
+ if (Number.isNaN(server))
38910
+ return;
38911
+ this.#offset = this.#now() - server;
38912
+ }
38913
+ offset() {
38914
+ return this.#offset;
38915
+ }
38916
+ }
38917
+
38700
38918
  // src/session-answers-context.ts
38701
38919
  var SIDE_TURN_NOTICE = "Ephemeral side-channel turn; reuses current conversation context.";
38702
38920
  var HANDOFF_PROMPT = `<critical>
@@ -42759,9 +42977,14 @@ function envoyExtension(pi) {
42759
42977
  }
42760
42978
  const askgateOwner = askgateFile === null ? undefined : selfOwner(sessionStateRoot(process.env));
42761
42979
  const askgateRecords = new Set;
42980
+ const serverClock = new ServerClock(() => Date.now());
42762
42981
  const active = envoy.enabled ? {
42763
42982
  settings: envoy,
42764
- client: createEnvoyClient({ baseUrl: envoy.url, fetch, token: envoy.token })
42983
+ client: createEnvoyClient({
42984
+ baseUrl: envoy.url,
42985
+ fetch: serverClock.observing(fetch),
42986
+ token: envoy.token
42987
+ })
42765
42988
  } : undefined;
42766
42989
  const requireEnvoy = () => {
42767
42990
  if (active === undefined) {
@@ -42996,6 +43219,10 @@ function envoyExtension(pi) {
42996
43219
  startupTurn: () => publishedInterface?.startupTurn,
42997
43220
  isOwnSession: (session) => sessionOpen(session)
42998
43221
  });
43222
+ const cardAges = new CardAges({
43223
+ now: () => Date.now(),
43224
+ clockOffset: () => serverClock.offset()
43225
+ });
42999
43226
  const handCard = (content, deliverAs, identity) => {
43000
43227
  const known = identity === undefined ? {} : replayLedgerIdentity(identity);
43001
43228
  const frame = unwrittenCardKeys(known).length === 0 ? undefined : { ...known };
@@ -43055,7 +43282,7 @@ function envoyExtension(pi) {
43055
43282
  });
43056
43283
  }
43057
43284
  });
43058
- const showReplayCard = (content, envelope, deliverAs = "steer") => {
43285
+ const showReplayCard = (content, envelope, deliverAs = "card") => {
43059
43286
  const parsed = ClaimIdentitySchema.safeParse(envelope);
43060
43287
  const identity = parsed.success ? parsed.data : undefined;
43061
43288
  const claim = delivered.claim(identity);
@@ -43224,7 +43451,7 @@ function envoyExtension(pi) {
43224
43451
  const shown = shownPictures(sessionID);
43225
43452
  if (accepted === undefined) {
43226
43453
  const card = await withDeliveredPictures(rendered.content, rendered.pictures ?? [], () => timedDispatchClient(DELIVERY_PICTURES_TIMEOUT_MS), true, shown);
43227
- unwritten.sendCard(card.content, rendered.delivery?.mode === "aside" ? "aside" : "steer", identity, claim);
43454
+ unwritten.sendCard(card.content, rendered.delivery?.mode === "aside" ? "aside" : "card", identity, claim);
43228
43455
  markPicturesShown(shownPictures(sessionID), card.shown);
43229
43456
  } else {
43230
43457
  const { turn } = accepted;
@@ -43391,7 +43618,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
43391
43618
  writeSessionID: transcriptSessionID,
43392
43619
  followedSubjects,
43393
43620
  deliver: showReplayed,
43394
- showFailureNotice: async (notice) => showReplayCard(envoyNoticeText(failureNoticeFields(notice)), notice.envelope, btwEvents.has(notice.eventId) ? "inert" : "steer"),
43621
+ showFailureNotice: async (notice) => showReplayCard(envoyNoticeText(failureNoticeFields(notice)), notice.envelope, btwEvents.has(notice.eventId) ? "inert" : "card"),
43395
43622
  failureNoticeFailed: (notice, error) => {
43396
43623
  logger3.warn("envoy: a message this session was not shown could not be reported", {
43397
43624
  eventID: notice.eventId,
@@ -43567,6 +43794,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
43567
43794
  if (!shuttingDown)
43568
43795
  cardWake.messageEnd(message, context);
43569
43796
  recordAgentStreamMessage(message, false);
43797
+ cardAges.written(message, context.sessionManager.getSessionId());
43570
43798
  await unwritten.written(message);
43571
43799
  });
43572
43800
  pi.on("session_compact", async (_event, context) => cardWake.noteIfIdle(context));
@@ -44149,10 +44377,13 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
44149
44377
  return sessionAnswersFailureLine(messageFor(error));
44150
44378
  }
44151
44379
  };
44152
- if (atStart.dispatch.enabled) {
44380
+ if (atStart.dispatch.enabled || inbound) {
44153
44381
  pi.on("context", async (event, context) => {
44154
- const withSkill = withDispatchFirst(event.messages, DISPATCH_FIRST_CONTEXT);
44155
- const messages = await withSessionAnswers(withSkill ?? event.messages, {
44382
+ const aged = cardAges.annotate(event.messages, () => context.sessionManager.getBranch?.() ?? [], context.sessionManager.getSessionId());
44383
+ if (!atStart.dispatch.enabled)
44384
+ return aged === undefined ? undefined : { messages: aged };
44385
+ const withSkill = withDispatchFirst(aged ?? event.messages, DISPATCH_FIRST_CONTEXT);
44386
+ const messages = await withSessionAnswers(withSkill ?? aged ?? event.messages, {
44156
44387
  branch: () => context.sessionManager.getBranch?.() ?? [],
44157
44388
  session: context.sessionManager,
44158
44389
  compacting: () => {
@@ -44161,7 +44392,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
44161
44392
  },
44162
44393
  read: () => sessionAnswersText(context)
44163
44394
  });
44164
- const result = messages ?? withSkill;
44395
+ const result = messages ?? withSkill ?? aged;
44165
44396
  return result === undefined ? undefined : { messages: result };
44166
44397
  });
44167
44398
  }
@@ -15,7 +15,7 @@ Envoy delivers external events and messages between sessions. Delivery is at-lea
15
15
  - Reply with `in_reply_to=<the delivery's id>`, so the recipient can match the answer to its question.
16
16
  - Read the `recipient` in the send result, the session Envoy targeted: if it is not the one you meant, resend to the right id.
17
17
  - Put the URL or path of what you report in the message, because the recipient cannot find your files any other way.
18
- - Set `expects_reply="none"` on a message that needs no answer, and set `urgency` only when the work waits on the answer, so the recipient knows whether to answer and how soon.
18
+ - Set `expects_reply="none"` on a message that needs no answer, and set `urgency` only when the work waits on the answer, so the recipient knows whether to answer and how soon. `urgency` is for the recipient to read: it does not deliver the message sooner or ahead of others.
19
19
 
20
20
  ```text
21
21
  envoy_send(session_id="<id>", message="Review complete: <url>", in_reply_to="<id>", expects_reply="none")
@@ -11,6 +11,7 @@ envoy:
11
11
  to: you (ses_example_recipient)
12
12
  from: 01a0bbbb-cccc-7ddd-eeee-0123456789ab (Reviewer)
13
13
  at: "2026-09-07T04:41:12Z"
14
+ delivered: "2026-09-07T04:41:13Z"
14
15
  id: agent-message-2
15
16
  by: "2026-09-07T05:00:00Z"
16
17
  urgency: high
@@ -35,10 +36,13 @@ envoy:
35
36
 
36
37
  - `to`: the local inbox that receives this delivery.
37
38
  - `from`: the sending session's self-asserted id, with its session title in parentheses when the envelope carries one. Attribution and a direct-reply target, not an authenticated identity.
38
- - `at`: the envelope timestamp; judge freshness by it.
39
+ - `at`: when the server that accepted the delivery took it, by that server's clock: the Envoy listener the sender sent through for a session's message or a webhook event, Dispatch's server for a Dispatch event. The sending session sets no time of its own; its machine's clock counts only where that listener runs on the same machine. It is not the present time: a delivery read late carries an old `at`.
40
+ - `delivered`: when this session got the delivery, by this machine's clock. An Oh My Pi session shows it in every model request, beside `at`, or beside `published_at` on a notice that names a message the session could not be shown. A session the host moves to shows when it got the delivery there, which can be later than another session got it. A session that got the delivery before its process restarted can show an estimate of that time, taken from its transcript, never later than the delivery.
41
+ - `waited`: present when `delivered` is 15 minutes or more after the send time, less any clock difference `clocks` states: how long the delivery waited, in words. An old send time on a late delivery says the delivery waited, not that a clock is wrong.
42
+ - `clocks`: present when this machine's clock runs 15 minutes or more ahead of or behind the Envoy listener's, read from the listener's replies, or when `delivered` is 15 minutes or more before the send time less that difference: which way the clocks differ, and by how much. Only this machine's clock and the listener's are measured, so a send time still after the delivery once the measured difference is taken off says the sending server's own clock runs ahead of the listener's. A difference under 15 minutes is not shown and stays in `waited`.
39
43
  - `id`: the delivery id; pass it as `in_reply_to` when you reply.
40
44
  - `by`: the expiry deadline, when the sender set one.
41
- - `urgency`: the sender's priority: `low`, `med`, `high` or `blocking`.
45
+ - `urgency`: how soon the sender asks you to act: `low`, `med`, `high` or `blocking`. It is for you to read only: it does not change when a delivery reaches you, or its place among others.
42
46
  - `expects_reply`: `none`, `optional` or `required`.
43
47
  - `re`: the delivery this one replies to. A Dispatch frame names it as a `dispatch://` ref: the ask (`dispatch://KEY/ask/<id>`, or `dispatch://PROJECT/artifact/<slug>/ask/<id>` for a document ask) or the message (`dispatch://KEY/message/<id>`), never the quoted text. On an ask, `dispatch.question` holds the start of the question's text; `dispatch read` gives the whole.
44
48
  - `supersedes`: an earlier delivery this one replaces; act on this one in its place.
@@ -54,7 +58,7 @@ envoy:
54
58
  It depends on where a session takes its deliveries, not on whether the topic is built in or your own.
55
59
 
56
60
  - A session that holds its own NATS connection (every Oh My Pi session, and a Claude Code one) receives every message published on a subject it subscribes to, whoever sent it: its own publish included, and a subagent's publish to a topic the parent subscribes to. This holds for a topic the stream keeps and for a live team topic alike while it is connected. After an outage, once its connection or subscription is back, the session recovers from the stream what was published meanwhile on its own inbox and on each kept topic it follows, up to 72 hours back, and is shown each message once, marked as published while its connection was down. That includes a team topic it registered with the listener (every topic it follows with `envoy_subscribe`): the listener forwards each team topic message to the inbox of every session registered on it but the sender, and the stream keeps that copy. A team topic it subscribes to without registering it is gone for the outage.
57
- - A session the listener delivers to by push, over a serve port (such as the OpenCode plugin), does not receive its own publish, and receives a team topic only through the listener that owns it when that listener runs with `ENVOY_SUBSCRIBE_ALL_TOPICS=1` (the shared hub's listener does not).
61
+ - A session the listener delivers to by push, over a serve port, does not receive its own publish, and receives a team topic only through the listener that owns it when that listener runs with `ENVOY_SUBSCRIBE_ALL_TOPICS=1` (the shared hub's listener does not).
58
62
  - A role is not a subject its holder subscribes to: the listener finds the live holder and forwards the message to it, and drops the message when that holder is the message's source session.
59
63
 
60
64
  ## Listener API errors
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sjawhar/pi-envoy",
3
- "version": "13.13.0",
3
+ "version": "14.0.0",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "omp": {