@sjawhar/pi-envoy 16.29.0 → 16.31.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/dist/envoy.js CHANGED
@@ -30020,6 +30020,17 @@ function itemFromSearch(search) {
30020
30020
  // ../contracts/src/dispatch-text-rules.ts
30021
30021
  var SESSION_ID_PATTERN = "[^/?#\\s\\p{Z}\\p{Cc}<>\"'`\\[\\]|]+";
30022
30022
  var sessionIdOnly = new RegExp(`^${SESSION_ID_PATTERN}$`, "u");
30023
+ var PICTURE_CAPTION = String.raw`(?:\\.|[^\\\]\n]){0,512}`;
30024
+ var PICTURE_ADDRESS = String.raw`dispatch://[^\s()]{1,2048}@v[1-9][0-9]{0,18}`;
30025
+ var PICTURE_TITLE = String.raw`(?:\s{1,4}"(?:\\.|[^\\"]){0,256}")?`;
30026
+ var PICTURE_SYNTAX = String.raw`!\[${PICTURE_CAPTION}\]\((${PICTURE_ADDRESS})${PICTURE_TITLE}\)`;
30027
+ function pictureSyntax() {
30028
+ return new RegExp(PICTURE_SYNTAX, "g");
30029
+ }
30030
+ function blockPlaceholder(type) {
30031
+ return `[${type}]`;
30032
+ }
30033
+ var PICTURE_PLACEHOLDER = blockPlaceholder("image");
30023
30034
  var PICTURE_TYPES = {
30024
30035
  "image/png": true,
30025
30036
  "image/jpeg": true,
@@ -35914,9 +35925,9 @@ class DispatchClient {
35914
35925
  async messageReply(id, input, options = {}) {
35915
35926
  return this.#json("POST", ["api", "v1", "messages", id, "reply"], input, options.followUp === true ? { follow_up: "true" } : undefined);
35916
35927
  }
35917
- async deliveryReply(resource, id, input) {
35928
+ async deliveryReply(resource, id, input, options = {}) {
35918
35929
  const collection = resource === "message" ? "messages" : "comments";
35919
- await this.#json("POST", ["api", "v1", collection, id, "reply"], input);
35930
+ await this.#json("POST", ["api", "v1", collection, id, "reply"], input, options.followUp === true ? { follow_up: "true" } : undefined);
35920
35931
  }
35921
35932
  async getMessage(issue, id) {
35922
35933
  return this.#json("GET", [
@@ -36425,9 +36436,8 @@ function toolImage(bytes) {
36425
36436
  function imageBlocks(images) {
36426
36437
  return images.map(({ data, mimeType }) => ({ type: "image", data, mimeType }));
36427
36438
  }
36428
- var PICTURE_SYNTAX = /!\[(?:\\.|[^\\\]])*\]\((dispatch:\/\/[^\s()]+@v[1-9][0-9]*)(?:\s+"(?:\\.|[^\\"])*")?\)/g;
36429
36439
  function pictureAddresses(text) {
36430
- return [...text.matchAll(PICTURE_SYNTAX)].map((match) => match[1]);
36440
+ return [...text.matchAll(pictureSyntax())].map((match) => match[1]);
36431
36441
  }
36432
36442
 
36433
36443
  // ../envoy-client/src/human-edit.ts
@@ -36516,13 +36526,14 @@ function dispatchReplyPath(resource, id) {
36516
36526
  return `/api/v1/${collection}/${encodeURIComponent(id)}/reply`;
36517
36527
  }
36518
36528
  async function postDeliveryReply(config, sessionId, delivery, result) {
36529
+ const { followUp, ...reply } = result;
36519
36530
  const client = new DispatchClient(config.url, config.credential);
36520
36531
  await client.deliveryReply(delivery.resource, delivery.id, {
36521
36532
  actor: { kind: "session", id: sessionId },
36522
36533
  attempt: delivery.attempt,
36523
36534
  ...delivery.replyFields,
36524
- ...result
36525
- });
36535
+ ...reply
36536
+ }, followUp === undefined ? {} : { followUp });
36526
36537
  }
36527
36538
  function expectsLaneReceipt(frame) {
36528
36539
  return frame.reply !== undefined && frame.reply !== "" && frame.subject === frame.directSubject && frame.envelopeTopic !== undefined && frame.envelopeTopic !== frame.directSubject;
@@ -41860,668 +41871,833 @@ function parseEnvoyToolArguments(operation, parameters) {
41860
41871
  return data;
41861
41872
  }
41862
41873
 
41863
- // ../pi-shared/src/dispatch-session-id.ts
41864
- function currentSessionID() {
41865
- return process.env.DISPATCH_SESSION_ID ?? "";
41874
+ // ../pi-shared/src/dispatch-user-turn.ts
41875
+ var HANDLED_ATTEMPT_ENTRY = "envoy-dispatch-handled-attempt";
41876
+ function handledAttemptKey(messageId, attempt) {
41877
+ return `${messageId}#${attempt}`;
41878
+ }
41879
+ function handledAttempts(entries) {
41880
+ const handled = new Set;
41881
+ for (const entry of entries) {
41882
+ if (typeof entry !== "object" || entry === null)
41883
+ continue;
41884
+ if (!("type" in entry) || entry.type !== "custom")
41885
+ continue;
41886
+ if (!("customType" in entry) || entry.customType !== HANDLED_ATTEMPT_ENTRY)
41887
+ continue;
41888
+ if (!("data" in entry) || typeof entry.data !== "object" || entry.data === null)
41889
+ continue;
41890
+ const { data } = entry;
41891
+ if (!("message_id" in data) || typeof data.message_id !== "string")
41892
+ continue;
41893
+ if (!("attempt" in data) || typeof data.attempt !== "number")
41894
+ continue;
41895
+ handled.add(handledAttemptKey(data.message_id, data.attempt));
41896
+ }
41897
+ return handled;
41898
+ }
41899
+ function typedInputReply(text, outcome) {
41900
+ const typed = /^\/\S+/.exec(text)?.[0];
41901
+ const command = typed ?? "This message";
41902
+ if ("error" in outcome)
41903
+ return `${command} was not run: ${outcome.error}`;
41904
+ if ("hostVersion" in outcome) {
41905
+ return typed === undefined ? undefined : `${typed} was not run: this session's agent, version ${outcome.hostVersion}, cannot run commands sent from Dispatch; nothing was sent.`;
41906
+ }
41907
+ if (outcome.handled === "terminal-only") {
41908
+ return `${command} runs only in the session's own terminal; nothing was sent.`;
41909
+ }
41910
+ if (outcome.handled === "unavailable") {
41911
+ return `${command} was not run: this session's host cannot run typed input from Dispatch; nothing was sent.`;
41912
+ }
41913
+ return outcome.output?.trim() ? outcome.output : undefined;
41866
41914
  }
41867
41915
 
41868
- // ../pi-shared/src/interface.ts
41869
- import { logger } from "@oh-my-pi/pi-utils";
41870
-
41871
- // ../pi-shared/src/envoy-notice.ts
41872
- var LOCAL_ENVOY_NOTICE = { localNotice: true };
41873
-
41874
- // ../pi-shared/src/interface.ts
41875
- var ENVOY_PLUGIN_INTERFACE_VERSION = 5;
41876
- var ENVOY_PLUGIN_INTERFACE_KEY = Symbol.for("legion.pi-shared.envoy-plugin-interface");
41877
- var LEGION_PLUGIN_LOADED_KEY = Symbol.for("legion.pi-legion.loaded");
41878
- var LEGACY_LEGION_LOADED_KEY = Symbol.for("legion.pi-envoy.legion-loaded");
41879
- var store = globalThis;
41880
- var mismatchWarned = false;
41881
- function envoyPluginInterface() {
41882
- const existing = store[ENVOY_PLUGIN_INTERFACE_KEY];
41883
- if (existing !== undefined)
41884
- return existing;
41885
- const created = {
41886
- version: ENVOY_PLUGIN_INTERFACE_VERSION,
41887
- publishers: [],
41888
- roleClaim: {
41889
- instances: [],
41890
- managedSessions: new Set,
41891
- regained: undefined,
41892
- slackRoleOwned: false
41893
- },
41894
- injectedUserTurns: new Map,
41895
- bootstrappedSession: { file: undefined },
41896
- startupTurn: undefined
41897
- };
41898
- store[ENVOY_PLUGIN_INTERFACE_KEY] = created;
41899
- return created;
41916
+ // ../pi-shared/src/accept-user-turn.ts
41917
+ function isUserTurnCandidate(rendered) {
41918
+ const { delivery } = rendered;
41919
+ return rendered.envelope?.source === "dispatch" && delivery?.resource === "message" && delivery.issueKey === null && delivery.broadcastId === undefined && rendered.dispatchActor?.kind === "user" && (delivery.mode === "aside" || delivery.mode === "steer");
41900
41920
  }
41901
- function publishEnvoyPluginInterface(from) {
41902
- const iface = envoyPluginInterface();
41903
- if (iface.version !== ENVOY_PLUGIN_INTERFACE_VERSION) {
41904
- if (!mismatchWarned) {
41905
- mismatchWarned = true;
41906
- logger.warn(`Envoy plugin interface version ${iface.version} is already published by ${iface.publishers[0] ?? "no Envoy entry (a consumer created it)"}; the Envoy entry at ${from} speaks version ${ENVOY_PLUGIN_INTERFACE_VERSION} and publishes nothing`, {
41907
- found: iface.version,
41908
- expected: ENVOY_PLUGIN_INTERFACE_VERSION,
41909
- publishers: iface.publishers,
41910
- from
41911
- });
41921
+ var AcceptedDeliverySchema = object({
41922
+ message_id: string2(),
41923
+ body: string2(),
41924
+ delivery: _enum2(["aside", "steer"])
41925
+ });
41926
+ function turnFromAccept(accepted) {
41927
+ const parsed = AcceptedDeliverySchema.safeParse(accepted);
41928
+ if (!parsed.success)
41929
+ return;
41930
+ return { body: parsed.data.body, messageId: parsed.data.message_id, mode: parsed.data.delivery };
41931
+ }
41932
+ async function acceptUserTurn(options) {
41933
+ const { rendered } = options;
41934
+ if (!isUserTurnCandidate(rendered))
41935
+ return;
41936
+ const { delivery } = rendered;
41937
+ const key = handledAttemptKey(delivery.id, delivery.attempt);
41938
+ if (options.handled(key)) {
41939
+ options.warn({ delivery, reason: "handled" });
41940
+ return;
41941
+ }
41942
+ await options.handle(key, delivery);
41943
+ try {
41944
+ const dispatch = options.dispatch();
41945
+ if (dispatch === undefined)
41946
+ return;
41947
+ const accepted = await dispatch.acceptMessageDelivery(delivery.id, delivery.attempt, {
41948
+ actor: { id: options.actorId, kind: "session" }
41949
+ });
41950
+ const turn = turnFromAccept(accepted);
41951
+ if (turn === undefined) {
41952
+ options.warn({ delivery, reason: "no-body" });
41953
+ return;
41912
41954
  }
41955
+ return { delivery, turn };
41956
+ } catch (error) {
41957
+ options.warn({ delivery, error, reason: "failed" });
41913
41958
  return;
41914
41959
  }
41915
- if (!iface.publishers.includes(from))
41916
- iface.publishers.push(from);
41917
- return iface;
41918
41960
  }
41919
41961
 
41920
- // ../pi-shared/src/injected-user-turns.ts
41921
- function userMessageText(content) {
41962
+ // ../pi-shared/src/agent-stream.ts
41963
+ var encoder4 = new TextEncoder;
41964
+ var REPLAY_ARRAY_BYTES = 2;
41965
+ function jsonBytes(value) {
41966
+ return encoder4.encode(JSON.stringify(value)).length;
41967
+ }
41968
+ var SEQ_PER_MS = 1000;
41969
+ function modelReference(provider, id) {
41970
+ if (typeof id !== "string" || id === "")
41971
+ return;
41972
+ if (typeof provider !== "string" || provider === "")
41973
+ return;
41974
+ return `${provider}/${id}`;
41975
+ }
41976
+ function readModel(message) {
41977
+ const model = modelReference(message.provider, message.model);
41978
+ return model === undefined ? undefined : capAgentStreamText(model, AGENT_STREAM_LIMITS.modelChars);
41979
+ }
41980
+ function readMessage(raw) {
41981
+ if (typeof raw !== "object" || raw === null)
41982
+ return null;
41983
+ const message = raw;
41984
+ if (typeof message.role !== "string" || typeof message.timestamp !== "number")
41985
+ return null;
41986
+ return {
41987
+ host: message,
41988
+ isError: message.isError === true,
41989
+ model: readModel(message),
41990
+ role: message.role,
41991
+ timestamp: message.timestamp,
41992
+ toolCallId: typeof message.toolCallId === "string" ? message.toolCallId : undefined,
41993
+ toolName: typeof message.toolName === "string" ? message.toolName : undefined,
41994
+ tag: typeof message.tag === "string" ? message.tag : undefined
41995
+ };
41996
+ }
41997
+ function keyFor(message) {
41998
+ if (message.role === "toolResult") {
41999
+ return message.toolCallId === undefined ? null : `t:${message.toolCallId}`;
42000
+ }
42001
+ if (message.role === "assistant")
42002
+ return `m:a${message.timestamp}`;
42003
+ if (message.role !== "user")
42004
+ return null;
42005
+ return message.tag === undefined ? `m:u${message.timestamp}` : `m:u${message.timestamp}:${message.tag}`;
42006
+ }
42007
+ function contentText(content) {
41922
42008
  if (typeof content === "string")
41923
42009
  return content;
41924
42010
  if (!Array.isArray(content))
41925
42011
  return "";
41926
42012
  const pieces = [];
41927
- for (const part of content) {
41928
- if (typeof part !== "object" || part === null)
42013
+ for (const raw of content) {
42014
+ if (typeof raw !== "object" || raw === null)
41929
42015
  continue;
41930
- if ("type" in part && part.type === "text" && "text" in part && typeof part.text === "string") {
42016
+ const part = raw;
42017
+ if (typeof part.text === "string")
41931
42018
  pieces.push(part.text);
41932
- }
42019
+ else if (typeof part.type === "string")
42020
+ pieces.push(blockPlaceholder(part.type));
41933
42021
  }
41934
42022
  return pieces.join(`
41935
42023
  `);
41936
42024
  }
41937
- function sessionTurns(sessionID) {
41938
- const turns = envoyPluginInterface().injectedUserTurns;
41939
- const session = turns.get(sessionID) ?? { found: new Map, sent: [] };
41940
- turns.set(sessionID, session);
41941
- return session;
41942
- }
41943
- function noteInjectedUserTurn(sessionID, body, messageId) {
41944
- sessionTurns(sessionID).sent.push({ body, messageId, via: "text" });
41945
- }
41946
- function noteTypedUserTurn(sessionID, messageId) {
41947
- sessionTurns(sessionID).sent.push({ messageId, via: "typed" });
42025
+ function boundedStrings(_key, value) {
42026
+ return typeof value === "string" ? capAgentStreamText(value, AGENT_STREAM_LIMITS.toolChars) : value;
41948
42027
  }
41949
- function dropInjectedUserTurn(sessionID, messageId) {
41950
- const session = envoyPluginInterface().injectedUserTurns.get(sessionID);
41951
- if (session === undefined)
41952
- return;
41953
- const index = session.sent.findIndex((sent) => sent.messageId === messageId);
41954
- if (index !== -1)
41955
- session.sent.splice(index, 1);
42028
+ function renderArguments(value) {
42029
+ if (value === undefined || value === null)
42030
+ return "";
42031
+ try {
42032
+ return JSON.stringify(value, boundedStrings, 2) ?? "";
42033
+ } catch {
42034
+ return "[unserialisable arguments]";
42035
+ }
41956
42036
  }
41957
- function matchInjectedUserTurn(sessionID, message) {
41958
- if (typeof message !== "object" || message === null)
41959
- return;
41960
- if (!("role" in message) || message.role !== "user" && message.role !== "custom") {
41961
- return;
42037
+ function conversationParts(content) {
42038
+ const { partChars, toolChars } = AGENT_STREAM_LIMITS;
42039
+ if (typeof content === "string") {
42040
+ return content === "" ? [] : [{ text: capAgentStreamText(content, partChars), type: "text" }];
41962
42041
  }
41963
- if (!("timestamp" in message) || typeof message.timestamp !== "number")
41964
- return;
41965
- const session = envoyPluginInterface().injectedUserTurns.get(sessionID);
41966
- if (session === undefined)
41967
- return;
41968
- const tag = messageTag(message);
41969
- const memo = tag === undefined ? `${message.timestamp}` : `${message.timestamp}:${tag}`;
41970
- const known = session.found.get(memo);
41971
- if (known !== undefined)
41972
- return known;
41973
- let index = tag === undefined ? -1 : session.sent.findIndex((sent) => sent.messageId === tag);
41974
- if (index === -1 && message.role === "user") {
41975
- const text = userMessageText("content" in message ? message.content : undefined);
41976
- index = session.sent.findIndex((sent) => sent.via === "text" && sent.body === text);
42042
+ if (!Array.isArray(content))
42043
+ return [];
42044
+ const parts = [];
42045
+ for (const raw of content) {
42046
+ if (typeof raw !== "object" || raw === null)
42047
+ continue;
42048
+ const part = raw;
42049
+ if (part.type === "text" && typeof part.text === "string") {
42050
+ parts.push({ text: capAgentStreamText(part.text, partChars), type: "text" });
42051
+ } else if (part.type === "thinking" && typeof part.thinking === "string") {
42052
+ parts.push({ text: capAgentStreamText(part.thinking, partChars), type: "reasoning" });
42053
+ } else if (part.type === "toolCall" && typeof part.id === "string") {
42054
+ parts.push({
42055
+ argsText: capAgentStreamText(renderArguments(part.arguments), toolChars),
42056
+ toolCallId: part.id,
42057
+ toolName: typeof part.name === "string" ? part.name : "tool",
42058
+ type: "tool-call"
42059
+ });
42060
+ } else if (typeof part.type === "string") {
42061
+ parts.push({ text: blockPlaceholder(part.type), type: "text" });
42062
+ }
41977
42063
  }
41978
- const sent = session.sent[index];
41979
- if (sent === undefined)
41980
- return;
41981
- session.sent.splice(index, 1);
41982
- session.found.set(memo, sent.messageId);
41983
- return sent.messageId;
41984
- }
41985
- function messageTag(message) {
41986
- if (typeof message !== "object" || message === null || !("tag" in message))
41987
- return;
41988
- return typeof message.tag === "string" ? message.tag : undefined;
42064
+ return parts;
41989
42065
  }
41990
- function endInjectedUserTurns(sessionID) {
41991
- const turns = envoyPluginInterface().injectedUserTurns;
41992
- const typed = turns.get(sessionID)?.sent.filter((sent) => sent.via === "typed") ?? [];
41993
- if (typed.length === 0)
41994
- turns.delete(sessionID);
41995
- else
41996
- turns.set(sessionID, { found: new Map, sent: typed });
41997
- }
41998
- function forgetInjectedUserTurns(sessionID) {
41999
- envoyPluginInterface().injectedUserTurns.delete(sessionID);
42000
- }
42001
-
42002
- // ../pi-shared/src/role-claim-bridge.ts
42003
- function legionRoleClaimBridge() {
42004
- return envoyPluginInterface().roleClaim;
42066
+ function frameFor(entry) {
42067
+ const { dispatchMessageId, message } = entry;
42068
+ if (message.role === "toolResult" && message.toolCallId !== undefined) {
42069
+ return {
42070
+ kind: "tool-result",
42071
+ result: {
42072
+ at: message.timestamp,
42073
+ isError: message.isError,
42074
+ output: capAgentStreamText(contentText(message.host.content), AGENT_STREAM_LIMITS.toolChars),
42075
+ toolCallId: message.toolCallId,
42076
+ toolName: message.toolName ?? "tool"
42077
+ },
42078
+ seq: entry.seq,
42079
+ v: AGENT_STREAM_PROTOCOL
42080
+ };
42081
+ }
42082
+ return {
42083
+ kind: "message",
42084
+ message: {
42085
+ at: message.timestamp,
42086
+ id: entry.key.slice(2),
42087
+ parts: conversationParts(message.host.content),
42088
+ role: message.role === "assistant" ? "assistant" : "user",
42089
+ streaming: entry.streaming,
42090
+ ...dispatchMessageId === undefined ? {} : { dispatchMessageId },
42091
+ ...message.role === "assistant" && message.model !== undefined ? { model: message.model } : {}
42092
+ },
42093
+ seq: entry.seq,
42094
+ v: AGENT_STREAM_PROTOCOL
42095
+ };
42005
42096
  }
42006
42097
 
42007
- // ../pi-shared/src/shell-command.ts
42008
- var HEREDOC_OPENING = /^(.*?)[ \t]*<<(-?)[ \t]*'([A-Za-z_][A-Za-z0-9_]*)'[ \t]*$/;
42009
- var BLANK_LINE = /^[ \t]*$/;
42010
- var REFUSED_UNQUOTED = "\n;&|$`<>()#\\";
42011
- var REFUSED_DOUBLE_QUOTED = "$`\\";
42012
- function dispatchCommandHead(command) {
42013
- if (typeof command !== "string" || hasControlCharacter2(command))
42014
- return;
42015
- const all = command.split(`
42016
- `);
42017
- const first = all.findIndex((line) => !BLANK_LINE.test(line));
42018
- if (first === -1)
42019
- return;
42020
- const last = all.findLastIndex((line) => !BLANK_LINE.test(line));
42021
- const lines = all.slice(first, last + 1);
42022
- let head = withoutComment(lines[0] ?? "");
42023
- if (lines.length > 1) {
42024
- const opening = HEREDOC_OPENING.exec(head);
42025
- if (opening === null)
42026
- return;
42027
- const stripTabs = opening[2] === "-";
42028
- const delimiter = opening[3];
42029
- const end = lines.findIndex((line, index) => index > 0 && (stripTabs ? line.replace(/^\t+/, "") : line) === delimiter);
42030
- if (end !== lines.length - 1)
42031
- return;
42032
- head = opening[1] ?? "";
42098
+ class AgentStreamPublisher {
42099
+ #deps;
42100
+ #history = new Map;
42101
+ #settled = new Set;
42102
+ #publishedAt = new Map;
42103
+ #seq;
42104
+ #watchedUntil = 0;
42105
+ #listedCommands;
42106
+ #commands;
42107
+ #commandsSeq = 0;
42108
+ #settings;
42109
+ #settingsSeq = 0;
42110
+ #settingsJson;
42111
+ constructor(deps) {
42112
+ this.#deps = deps;
42113
+ this.#seq = Math.trunc(deps.now()) * SEQ_PER_MS;
42033
42114
  }
42034
- head = head.replace(/^[ \t]+|[ \t]+$/g, "");
42035
- return firstWord(head) === "dispatch" && headScan(head) ? head : undefined;
42036
- }
42037
- function firstWord(head) {
42038
- return head.split(/[ \t]/, 1)[0] ?? "";
42039
- }
42040
- function withoutComment(line) {
42041
- let quote;
42042
- for (let index = 0;index < line.length; index += 1) {
42043
- const char = line[index];
42044
- if (quote !== undefined) {
42045
- if (char === quote)
42046
- quote = undefined;
42047
- else if (char === "\\" && quote === '"')
42048
- return line;
42049
- continue;
42115
+ noteViewer() {
42116
+ this.#watchedUntil = this.#deps.now() + AGENT_STREAM_WATCH_TTL_MS;
42117
+ }
42118
+ publishState(subject) {
42119
+ if (!this.watched)
42120
+ return;
42121
+ if (this.#settings !== undefined) {
42122
+ this.#deps.publish(subject, JSON.stringify(this.#settingsFrame(this.#settings)));
42123
+ }
42124
+ if (this.#commands !== undefined) {
42125
+ this.#deps.publish(subject, JSON.stringify(this.#commandsFrame(this.#commands)));
42050
42126
  }
42051
- if (char === "\\")
42052
- return line;
42053
- if (char === "'" || char === '"')
42054
- quote = char;
42055
- else if (char === "#" && (index === 0 || line[index - 1] === " " || line[index - 1] === "\t"))
42056
- return line.slice(0, index);
42057
42127
  }
42058
- return line;
42059
- }
42060
- function hasControlCharacter2(text) {
42061
- for (let index = 0;index < text.length; index += 1) {
42062
- const code = text.charCodeAt(index);
42063
- if (code < 32 && code !== 10 && code !== 9 || code === 127)
42064
- return true;
42128
+ get watched() {
42129
+ return this.#deps.now() < this.#watchedUntil;
42065
42130
  }
42066
- return false;
42067
- }
42068
- function headScan(head) {
42069
- let quote;
42070
- for (const char of head) {
42071
- if (quote === "'") {
42072
- if (char === "'")
42073
- quote = undefined;
42074
- continue;
42131
+ reset() {
42132
+ this.#history.clear();
42133
+ this.#settled.clear();
42134
+ this.#publishedAt.clear();
42135
+ this.#watchedUntil = 0;
42136
+ this.#listedCommands = undefined;
42137
+ this.#commands = undefined;
42138
+ this.#settings = undefined;
42139
+ this.#settingsJson = undefined;
42140
+ }
42141
+ setCommands(subject, commands) {
42142
+ const seen = new Set;
42143
+ const listed = [];
42144
+ for (const command of commands) {
42145
+ if (listed.length >= AGENT_STREAM_LIMITS.commands)
42146
+ break;
42147
+ const name = command.name;
42148
+ if (name.length > AGENT_STREAM_LIMITS.commandNameChars)
42149
+ continue;
42150
+ if (!isTypableCommandName(name) || seen.has(name))
42151
+ continue;
42152
+ seen.add(name);
42153
+ listed.push({
42154
+ name,
42155
+ source: command.source,
42156
+ ...command.description !== undefined && {
42157
+ description: capAgentStreamText(command.description, AGENT_STREAM_LIMITS.commandDescriptionChars)
42158
+ },
42159
+ ...command.terminalOnly === true && { terminalOnly: true }
42160
+ });
42075
42161
  }
42076
- if (quote === '"') {
42077
- if (char === '"')
42078
- quote = undefined;
42079
- else if (REFUSED_DOUBLE_QUOTED.includes(char))
42080
- return false;
42081
- continue;
42162
+ this.#listedCommands = listed;
42163
+ this.#fitCommands(subject);
42164
+ }
42165
+ setSettings(subject, settings) {
42166
+ const kept = settings.reported ? {
42167
+ ...settings.model !== undefined && { model: settings.model },
42168
+ models: [...settings.models],
42169
+ reported: true,
42170
+ thinking: settings.thinking === null ? null : { level: settings.thinking.level, levels: [...settings.thinking.levels] }
42171
+ } : { reported: false };
42172
+ const json = JSON.stringify(kept);
42173
+ if (json === this.#settingsJson)
42174
+ return;
42175
+ this.#settings = kept;
42176
+ this.#settingsJson = json;
42177
+ this.#seq += 1;
42178
+ this.#settingsSeq = this.#seq;
42179
+ if (this.watched)
42180
+ this.#deps.publish(subject, JSON.stringify(this.#settingsFrame(kept)));
42181
+ this.#fitCommands(subject);
42182
+ }
42183
+ #fitCommands(subject) {
42184
+ const listed = this.#listedCommands;
42185
+ if (listed === undefined)
42186
+ return;
42187
+ const settings = this.#settings === undefined ? 0 : jsonBytes(this.#settingsFrame(this.#settings)) + 1;
42188
+ const limit = AGENT_STREAM_LIMITS.historyBytes - REPLAY_ARRAY_BYTES - settings;
42189
+ let bytes = jsonBytes(this.#commandsFrame([], this.#seq + 1));
42190
+ const kept = [];
42191
+ for (const command of listed) {
42192
+ const cost = jsonBytes(command) + (kept.length === 0 ? 0 : 1);
42193
+ if (bytes + cost > limit)
42194
+ break;
42195
+ bytes += cost;
42196
+ kept.push(command);
42082
42197
  }
42083
- if (char === "'" || char === '"')
42084
- quote = char;
42085
- else if (REFUSED_UNQUOTED.includes(char))
42086
- return false;
42198
+ if (JSON.stringify(kept) === JSON.stringify(this.#commands))
42199
+ return;
42200
+ this.#commands = kept;
42201
+ this.#seq += 1;
42202
+ this.#commandsSeq = this.#seq;
42203
+ if (this.watched)
42204
+ this.#deps.publish(subject, JSON.stringify(this.#commandsFrame(kept)));
42087
42205
  }
42088
- return quote === undefined;
42089
- }
42090
-
42091
- // ../pi-shared/src/subagent-session.ts
42092
- import fs from "fs";
42093
- import path2 from "path";
42094
- import * as host from "@oh-my-pi/pi-coding-agent";
42095
- import { logger as logger2 } from "@oh-my-pi/pi-utils";
42096
- async function isSubagentSession(context) {
42097
- const registered = registeredSubagent(context);
42098
- if (registered !== undefined)
42099
- return { subagent: registered, settled: true };
42100
- try {
42101
- await context.sessionManager.ensureOnDisk();
42102
- } catch (error) {
42103
- const subagent = transcriptSaysSubagent(context);
42104
- logger2.warn("subagent check: publishing the transcript failed; answered from the transcript on disk, and the next call asks again", { sessionFile: context.sessionManager.getSessionFile(), subagent, error: messageFor(error) });
42105
- return { subagent, settled: false };
42206
+ #commandsFrame(commands, seq = this.#commandsSeq) {
42207
+ return { commands, kind: "commands", seq, v: AGENT_STREAM_PROTOCOL };
42106
42208
  }
42107
- return { subagent: transcriptSaysSubagent(context), settled: true };
42108
- }
42109
- function transcriptSaysSubagent(context) {
42110
- const sessionFile = context.sessionManager.getSessionFile();
42111
- if (sessionFile !== undefined) {
42112
- if (fs.existsSync(`${path2.dirname(sessionFile)}.jsonl`))
42113
- return true;
42114
- if (fs.existsSync(sessionFile))
42115
- return false;
42209
+ #settingsFrame(settings) {
42210
+ return { ...settings, kind: "settings", seq: this.#settingsSeq, v: AGENT_STREAM_PROTOCOL };
42211
+ }
42212
+ record(subject, raw, streaming, dispatchMessageId) {
42213
+ const message = readMessage(raw);
42214
+ if (message === null)
42215
+ return false;
42216
+ const key = keyFor(message);
42217
+ if (key === null)
42218
+ return false;
42219
+ const stillStreaming = message.role === "assistant" && streaming;
42220
+ if (stillStreaming && this.#settled.has(key))
42221
+ return false;
42222
+ this.#seq += 1;
42223
+ const entry = {
42224
+ at: message.timestamp,
42225
+ dispatchMessageId: dispatchMessageId ?? this.#history.get(key)?.dispatchMessageId,
42226
+ key,
42227
+ message,
42228
+ seq: this.#seq,
42229
+ streaming: stillStreaming
42230
+ };
42231
+ this.#history.set(key, entry);
42232
+ if (!stillStreaming)
42233
+ this.#settled.add(key);
42234
+ while (this.#history.size > AGENT_STREAM_LIMITS.historyMessages) {
42235
+ const oldest = this.#history.keys().next();
42236
+ if (oldest.done === true)
42237
+ break;
42238
+ this.#history.delete(oldest.value);
42239
+ this.#settled.delete(oldest.value);
42240
+ this.#publishedAt.delete(oldest.value);
42241
+ }
42242
+ if (!this.watched)
42243
+ return true;
42244
+ const now = this.#deps.now();
42245
+ const published = this.#publishedAt.get(key);
42246
+ const tooSoon = published !== undefined && now - published < AGENT_STREAM_LIMITS.snapshotIntervalMs;
42247
+ if (stillStreaming && tooSoon)
42248
+ return true;
42249
+ this.#publishedAt.set(key, now);
42250
+ this.#deps.publish(subject, JSON.stringify(frameFor(entry)));
42251
+ return true;
42252
+ }
42253
+ replay(sessionID) {
42254
+ if (!this.watched)
42255
+ return { frames: [], session_id: sessionID, v: AGENT_STREAM_PROTOCOL };
42256
+ const ordered = [...this.#history.values()].sort((left, right) => left.at === right.at ? left.seq - right.seq : left.at - right.at);
42257
+ const tail = [];
42258
+ if (this.#settings !== undefined)
42259
+ tail.push(this.#settingsFrame(this.#settings));
42260
+ if (this.#commands !== undefined)
42261
+ tail.push(this.#commandsFrame(this.#commands));
42262
+ let used = REPLAY_ARRAY_BYTES + tail.reduce((bytes, frame, index) => bytes + jsonBytes(frame) + (index === 0 ? 0 : 1), 0);
42263
+ const kept = [];
42264
+ for (let index = ordered.length - 1;index >= 0; index -= 1) {
42265
+ const entry = ordered[index];
42266
+ if (entry === undefined)
42267
+ continue;
42268
+ const frame = frameFor(entry);
42269
+ const separated = kept.length > 0 || tail.length > 0;
42270
+ const cost = jsonBytes(frame) + (separated ? 1 : 0);
42271
+ if (used + cost > AGENT_STREAM_LIMITS.historyBytes)
42272
+ break;
42273
+ used += cost;
42274
+ kept.unshift(frame);
42275
+ }
42276
+ kept.push(...tail);
42277
+ return { frames: kept, session_id: sessionID, v: AGENT_STREAM_PROTOCOL };
42116
42278
  }
42117
- const bootstrapped = envoyPluginInterface().bootstrappedSession.file;
42118
- return bootstrapped !== undefined && bootstrapped !== sessionFile;
42119
- }
42120
- function registeredSubagent(context) {
42121
- const registry = host.AgentRegistry?.global();
42122
- if (registry === undefined)
42123
- return;
42124
- const sessionID = context.sessionManager.getSessionId();
42125
- const sessionFile = context.sessionManager.getSessionFile();
42126
- const own = registry.list().filter((ref) => ref.session === null ? sessionFile !== undefined && ref.sessionFile === sessionFile : ref.session.sessionManager.getSessionId() === sessionID);
42127
- if (own.length === 0)
42128
- return;
42129
- return own.some((ref) => ref.kind !== "main");
42130
- }
42131
- function subagentSessionCheck() {
42132
- let settled;
42133
- return async (context) => {
42134
- if (settled !== undefined)
42135
- return settled;
42136
- const answer = await isSubagentSession(context);
42137
- if (answer.settled)
42138
- settled = answer.subagent;
42139
- return answer.subagent;
42140
- };
42141
- }
42142
-
42143
- // ../pi-shared/src/tool-result.ts
42144
- function toolSuccess(text, details = {}, images = []) {
42145
- return { content: [{ type: "text", text }, ...imageBlocks(images)], details };
42146
- }
42147
- function toolFailure(error) {
42148
- return { content: [{ type: "text", text: messageFor(error) }], details: {}, isError: true };
42149
42279
  }
42150
42280
 
42151
- // extensions/envoy.ts
42152
- import * as host2 from "@oh-my-pi/pi-coding-agent";
42153
- import { logger as logger3, procmgr, VERSION } from "@oh-my-pi/pi-utils";
42154
- var import_nats2 = __toESM(require_mod4(), 1);
42155
-
42156
- // package.json
42157
- var name = "@sjawhar/pi-envoy";
42158
- var version2 = "16.29.0";
42159
- var package_default = {
42160
- name,
42161
- version: version2,
42162
- license: "Apache-2.0",
42163
- type: "module",
42164
- omp: {
42165
- extensions: [
42166
- "dist/envoy.js"
42167
- ],
42168
- skills: [
42169
- "dist/skills"
42170
- ],
42171
- bin: [
42172
- "bin"
42173
- ]
42174
- },
42175
- repository: {
42176
- type: "git",
42177
- url: "https://github.com/cybermonklabs/legion"
42178
- },
42179
- files: [
42180
- "dist",
42181
- "bin"
42182
- ],
42183
- scripts: {
42184
- build: "bun build extensions/envoy.ts --outdir dist --target bun --format esm --external @oh-my-pi/pi-ai --external @oh-my-pi/pi-coding-agent --external @oh-my-pi/pi-tui --external @oh-my-pi/pi-utils && ../envoy-client/scripts/build-dispatch-cli.sh dist",
42185
- prepack: "../../scripts/pi-plugin-prepack.sh",
42186
- postpack: "rm -rf dist/skills",
42187
- typecheck: "bunx tsc --noEmit",
42188
- test: "bun test --path-ignore-patterns=extensions/card-delivery-omp.test.ts && bun test ./extensions/card-delivery-omp.test.ts",
42189
- lint: "bunx biome lint extensions/ src/"
42190
- },
42191
- devDependencies: {
42192
- "@biomejs/biome": "^2.3.14",
42193
- "@legion/contracts": "workspace:*",
42194
- "@legion/envoy-client": "workspace:*",
42195
- "@legion/pi-shared": "workspace:*",
42196
- "@oh-my-pi/pi-tui": "^18.6.0",
42197
- "@oh-my-pi/pi-utils": "^18.6.0",
42198
- "@toon-format/toon": "^4.1.1",
42199
- "@types/bun": "latest",
42200
- nats: "^2.29.2",
42201
- typescript: "^5.3.0",
42202
- zod: "4.3.6"
42281
+ // ../pi-shared/src/delivery-pictures.ts
42282
+ async function withDeliveredPictures(text, addresses, client, named, shown) {
42283
+ const textAlone = { content: text, shown: [] };
42284
+ if (addresses.length === 0)
42285
+ return textAlone;
42286
+ let dispatch;
42287
+ try {
42288
+ dispatch = client();
42289
+ } catch {
42290
+ return textAlone;
42203
42291
  }
42204
- };
42292
+ if (dispatch === undefined)
42293
+ return textAlone;
42294
+ const unique = [...new Set(addresses)];
42295
+ const shownEarlier = unique.some((address) => shown.has(address));
42296
+ const pictures = await readPictures(dispatch, unique, shown);
42297
+ const content = named ? `${text}
42205
42298
 
42206
- // src/agent-stream.ts
42207
- var encoder4 = new TextEncoder;
42208
- var REPLAY_ARRAY_BYTES = 2;
42209
- function jsonBytes(value) {
42210
- return encoder4.encode(JSON.stringify(value)).length;
42299
+ ${pictures.lines.join(`
42300
+ `)}` : text;
42301
+ if (pictures.images.length === 0)
42302
+ return shownEarlier ? { content, shown: [] } : textAlone;
42303
+ return {
42304
+ content: [{ type: "text", text: content }, ...imageBlocks(pictures.images)],
42305
+ shown: pictures.shown
42306
+ };
42211
42307
  }
42212
- var SEQ_PER_MS = 1000;
42213
- function modelReference(provider, id) {
42214
- if (typeof id !== "string" || id === "")
42308
+ function entryMessage(entry) {
42309
+ if (typeof entry !== "object" || entry === null || !("type" in entry))
42215
42310
  return;
42216
- if (typeof provider !== "string" || provider === "")
42311
+ if (entry.type === "custom_message") {
42312
+ return { role: "custom", content: "content" in entry ? entry.content : undefined };
42313
+ }
42314
+ if (entry.type !== "message" || !("message" in entry))
42315
+ return;
42316
+ const { message } = entry;
42317
+ if (typeof message !== "object" || message === null)
42217
42318
  return;
42218
- return `${provider}/${id}`;
42219
- }
42220
- function readModel(message) {
42221
- const model = modelReference(message.provider, message.model);
42222
- return model === undefined ? undefined : capAgentStreamText(model, AGENT_STREAM_LIMITS.modelChars);
42223
- }
42224
- function readMessage(raw) {
42225
- if (typeof raw !== "object" || raw === null)
42226
- return null;
42227
- const message = raw;
42228
- if (typeof message.role !== "string" || typeof message.timestamp !== "number")
42229
- return null;
42230
42319
  return {
42231
- host: message,
42232
- isError: message.isError === true,
42233
- model: readModel(message),
42234
- role: message.role,
42235
- timestamp: message.timestamp,
42236
- toolCallId: typeof message.toolCallId === "string" ? message.toolCallId : undefined,
42237
- toolName: typeof message.toolName === "string" ? message.toolName : undefined,
42238
- tag: typeof message.tag === "string" ? message.tag : undefined
42320
+ role: "role" in message ? message.role : undefined,
42321
+ content: "content" in message ? message.content : undefined
42239
42322
  };
42240
42323
  }
42241
- function keyFor(message) {
42242
- if (message.role === "toolResult") {
42243
- return message.toolCallId === undefined ? null : `t:${message.toolCallId}`;
42244
- }
42245
- if (message.role === "assistant")
42246
- return `m:a${message.timestamp}`;
42247
- if (message.role !== "user")
42248
- return null;
42249
- return message.tag === undefined ? `m:u${message.timestamp}` : `m:u${message.timestamp}:${message.tag}`;
42250
- }
42251
- function contentText(content) {
42252
- if (typeof content === "string")
42253
- return content;
42254
- if (!Array.isArray(content))
42255
- return "";
42256
- const pieces = [];
42257
- for (const raw of content) {
42258
- if (typeof raw !== "object" || raw === null)
42324
+ function transcriptPictures(entries) {
42325
+ const shown = new Set;
42326
+ for (const entry of entries) {
42327
+ const message = entryMessage(entry);
42328
+ if (message === undefined)
42259
42329
  continue;
42260
- const part = raw;
42261
- if (typeof part.text === "string")
42262
- pieces.push(part.text);
42263
- else if (typeof part.type === "string")
42264
- pieces.push(`[${part.type}]`);
42330
+ const { content } = message;
42331
+ const texts = [];
42332
+ let images = 0;
42333
+ if (typeof content === "string")
42334
+ texts.push(content);
42335
+ else if (Array.isArray(content)) {
42336
+ for (const block of content) {
42337
+ if (typeof block !== "object" || block === null || !("type" in block))
42338
+ continue;
42339
+ if (block.type === "image")
42340
+ images++;
42341
+ if (block.type === "text" && "text" in block && typeof block.text === "string") {
42342
+ texts.push(block.text);
42343
+ }
42344
+ }
42345
+ }
42346
+ for (const address of shownPictureAddresses(texts))
42347
+ shown.add(address);
42348
+ if (message.role !== "user" || images === 0)
42349
+ continue;
42350
+ const embedded = new Set(texts.flatMap(pictureAddresses));
42351
+ if (embedded.size === images)
42352
+ for (const address of embedded)
42353
+ shown.add(address);
42265
42354
  }
42266
- return pieces.join(`
42267
- `);
42355
+ return [...shown];
42268
42356
  }
42269
- function boundedStrings(_key, value) {
42270
- return typeof value === "string" ? capAgentStreamText(value, AGENT_STREAM_LIMITS.toolChars) : value;
42357
+
42358
+ // ../pi-shared/src/dispatch-session-id.ts
42359
+ function currentSessionID() {
42360
+ return process.env.DISPATCH_SESSION_ID ?? "";
42271
42361
  }
42272
- function renderArguments(value) {
42273
- if (value === undefined || value === null)
42274
- return "";
42275
- try {
42276
- return JSON.stringify(value, boundedStrings, 2) ?? "";
42277
- } catch {
42278
- return "[unserialisable arguments]";
42279
- }
42362
+
42363
+ // ../pi-shared/src/interface.ts
42364
+ import { logger } from "@oh-my-pi/pi-utils";
42365
+
42366
+ // ../pi-shared/src/envoy-notice.ts
42367
+ var LOCAL_ENVOY_NOTICE = { localNotice: true };
42368
+
42369
+ // ../pi-shared/src/interface.ts
42370
+ var ENVOY_PLUGIN_INTERFACE_VERSION = 5;
42371
+ var ENVOY_PLUGIN_INTERFACE_KEY = Symbol.for("legion.pi-shared.envoy-plugin-interface");
42372
+ var LEGION_PLUGIN_LOADED_KEY = Symbol.for("legion.pi-legion.loaded");
42373
+ var LEGACY_LEGION_LOADED_KEY = Symbol.for("legion.pi-envoy.legion-loaded");
42374
+ var store = globalThis;
42375
+ var mismatchWarned = false;
42376
+ function envoyPluginInterface() {
42377
+ const existing = store[ENVOY_PLUGIN_INTERFACE_KEY];
42378
+ if (existing !== undefined)
42379
+ return existing;
42380
+ const created = {
42381
+ version: ENVOY_PLUGIN_INTERFACE_VERSION,
42382
+ publishers: [],
42383
+ roleClaim: {
42384
+ instances: [],
42385
+ managedSessions: new Set,
42386
+ regained: undefined,
42387
+ slackRoleOwned: false
42388
+ },
42389
+ injectedUserTurns: new Map,
42390
+ bootstrappedSession: { file: undefined },
42391
+ startupTurn: undefined
42392
+ };
42393
+ store[ENVOY_PLUGIN_INTERFACE_KEY] = created;
42394
+ return created;
42280
42395
  }
42281
- function conversationParts(content) {
42282
- const { partChars, toolChars } = AGENT_STREAM_LIMITS;
42283
- if (typeof content === "string") {
42284
- return content === "" ? [] : [{ text: capAgentStreamText(content, partChars), type: "text" }];
42396
+ function publishEnvoyPluginInterface(from) {
42397
+ const iface = envoyPluginInterface();
42398
+ if (iface.version !== ENVOY_PLUGIN_INTERFACE_VERSION) {
42399
+ if (!mismatchWarned) {
42400
+ mismatchWarned = true;
42401
+ logger.warn(`Envoy plugin interface version ${iface.version} is already published by ${iface.publishers[0] ?? "no Envoy entry (a consumer created it)"}; the Envoy entry at ${from} speaks version ${ENVOY_PLUGIN_INTERFACE_VERSION} and publishes nothing`, {
42402
+ found: iface.version,
42403
+ expected: ENVOY_PLUGIN_INTERFACE_VERSION,
42404
+ publishers: iface.publishers,
42405
+ from
42406
+ });
42407
+ }
42408
+ return;
42285
42409
  }
42410
+ if (!iface.publishers.includes(from))
42411
+ iface.publishers.push(from);
42412
+ return iface;
42413
+ }
42414
+
42415
+ // ../pi-shared/src/injected-user-turns.ts
42416
+ function userMessageText(content) {
42417
+ if (typeof content === "string")
42418
+ return content;
42286
42419
  if (!Array.isArray(content))
42287
- return [];
42288
- const parts = [];
42289
- for (const raw of content) {
42290
- if (typeof raw !== "object" || raw === null)
42420
+ return "";
42421
+ const pieces = [];
42422
+ for (const part of content) {
42423
+ if (typeof part !== "object" || part === null)
42291
42424
  continue;
42292
- const part = raw;
42293
- if (part.type === "text" && typeof part.text === "string") {
42294
- parts.push({ text: capAgentStreamText(part.text, partChars), type: "text" });
42295
- } else if (part.type === "thinking" && typeof part.thinking === "string") {
42296
- parts.push({ text: capAgentStreamText(part.thinking, partChars), type: "reasoning" });
42297
- } else if (part.type === "toolCall" && typeof part.id === "string") {
42298
- parts.push({
42299
- argsText: capAgentStreamText(renderArguments(part.arguments), toolChars),
42300
- toolCallId: part.id,
42301
- toolName: typeof part.name === "string" ? part.name : "tool",
42302
- type: "tool-call"
42303
- });
42304
- } else if (typeof part.type === "string") {
42305
- parts.push({ text: `[${part.type}]`, type: "text" });
42425
+ if ("type" in part && part.type === "text" && "text" in part && typeof part.text === "string") {
42426
+ pieces.push(part.text);
42306
42427
  }
42307
42428
  }
42308
- return parts;
42429
+ return pieces.join(`
42430
+ `);
42309
42431
  }
42310
- function frameFor(entry) {
42311
- const { dispatchMessageId, message } = entry;
42312
- if (message.role === "toolResult" && message.toolCallId !== undefined) {
42313
- return {
42314
- kind: "tool-result",
42315
- result: {
42316
- at: message.timestamp,
42317
- isError: message.isError,
42318
- output: capAgentStreamText(contentText(message.host.content), AGENT_STREAM_LIMITS.toolChars),
42319
- toolCallId: message.toolCallId,
42320
- toolName: message.toolName ?? "tool"
42321
- },
42322
- seq: entry.seq,
42323
- v: AGENT_STREAM_PROTOCOL
42324
- };
42325
- }
42326
- return {
42327
- kind: "message",
42328
- message: {
42329
- at: message.timestamp,
42330
- id: entry.key.slice(2),
42331
- parts: conversationParts(message.host.content),
42332
- role: message.role === "assistant" ? "assistant" : "user",
42333
- streaming: entry.streaming,
42334
- ...dispatchMessageId === undefined ? {} : { dispatchMessageId },
42335
- ...message.role === "assistant" && message.model !== undefined ? { model: message.model } : {}
42336
- },
42337
- seq: entry.seq,
42338
- v: AGENT_STREAM_PROTOCOL
42339
- };
42432
+ function sessionTurns(sessionID) {
42433
+ const turns = envoyPluginInterface().injectedUserTurns;
42434
+ const session = turns.get(sessionID) ?? { found: new Map, sent: [] };
42435
+ turns.set(sessionID, session);
42436
+ return session;
42340
42437
  }
42341
-
42342
- class AgentStreamPublisher {
42343
- #deps;
42344
- #history = new Map;
42345
- #settled = new Set;
42346
- #publishedAt = new Map;
42347
- #seq;
42348
- #watchedUntil = 0;
42349
- #listedCommands;
42350
- #commands;
42351
- #commandsSeq = 0;
42352
- #settings;
42353
- #settingsSeq = 0;
42354
- #settingsJson;
42355
- constructor(deps) {
42356
- this.#deps = deps;
42357
- this.#seq = Math.trunc(deps.now()) * SEQ_PER_MS;
42438
+ function noteInjectedUserTurn(sessionID, body, messageId) {
42439
+ sessionTurns(sessionID).sent.push({ body, messageId, via: "text" });
42440
+ }
42441
+ function noteTypedUserTurn(sessionID, messageId) {
42442
+ sessionTurns(sessionID).sent.push({ messageId, via: "typed" });
42443
+ }
42444
+ function dropInjectedUserTurn(sessionID, messageId) {
42445
+ const session = envoyPluginInterface().injectedUserTurns.get(sessionID);
42446
+ if (session === undefined)
42447
+ return;
42448
+ const index = session.sent.findIndex((sent) => sent.messageId === messageId);
42449
+ if (index !== -1)
42450
+ session.sent.splice(index, 1);
42451
+ }
42452
+ function matchInjectedUserTurn(sessionID, message) {
42453
+ if (typeof message !== "object" || message === null)
42454
+ return;
42455
+ if (!("role" in message) || message.role !== "user" && message.role !== "custom") {
42456
+ return;
42358
42457
  }
42359
- noteViewer() {
42360
- this.#watchedUntil = this.#deps.now() + AGENT_STREAM_WATCH_TTL_MS;
42458
+ if (!("timestamp" in message) || typeof message.timestamp !== "number")
42459
+ return;
42460
+ const session = envoyPluginInterface().injectedUserTurns.get(sessionID);
42461
+ if (session === undefined)
42462
+ return;
42463
+ const tag = messageTag(message);
42464
+ const memo = tag === undefined ? `${message.timestamp}` : `${message.timestamp}:${tag}`;
42465
+ const known = session.found.get(memo);
42466
+ if (known !== undefined)
42467
+ return known;
42468
+ let index = tag === undefined ? -1 : session.sent.findIndex((sent) => sent.messageId === tag);
42469
+ if (index === -1 && message.role === "user") {
42470
+ const text = userMessageText("content" in message ? message.content : undefined);
42471
+ index = session.sent.findIndex((sent) => sent.via === "text" && sent.body === text);
42361
42472
  }
42362
- publishState(subject) {
42363
- if (!this.watched)
42473
+ const sent = session.sent[index];
42474
+ if (sent === undefined)
42475
+ return;
42476
+ session.sent.splice(index, 1);
42477
+ session.found.set(memo, sent.messageId);
42478
+ return sent.messageId;
42479
+ }
42480
+ function messageTag(message) {
42481
+ if (typeof message !== "object" || message === null || !("tag" in message))
42482
+ return;
42483
+ return typeof message.tag === "string" ? message.tag : undefined;
42484
+ }
42485
+ function endInjectedUserTurns(sessionID) {
42486
+ const turns = envoyPluginInterface().injectedUserTurns;
42487
+ const typed = turns.get(sessionID)?.sent.filter((sent) => sent.via === "typed") ?? [];
42488
+ if (typed.length === 0)
42489
+ turns.delete(sessionID);
42490
+ else
42491
+ turns.set(sessionID, { found: new Map, sent: typed });
42492
+ }
42493
+ function forgetInjectedUserTurns(sessionID) {
42494
+ envoyPluginInterface().injectedUserTurns.delete(sessionID);
42495
+ }
42496
+
42497
+ // ../pi-shared/src/role-claim-bridge.ts
42498
+ function legionRoleClaimBridge() {
42499
+ return envoyPluginInterface().roleClaim;
42500
+ }
42501
+
42502
+ // ../pi-shared/src/shell-command.ts
42503
+ var HEREDOC_OPENING = /^(.*?)[ \t]*<<(-?)[ \t]*'([A-Za-z_][A-Za-z0-9_]*)'[ \t]*$/;
42504
+ var BLANK_LINE = /^[ \t]*$/;
42505
+ var REFUSED_UNQUOTED = "\n;&|$`<>()#\\";
42506
+ var REFUSED_DOUBLE_QUOTED = "$`\\";
42507
+ function dispatchCommandHead(command) {
42508
+ if (typeof command !== "string" || hasControlCharacter2(command))
42509
+ return;
42510
+ const all = command.split(`
42511
+ `);
42512
+ const first = all.findIndex((line) => !BLANK_LINE.test(line));
42513
+ if (first === -1)
42514
+ return;
42515
+ const last = all.findLastIndex((line) => !BLANK_LINE.test(line));
42516
+ const lines = all.slice(first, last + 1);
42517
+ let head = withoutComment(lines[0] ?? "");
42518
+ if (lines.length > 1) {
42519
+ const opening = HEREDOC_OPENING.exec(head);
42520
+ if (opening === null)
42364
42521
  return;
42365
- if (this.#settings !== undefined) {
42366
- this.#deps.publish(subject, JSON.stringify(this.#settingsFrame(this.#settings)));
42367
- }
42368
- if (this.#commands !== undefined) {
42369
- this.#deps.publish(subject, JSON.stringify(this.#commandsFrame(this.#commands)));
42370
- }
42371
- }
42372
- get watched() {
42373
- return this.#deps.now() < this.#watchedUntil;
42374
- }
42375
- reset() {
42376
- this.#history.clear();
42377
- this.#settled.clear();
42378
- this.#publishedAt.clear();
42379
- this.#watchedUntil = 0;
42380
- this.#listedCommands = undefined;
42381
- this.#commands = undefined;
42382
- this.#settings = undefined;
42383
- this.#settingsJson = undefined;
42384
- }
42385
- setCommands(subject, commands) {
42386
- const seen = new Set;
42387
- const listed = [];
42388
- for (const command of commands) {
42389
- if (listed.length >= AGENT_STREAM_LIMITS.commands)
42390
- break;
42391
- const name = command.name;
42392
- if (name.length > AGENT_STREAM_LIMITS.commandNameChars)
42393
- continue;
42394
- if (!isTypableCommandName(name) || seen.has(name))
42395
- continue;
42396
- seen.add(name);
42397
- listed.push({
42398
- name,
42399
- source: command.source,
42400
- ...command.description !== undefined && {
42401
- description: capAgentStreamText(command.description, AGENT_STREAM_LIMITS.commandDescriptionChars)
42402
- },
42403
- ...command.terminalOnly === true && { terminalOnly: true }
42404
- });
42405
- }
42406
- this.#listedCommands = listed;
42407
- this.#fitCommands(subject);
42408
- }
42409
- setSettings(subject, settings) {
42410
- const kept = settings.reported ? {
42411
- ...settings.model !== undefined && { model: settings.model },
42412
- models: [...settings.models],
42413
- reported: true,
42414
- thinking: settings.thinking === null ? null : { level: settings.thinking.level, levels: [...settings.thinking.levels] }
42415
- } : { reported: false };
42416
- const json = JSON.stringify(kept);
42417
- if (json === this.#settingsJson)
42522
+ const stripTabs = opening[2] === "-";
42523
+ const delimiter = opening[3];
42524
+ const end = lines.findIndex((line, index) => index > 0 && (stripTabs ? line.replace(/^\t+/, "") : line) === delimiter);
42525
+ if (end !== lines.length - 1)
42418
42526
  return;
42419
- this.#settings = kept;
42420
- this.#settingsJson = json;
42421
- this.#seq += 1;
42422
- this.#settingsSeq = this.#seq;
42423
- if (this.watched)
42424
- this.#deps.publish(subject, JSON.stringify(this.#settingsFrame(kept)));
42425
- this.#fitCommands(subject);
42527
+ head = opening[1] ?? "";
42426
42528
  }
42427
- #fitCommands(subject) {
42428
- const listed = this.#listedCommands;
42429
- if (listed === undefined)
42430
- return;
42431
- const settings = this.#settings === undefined ? 0 : jsonBytes(this.#settingsFrame(this.#settings)) + 1;
42432
- const limit = AGENT_STREAM_LIMITS.historyBytes - REPLAY_ARRAY_BYTES - settings;
42433
- let bytes = jsonBytes(this.#commandsFrame([], this.#seq + 1));
42434
- const kept = [];
42435
- for (const command of listed) {
42436
- const cost = jsonBytes(command) + (kept.length === 0 ? 0 : 1);
42437
- if (bytes + cost > limit)
42438
- break;
42439
- bytes += cost;
42440
- kept.push(command);
42529
+ head = head.replace(/^[ \t]+|[ \t]+$/g, "");
42530
+ return firstWord(head) === "dispatch" && headScan(head) ? head : undefined;
42531
+ }
42532
+ function firstWord(head) {
42533
+ return head.split(/[ \t]/, 1)[0] ?? "";
42534
+ }
42535
+ function withoutComment(line) {
42536
+ let quote;
42537
+ for (let index = 0;index < line.length; index += 1) {
42538
+ const char = line[index];
42539
+ if (quote !== undefined) {
42540
+ if (char === quote)
42541
+ quote = undefined;
42542
+ else if (char === "\\" && quote === '"')
42543
+ return line;
42544
+ continue;
42441
42545
  }
42442
- if (JSON.stringify(kept) === JSON.stringify(this.#commands))
42443
- return;
42444
- this.#commands = kept;
42445
- this.#seq += 1;
42446
- this.#commandsSeq = this.#seq;
42447
- if (this.watched)
42448
- this.#deps.publish(subject, JSON.stringify(this.#commandsFrame(kept)));
42449
- }
42450
- #commandsFrame(commands, seq = this.#commandsSeq) {
42451
- return { commands, kind: "commands", seq, v: AGENT_STREAM_PROTOCOL };
42452
- }
42453
- #settingsFrame(settings) {
42454
- return { ...settings, kind: "settings", seq: this.#settingsSeq, v: AGENT_STREAM_PROTOCOL };
42546
+ if (char === "\\")
42547
+ return line;
42548
+ if (char === "'" || char === '"')
42549
+ quote = char;
42550
+ else if (char === "#" && (index === 0 || line[index - 1] === " " || line[index - 1] === "\t"))
42551
+ return line.slice(0, index);
42455
42552
  }
42456
- record(subject, raw, streaming, dispatchMessageId) {
42457
- const message = readMessage(raw);
42458
- if (message === null)
42459
- return false;
42460
- const key = keyFor(message);
42461
- if (key === null)
42462
- return false;
42463
- const stillStreaming = message.role === "assistant" && streaming;
42464
- if (stillStreaming && this.#settled.has(key))
42465
- return false;
42466
- this.#seq += 1;
42467
- const entry = {
42468
- at: message.timestamp,
42469
- dispatchMessageId: dispatchMessageId ?? this.#history.get(key)?.dispatchMessageId,
42470
- key,
42471
- message,
42472
- seq: this.#seq,
42473
- streaming: stillStreaming
42474
- };
42475
- this.#history.set(key, entry);
42476
- if (!stillStreaming)
42477
- this.#settled.add(key);
42478
- while (this.#history.size > AGENT_STREAM_LIMITS.historyMessages) {
42479
- const oldest = this.#history.keys().next();
42480
- if (oldest.done === true)
42481
- break;
42482
- this.#history.delete(oldest.value);
42483
- this.#settled.delete(oldest.value);
42484
- this.#publishedAt.delete(oldest.value);
42485
- }
42486
- if (!this.watched)
42487
- return true;
42488
- const now = this.#deps.now();
42489
- const published = this.#publishedAt.get(key);
42490
- const tooSoon = published !== undefined && now - published < AGENT_STREAM_LIMITS.snapshotIntervalMs;
42491
- if (stillStreaming && tooSoon)
42553
+ return line;
42554
+ }
42555
+ function hasControlCharacter2(text) {
42556
+ for (let index = 0;index < text.length; index += 1) {
42557
+ const code = text.charCodeAt(index);
42558
+ if (code < 32 && code !== 10 && code !== 9 || code === 127)
42492
42559
  return true;
42493
- this.#publishedAt.set(key, now);
42494
- this.#deps.publish(subject, JSON.stringify(frameFor(entry)));
42495
- return true;
42496
42560
  }
42497
- replay(sessionID) {
42498
- if (!this.watched)
42499
- return { frames: [], session_id: sessionID, v: AGENT_STREAM_PROTOCOL };
42500
- const ordered = [...this.#history.values()].sort((left, right) => left.at === right.at ? left.seq - right.seq : left.at - right.at);
42501
- const tail = [];
42502
- if (this.#settings !== undefined)
42503
- tail.push(this.#settingsFrame(this.#settings));
42504
- if (this.#commands !== undefined)
42505
- tail.push(this.#commandsFrame(this.#commands));
42506
- let used = REPLAY_ARRAY_BYTES + tail.reduce((bytes, frame, index) => bytes + jsonBytes(frame) + (index === 0 ? 0 : 1), 0);
42507
- const kept = [];
42508
- for (let index = ordered.length - 1;index >= 0; index -= 1) {
42509
- const entry = ordered[index];
42510
- if (entry === undefined)
42511
- continue;
42512
- const frame = frameFor(entry);
42513
- const separated = kept.length > 0 || tail.length > 0;
42514
- const cost = jsonBytes(frame) + (separated ? 1 : 0);
42515
- if (used + cost > AGENT_STREAM_LIMITS.historyBytes)
42516
- break;
42517
- used += cost;
42518
- kept.unshift(frame);
42561
+ return false;
42562
+ }
42563
+ function headScan(head) {
42564
+ let quote;
42565
+ for (const char of head) {
42566
+ if (quote === "'") {
42567
+ if (char === "'")
42568
+ quote = undefined;
42569
+ continue;
42519
42570
  }
42520
- kept.push(...tail);
42521
- return { frames: kept, session_id: sessionID, v: AGENT_STREAM_PROTOCOL };
42571
+ if (quote === '"') {
42572
+ if (char === '"')
42573
+ quote = undefined;
42574
+ else if (REFUSED_DOUBLE_QUOTED.includes(char))
42575
+ return false;
42576
+ continue;
42577
+ }
42578
+ if (char === "'" || char === '"')
42579
+ quote = char;
42580
+ else if (REFUSED_UNQUOTED.includes(char))
42581
+ return false;
42582
+ }
42583
+ return quote === undefined;
42584
+ }
42585
+
42586
+ // ../pi-shared/src/subagent-session.ts
42587
+ import fs from "fs";
42588
+ import path2 from "path";
42589
+ import * as host from "@oh-my-pi/pi-coding-agent";
42590
+ import { logger as logger2 } from "@oh-my-pi/pi-utils";
42591
+ async function isSubagentSession(context) {
42592
+ const registered = registeredSubagent(context);
42593
+ if (registered !== undefined)
42594
+ return { subagent: registered, settled: true };
42595
+ try {
42596
+ await context.sessionManager.ensureOnDisk();
42597
+ } catch (error) {
42598
+ const subagent = transcriptSaysSubagent(context);
42599
+ logger2.warn("subagent check: publishing the transcript failed; answered from the transcript on disk, and the next call asks again", { sessionFile: context.sessionManager.getSessionFile(), subagent, error: messageFor(error) });
42600
+ return { subagent, settled: false };
42601
+ }
42602
+ return { subagent: transcriptSaysSubagent(context), settled: true };
42603
+ }
42604
+ function transcriptSaysSubagent(context) {
42605
+ const sessionFile = context.sessionManager.getSessionFile();
42606
+ if (sessionFile !== undefined) {
42607
+ if (fs.existsSync(`${path2.dirname(sessionFile)}.jsonl`))
42608
+ return true;
42609
+ if (fs.existsSync(sessionFile))
42610
+ return false;
42522
42611
  }
42612
+ const bootstrapped = envoyPluginInterface().bootstrappedSession.file;
42613
+ return bootstrapped !== undefined && bootstrapped !== sessionFile;
42614
+ }
42615
+ function registeredSubagent(context) {
42616
+ const registry = host.AgentRegistry?.global();
42617
+ if (registry === undefined)
42618
+ return;
42619
+ const sessionID = context.sessionManager.getSessionId();
42620
+ const sessionFile = context.sessionManager.getSessionFile();
42621
+ const own = registry.list().filter((ref) => ref.session === null ? sessionFile !== undefined && ref.sessionFile === sessionFile : ref.session.sessionManager.getSessionId() === sessionID);
42622
+ if (own.length === 0)
42623
+ return;
42624
+ return own.some((ref) => ref.kind !== "main");
42625
+ }
42626
+ function subagentSessionCheck() {
42627
+ let settled;
42628
+ return async (context) => {
42629
+ if (settled !== undefined)
42630
+ return settled;
42631
+ const answer = await isSubagentSession(context);
42632
+ if (answer.settled)
42633
+ settled = answer.subagent;
42634
+ return answer.subagent;
42635
+ };
42636
+ }
42637
+
42638
+ // ../pi-shared/src/tool-result.ts
42639
+ function toolSuccess(text, details = {}, images = []) {
42640
+ return { content: [{ type: "text", text }, ...imageBlocks(images)], details };
42641
+ }
42642
+ function toolFailure(error) {
42643
+ return { content: [{ type: "text", text: messageFor(error) }], details: {}, isError: true };
42523
42644
  }
42524
42645
 
42646
+ // extensions/envoy.ts
42647
+ import * as host2 from "@oh-my-pi/pi-coding-agent";
42648
+ import { logger as logger3, procmgr, VERSION } from "@oh-my-pi/pi-utils";
42649
+ var import_nats2 = __toESM(require_mod4(), 1);
42650
+
42651
+ // package.json
42652
+ var name = "@sjawhar/pi-envoy";
42653
+ var version2 = "16.31.0";
42654
+ var package_default = {
42655
+ name,
42656
+ version: version2,
42657
+ license: "Apache-2.0",
42658
+ type: "module",
42659
+ omp: {
42660
+ extensions: [
42661
+ "dist/envoy.js"
42662
+ ],
42663
+ skills: [
42664
+ "dist/skills"
42665
+ ],
42666
+ bin: [
42667
+ "bin"
42668
+ ]
42669
+ },
42670
+ repository: {
42671
+ type: "git",
42672
+ url: "https://github.com/cybermonklabs/legion"
42673
+ },
42674
+ files: [
42675
+ "dist",
42676
+ "bin"
42677
+ ],
42678
+ scripts: {
42679
+ build: "bun build extensions/envoy.ts --outdir dist --target bun --format esm --external @oh-my-pi/pi-ai --external @oh-my-pi/pi-coding-agent --external @oh-my-pi/pi-tui --external @oh-my-pi/pi-utils && ../envoy-client/scripts/build-dispatch-cli.sh dist",
42680
+ prepack: "../../scripts/pi-plugin-prepack.sh",
42681
+ postpack: "rm -rf dist/skills",
42682
+ typecheck: "bunx tsc --noEmit",
42683
+ test: "bun test --path-ignore-patterns=extensions/card-delivery-omp.test.ts && bun test ./extensions/card-delivery-omp.test.ts",
42684
+ lint: "bunx biome lint extensions/ src/"
42685
+ },
42686
+ devDependencies: {
42687
+ "@biomejs/biome": "^2.3.14",
42688
+ "@legion/contracts": "workspace:*",
42689
+ "@legion/envoy-client": "workspace:*",
42690
+ "@legion/pi-shared": "workspace:*",
42691
+ "@oh-my-pi/pi-tui": "^18.6.0",
42692
+ "@oh-my-pi/pi-utils": "^18.6.0",
42693
+ "@toon-format/toon": "^4.1.1",
42694
+ "@types/bun": "latest",
42695
+ nats: "^2.29.2",
42696
+ typescript: "^5.3.0",
42697
+ zod: "4.3.6"
42698
+ }
42699
+ };
42700
+
42525
42701
  // src/missed-messages.ts
42526
42702
  var ENVOY_MESSAGE = "envoy-message";
42527
42703
  var REPLAY_DELIVERED_ENTRY = "envoy-replay-delivered";
@@ -43116,83 +43292,6 @@ class CardWake {
43116
43292
  }
43117
43293
  }
43118
43294
 
43119
- // src/delivery-pictures.ts
43120
- async function withDeliveredPictures(text, addresses, client, named, shown) {
43121
- const textAlone = { content: text, shown: [] };
43122
- if (addresses.length === 0)
43123
- return textAlone;
43124
- let dispatch;
43125
- try {
43126
- dispatch = client();
43127
- } catch {
43128
- return textAlone;
43129
- }
43130
- if (dispatch === undefined)
43131
- return textAlone;
43132
- const unique = [...new Set(addresses)];
43133
- const shownEarlier = unique.some((address) => shown.has(address));
43134
- const pictures = await readPictures(dispatch, unique, shown);
43135
- const content = named ? `${text}
43136
-
43137
- ${pictures.lines.join(`
43138
- `)}` : text;
43139
- if (pictures.images.length === 0)
43140
- return shownEarlier ? { content, shown: [] } : textAlone;
43141
- return {
43142
- content: [{ type: "text", text: content }, ...imageBlocks(pictures.images)],
43143
- shown: pictures.shown
43144
- };
43145
- }
43146
- function entryMessage(entry) {
43147
- if (typeof entry !== "object" || entry === null || !("type" in entry))
43148
- return;
43149
- if (entry.type === "custom_message") {
43150
- return { role: "custom", content: "content" in entry ? entry.content : undefined };
43151
- }
43152
- if (entry.type !== "message" || !("message" in entry))
43153
- return;
43154
- const { message } = entry;
43155
- if (typeof message !== "object" || message === null)
43156
- return;
43157
- return {
43158
- role: "role" in message ? message.role : undefined,
43159
- content: "content" in message ? message.content : undefined
43160
- };
43161
- }
43162
- function transcriptPictures(entries) {
43163
- const shown = new Set;
43164
- for (const entry of entries) {
43165
- const message = entryMessage(entry);
43166
- if (message === undefined)
43167
- continue;
43168
- const { content } = message;
43169
- const texts = [];
43170
- let images = 0;
43171
- if (typeof content === "string")
43172
- texts.push(content);
43173
- else if (Array.isArray(content)) {
43174
- for (const block of content) {
43175
- if (typeof block !== "object" || block === null || !("type" in block))
43176
- continue;
43177
- if (block.type === "image")
43178
- images++;
43179
- if (block.type === "text" && "text" in block && typeof block.text === "string") {
43180
- texts.push(block.text);
43181
- }
43182
- }
43183
- }
43184
- for (const address of shownPictureAddresses(texts))
43185
- shown.add(address);
43186
- if (message.role !== "user" || images === 0)
43187
- continue;
43188
- const embedded = new Set(texts.flatMap(pictureAddresses));
43189
- if (embedded.size === images)
43190
- for (const address of embedded)
43191
- shown.add(address);
43192
- }
43193
- return [...shown];
43194
- }
43195
-
43196
43295
  // src/context-message.ts
43197
43296
  function leadingText(message, role) {
43198
43297
  if (typeof message !== "object" || message === null || !("role" in message) || message.role !== role || !("content" in message) || !Array.isArray(message.content)) {
@@ -43232,63 +43331,6 @@ function sessionDispatchClient(file, cwd, signal, session) {
43232
43331
  };
43233
43332
  }
43234
43333
 
43235
- // src/dispatch-user-turn.ts
43236
- function isUserTurnCandidate(rendered) {
43237
- const { delivery } = rendered;
43238
- return rendered.envelope?.source === "dispatch" && delivery?.resource === "message" && delivery.issueKey === null && delivery.broadcastId === undefined && rendered.dispatchActor?.kind === "user" && (delivery.mode === "aside" || delivery.mode === "steer");
43239
- }
43240
- var AcceptedDeliverySchema = object({
43241
- message_id: string2(),
43242
- body: string2(),
43243
- delivery: _enum2(["aside", "steer"])
43244
- });
43245
- function turnFromAccept(accepted) {
43246
- const parsed = AcceptedDeliverySchema.safeParse(accepted);
43247
- if (!parsed.success)
43248
- return;
43249
- return { body: parsed.data.body, messageId: parsed.data.message_id, mode: parsed.data.delivery };
43250
- }
43251
- var HANDLED_ATTEMPT_ENTRY = "envoy-dispatch-handled-attempt";
43252
- function handledAttemptKey(messageId, attempt) {
43253
- return `${messageId}#${attempt}`;
43254
- }
43255
- function handledAttempts(entries) {
43256
- const handled = new Set;
43257
- for (const entry of entries) {
43258
- if (typeof entry !== "object" || entry === null)
43259
- continue;
43260
- if (!("type" in entry) || entry.type !== "custom")
43261
- continue;
43262
- if (!("customType" in entry) || entry.customType !== HANDLED_ATTEMPT_ENTRY)
43263
- continue;
43264
- if (!("data" in entry) || typeof entry.data !== "object" || entry.data === null)
43265
- continue;
43266
- const { data } = entry;
43267
- if (!("message_id" in data) || typeof data.message_id !== "string")
43268
- continue;
43269
- if (!("attempt" in data) || typeof data.attempt !== "number")
43270
- continue;
43271
- handled.add(handledAttemptKey(data.message_id, data.attempt));
43272
- }
43273
- return handled;
43274
- }
43275
- function typedInputReply(text, outcome) {
43276
- const typed = /^\/\S+/.exec(text)?.[0];
43277
- const command = typed ?? "This message";
43278
- if ("error" in outcome)
43279
- return `${command} was not run: ${outcome.error}`;
43280
- if ("hostVersion" in outcome) {
43281
- return typed === undefined ? undefined : `${typed} was not run: this session's Oh My Pi ${outcome.hostVersion} cannot run commands sent from Dispatch; nothing was sent.`;
43282
- }
43283
- if (outcome.handled === "terminal-only") {
43284
- return `${command} runs only in the session's own terminal; nothing was sent.`;
43285
- }
43286
- if (outcome.handled === "unavailable") {
43287
- return `${command} was not run: this session's host cannot run typed input from Dispatch; nothing was sent.`;
43288
- }
43289
- return outcome.output?.trim() ? outcome.output : undefined;
43290
- }
43291
-
43292
43334
  // src/envoy-session.ts
43293
43335
  import path3 from "path";
43294
43336
  var ENVOY_SESSIONS = Symbol.for("legion.pi-envoy.envoy-session");
@@ -46324,7 +46366,7 @@ function textOf(content) {
46324
46366
  else if (isRecord(part) && part.type === "text" && typeof part.text === "string")
46325
46367
  parts.push(part.text);
46326
46368
  else if (isRecord(part) && part.type === "image")
46327
- parts.push("[image]");
46369
+ parts.push(PICTURE_PLACEHOLDER);
46328
46370
  }
46329
46371
  return parts.join(`
46330
46372
  `);
@@ -48494,35 +48536,31 @@ function envoyExtension(pi) {
48494
48536
  });
48495
48537
  });
48496
48538
  };
48497
- const acceptedUserTurn = async (rendered, acceptedSessionID) => {
48498
- if (!isUserTurnCandidate(rendered))
48499
- return;
48500
- const { delivery } = rendered;
48501
- const key = handledAttemptKey(delivery.id, delivery.attempt);
48502
- if (handledDispatchAttempts.has(key)) {
48503
- logger3.warn("envoy: a frame names a Dispatch attempt this session already delivered; it arrives as a card", { attempt: delivery.attempt, messageID: delivery.id });
48504
- return;
48505
- }
48506
- handledDispatchAttempts.add(key);
48507
- pi.appendEntry(HANDLED_ATTEMPT_ENTRY, { attempt: delivery.attempt, message_id: delivery.id });
48508
- try {
48509
- const dispatch = timedDispatchClient(USER_TURN_ACCEPT_TIMEOUT_MS);
48510
- if (dispatch === undefined)
48511
- return;
48512
- const accepted = await dispatch.acceptMessageDelivery(delivery.id, delivery.attempt, {
48513
- actor: { id: acceptedSessionID, kind: "session" }
48539
+ const acceptedUserTurn = (rendered, acceptedSessionID) => acceptUserTurn({
48540
+ actorId: acceptedSessionID,
48541
+ dispatch: () => timedDispatchClient(USER_TURN_ACCEPT_TIMEOUT_MS),
48542
+ handle: (key, delivery) => {
48543
+ handledDispatchAttempts.add(key);
48544
+ pi.appendEntry(HANDLED_ATTEMPT_ENTRY, {
48545
+ attempt: delivery.attempt,
48546
+ message_id: delivery.id
48514
48547
  });
48515
- const turn = turnFromAccept(accepted);
48516
- if (turn === undefined) {
48517
- logger3.warn("envoy: Dispatch accepted a direct message without the stored body and mode to inject; it arrives as a card", { attempt: delivery.attempt, messageID: delivery.id });
48548
+ },
48549
+ handled: (key) => handledDispatchAttempts.has(key),
48550
+ rendered,
48551
+ warn: (refusal) => {
48552
+ const fields = { attempt: refusal.delivery.attempt, messageID: refusal.delivery.id };
48553
+ if (refusal.reason === "handled") {
48554
+ logger3.warn("envoy: a frame names a Dispatch attempt this session already delivered; it arrives as a card", fields);
48518
48555
  return;
48519
48556
  }
48520
- return { delivery, turn };
48521
- } catch (error) {
48522
- logger3.warn("envoy: Dispatch did not accept a direct message as this session's turn; it arrives as a card", { attempt: delivery.attempt, messageID: delivery.id, error: messageFor(error) });
48523
- return;
48557
+ if (refusal.reason === "no-body") {
48558
+ logger3.warn("envoy: Dispatch accepted a direct message without the stored body and mode to inject; it arrives as a card", fields);
48559
+ return;
48560
+ }
48561
+ logger3.warn("envoy: Dispatch did not accept a direct message as this session's turn; it arrives as a card", { ...fields, error: messageFor(refusal.error) });
48524
48562
  }
48525
- };
48563
+ });
48526
48564
  const deliver = async (topic, subject, raw, reply, receivedAt, relayed) => {
48527
48565
  let rendered = renderInbound(raw, sessionID, subject);
48528
48566
  const directSubject = agentSubject(sessionID);