@sjawhar/pi-envoy 11.8.0 → 11.9.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.
Files changed (3) hide show
  1. package/README.md +4 -4
  2. package/dist/envoy.js +253 -13
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -3,9 +3,9 @@
3
3
  `@sjawhar/pi-envoy` is the Oh My Pi extension for Envoy messaging and the `dispatch` command,
4
4
  the plugin every session loads. It shares the Envoy HTTP client, tool contract, envelope parsing,
5
5
  and subject helpers with the other Legion adapters while keeping OMP's direct NATS subscriptions
6
- and Pi steering delivery local (inbound messages steer an in-flight turn instead of queueing behind
7
- it). The Legion lifecycle — the entry a Legion pane boots a root architect, a phase worker or the
8
- controller with — is the separate plugin `@sjawhar/pi-legion` (`packages/pi-legion`), installed
6
+ and Pi delivery local (an inbound message reaches an in-flight turn at its next step instead of
7
+ waiting for it to end). The Legion lifecycle — the entry a Legion pane boots a root architect, a
8
+ phase worker or the controller with — is the separate plugin `@sjawhar/pi-legion` (`packages/pi-legion`), installed
9
9
  beside this one in a Legion deployment; it reaches this plugin through the in-process interface
10
10
  described in `packages/pi-shared/AGENTS.md`.
11
11
 
@@ -68,7 +68,7 @@ set -g set-clipboard on
68
68
  ## Development install
69
69
 
70
70
  This package declares one OMP extension entry in `package.json`, `extensions/envoy.ts`: Envoy
71
- messaging, subscriptions, steering delivery, and the Dispatch tools. For local development, link
71
+ messaging, subscriptions, inbound delivery, and the Dispatch tools. For local development, link
72
72
  the entry into OMP:
73
73
 
74
74
  ```sh
package/dist/envoy.js CHANGED
@@ -35793,7 +35793,7 @@ function parseEnvoyToolArguments(operation, parameters) {
35793
35793
 
35794
35794
  // ../pi-shared/src/interface.ts
35795
35795
  import { logger } from "@oh-my-pi/pi-utils";
35796
- var ENVOY_PLUGIN_INTERFACE_VERSION = 4;
35796
+ var ENVOY_PLUGIN_INTERFACE_VERSION = 5;
35797
35797
  var ENVOY_PLUGIN_INTERFACE_KEY = Symbol.for("legion.pi-shared.envoy-plugin-interface");
35798
35798
  var LEGION_PLUGIN_LOADED_KEY = Symbol.for("legion.pi-legion.loaded");
35799
35799
  var LEGACY_LEGION_LOADED_KEY = Symbol.for("legion.pi-envoy.legion-loaded");
@@ -36057,7 +36057,7 @@ var import_nats2 = __toESM(require_mod4(), 1);
36057
36057
 
36058
36058
  // package.json
36059
36059
  var name = "@sjawhar/pi-envoy";
36060
- var version2 = "11.8.0";
36060
+ var version2 = "11.9.0";
36061
36061
 
36062
36062
  // src/agent-stream.ts
36063
36063
  var encoder2 = new TextEncoder;
@@ -36378,6 +36378,219 @@ class AgentStreamPublisher {
36378
36378
  }
36379
36379
  }
36380
36380
 
36381
+ // src/card-wake.ts
36382
+ import { randomUUID } from "crypto";
36383
+ var STARTUP_CARD_CAP_MS = 30000;
36384
+ var STARTUP_TURN_CAP_MS = 30000;
36385
+ var STARTUP_TURN_POLL_MS = 1000;
36386
+ var USER_INTERRUPT_LABEL = "Interrupted by user";
36387
+ var RETRY_CANCELLED = "Retry cancelled";
36388
+ function envoyCardMarker(details) {
36389
+ if (typeof details !== "object" || details === null || !("envoyCard" in details)) {
36390
+ return;
36391
+ }
36392
+ const { envoyCard } = details;
36393
+ if (typeof envoyCard !== "string")
36394
+ return;
36395
+ const wake = "wake" in details ? details.wake : undefined;
36396
+ return wake === "startup" || wake === "fold" ? { envoyCard, wake } : { envoyCard };
36397
+ }
36398
+ function endsModelTurn(message) {
36399
+ if (!("stopReason" in message) || typeof message.stopReason !== "string")
36400
+ return false;
36401
+ return message.stopReason !== "toolUse" && message.stopReason !== "error";
36402
+ }
36403
+ var NO_CARDS = new Set;
36404
+ function unreadCards(branch, cards, owed = NO_CARDS) {
36405
+ const unplaced = new Set(cards);
36406
+ let unread = 0;
36407
+ let replied = false;
36408
+ let repliedAfterTurn = false;
36409
+ for (let index = branch.length - 1;index >= 0 && unplaced.size > 0; index -= 1) {
36410
+ const entry = branch[index];
36411
+ if (typeof entry !== "object" || entry === null || !("type" in entry))
36412
+ continue;
36413
+ if (entry.type === "message" && "message" in entry) {
36414
+ const { message } = entry;
36415
+ if (typeof message === "object" && message !== null && "role" in message) {
36416
+ if (message.role !== "assistant")
36417
+ continue;
36418
+ repliedAfterTurn ||= replied && endsModelTurn(message);
36419
+ replied = true;
36420
+ }
36421
+ } else if (entry.type === "custom_message" && "details" in entry) {
36422
+ const marker = envoyCardMarker(entry.details);
36423
+ if (marker === undefined || !unplaced.delete(marker.envoyCard))
36424
+ continue;
36425
+ if (!(owed.has(marker.envoyCard) ? repliedAfterTurn : replied))
36426
+ unread += 1;
36427
+ }
36428
+ }
36429
+ return unread + unplaced.size;
36430
+ }
36431
+
36432
+ class CardWake {
36433
+ #deps;
36434
+ #run = 0;
36435
+ #interrupted = false;
36436
+ #runActive = false;
36437
+ #startupPhase = true;
36438
+ #unseenStartup = new Map;
36439
+ #seen = [];
36440
+ #owed = new Set;
36441
+ #unsentMark;
36442
+ #checkDue;
36443
+ #checkGeneration = 0;
36444
+ constructor(deps) {
36445
+ this.#deps = deps;
36446
+ }
36447
+ deliveryFor(targetedAside, context) {
36448
+ const idle = context?.isIdle?.();
36449
+ if (idle === true)
36450
+ this.#runActive = false;
36451
+ const startup = this.#startupPhase && idle === true && (context?.mode === "rpc" || this.#startTurnHold() !== undefined);
36452
+ const setup = idle === false && !this.#runActive;
36453
+ const wake = startup ? "startup" : setup || targetedAside ? undefined : "fold";
36454
+ const details = {
36455
+ envoyCard: randomUUID(),
36456
+ ...wake !== undefined && { wake }
36457
+ };
36458
+ if (startup) {
36459
+ this.#unseenStartup.set(details.envoyCard, this.#deps.now());
36460
+ return { deliverAs: "followUp", triggerTurn: false, details };
36461
+ }
36462
+ return {
36463
+ deliverAs: targetedAside || idle === false ? "aside" : "steer",
36464
+ triggerTurn: true,
36465
+ details
36466
+ };
36467
+ }
36468
+ messageEnd(message, context) {
36469
+ if (typeof message !== "object" || message === null || !("role" in message))
36470
+ return;
36471
+ if (message.role === "assistant") {
36472
+ if ("stopReason" in message && message.stopReason === "aborted" && "errorMessage" in message && message.errorMessage === USER_INTERRUPT_LABEL) {
36473
+ this.#interrupted = true;
36474
+ }
36475
+ return;
36476
+ }
36477
+ if (message.role !== "custom" || !("customType" in message) || message.customType !== "envoy-message" || !("details" in message)) {
36478
+ return;
36479
+ }
36480
+ const marker = envoyCardMarker(message.details);
36481
+ if (marker?.wake === undefined)
36482
+ return;
36483
+ if (marker.wake === "startup") {
36484
+ this.#unseenStartup.delete(marker.envoyCard);
36485
+ if (this.#startTurnHold() !== undefined)
36486
+ this.#owed.add(marker.envoyCard);
36487
+ }
36488
+ this.#seen.push({ id: marker.envoyCard, run: this.#run, startup: marker.wake === "startup" });
36489
+ this.#arm(context);
36490
+ }
36491
+ agentStart() {
36492
+ this.#run += 1;
36493
+ this.#interrupted = false;
36494
+ this.#runActive = true;
36495
+ }
36496
+ agentEnd(context) {
36497
+ this.#runActive = false;
36498
+ if (this.#unseenStartup.size > 0 || this.#seen.some((card) => card.startup)) {
36499
+ this.#arm(context);
36500
+ }
36501
+ }
36502
+ noteIfIdle(context) {
36503
+ if (context.isIdle?.() === true)
36504
+ this.#runActive = false;
36505
+ }
36506
+ autoCompactionEnd(event) {
36507
+ if (event.aborted)
36508
+ this.#interrupted = true;
36509
+ }
36510
+ autoRetryEnd(event) {
36511
+ if (!event.success && event.finalError === RETRY_CANCELLED)
36512
+ this.#interrupted = true;
36513
+ }
36514
+ cancel() {
36515
+ this.#checkGeneration += 1;
36516
+ this.#checkDue = undefined;
36517
+ this.#seen = [];
36518
+ this.#unseenStartup.clear();
36519
+ this.#owed.clear();
36520
+ }
36521
+ #startTurnHold() {
36522
+ const mark = this.#deps.startupTurn();
36523
+ if (mark === undefined || !this.#deps.isOwnSession(mark.session))
36524
+ return;
36525
+ const now = this.#deps.now();
36526
+ if (mark.sentAt !== undefined) {
36527
+ const left = mark.sentAt + STARTUP_TURN_CAP_MS - now;
36528
+ return left > 0 ? left : undefined;
36529
+ }
36530
+ if (this.#unsentMark?.mark !== mark)
36531
+ this.#unsentMark = { mark, firstRead: now };
36532
+ const left = this.#unsentMark.firstRead + STARTUP_TURN_CAP_MS - now;
36533
+ return left > 0 ? Math.min(left, STARTUP_TURN_POLL_MS) : undefined;
36534
+ }
36535
+ #arm(context, delayMs = 0) {
36536
+ const due = this.#deps.now() + delayMs;
36537
+ if (this.#checkDue !== undefined && this.#checkDue <= due)
36538
+ return;
36539
+ this.#checkGeneration += 1;
36540
+ this.#checkDue = due;
36541
+ const generation = this.#checkGeneration;
36542
+ context.setTimeout(() => {
36543
+ if (generation !== this.#checkGeneration)
36544
+ return;
36545
+ this.#checkDue = undefined;
36546
+ this.#check(context);
36547
+ }, delayMs);
36548
+ }
36549
+ #check(context) {
36550
+ let waitMs;
36551
+ const now = this.#deps.now();
36552
+ for (const [id, sentAt] of this.#unseenStartup) {
36553
+ const left = sentAt + STARTUP_CARD_CAP_MS - now;
36554
+ if (left <= 0)
36555
+ this.#unseenStartup.delete(id);
36556
+ else
36557
+ waitMs = Math.min(waitMs ?? left, left);
36558
+ }
36559
+ if (waitMs !== undefined) {
36560
+ this.#arm(context, waitMs);
36561
+ return;
36562
+ }
36563
+ if (context.isIdle?.() !== true) {
36564
+ this.#seen = this.#seen.filter((card) => card.startup);
36565
+ return;
36566
+ }
36567
+ this.#runActive = false;
36568
+ const holdMs = this.#startTurnHold();
36569
+ if (holdMs !== undefined) {
36570
+ for (const card of this.#seen) {
36571
+ if (card.startup)
36572
+ this.#owed.add(card.id);
36573
+ }
36574
+ if (this.#seen.length > 0)
36575
+ this.#arm(context, holdMs);
36576
+ return;
36577
+ }
36578
+ const pending = new Set(this.#seen.filter((card) => card.startup ? !(this.#interrupted && this.#owed.has(card.id)) : !this.#interrupted && card.run === this.#run).map((card) => card.id));
36579
+ const unread = pending.size === 0 ? 0 : unreadCards(context.sessionManager.getBranch?.() ?? [], pending, this.#owed);
36580
+ this.#seen = [];
36581
+ this.#owed.clear();
36582
+ this.#startupPhase = false;
36583
+ if (unread === 0)
36584
+ return;
36585
+ this.#deps.sendMessage({
36586
+ customType: "envoy-message",
36587
+ content: unread === 1 ? "1 Envoy message above arrived with no turn to read it: read it and act on it." : `${unread} Envoy messages above arrived with no turn to read them: read them and act on them.`,
36588
+ display: false,
36589
+ details: LOCAL_ENVOY_NOTICE
36590
+ }, { deliverAs: "nextTurn", triggerTurn: true });
36591
+ }
36592
+ }
36593
+
36381
36594
  // src/delivery-pictures.ts
36382
36595
  async function withDeliveredPictures(text, addresses, client, named, shown) {
36383
36596
  const textAlone = { content: text, shown: [] };
@@ -39490,20 +39703,33 @@ function envoyExtension(pi) {
39490
39703
  await postDeliveryReply(currentDispatchConfig(), replySessionID, delivery, result);
39491
39704
  };
39492
39705
  const typedPictures = new TypedPictures;
39493
- pi.on("input", async (event) => {
39706
+ pi.on("input", async (event, context) => {
39707
+ cardWake.noteIfIdle(context);
39494
39708
  if (event.source !== "extension")
39495
39709
  return;
39496
39710
  const images = typedPictures.handOver(event.text);
39497
39711
  return images === undefined ? undefined : { images: [...event.images ?? [], ...images] };
39498
39712
  });
39713
+ const cardWake = new CardWake({
39714
+ now: () => Date.now(),
39715
+ sendMessage: (message, options) => pi.sendMessage(message, options),
39716
+ startupTurn: () => publishedInterface?.startupTurn,
39717
+ isOwnSession: (session) => sessionOpen(session)
39718
+ });
39499
39719
  const handCard = (content, deliverAs, identity) => {
39500
39720
  const known = identity === undefined ? {} : replayLedgerIdentity(identity);
39501
- pi.sendMessage({
39502
- customType: "envoy-message",
39503
- content,
39504
- display: true,
39505
- ...unwrittenCardKeys(known).length === 0 ? {} : { details: { ...known } }
39506
- }, deliverAs === "inert" ? { deliverAs: "steer", triggerTurn: false } : { deliverAs, triggerTurn: true });
39721
+ const frame = unwrittenCardKeys(known).length === 0 ? undefined : { ...known };
39722
+ if (deliverAs === "inert") {
39723
+ pi.sendMessage({
39724
+ customType: "envoy-message",
39725
+ content,
39726
+ display: true,
39727
+ ...frame === undefined ? {} : { details: frame }
39728
+ }, { deliverAs: "steer", triggerTurn: false });
39729
+ return;
39730
+ }
39731
+ const { details, ...options } = cardWake.deliveryFor(deliverAs === "aside", activeSessionContext);
39732
+ pi.sendMessage({ customType: "envoy-message", content, display: true, details: { ...frame, ...details } }, options);
39507
39733
  };
39508
39734
  const hostSettled = () => {
39509
39735
  const hostContext = activeSessionContext;
@@ -40060,10 +40286,16 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
40060
40286
  pi.on("message_update", async (event) => {
40061
40287
  recordAgentStreamMessage(event.message, true);
40062
40288
  });
40063
- pi.on("message_end", async (event) => {
40064
- recordAgentStreamMessage(event.message, false);
40065
- await unwritten.written(event.message);
40289
+ pi.on("message_end", async (event, context) => {
40290
+ const { message } = event;
40291
+ if (!shuttingDown)
40292
+ cardWake.messageEnd(message, context);
40293
+ recordAgentStreamMessage(message, false);
40294
+ await unwritten.written(message);
40066
40295
  });
40296
+ pi.on("session_compact", async (_event, context) => cardWake.noteIfIdle(context));
40297
+ pi.on("auto_compaction_end", async (event) => cardWake.autoCompactionEnd(event));
40298
+ pi.on("auto_retry_end", async (event) => cardWake.autoRetryEnd(event));
40067
40299
  pi.on("turn_start", async () => {
40068
40300
  refreshAgentStreamSettings(sessionID);
40069
40301
  });
@@ -40757,6 +40989,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
40757
40989
  });
40758
40990
  const carriesSession = (reason) => reason !== "new" && reason !== "resume";
40759
40991
  const rebind = async (reason, context) => {
40992
+ cardWake.cancel();
40760
40993
  if (await isSubagent(context))
40761
40994
  return;
40762
40995
  const host = context.sessionManager.getSessionId();
@@ -40780,10 +41013,14 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
40780
41013
  }
40781
41014
  await rebind(reason, context);
40782
41015
  };
40783
- pi.on("session_switch", (event, context) => rebindDispatch(event.reason, context));
41016
+ pi.on("session_switch", (event, context) => {
41017
+ cardWake.noteIfIdle(context);
41018
+ return rebindDispatch(event.reason, context);
41019
+ });
40784
41020
  pi.on("session_branch", (_event, context) => rebindDispatch(undefined, context));
40785
41021
  pi.on("session_tree", (_event, context) => rebind(undefined, context));
40786
41022
  const announce = (reason, context) => {
41023
+ cardWake.cancel();
40787
41024
  const from = context.sessionManager.getSessionId();
40788
41025
  noteMove(from);
40789
41026
  if (from === "" || sessionID === "")
@@ -40794,6 +41031,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
40794
41031
  pi.on("session_before_branch", async (_event, context) => announce(undefined, context));
40795
41032
  pi.on("session_shutdown", async (_event, context) => {
40796
41033
  shuttingDown = true;
41034
+ cardWake.cancel();
40797
41035
  if (publishedInterface !== undefined) {
40798
41036
  const bound = publishedInterface.roleClaim.instances.indexOf(claimInstance);
40799
41037
  if (bound !== -1)
@@ -40882,6 +41120,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
40882
41120
  });
40883
41121
  pi.on("agent_start", async (_event, context) => {
40884
41122
  runSeq += 1;
41123
+ cardWake.agentStart();
40885
41124
  runUnderAnnouncement = announced?.from === context.sessionManager.getSessionId() ? announced : undefined;
40886
41125
  });
40887
41126
  function armAskAwareness(id, asOf) {
@@ -40894,6 +41133,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
40894
41133
  };
40895
41134
  }
40896
41135
  pi.on("agent_end", async (event, context) => {
41136
+ cardWake.agentEnd(context);
40897
41137
  const id = context.sessionManager.getSessionId();
40898
41138
  const lastReply = event.messages?.findLast((message) => message.role === "assistant");
40899
41139
  if (lastReply?.stopReason === "aborted")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sjawhar/pi-envoy",
3
- "version": "11.8.0",
3
+ "version": "11.9.0",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "omp": {
@@ -24,7 +24,7 @@
24
24
  "prepack": "../../scripts/pi-plugin-prepack.sh",
25
25
  "postpack": "rm -rf dist/skills",
26
26
  "typecheck": "bunx tsc --noEmit",
27
- "test": "bun test",
27
+ "test": "bun test --path-ignore-patterns=extensions/card-delivery-omp.test.ts && bun test ./extensions/card-delivery-omp.test.ts",
28
28
  "lint": "bunx biome lint extensions/ src/"
29
29
  },
30
30
  "devDependencies": {