@sjawhar/pi-envoy 11.7.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.
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
 
@@ -38,7 +38,9 @@ A message published while the session's NATS connection or one of its subscripti
38
38
  recovered from Envoy's notification stream, which keeps messages for 72 hours: the session asks
39
39
  its listener (`POST /v1/replay`) for what the stream stored on its own agent subject and on each
40
40
  topic it follows, after the place it last read to, and shows each missed message once, as a card
41
- saying it was published while the connection was down. It asks after it reconnects, after a
41
+ saying it was published while the connection was down. The session pings NATS every 10 seconds
42
+ and drops a connection that leaves two pings unanswered, so a connection that stops answering
43
+ without closing is left within 30 seconds and redialed. It asks after it reconnects, after a
42
44
  subscription is reopened, when it starts or resumes, and on every heartbeat. A targeted Dispatch
43
45
  delivery recovered this way (BTW, Aside, Steer, a person's Send) is shown as that card only and
44
46
  runs nothing. Role messages and team or other ad-hoc topics are live only and are not recovered,
@@ -66,7 +68,7 @@ set -g set-clipboard on
66
68
  ## Development install
67
69
 
68
70
  This package declares one OMP extension entry in `package.json`, `extensions/envoy.ts`: Envoy
69
- 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
70
72
  the entry into OMP:
71
73
 
72
74
  ```sh
package/dist/dispatch.js CHANGED
@@ -14663,7 +14663,7 @@ var dispatchToolSpecs = [
14663
14663
  {
14664
14664
  name: "dispatch_doc_read",
14665
14665
  example: { issue: "DSP-1" },
14666
- description: "Read a live document or a named document version, or the text of an uploaded file at its latest or named version. " + "Do not use it for issue status, asks, or events; " + "use dispatch read instead. Supply ref, issue, or project plus artifact; issue plus an omitted artifact reads the primary document. " + "A live read returns its document token for an optional dispatch doc-edit precondition. With blocks it lists the live document's blocks instead of its markdown, in document order: each block's id, type, token, anchored comments and asks, and opening words, and under a table each row by the index delete_row takes and each cell by its row and the column delete_column takes; block ids, block tokens and those indexes are what dispatch doc-edit takes. " + "A picture (an uploaded PNG, JPEG, GIF or WebP of at most 3,750,000 bytes, 5 MB once base64-encoded) comes back as an image you see, with its name, type, size and version, every time you ask, including one a read already showed this session; " + "any other file that is not UTF-8 text is described, with the route that serves its bytes. " + OWNER_REFERENCE,
14666
+ description: "Read a live document or a named document version, or the text of an uploaded file at its latest or named version. " + "Do not use it for issue status, asks, or events; " + "use dispatch read instead. Supply ref, issue, or project plus artifact; issue plus an omitted artifact reads the primary document. " + "A live read returns its document token for an optional dispatch doc-edit precondition. With blocks it lists the live document's blocks instead of its markdown, in document order: each block's id, type, token, anchored comments and asks, and opening words, and under a table each row by the index delete_row takes and each cell by its row and the column delete_column takes; block ids, block tokens and those indexes are what dispatch doc-edit takes. " + "After the markdown it prints every open thread anchored on the document in full: an open ask with its id and question and each reply's author, time and text, and a comment thread with its root's id, author, quote and text and each reply's author, time and text, in order; a resolved thread, and an ask that is answered or resolved, is not printed. " + "A picture (an uploaded PNG, JPEG, GIF or WebP of at most 3,750,000 bytes, 5 MB once base64-encoded) comes back as an image you see, with its name, type, size and version, every time you ask, including one a read already showed this session; " + "any other file that is not UTF-8 text is described, with the route that serves its bytes. " + OWNER_REFERENCE,
14667
14667
  arguments: (z) => ({
14668
14668
  issue: z.string().describe(ISSUE_REFERENCE).optional(),
14669
14669
  project: z.string().describe("Project key owning the document.").optional(),
@@ -15933,8 +15933,8 @@ class DispatchClient {
15933
15933
  async resolveComment(id, actor) {
15934
15934
  return this.#json("POST", ["api", "v1", "comments", id, "resolve"], { actor });
15935
15935
  }
15936
- async getComments(issue, artifact) {
15937
- return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "comments"], undefined, artifact ? { artifact } : undefined);
15936
+ async getComments(issue) {
15937
+ return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "comments"]);
15938
15938
  }
15939
15939
  async getIssueReferences(issue) {
15940
15940
  return this.#json("GET", [
@@ -18040,22 +18040,64 @@ function messageSummary({ message, replies }, graph) {
18040
18040
  ].join(`
18041
18041
  `);
18042
18042
  }
18043
- async function openArtifactMarks(client, resolved) {
18043
+ async function openAnchoredThreads(client, resolved) {
18044
18044
  const asksPromise = resolved.owner.kind === "project" ? client.getArtifactAsks(resolved.artifact.id) : Promise.resolve(resolved.issue?.open_asks ?? []);
18045
- const commentsPromise = resolved.owner.kind === "project" ? client.getArtifactComments(resolved.artifact.id) : client.getComments(resolved.issue?.key ?? "", resolved.artifact.id);
18045
+ const commentsPromise = resolved.owner.kind === "project" ? client.getArtifactComments(resolved.artifact.id) : client.getComments(resolved.issue?.key ?? "");
18046
18046
  const commentsResultPromise = commentsPromise.then((value) => ({ status: "fulfilled", value }), (reason) => ({ status: "rejected", reason }));
18047
- const asks = await asksPromise;
18048
- const marks = asks.filter((ask) => ask.state === "open" && ask.anchor?.artifact_id === resolved.artifact.id).map((ask) => `ask ${ask.id}`);
18047
+ const asks = (await asksPromise).filter((ask) => ask.state === "open" && ask.anchor?.artifact_id === resolved.artifact.id);
18049
18048
  const commentsResult = await commentsResultPromise;
18050
- if (commentsResult.status === "rejected") {
18051
- if (dispatchAnswered(commentsResult.reason, 404))
18052
- return marks;
18049
+ if (commentsResult.status === "rejected" && !dispatchAnswered(commentsResult.reason, 404)) {
18053
18050
  throw commentsResult.reason;
18054
18051
  }
18055
- return [
18056
- ...marks,
18057
- ...commentsResult.value.filter((comment) => !comment.resolved && comment.anchor?.artifact_id === resolved.artifact.id).map((comment) => `comment ${comment.id}`)
18058
- ];
18052
+ const comments = commentsResult.status === "fulfilled" ? commentsResult.value : [];
18053
+ const askReplies = new Map(asks.map((ask) => [ask.id, []]));
18054
+ for (const comment of comments) {
18055
+ if (comment.ask_id)
18056
+ askReplies.get(comment.ask_id)?.push(comment);
18057
+ }
18058
+ const askThreads = asks.map((ask) => [
18059
+ `ask ${ask.id} \xB7 ${actorText(ask.author)} \xB7 ${ask.created_at}`,
18060
+ ...anchorLines(ask),
18061
+ `Question: ${ask.question}`,
18062
+ ...threadReplyLines(askReplies.get(ask.id) ?? [])
18063
+ ].join(`
18064
+ `));
18065
+ const byId = new Map(comments.map((comment) => [comment.id, comment]));
18066
+ const roots = comments.filter((comment) => comment.reply_to === null && !comment.ask_id && !comment.resolved && comment.anchor?.artifact_id === resolved.artifact.id);
18067
+ const replies = new Map(roots.map((root) => [root.id, []]));
18068
+ for (const comment of comments) {
18069
+ const root = comment.reply_to === null ? undefined : threadRootId(comment, byId);
18070
+ if (root !== undefined)
18071
+ replies.get(root)?.push(comment);
18072
+ }
18073
+ const commentThreads = roots.map((root) => [
18074
+ `comment ${root.id} \xB7 ${actorText(root.author)} \xB7 ${root.created_at}`,
18075
+ ...anchorLines(root),
18076
+ `Body: ${root.body}`,
18077
+ ...threadReplyLines(replies.get(root.id) ?? [])
18078
+ ].join(`
18079
+ `));
18080
+ return [...askThreads, ...commentThreads];
18081
+ }
18082
+ function threadReplyLines(replies) {
18083
+ return replies.flatMap((reply) => [
18084
+ `reply ${reply.id} \xB7 ${actorText(reply.author)} \xB7 ${reply.created_at}`,
18085
+ `Body: ${reply.body}`
18086
+ ]);
18087
+ }
18088
+ function threadRootId(comment, byId) {
18089
+ const seen = new Set;
18090
+ let current = comment;
18091
+ while (current.reply_to !== null) {
18092
+ if (seen.has(current.id))
18093
+ return;
18094
+ seen.add(current.id);
18095
+ const parent = byId.get(current.reply_to);
18096
+ if (parent === undefined)
18097
+ return;
18098
+ current = parent;
18099
+ }
18100
+ return current.id;
18059
18101
  }
18060
18102
  async function blockAsks(client, resolved, state) {
18061
18103
  const asks = await (resolved.issue === undefined ? client.getArtifactAsks(resolved.artifact.id, state) : client.listIssueAsks(resolved.issue.key, state));
@@ -19020,24 +19062,27 @@ Document token: ${listed.token}`,
19020
19062
  } : { issue: resolved.issue?.key }, version, resolved.owner.kind === "project" ? resolved.owner.project : resolved.owner.issue, shown);
19021
19063
  }
19022
19064
  const documentPromise = client.docRead(resolved.artifact.id, version);
19023
- const marksPromise = openArtifactMarks(client, resolved);
19024
- const marksResultPromise = marksPromise.then((value) => ({ status: "fulfilled", value }), (reason) => ({ status: "rejected", reason }));
19065
+ const threadsPromise = openAnchoredThreads(client, resolved);
19066
+ const threadsResultPromise = threadsPromise.then((value) => ({ status: "fulfilled", value }), (reason) => ({ status: "rejected", reason }));
19025
19067
  const document = await documentPromise;
19026
- const marksResult = await marksResultPromise;
19027
- if (marksResult.status === "rejected")
19028
- throw marksResult.reason;
19029
- const marks = marksResult.value;
19068
+ const threadsResult = await threadsResultPromise;
19069
+ if (threadsResult.status === "rejected")
19070
+ throw threadsResult.reason;
19071
+ const threads = threadsResult.value;
19030
19072
  const approval = approvalLine(resolved.artifact);
19031
19073
  const trailer = [
19032
19074
  ..."token" in document && document.token !== undefined ? [`Document token: ${document.token}`] : [],
19033
- ...marks.length === 0 ? [] : [`Open anchored asks/comments: ${marks.join(", ")}`],
19034
19075
  ...approval === undefined ? [] : [approval]
19035
19076
  ];
19036
19077
  return {
19037
- text: trailer.length === 0 ? document.markdown : `${document.markdown}
19078
+ text: [
19079
+ document.markdown,
19080
+ ...trailer.length === 0 ? [] : [trailer.join(`
19081
+ `)],
19082
+ ...threads.length === 0 ? [] : ["Open anchored threads:", ...threads]
19083
+ ].join(`
19038
19084
 
19039
- ${trailer.join(`
19040
- `)}`,
19085
+ `),
19041
19086
  details: resolved.owner.kind === "project" ? {
19042
19087
  project: resolved.artifact.project,
19043
19088
  document: `${resolved.artifact.project}/${resolved.artifact.slug}`
@@ -20191,7 +20236,9 @@ var SessionWireSchema = object({
20191
20236
  roles: array(string2()).optional(),
20192
20237
  capabilities: array(string2()).optional(),
20193
20238
  self_subscribed: boolean2(),
20194
- last_seen: number2().int().optional()
20239
+ last_seen: number2().int().optional(),
20240
+ plugin: string2().optional(),
20241
+ plugin_version: string2().optional()
20195
20242
  });
20196
20243
  var RoleWireSchema = object({
20197
20244
  role: string2(),
@@ -20327,7 +20374,9 @@ function createEnvoyClient(config) {
20327
20374
  ...input.capabilities === undefined ? {} : { capabilities: input.capabilities },
20328
20375
  driving: input.driving,
20329
20376
  ...input.selfSubscribed === undefined ? {} : { self_subscribed: input.selfSubscribed },
20330
- host: machineID()
20377
+ host: machineID(),
20378
+ plugin: input.plugin.name,
20379
+ plugin_version: input.plugin.version
20331
20380
  }))),
20332
20381
  unsubscribe: async (input) => {
20333
20382
  await post("/v1/interests/unsubscribe", {
package/dist/envoy.js CHANGED
@@ -6792,7 +6792,7 @@ var require_protocol = __commonJS(function(exports) {
6792
6792
  }
6793
6793
  disconnect() {
6794
6794
  this.dispatchStatus({ type: core_1.DebugEvents.StaleConnection, data: "" });
6795
- this.transport.disconnect();
6795
+ this.transport.close();
6796
6796
  }
6797
6797
  reconnect() {
6798
6798
  if (this.connected) {
@@ -15633,6 +15633,7 @@ var require_node_transport = __commonJS(function(exports) {
15633
15633
  d.resolve(socket);
15634
15634
  socket.removeAllListeners();
15635
15635
  });
15636
+ this.socket = socket;
15636
15637
  socket.on("error", (err) => {
15637
15638
  dialError = err;
15638
15639
  });
@@ -15915,8 +15916,11 @@ var require_node_transport = __commonJS(function(exports) {
15915
15916
  }
15916
15917
  _closed(err_1) {
15917
15918
  return __awaiter(this, arguments, undefined, function* (err, internal = true) {
15918
- if (!this.connected)
15919
+ if (!this.connected) {
15920
+ if (this.socket)
15921
+ this.socket.destroy();
15919
15922
  return;
15923
+ }
15920
15924
  if (this.done)
15921
15925
  return;
15922
15926
  this.closeError = err;
@@ -30354,7 +30358,7 @@ var dispatchToolSpecs = [
30354
30358
  {
30355
30359
  name: "dispatch_doc_read",
30356
30360
  example: { issue: "DSP-1" },
30357
- description: "Read a live document or a named document version, or the text of an uploaded file at its latest or named version. " + "Do not use it for issue status, asks, or events; " + "use dispatch read instead. Supply ref, issue, or project plus artifact; issue plus an omitted artifact reads the primary document. " + "A live read returns its document token for an optional dispatch doc-edit precondition. With blocks it lists the live document's blocks instead of its markdown, in document order: each block's id, type, token, anchored comments and asks, and opening words, and under a table each row by the index delete_row takes and each cell by its row and the column delete_column takes; block ids, block tokens and those indexes are what dispatch doc-edit takes. " + "A picture (an uploaded PNG, JPEG, GIF or WebP of at most 3,750,000 bytes, 5 MB once base64-encoded) comes back as an image you see, with its name, type, size and version, every time you ask, including one a read already showed this session; " + "any other file that is not UTF-8 text is described, with the route that serves its bytes. " + OWNER_REFERENCE,
30361
+ description: "Read a live document or a named document version, or the text of an uploaded file at its latest or named version. " + "Do not use it for issue status, asks, or events; " + "use dispatch read instead. Supply ref, issue, or project plus artifact; issue plus an omitted artifact reads the primary document. " + "A live read returns its document token for an optional dispatch doc-edit precondition. With blocks it lists the live document's blocks instead of its markdown, in document order: each block's id, type, token, anchored comments and asks, and opening words, and under a table each row by the index delete_row takes and each cell by its row and the column delete_column takes; block ids, block tokens and those indexes are what dispatch doc-edit takes. " + "After the markdown it prints every open thread anchored on the document in full: an open ask with its id and question and each reply's author, time and text, and a comment thread with its root's id, author, quote and text and each reply's author, time and text, in order; a resolved thread, and an ask that is answered or resolved, is not printed. " + "A picture (an uploaded PNG, JPEG, GIF or WebP of at most 3,750,000 bytes, 5 MB once base64-encoded) comes back as an image you see, with its name, type, size and version, every time you ask, including one a read already showed this session; " + "any other file that is not UTF-8 text is described, with the route that serves its bytes. " + OWNER_REFERENCE,
30358
30362
  arguments: (z) => ({
30359
30363
  issue: z.string().describe(ISSUE_REFERENCE).optional(),
30360
30364
  project: z.string().describe("Project key owning the document.").optional(),
@@ -33561,8 +33565,8 @@ class DispatchClient {
33561
33565
  async resolveComment(id, actor) {
33562
33566
  return this.#json("POST", ["api", "v1", "comments", id, "resolve"], { actor });
33563
33567
  }
33564
- async getComments(issue, artifact) {
33565
- return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "comments"], undefined, artifact ? { artifact } : undefined);
33568
+ async getComments(issue) {
33569
+ return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "comments"]);
33566
33570
  }
33567
33571
  async getIssueReferences(issue) {
33568
33572
  return this.#json("GET", [
@@ -34251,6 +34255,22 @@ function natsAuthOptions(seed) {
34251
34255
  return { authenticator: import_nats.nkeyAuthenticator(bytes) };
34252
34256
  }
34253
34257
 
34258
+ // ../envoy-client/src/nats-connection.ts
34259
+ var NATS_PING_INTERVAL_MS = 1e4;
34260
+ var NATS_MAX_PINGS_OUT = 2;
34261
+ function natsConnectionOptions(input) {
34262
+ return {
34263
+ servers: [...input.servers],
34264
+ name: input.name,
34265
+ ...natsAuthOptions(input.seed),
34266
+ reconnect: true,
34267
+ maxReconnectAttempts: -1,
34268
+ reconnectTimeWait: 2000,
34269
+ pingInterval: NATS_PING_INTERVAL_MS,
34270
+ maxPingOut: NATS_MAX_PINGS_OUT
34271
+ };
34272
+ }
34273
+
34254
34274
  // ../envoy-client/src/transport.ts
34255
34275
  var DEFAULT_TIMEOUT_MS = 5000;
34256
34276
  var RETRY_DELAY_MS = 250;
@@ -34275,7 +34295,9 @@ var SessionWireSchema = object({
34275
34295
  roles: array(string2()).optional(),
34276
34296
  capabilities: array(string2()).optional(),
34277
34297
  self_subscribed: boolean2(),
34278
- last_seen: number2().int().optional()
34298
+ last_seen: number2().int().optional(),
34299
+ plugin: string2().optional(),
34300
+ plugin_version: string2().optional()
34279
34301
  });
34280
34302
  var RoleWireSchema = object({
34281
34303
  role: string2(),
@@ -34422,7 +34444,9 @@ function createEnvoyClient(config) {
34422
34444
  ...input.capabilities === undefined ? {} : { capabilities: input.capabilities },
34423
34445
  driving: input.driving,
34424
34446
  ...input.selfSubscribed === undefined ? {} : { self_subscribed: input.selfSubscribed },
34425
- host: machineID()
34447
+ host: machineID(),
34448
+ plugin: input.plugin.name,
34449
+ plugin_version: input.plugin.version
34426
34450
  }))),
34427
34451
  unsubscribe: async (input) => {
34428
34452
  await post("/v1/interests/unsubscribe", {
@@ -35103,9 +35127,10 @@ function createReplayEngine(options) {
35103
35127
  function replaySuppressed(rendered) {
35104
35128
  return rendered.skip || rendered.malformedDelivery === true;
35105
35129
  }
35130
+ var REPLAYED_SUFFIX = "while this session's connection was down.";
35106
35131
  function replayedText(content, publishedAt) {
35107
35132
  return `${content}
35108
- Published at ${publishedAt} while this session's connection was down.`;
35133
+ Published at ${publishedAt} ${REPLAYED_SUFFIX}`;
35109
35134
  }
35110
35135
  function failureNoticeFields(notice) {
35111
35136
  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.";
@@ -35768,7 +35793,7 @@ function parseEnvoyToolArguments(operation, parameters) {
35768
35793
 
35769
35794
  // ../pi-shared/src/interface.ts
35770
35795
  import { logger } from "@oh-my-pi/pi-utils";
35771
- var ENVOY_PLUGIN_INTERFACE_VERSION = 4;
35796
+ var ENVOY_PLUGIN_INTERFACE_VERSION = 5;
35772
35797
  var ENVOY_PLUGIN_INTERFACE_KEY = Symbol.for("legion.pi-shared.envoy-plugin-interface");
35773
35798
  var LEGION_PLUGIN_LOADED_KEY = Symbol.for("legion.pi-legion.loaded");
35774
35799
  var LEGACY_LEGION_LOADED_KEY = Symbol.for("legion.pi-envoy.legion-loaded");
@@ -36030,6 +36055,10 @@ import * as host2 from "@oh-my-pi/pi-coding-agent";
36030
36055
  import { logger as logger3, procmgr, VERSION } from "@oh-my-pi/pi-utils";
36031
36056
  var import_nats2 = __toESM(require_mod4(), 1);
36032
36057
 
36058
+ // package.json
36059
+ var name = "@sjawhar/pi-envoy";
36060
+ var version2 = "11.9.0";
36061
+
36033
36062
  // src/agent-stream.ts
36034
36063
  var encoder2 = new TextEncoder;
36035
36064
  var REPLAY_ARRAY_BYTES = 2;
@@ -36349,6 +36378,219 @@ class AgentStreamPublisher {
36349
36378
  }
36350
36379
  }
36351
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
+
36352
36594
  // src/delivery-pictures.ts
36353
36595
  async function withDeliveredPictures(text, addresses, client, named, shown) {
36354
36596
  const textAlone = { content: text, shown: [] };
@@ -39428,14 +39670,11 @@ function envoyExtension(pi) {
39428
39670
  if (connection?.isClosed() === false)
39429
39671
  return connection;
39430
39672
  const { natsUrls, natsSeed } = requireInbound();
39431
- const dialled = await import_nats2.connect({
39432
- servers: [...natsUrls],
39673
+ const dialled = await import_nats2.connect(natsConnectionOptions({
39674
+ servers: natsUrls,
39433
39675
  name: `omp-${sessionID || "unknown"}`,
39434
- ...natsAuthOptions(natsSeed),
39435
- reconnect: true,
39436
- maxReconnectAttempts: -1,
39437
- reconnectTimeWait: 2000
39438
- });
39676
+ seed: natsSeed
39677
+ }));
39439
39678
  if (!live() || shuttingDown || connection?.isClosed() === false) {
39440
39679
  await dialled.close().catch(() => {});
39441
39680
  if (!shuttingDown && connection?.isClosed() === false)
@@ -39464,20 +39703,33 @@ function envoyExtension(pi) {
39464
39703
  await postDeliveryReply(currentDispatchConfig(), replySessionID, delivery, result);
39465
39704
  };
39466
39705
  const typedPictures = new TypedPictures;
39467
- pi.on("input", async (event) => {
39706
+ pi.on("input", async (event, context) => {
39707
+ cardWake.noteIfIdle(context);
39468
39708
  if (event.source !== "extension")
39469
39709
  return;
39470
39710
  const images = typedPictures.handOver(event.text);
39471
39711
  return images === undefined ? undefined : { images: [...event.images ?? [], ...images] };
39472
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
+ });
39473
39719
  const handCard = (content, deliverAs, identity) => {
39474
39720
  const known = identity === undefined ? {} : replayLedgerIdentity(identity);
39475
- pi.sendMessage({
39476
- customType: "envoy-message",
39477
- content,
39478
- display: true,
39479
- ...unwrittenCardKeys(known).length === 0 ? {} : { details: { ...known } }
39480
- }, 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);
39481
39733
  };
39482
39734
  const hostSettled = () => {
39483
39735
  const hostContext = activeSessionContext;
@@ -40034,10 +40286,16 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
40034
40286
  pi.on("message_update", async (event) => {
40035
40287
  recordAgentStreamMessage(event.message, true);
40036
40288
  });
40037
- pi.on("message_end", async (event) => {
40038
- recordAgentStreamMessage(event.message, false);
40039
- 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);
40040
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));
40041
40299
  pi.on("turn_start", async () => {
40042
40300
  refreshAgentStreamSettings(sessionID);
40043
40301
  });
@@ -40110,7 +40368,8 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
40110
40368
  title: activeSessionContext?.sessionManager.getSessionName?.() ?? "",
40111
40369
  capabilities: sideTurn(activeSessionContext) === undefined ? CAPABILITIES_WITHOUT_BTW : DELIVERY_CAPABILITIES,
40112
40370
  driving: false,
40113
- selfSubscribed: true
40371
+ selfSubscribed: true,
40372
+ plugin: { name, version: version2 }
40114
40373
  }).then((result) => {
40115
40374
  registeredFor = registeringFor;
40116
40375
  registeredAt = Date.now();
@@ -40730,6 +40989,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
40730
40989
  });
40731
40990
  const carriesSession = (reason) => reason !== "new" && reason !== "resume";
40732
40991
  const rebind = async (reason, context) => {
40992
+ cardWake.cancel();
40733
40993
  if (await isSubagent(context))
40734
40994
  return;
40735
40995
  const host = context.sessionManager.getSessionId();
@@ -40753,10 +41013,14 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
40753
41013
  }
40754
41014
  await rebind(reason, context);
40755
41015
  };
40756
- 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
+ });
40757
41020
  pi.on("session_branch", (_event, context) => rebindDispatch(undefined, context));
40758
41021
  pi.on("session_tree", (_event, context) => rebind(undefined, context));
40759
41022
  const announce = (reason, context) => {
41023
+ cardWake.cancel();
40760
41024
  const from = context.sessionManager.getSessionId();
40761
41025
  noteMove(from);
40762
41026
  if (from === "" || sessionID === "")
@@ -40767,6 +41031,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
40767
41031
  pi.on("session_before_branch", async (_event, context) => announce(undefined, context));
40768
41032
  pi.on("session_shutdown", async (_event, context) => {
40769
41033
  shuttingDown = true;
41034
+ cardWake.cancel();
40770
41035
  if (publishedInterface !== undefined) {
40771
41036
  const bound = publishedInterface.roleClaim.instances.indexOf(claimInstance);
40772
41037
  if (bound !== -1)
@@ -40855,6 +41120,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
40855
41120
  });
40856
41121
  pi.on("agent_start", async (_event, context) => {
40857
41122
  runSeq += 1;
41123
+ cardWake.agentStart();
40858
41124
  runUnderAnnouncement = announced?.from === context.sessionManager.getSessionId() ? announced : undefined;
40859
41125
  });
40860
41126
  function armAskAwareness(id, asOf) {
@@ -40867,6 +41133,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
40867
41133
  };
40868
41134
  }
40869
41135
  pi.on("agent_end", async (event, context) => {
41136
+ cardWake.agentEnd(context);
40870
41137
  const id = context.sessionManager.getSessionId();
40871
41138
  const lastReply = event.messages?.findLast((message) => message.role === "assistant");
40872
41139
  if (lastReply?.stopReason === "aborted")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sjawhar/pi-envoy",
3
- "version": "11.7.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": {