@sjawhar/pi-envoy 16.48.0 → 16.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/envoy.js +564 -93
  2. package/package.json +1 -1
package/dist/envoy.js CHANGED
@@ -30002,6 +30002,9 @@ function capAgentStreamText(text, limit) {
30002
30002
  return text;
30003
30003
  return text.slice(0, limit) + AGENT_STREAM_TRUNCATION_SUFFIX;
30004
30004
  }
30005
+ var SHELL_COMMAND_REPORT_SEPARATOR = `
30006
+
30007
+ `;
30005
30008
  // ../contracts/src/dispatch-href.ts
30006
30009
  function hasControlCharacter(value) {
30007
30010
  return /\p{Cc}/u.test(value);
@@ -37971,16 +37974,16 @@ function createReplayEngine(options) {
37971
37974
  unwritten.push(entry);
37972
37975
  };
37973
37976
  const flush = (alive, atOnce = false) => {
37974
- writes = writes.then(async () => {
37977
+ const written = writes.then(async () => {
37975
37978
  if (!alive())
37976
- return;
37979
+ return false;
37977
37980
  const json = stateJSON();
37978
37981
  const delivered = unwritten;
37979
37982
  if (json === writtenState && delivered.length === 0)
37980
- return;
37983
+ return true;
37981
37984
  const shape = stateJSON(false);
37982
37985
  if (delivered.length === 0 && !atOnce && shape === writtenShape && writtenAt !== undefined && now() - writtenAt < REPLAY_STATE_REFRESH_MS) {
37983
- return;
37986
+ return true;
37984
37987
  }
37985
37988
  unwritten = [];
37986
37989
  const state = json === writtenState ? undefined : JSON.parse(json);
@@ -37995,12 +37998,17 @@ function createReplayEngine(options) {
37995
37998
  writtenShape = shape;
37996
37999
  writtenAt = now();
37997
38000
  }
38001
+ return true;
37998
38002
  } catch (error) {
37999
38003
  unwritten = [...delivered, ...unwritten];
38000
38004
  log("replay: could not persist the replay state; the next write carries it", error);
38005
+ return false;
38001
38006
  }
38002
38007
  });
38003
- return writes;
38008
+ writes = written.then(() => {
38009
+ return;
38010
+ });
38011
+ return written;
38004
38012
  };
38005
38013
  const syncFollowed = () => {
38006
38014
  const followed = new Set(host.followedSubjects());
@@ -38466,18 +38474,20 @@ function createReplayEngine(options) {
38466
38474
  async recordDeliveredFor(sessionID, frame) {
38467
38475
  const alive = bindTo(sessionID, writeSession)?.alive;
38468
38476
  if (alive === undefined)
38469
- return;
38477
+ return false;
38470
38478
  record2(replayLedgerIdentity(frame));
38471
- await flush(alive);
38479
+ return await flush(alive);
38472
38480
  },
38473
- async liveFailed(followed, envelope, error, receivedAt) {
38481
+ async liveFailed(sessionID, followed, envelope, error, receivedAt) {
38474
38482
  const started = cursorStarts.get(followed);
38475
38483
  if (!isRoleForward(envelope) && answered.has(followed) && cursors.get(followed)?.after !== undefined && (started === undefined || started <= receivedAt)) {
38476
38484
  return;
38477
38485
  }
38478
- const alive = bind()?.alive;
38479
- if (alive === undefined)
38486
+ const alive = bindTo(sessionID, currentSession)?.alive;
38487
+ if (alive === undefined) {
38488
+ log("replay: a failed frame was not reported here; the session it names is closed");
38480
38489
  return;
38490
+ }
38481
38491
  try {
38482
38492
  await showFailureNotice(failureNotice(envelope, inboundTimestamp(envelope.issued_at), messageFor(error)), alive);
38483
38493
  } catch (thrown) {
@@ -38880,11 +38890,12 @@ function createConsumerDelivery(options) {
38880
38890
  settle(entry, "nak");
38881
38891
  return;
38882
38892
  }
38893
+ log(`frame ${entry.frame.streamSeq} failed and does not come again; its session gets the notice`, error);
38883
38894
  safely("failure notice", () => {
38884
38895
  const { subject, data } = entry.frame;
38885
38896
  const { envelope } = renderInbound(data, sessionID, subject);
38886
38897
  if (envelope !== undefined)
38887
- ledger.liveFailed(subject, envelope, error, now());
38898
+ ledger.liveFailed(sessionID, subject, envelope, error, now());
38888
38899
  });
38889
38900
  settle(entry, "done");
38890
38901
  };
@@ -42173,9 +42184,15 @@ class AgentStreamPublisher {
42173
42184
  #listedCommands;
42174
42185
  #commands;
42175
42186
  #commandsSeq = 0;
42187
+ #fitListed;
42188
+ #fitLimit = 0;
42189
+ #fitEmptyBytes = 0;
42176
42190
  #settings;
42177
42191
  #settingsSeq = 0;
42178
42192
  #settingsJson;
42193
+ #context;
42194
+ #contextSeq = 0;
42195
+ #contextJson;
42179
42196
  constructor(deps) {
42180
42197
  this.#deps = deps;
42181
42198
  this.#seq = Math.trunc(deps.now()) * SEQ_PER_MS;
@@ -42189,6 +42206,9 @@ class AgentStreamPublisher {
42189
42206
  if (this.#settings !== undefined) {
42190
42207
  this.#deps.publish(subject, JSON.stringify(this.#settingsFrame(this.#settings)));
42191
42208
  }
42209
+ if (this.#context !== undefined) {
42210
+ this.#deps.publish(subject, JSON.stringify(this.#contextFrame(this.#context)));
42211
+ }
42192
42212
  if (this.#commands !== undefined) {
42193
42213
  this.#deps.publish(subject, JSON.stringify(this.#commandsFrame(this.#commands)));
42194
42214
  }
@@ -42205,6 +42225,8 @@ class AgentStreamPublisher {
42205
42225
  this.#commands = undefined;
42206
42226
  this.#settings = undefined;
42207
42227
  this.#settingsJson = undefined;
42228
+ this.#context = undefined;
42229
+ this.#contextJson = undefined;
42208
42230
  }
42209
42231
  setCommands(subject, commands) {
42210
42232
  const seen = new Set;
@@ -42248,13 +42270,43 @@ class AgentStreamPublisher {
42248
42270
  this.#deps.publish(subject, JSON.stringify(this.#settingsFrame(kept)));
42249
42271
  this.#fitCommands(subject);
42250
42272
  }
42273
+ setContext(subject, usage) {
42274
+ if (usage === undefined)
42275
+ return;
42276
+ if (!(usage.contextWindow > 0))
42277
+ return;
42278
+ if (typeof usage.percent !== "number" && !(usage.tokens > 0))
42279
+ return;
42280
+ const kept = {
42281
+ contextWindow: usage.contextWindow,
42282
+ tokens: usage.tokens
42283
+ };
42284
+ const json = JSON.stringify(kept);
42285
+ if (json === this.#contextJson)
42286
+ return;
42287
+ this.#context = kept;
42288
+ this.#contextJson = json;
42289
+ this.#seq += 1;
42290
+ this.#contextSeq = this.#seq;
42291
+ if (this.watched)
42292
+ this.#deps.publish(subject, JSON.stringify(this.#contextFrame(kept)));
42293
+ this.#fitCommands(subject);
42294
+ }
42251
42295
  #fitCommands(subject) {
42252
42296
  const listed = this.#listedCommands;
42253
42297
  if (listed === undefined)
42254
42298
  return;
42255
42299
  const settings = this.#settings === undefined ? 0 : jsonBytes(this.#settingsFrame(this.#settings)) + 1;
42256
- const limit = AGENT_STREAM_LIMITS.historyBytes - REPLAY_ARRAY_BYTES - settings;
42257
- let bytes = jsonBytes(this.#commandsFrame([], this.#seq + 1));
42300
+ const context = this.#context === undefined ? 0 : jsonBytes(this.#contextFrame(this.#context)) + 1;
42301
+ const limit = AGENT_STREAM_LIMITS.historyBytes - REPLAY_ARRAY_BYTES - settings - context;
42302
+ const emptyBytes = jsonBytes(this.#commandsFrame([], this.#seq + 1));
42303
+ const unchanged = listed === this.#fitListed && limit === this.#fitLimit && emptyBytes === this.#fitEmptyBytes;
42304
+ if (unchanged)
42305
+ return;
42306
+ this.#fitListed = listed;
42307
+ this.#fitLimit = limit;
42308
+ this.#fitEmptyBytes = emptyBytes;
42309
+ let bytes = emptyBytes;
42258
42310
  const kept = [];
42259
42311
  for (const command of listed) {
42260
42312
  const cost = jsonBytes(command) + (kept.length === 0 ? 0 : 1);
@@ -42277,6 +42329,9 @@ class AgentStreamPublisher {
42277
42329
  #settingsFrame(settings) {
42278
42330
  return { ...settings, kind: "settings", seq: this.#settingsSeq, v: AGENT_STREAM_PROTOCOL };
42279
42331
  }
42332
+ #contextFrame(context) {
42333
+ return { ...context, kind: "context", seq: this.#contextSeq, v: AGENT_STREAM_PROTOCOL };
42334
+ }
42280
42335
  record(subject, raw, streaming, dispatchMessageId) {
42281
42336
  const message = readMessage(raw);
42282
42337
  if (message === null)
@@ -42325,6 +42380,8 @@ class AgentStreamPublisher {
42325
42380
  const tail = [];
42326
42381
  if (this.#settings !== undefined)
42327
42382
  tail.push(this.#settingsFrame(this.#settings));
42383
+ if (this.#context !== undefined)
42384
+ tail.push(this.#contextFrame(this.#context));
42328
42385
  if (this.#commands !== undefined)
42329
42386
  tail.push(this.#commandsFrame(this.#commands));
42330
42387
  let used = REPLAY_ARRAY_BYTES + tail.reduce((bytes, frame, index) => bytes + jsonBytes(frame) + (index === 0 ? 0 : 1), 0);
@@ -42713,12 +42770,12 @@ function toolFailure(error) {
42713
42770
 
42714
42771
  // extensions/envoy.ts
42715
42772
  import * as host2 from "@oh-my-pi/pi-coding-agent";
42716
- import { logger as logger3, procmgr, VERSION } from "@oh-my-pi/pi-utils";
42773
+ import { logger as logger3, procmgr as procmgr2, VERSION } from "@oh-my-pi/pi-utils";
42717
42774
  var import_nats2 = __toESM(require_mod4(), 1);
42718
42775
 
42719
42776
  // package.json
42720
42777
  var name = "@sjawhar/pi-envoy";
42721
- var version2 = "16.48.0";
42778
+ var version2 = "16.49.0";
42722
42779
  var package_default = {
42723
42780
  name,
42724
42781
  version: version2,
@@ -44194,6 +44251,195 @@ class TypedPictures {
44194
44251
  }
44195
44252
  }
44196
44253
 
44254
+ // src/typed-shell.ts
44255
+ import { basename } from "path";
44256
+ import { procmgr } from "@oh-my-pi/pi-utils";
44257
+ var SHELL_OUTPUT_MAX = 8000;
44258
+ var SHELL_OUTPUT_BYTES = 4 * SHELL_OUTPUT_MAX;
44259
+ var SHELL_DRAIN_GRACE_MS = 1000;
44260
+ var NOTHING_PRINTED = "The command printed nothing.";
44261
+ var SHELL_COMMAND_HEADING = "A person ran this shell command in this session from Dispatch. Nothing is asked of you; this is the command and what it printed.";
44262
+ function shellCommandFrom(body) {
44263
+ if (!body.startsWith("!"))
44264
+ return;
44265
+ const command = body.slice(1).trim();
44266
+ return command === "" ? undefined : command;
44267
+ }
44268
+ function shellInvocation(command) {
44269
+ const { shell, env, prefix } = procmgr.getShellConfig();
44270
+ const childEnv = { ...env };
44271
+ delete childEnv.BASH_ENV;
44272
+ delete childEnv.ENV;
44273
+ const args = basename(shell).includes("zsh") ? ["-f", "-c"] : ["-c"];
44274
+ return { argv: [shell, ...args, prefix ? `${prefix} ${command}` : command], env: childEnv };
44275
+ }
44276
+ function killGroup(pid) {
44277
+ try {
44278
+ process.kill(-pid, "SIGKILL");
44279
+ } catch {}
44280
+ }
44281
+ var runningGroups = new Set;
44282
+ var killsGroupsOnExit = false;
44283
+ function killGroupsOnExit() {
44284
+ if (killsGroupsOnExit)
44285
+ return;
44286
+ killsGroupsOnExit = true;
44287
+ process.on("exit", () => {
44288
+ for (const pid of runningGroups)
44289
+ killGroup(pid);
44290
+ });
44291
+ }
44292
+
44293
+ class BoundedOutput {
44294
+ #kept = new Uint8Array(SHELL_OUTPUT_BYTES);
44295
+ #length = 0;
44296
+ take(chunk) {
44297
+ const room = this.#kept.length - this.#length;
44298
+ if (room <= 0)
44299
+ return;
44300
+ const keep = chunk.length <= room ? chunk : chunk.subarray(0, room);
44301
+ this.#kept.set(keep, this.#length);
44302
+ this.#length += keep.length;
44303
+ }
44304
+ text() {
44305
+ return new TextDecoder().decode(this.#kept.subarray(0, this.#length));
44306
+ }
44307
+ }
44308
+ function drain(stream, output) {
44309
+ const reader = stream.getReader();
44310
+ const read = (async () => {
44311
+ try {
44312
+ for (;; ) {
44313
+ const chunk = await reader.read();
44314
+ if (chunk.done)
44315
+ return;
44316
+ output.take(chunk.value);
44317
+ }
44318
+ } catch {}
44319
+ })();
44320
+ return {
44321
+ read,
44322
+ cancel: () => {
44323
+ reader.cancel().catch(() => {});
44324
+ }
44325
+ };
44326
+ }
44327
+ async function drained(reads) {
44328
+ const { promise, resolve } = Promise.withResolvers();
44329
+ const give = setTimeout(() => {
44330
+ for (const read of reads)
44331
+ read.cancel();
44332
+ resolve();
44333
+ }, SHELL_DRAIN_GRACE_MS);
44334
+ try {
44335
+ await Promise.race([Promise.all(reads.map((read) => read.read)), promise]);
44336
+ } finally {
44337
+ clearTimeout(give);
44338
+ }
44339
+ }
44340
+ async function runShellCommand(command, options) {
44341
+ let child;
44342
+ try {
44343
+ killGroupsOnExit();
44344
+ const invocation = shellInvocation(command);
44345
+ child = Bun.spawn(invocation.argv, {
44346
+ cwd: options.cwd,
44347
+ detached: true,
44348
+ env: invocation.env,
44349
+ stderr: "pipe",
44350
+ stdin: "ignore",
44351
+ stdout: "pipe"
44352
+ });
44353
+ } catch (error) {
44354
+ return {
44355
+ cut: false,
44356
+ output: "",
44357
+ status: `The command could not start: ${messageFor(error)}.`
44358
+ };
44359
+ }
44360
+ runningGroups.add(child.pid);
44361
+ const printed = new BoundedOutput;
44362
+ const reads = [drain(child.stdout, printed), drain(child.stderr, printed)];
44363
+ let ended;
44364
+ let over = false;
44365
+ const kill = (why) => {
44366
+ if (over)
44367
+ return;
44368
+ ended ??= why;
44369
+ child.kill("SIGKILL");
44370
+ killGroup(child.pid);
44371
+ };
44372
+ const limit = setTimeout(() => kill("limit"), options.limitMs);
44373
+ options.started?.(() => kill("stop"));
44374
+ try {
44375
+ await child.exited;
44376
+ } finally {
44377
+ over = true;
44378
+ clearTimeout(limit);
44379
+ killGroup(child.pid);
44380
+ runningGroups.delete(child.pid);
44381
+ }
44382
+ await drained(reads);
44383
+ const output = printable(printed.text());
44384
+ const cut = output.length > SHELL_OUTPUT_MAX;
44385
+ return {
44386
+ cut,
44387
+ output: output.slice(0, SHELL_OUTPUT_MAX).trimEnd(),
44388
+ status: statusOf2(child, ended, options.limitMs)
44389
+ };
44390
+ }
44391
+ function printable(output) {
44392
+ return output.replace(/\p{Cc}/gu, (control) => control === `
44393
+ ` || control === "\t" ? control : "");
44394
+ }
44395
+ function statusOf2(child, ended, limitMs) {
44396
+ if (ended === "limit")
44397
+ return `The command was stopped after ${limitMs} ms.`;
44398
+ if (ended === "stop")
44399
+ return "The command was stopped.";
44400
+ if (child.signalCode !== null)
44401
+ return `The command was killed by ${child.signalCode}.`;
44402
+ if (child.exitCode !== 0)
44403
+ return `The command ended with exit status ${child.exitCode}.`;
44404
+ return;
44405
+ }
44406
+ function fenced(output) {
44407
+ let longest = 0;
44408
+ for (const run of output.match(/`+/g) ?? [])
44409
+ longest = Math.max(longest, run.length);
44410
+ const fence = "`".repeat(Math.max(3, longest + 1));
44411
+ return `${fence}
44412
+ ${output}
44413
+ ${fence}`;
44414
+ }
44415
+ function shellCommandReport(line, result) {
44416
+ const parts = [line, result.output === "" ? NOTHING_PRINTED : fenced(result.output)];
44417
+ if (result.cut)
44418
+ parts.push(`The output was cut at ${SHELL_OUTPUT_MAX} characters.`);
44419
+ if (result.status !== undefined)
44420
+ parts.push(result.status);
44421
+ return parts.join(SHELL_COMMAND_REPORT_SEPARATOR);
44422
+ }
44423
+ var MOVED_SESSION_REASON = "this session is no longer the one open here.";
44424
+ function shellCommandWithheldReport(report) {
44425
+ return `${report}${SHELL_COMMAND_REPORT_SEPARATOR}The agent was not handed this output: ${MOVED_SESSION_REASON}`;
44426
+ }
44427
+ function shellCommandMessage(report) {
44428
+ return `${SHELL_COMMAND_HEADING}${SHELL_COMMAND_REPORT_SEPARATOR}${report}`;
44429
+ }
44430
+ function shellCommandRefusal(line, why) {
44431
+ return `${line}${SHELL_COMMAND_REPORT_SEPARATOR}The command was not run: ${why}`;
44432
+ }
44433
+ function shellCommandBusyReport(line, running) {
44434
+ return shellCommandRefusal(line, `this session is still running !${running}.`);
44435
+ }
44436
+ function shellCommandShutdownReport(line) {
44437
+ return shellCommandRefusal(line, "this session is shutting down.");
44438
+ }
44439
+ function shellCommandMovedReport(line) {
44440
+ return shellCommandRefusal(line, MOVED_SESSION_REASON);
44441
+ }
44442
+
44197
44443
  // src/unwritten-frames.ts
44198
44444
  function unwrittenCardKeys(identity) {
44199
44445
  return [
@@ -44212,11 +44458,16 @@ class UnwrittenFrames {
44212
44458
  constructor(host) {
44213
44459
  this.#host = host;
44214
44460
  }
44215
- sendCard(content, deliverAs, identity, claim) {
44461
+ sendCard(session, content, deliverAs, identity, claim) {
44462
+ if (!this.#host.hostIsOn(session)) {
44463
+ this.#host.cardNotShown(session, identity);
44464
+ claim?.release();
44465
+ return "closed";
44466
+ }
44216
44467
  const hand = deliverAs !== "inert" || this.#host.settled();
44217
44468
  const keys = identity === undefined ? [] : unwrittenCardKeys(replayLedgerIdentity(identity));
44218
44469
  const card = identity === undefined || keys.length === 0 ? undefined : {
44219
- sessionID: this.#host.sessionID(),
44470
+ sessionID: session,
44220
44471
  identity,
44221
44472
  claim,
44222
44473
  keys,
@@ -44390,9 +44641,7 @@ class UnwrittenFrames {
44390
44641
  }
44391
44642
  }
44392
44643
  async#recordWritten(frame) {
44393
- if (frame.sessionID === this.#host.sessionID()) {
44394
- await this.#host.recordDelivered(frame.identity);
44395
- }
44644
+ await this.#host.recordDelivered(frame.sessionID, frame.identity);
44396
44645
  frame.claim?.settle();
44397
44646
  }
44398
44647
  #awaitWrite(card) {
@@ -48049,6 +48298,7 @@ var DELIVERY_PICTURES_TIMEOUT_MS = 20000;
48049
48298
  var WHOLE_BODY_TIMEOUT_MS = 1e4;
48050
48299
  var BTW_EVENTS_LIMIT = 1000;
48051
48300
  var REPLAYED_BTW_NOTE = "This BTW was asked while this session was not taking messages. It is shown for your information only: it runs no side turn and needs no answer. Dispatch shows whether it was answered.";
48301
+ var MOVED_SESSION_REFUSAL = `The message was not sent: ${MOVED_SESSION_REASON}`;
48052
48302
  var CAPABILITIES_WITHOUT_BTW = DELIVERY_CAPABILITIES.filter((capability) => capability !== "btw");
48053
48303
  var ClaimIdentitySchema = DedupeIdentitySchema.extend({
48054
48304
  event_id: DedupeIdentitySchema.shape.event_id.catch(undefined),
@@ -48174,7 +48424,7 @@ process.env.DISPATCH_HOST = "omp";
48174
48424
  var CONFIG_FILE = sessionConfigFile("omp", process.env);
48175
48425
  if (CONFIG_FILE.path !== null)
48176
48426
  process.env.ENVOY_CONFIG_FILE = CONFIG_FILE.path;
48177
- var timedDispatchClient = (ms) => sessionDispatchClient(CONFIG_FILE, process.cwd(), AbortSignal.timeout(ms), currentSessionID)?.client;
48427
+ var timedDispatchClient = (ms, session = currentSessionID) => sessionDispatchClient(CONFIG_FILE, process.cwd(), AbortSignal.timeout(ms), session)?.client;
48178
48428
  function envoyExtension(pi) {
48179
48429
  logger3.debug("extension instance loaded", { extension: import.meta.url });
48180
48430
  const publishedInterface = publishEnvoyPluginInterface(import.meta.url);
@@ -48183,10 +48433,10 @@ function envoyExtension(pi) {
48183
48433
  session: currentSessionID
48184
48434
  });
48185
48435
  const { envoy } = atStart;
48186
- const currentDispatchConfig = () => {
48436
+ const dispatchConfigFor = (session) => {
48187
48437
  const resolution = sessionDispatchSettings(CONFIG_FILE, process.env, {
48188
48438
  cwd: process.cwd(),
48189
- session: currentSessionID
48439
+ session
48190
48440
  }).dispatch;
48191
48441
  const config = activeDispatchSettings(resolution);
48192
48442
  if (config === null) {
@@ -48462,8 +48712,14 @@ function envoyExtension(pi) {
48462
48712
  });
48463
48713
  }
48464
48714
  };
48465
- const postDispatchReply = async (delivery, result, replySessionID = sessionID) => {
48466
- await postDeliveryReply(currentDispatchConfig(), replySessionID, delivery, result);
48715
+ const postDispatchReply = async (delivery, result, replySessionID) => {
48716
+ if (!sessionOpen(replySessionID)) {
48717
+ logger3.warn("envoy: a reply is signed as the session its message reached, which is closed", {
48718
+ addressed: replySessionID,
48719
+ open: sessionID
48720
+ });
48721
+ }
48722
+ await postDeliveryReply(dispatchConfigFor(replySessionID), replySessionID, delivery, result);
48467
48723
  };
48468
48724
  const typedPictures = new TypedPictures;
48469
48725
  pi.on("input", async (event, context) => {
@@ -48503,11 +48759,19 @@ function envoyExtension(pi) {
48503
48759
  };
48504
48760
  const unwritten = new UnwrittenFrames({
48505
48761
  sessionID: () => sessionID,
48762
+ hostIsOn: (card) => hostSessionID() === card,
48506
48763
  settled: hostSettled,
48507
- recordDelivered: async (identity) => {
48508
- await replay?.recordDelivered(identity);
48764
+ recordDelivered: async (card, identity) => {
48765
+ await replay?.recordDeliveredFor(card, identity);
48509
48766
  },
48510
48767
  handCard,
48768
+ cardNotShown: (card, identity) => {
48769
+ logger3.warn("envoy: a card was not shown here; the session it names is closed", {
48770
+ addressed: card,
48771
+ eventID: identity?.event_id,
48772
+ open: sessionID
48773
+ });
48774
+ },
48511
48775
  handNotice: (content) => {
48512
48776
  pi.sendMessage({ customType: "envoy-message", content, display: true, details: LOCAL_ENVOY_NOTICE }, { deliverAs: "steer", triggerTurn: false });
48513
48777
  },
@@ -48541,14 +48805,15 @@ function envoyExtension(pi) {
48541
48805
  });
48542
48806
  }
48543
48807
  });
48544
- const showReplayCard = (content, envelope, deliverAs = "card") => {
48808
+ const showReplayCard = (session, content, envelope, deliverAs = "card") => {
48545
48809
  const parsed = ClaimIdentitySchema.safeParse(envelope);
48546
48810
  const identity = parsed.success ? parsed.data : undefined;
48547
48811
  const claim = delivered.claim(identity);
48548
48812
  if (claim === undefined && identity !== undefined && (delivered.pending(identity) || unwritten.waitsOnCard(identity))) {
48549
48813
  return "queued";
48550
48814
  }
48551
- return unwritten.sendCard(content, deliverAs, identity, claim);
48815
+ const outcome = unwritten.sendCard(session, content, deliverAs, identity, claim);
48816
+ return outcome === "closed" ? "failed" : outcome;
48552
48817
  };
48553
48818
  const btwEvents = new Set;
48554
48819
  const noteBtw = (eventID) => {
@@ -48562,6 +48827,94 @@ function envoyExtension(pi) {
48562
48827
  btwEvents.delete(oldest.value);
48563
48828
  }
48564
48829
  };
48830
+ const SHELL_COMMAND_LIMIT_MS = Number(process.env.ENVOY_SHELL_COMMAND_LIMIT_MS ?? "") || 120000;
48831
+ const runningShellCommands = new Map;
48832
+ const postTypedInputReply = async (delivery, replySessionID, body) => {
48833
+ try {
48834
+ await postDispatchReply(delivery, { body }, replySessionID);
48835
+ } catch (error) {
48836
+ if (!(error instanceof DispatchServiceError) || !error.fromDispatch)
48837
+ throw error;
48838
+ await postDispatchReply(delivery, { body: `Your command ran, and Dispatch refused its output: ${error.message}` }, replySessionID);
48839
+ }
48840
+ };
48841
+ const runShellCommandTurn = (delivery, replySessionID, turn, command, taken) => {
48842
+ typedPictures.withdraw(turn.messageId);
48843
+ const session = replySessionID;
48844
+ const running = runningShellCommands.get(session);
48845
+ const open = sessionOpen(session);
48846
+ const cwd = sessionDirectory2 || process.cwd();
48847
+ const line = turn.body;
48848
+ const refusalFor = () => {
48849
+ if (shuttingDown)
48850
+ return shellCommandShutdownReport(line);
48851
+ if (!open)
48852
+ return shellCommandMovedReport(line);
48853
+ if (running !== undefined)
48854
+ return shellCommandBusyReport(line, running.command);
48855
+ return;
48856
+ };
48857
+ const refusal = refusalFor();
48858
+ const claim = { command, stop: () => {} };
48859
+ if (refusal === undefined)
48860
+ runningShellCommands.set(session, claim);
48861
+ const ran = async () => {
48862
+ if (refusal !== undefined)
48863
+ return refusal;
48864
+ try {
48865
+ const result = await runShellCommand(command, {
48866
+ cwd,
48867
+ limitMs: SHELL_COMMAND_LIMIT_MS,
48868
+ started: (stop) => {
48869
+ claim.stop = stop;
48870
+ }
48871
+ });
48872
+ const handed = sessionOpen(session);
48873
+ const printed = shellCommandReport(line, result);
48874
+ const report = handed ? printed : shellCommandWithheldReport(printed);
48875
+ if (session !== "") {
48876
+ agentStream.record(agentStreamFramesSubject(session), {
48877
+ content: [{ text: report, type: "text" }],
48878
+ role: "user",
48879
+ tag: turn.messageId,
48880
+ timestamp: Date.now()
48881
+ }, false, turn.messageId);
48882
+ }
48883
+ if (handed) {
48884
+ pi.sendMessage({
48885
+ content: shellCommandMessage(report),
48886
+ customType: "envoy-message",
48887
+ details: LOCAL_ENVOY_NOTICE,
48888
+ display: true
48889
+ }, { deliverAs: "nextTurn", triggerTurn: false });
48890
+ }
48891
+ return report;
48892
+ } finally {
48893
+ if (runningShellCommands.get(session) === claim)
48894
+ runningShellCommands.delete(session);
48895
+ }
48896
+ };
48897
+ const answer = async () => {
48898
+ try {
48899
+ await postTypedInputReply(delivery, session, await ran());
48900
+ } catch (error) {
48901
+ logger3.warn("envoy: a person's shell command from Dispatch was not answered", {
48902
+ attempt: delivery.attempt,
48903
+ error: messageFor(error),
48904
+ messageID: delivery.id
48905
+ });
48906
+ } finally {
48907
+ await taken();
48908
+ }
48909
+ };
48910
+ answer().catch((error) => {
48911
+ logger3.warn("envoy: a person's shell command from Dispatch was not recorded as taken", {
48912
+ attempt: delivery.attempt,
48913
+ error: messageFor(error),
48914
+ messageID: delivery.id
48915
+ });
48916
+ });
48917
+ };
48565
48918
  const runTypedInput = (sendUserInput, delivery, replySessionID, turn, content, pictureAddresses) => {
48566
48919
  const images = typeof content === "string" ? [] : content.filter((block) => block.type === "image");
48567
48920
  const noted = sessionID;
@@ -48598,13 +48951,7 @@ function envoyExtension(pi) {
48598
48951
  refreshAgentStreamSettings(sessionID);
48599
48952
  if (reply === undefined)
48600
48953
  return;
48601
- try {
48602
- await postDispatchReply(delivery, { body: reply }, replySessionID);
48603
- } catch (error) {
48604
- if (!(error instanceof DispatchServiceError) || !error.fromDispatch)
48605
- throw error;
48606
- await postDispatchReply(delivery, { body: `Your command ran, and Dispatch refused its output: ${error.message}` }, replySessionID);
48607
- }
48954
+ await postTypedInputReply(delivery, replySessionID, reply);
48608
48955
  }).catch((error) => {
48609
48956
  logger3.warn("envoy: the reply to a person's typed input did not reach Dispatch", {
48610
48957
  attempt: delivery.attempt,
@@ -48615,13 +48962,22 @@ function envoyExtension(pi) {
48615
48962
  };
48616
48963
  const acceptedUserTurn = (rendered, acceptedSessionID) => acceptUserTurn({
48617
48964
  actorId: acceptedSessionID,
48618
- dispatch: () => timedDispatchClient(USER_TURN_ACCEPT_TIMEOUT_MS),
48965
+ dispatch: () => timedDispatchClient(USER_TURN_ACCEPT_TIMEOUT_MS, () => acceptedSessionID),
48619
48966
  handle: (key, delivery) => {
48620
48967
  handledDispatchAttempts.add(key);
48621
48968
  pi.appendEntry(HANDLED_ATTEMPT_ENTRY, {
48622
48969
  attempt: delivery.attempt,
48623
48970
  message_id: delivery.id
48624
48971
  });
48972
+ const open = hostSessionID();
48973
+ if (open !== acceptedSessionID) {
48974
+ logger3.warn("envoy: a handled attempt was written to another session's transcript", {
48975
+ addressed: acceptedSessionID,
48976
+ attempt: delivery.attempt,
48977
+ messageID: delivery.id,
48978
+ open
48979
+ });
48980
+ }
48625
48981
  },
48626
48982
  handled: (key) => handledDispatchAttempts.has(key),
48627
48983
  rendered,
@@ -48638,8 +48994,11 @@ function envoyExtension(pi) {
48638
48994
  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) });
48639
48995
  }
48640
48996
  });
48641
- const deliver = async (topic, subject, raw, reply, receivedAt, relayed) => {
48642
- let rendered = renderInbound(raw, sessionID, subject);
48997
+ const deliver = async (addressedSession, topic, subject, raw, reply, receivedAt, relayed) => {
48998
+ const session = addressedSession ?? sessionID;
48999
+ const addressedSessionOpen = () => addressedSession === undefined || sessionOpen(session);
49000
+ let rendered = renderInbound(raw, session, subject);
49001
+ const cardSession = () => rendered.delivery !== undefined && addressedSession !== undefined ? addressedSession : hostSessionID();
48643
49002
  const directSubject = agentSubject(sessionID);
48644
49003
  if (expectsLaneReceipt({
48645
49004
  subject,
@@ -48696,23 +49055,39 @@ function envoyExtension(pi) {
48696
49055
  return;
48697
49056
  }
48698
49057
  if (rendered.cutItem !== undefined) {
48699
- const dispatch = timedDispatchClient(WHOLE_BODY_TIMEOUT_MS);
48700
- const body = dispatch === undefined ? undefined : await wholeCarriedBody(dispatch, rendered.cutItem, sessionID);
49058
+ const dispatch = timedDispatchClient(WHOLE_BODY_TIMEOUT_MS, () => session);
49059
+ const body = dispatch === undefined ? undefined : await wholeCarriedBody(dispatch, rendered.cutItem, session);
48701
49060
  if (body !== undefined)
48702
- rendered = renderInbound(raw, sessionID, subject, body);
49061
+ rendered = renderInbound(raw, session, subject, body);
48703
49062
  }
48704
49063
  const envelope = rendered.envelope;
48705
49064
  if (envelope !== undefined)
48706
49065
  noteInbox(envelope);
48707
- const deliveredIn = sessionID;
49066
+ const recordTaken = async (frame) => {
49067
+ if (replay === undefined || await replay.recordDeliveredFor(session, frame))
49068
+ return;
49069
+ logger3.warn("envoy: a delivery was not recorded in the session it was addressed to", {
49070
+ addressed: session,
49071
+ eventID: frame.event_id,
49072
+ open: sessionID
49073
+ });
49074
+ };
48708
49075
  const taken = async () => {
48709
49076
  if (identity !== undefined)
48710
- await replay?.recordDeliveredFor(deliveredIn, identity);
49077
+ await recordTaken(identity);
48711
49078
  claim.settle();
48712
49079
  };
49080
+ const goBack = () => {
49081
+ logger3.warn("envoy: a delivery was not taken here; the session it names is closed", {
49082
+ addressed: session,
49083
+ eventID: envelope?.event_id,
49084
+ open: sessionID
49085
+ });
49086
+ claim.release();
49087
+ };
48713
49088
  const refuse = async (delivery, error) => {
48714
49089
  held.release();
48715
- await postDispatchReply(delivery, { error });
49090
+ await postDispatchReply(delivery, { error }, session);
48716
49091
  relayed?.done();
48717
49092
  };
48718
49093
  const offWorker = (work) => {
@@ -48723,7 +49098,7 @@ function envoyExtension(pi) {
48723
49098
  if (relayed !== undefined)
48724
49099
  relayed.done();
48725
49100
  else if (envelope !== undefined)
48726
- replay?.liveFailed(topic, envelope, error, receivedAt);
49101
+ replay?.liveFailed(cardSession(), topic, envelope, error, receivedAt);
48727
49102
  });
48728
49103
  };
48729
49104
  try {
@@ -48736,16 +49111,18 @@ function envoyExtension(pi) {
48736
49111
  claim.settle();
48737
49112
  } else if (rendered.delivery?.mode === "btw" && relayed?.late === true) {
48738
49113
  noteBtw(identity?.event_id);
48739
- unwritten.sendCard(`${replayedText(rendered.content, relayed.storedAt)}
49114
+ unwritten.sendCard(cardSession(), `${replayedText(rendered.content, relayed.storedAt)}
48740
49115
  ${REPLAYED_BTW_NOTE}`, "inert", identity, claim);
48741
49116
  } else if (rendered.delivery?.mode === "btw") {
48742
49117
  noteBtw(identity?.event_id);
48743
49118
  if (identity?.event_id !== undefined) {
48744
- await replay?.recordDeliveredFor(deliveredIn, { event_id: identity.event_id });
49119
+ await recordTaken({ event_id: identity.event_id });
48745
49120
  }
48746
49121
  const delivery = rendered.delivery;
48747
49122
  const answer = sideTurn(activeSessionContext);
48748
- if (shuttingDown) {
49123
+ if (!addressedSessionOpen()) {
49124
+ offWorker(() => refuse(delivery, MOVED_SESSION_REFUSAL));
49125
+ } else if (shuttingDown) {
48749
49126
  offWorker(() => refuse(delivery, "This OMP session is shutting down"));
48750
49127
  } else if (answer === undefined) {
48751
49128
  offWorker(() => refuse(delivery, "This OMP host does not support BTW delivery"));
@@ -48753,48 +49130,56 @@ ${REPLAYED_BTW_NOTE}`, "inert", identity, claim);
48753
49130
  offWorker(async () => {
48754
49131
  try {
48755
49132
  const reply = await answer({ prompt: delivery.body });
48756
- await postDispatchReply(delivery, { body: reply.replyText });
49133
+ await postDispatchReply(delivery, { body: reply.replyText }, session);
48757
49134
  await taken();
48758
49135
  } catch (error) {
48759
49136
  await refuse(delivery, messageFor(error));
48760
49137
  }
48761
49138
  });
48762
49139
  }
49140
+ } else if (rendered.delivery !== undefined && !addressedSessionOpen()) {
49141
+ goBack();
48763
49142
  } else {
48764
- const acceptedSessionID = sessionID;
48765
- const accepted = await acceptedUserTurn(rendered, acceptedSessionID);
49143
+ const accepted = await acceptedUserTurn(rendered, session);
48766
49144
  const shown = shownPictures(sessionID);
48767
49145
  if (accepted === undefined) {
48768
- const card = await withDeliveredPictures(rendered.content, rendered.pictures ?? [], () => timedDispatchClient(DELIVERY_PICTURES_TIMEOUT_MS), true, shown);
48769
- unwritten.sendCard(card.content, rendered.delivery?.mode === "aside" ? "aside" : "card", identity, claim);
48770
- markPicturesShown(shownPictures(sessionID), card.shown);
49146
+ const card = await withDeliveredPictures(rendered.content, rendered.pictures ?? [], () => timedDispatchClient(DELIVERY_PICTURES_TIMEOUT_MS, () => session), true, shown);
49147
+ const outcome = unwritten.sendCard(cardSession(), card.content, rendered.delivery?.mode === "aside" ? "aside" : "card", identity, claim);
49148
+ if (outcome !== "closed")
49149
+ markPicturesShown(shownPictures(sessionID), card.shown);
48771
49150
  } else {
48772
49151
  const { turn } = accepted;
48773
- const delivery = await withDeliveredPictures(turn.body, pictureAddresses(turn.body), () => timedDispatchClient(DELIVERY_PICTURES_TIMEOUT_MS), false, shown);
49152
+ const delivery = await withDeliveredPictures(turn.body, pictureAddresses(turn.body), () => timedDispatchClient(DELIVERY_PICTURES_TIMEOUT_MS, () => session), false, shown);
49153
+ const answerAndSettle = (body) => {
49154
+ offWorker(async () => {
49155
+ await postDispatchReply(accepted.delivery, { body }, session);
49156
+ await taken();
49157
+ });
49158
+ };
48774
49159
  const sendUserInput = pi.sendUserInput;
48775
- if (sendUserInput === undefined) {
48776
- const refusal = typedInputReply(turn.body, { hostVersion: VERSION });
48777
- if (refusal !== undefined) {
48778
- offWorker(async () => {
48779
- await postDispatchReply(accepted.delivery, { body: refusal }, acceptedSessionID);
48780
- await taken();
48781
- });
48782
- } else {
48783
- const injectionSessionID = sessionID;
48784
- noteInjectedUserTurn(injectionSessionID, turn.body, turn.messageId);
48785
- notedSessionIDs.add(injectionSessionID);
48786
- pi.sendUserMessage(delivery.content, turn.mode === "aside" ? { deliverAs: "aside" } : undefined);
48787
- markPicturesShown(shownPictures(injectionSessionID), delivery.shown);
48788
- unwritten.awaitTurn(turn.messageId, {
48789
- sessionID: injectionSessionID,
48790
- identity,
48791
- claim,
48792
- via: "text"
48793
- });
48794
- }
49160
+ const refusal = sendUserInput === undefined ? typedInputReply(turn.body, { hostVersion: VERSION }) : undefined;
49161
+ const command = sendUserInput === undefined ? undefined : shellCommandFrom(turn.body);
49162
+ if (refusal !== undefined) {
49163
+ answerAndSettle(refusal);
49164
+ } else if (command !== undefined) {
49165
+ runShellCommandTurn(accepted.delivery, session, turn, command, taken);
49166
+ } else if (!addressedSessionOpen()) {
49167
+ answerAndSettle(MOVED_SESSION_REFUSAL);
49168
+ } else if (sendUserInput === undefined) {
49169
+ const injectionSessionID = sessionID;
49170
+ noteInjectedUserTurn(injectionSessionID, turn.body, turn.messageId);
49171
+ notedSessionIDs.add(injectionSessionID);
49172
+ pi.sendUserMessage(delivery.content, turn.mode === "aside" ? { deliverAs: "aside" } : undefined);
49173
+ markPicturesShown(shownPictures(injectionSessionID), delivery.shown);
49174
+ unwritten.awaitTurn(turn.messageId, {
49175
+ sessionID: injectionSessionID,
49176
+ identity,
49177
+ claim,
49178
+ via: "text"
49179
+ });
48795
49180
  } else {
48796
49181
  unwritten.awaitTurn(turn.messageId, { sessionID, identity, claim, via: "typed" });
48797
- runTypedInput(sendUserInput, accepted.delivery, acceptedSessionID, turn, delivery.content, delivery.shown);
49182
+ runTypedInput(sendUserInput, accepted.delivery, session, turn, delivery.content, delivery.shown);
48798
49183
  }
48799
49184
  }
48800
49185
  }
@@ -48803,7 +49188,7 @@ ${REPLAYED_BTW_NOTE}`, "inert", identity, claim);
48803
49188
  held.release();
48804
49189
  console.warn(`[envoy] failed to deliver envelope ${envelope?.event_id ?? "unknown"}`, error);
48805
49190
  if (relayed === undefined && envelope !== undefined) {
48806
- replay?.liveFailed(topic, envelope, error, receivedAt);
49191
+ replay?.liveFailed(cardSession(), topic, envelope, error, receivedAt);
48807
49192
  }
48808
49193
  throw error;
48809
49194
  }
@@ -48834,23 +49219,26 @@ ${REPLAYED_BTW_NOTE}`, "inert", identity, claim);
48834
49219
  const lineage = continuedBy(id);
48835
49220
  return announced !== undefined && announced.from !== id && carriesSession(announced.reason) && !lineage.includes(announced.from) ? [...lineage, announced.from] : lineage;
48836
49221
  };
48837
- const replacedSessionTopic = (topic) => {
49222
+ const topicAddress = (topic) => {
48838
49223
  if (!topic.startsWith(agentSubject("")))
48839
- return false;
49224
+ return { addressed: undefined };
48840
49225
  const host = hostSessionID();
48841
- return host !== "" && !lineageOf(host).some((id) => topic === agentSubject(id));
49226
+ if (host === "")
49227
+ return { addressed: undefined };
49228
+ return lineageOf(host).some((id) => topic === agentSubject(id)) ? { addressed: host } : { replaced: true };
48842
49229
  };
48843
49230
  const pump = async (topic, subscription) => {
48844
49231
  try {
48845
49232
  for await (const { message, receivedAt } of readArrivals(subscription)) {
48846
- if (replacedSessionTopic(topic)) {
49233
+ const address = topicAddress(topic);
49234
+ if ("replaced" in address) {
48847
49235
  logger3.warn("envoy: frame for a session a switch replaced left undelivered", {
48848
49236
  subject: message.subject
48849
49237
  });
48850
49238
  continue;
48851
49239
  }
48852
49240
  try {
48853
- await deliver(topic, message.subject, codec2.decode(message.data), message.reply ?? "", receivedAt);
49241
+ await deliver(address.addressed, topic, message.subject, codec2.decode(message.data), message.reply ?? "", receivedAt);
48854
49242
  } catch {}
48855
49243
  }
48856
49244
  } catch {}
@@ -48979,18 +49367,27 @@ ${REPLAYED_BTW_NOTE}`, "inert", identity, claim);
48979
49367
  return replayFollowedSubjects(agentSubject(sessionID), open, registrationState.isRoleBound);
48980
49368
  };
48981
49369
  const showReplayed = async (frame) => {
48982
- const rendered = renderInbound(frame.data, sessionID, frame.subject);
49370
+ const addressed = sessionID;
49371
+ const rendered = renderInbound(frame.data, addressed, frame.subject);
48983
49372
  if (replay !== undefined) {
48984
49373
  await closeReplayedRemoval(frame, {
48985
- sessionID,
49374
+ sessionID: addressed,
48986
49375
  engine: replay,
48987
49376
  close: closeIntentionally,
48988
49377
  unregister: async (topics) => {
48989
- await active?.client.unsubscribe({ sessionID, topics }).catch((error) => logger3.warn("envoy: a replayed subscription removal was not taken out of the registry", { topics, error: messageFor(error) }));
49378
+ await active?.client.unsubscribe({ sessionID: addressed, topics }).catch((error) => logger3.warn("envoy: a replayed subscription removal was not taken out of the registry", { topics, error: messageFor(error) }));
48990
49379
  },
48991
49380
  followedChanged: replayFollowedChanged
48992
49381
  });
48993
49382
  }
49383
+ if (!sessionOpen(addressed)) {
49384
+ logger3.warn("envoy: a replayed card was not shown here; the session it names is closed", {
49385
+ addressed,
49386
+ eventID: rendered.envelope?.event_id,
49387
+ open: sessionID
49388
+ });
49389
+ return "failed";
49390
+ }
48994
49391
  if (replaySuppressed(rendered))
48995
49392
  return "suppressed";
48996
49393
  if (rendered.envelope !== undefined)
@@ -48998,10 +49395,10 @@ ${REPLAYED_BTW_NOTE}`, "inert", identity, claim);
48998
49395
  const shown = replayedText(rendered.content, frame.time);
48999
49396
  if (rendered.delivery?.mode === "btw") {
49000
49397
  noteBtw(rendered.envelope?.event_id);
49001
- return showReplayCard(`${shown}
49398
+ return showReplayCard(addressed, `${shown}
49002
49399
  ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
49003
49400
  }
49004
- return showReplayCard(shown, frame.envelope);
49401
+ return showReplayCard(addressed, shown, frame.envelope);
49005
49402
  };
49006
49403
  const transcriptSessionID = () => {
49007
49404
  const host = hostSessionID();
@@ -49020,7 +49417,12 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
49020
49417
  writeSessionID: transcriptSessionID,
49021
49418
  followedSubjects,
49022
49419
  deliver: showReplayed,
49023
- showFailureNotice: async (notice) => showReplayCard(envoyNoticeText(failureNoticeFields(notice)), notice.envelope, btwEvents.has(notice.eventId) ? "inert" : "card"),
49420
+ showFailureNotice: async (notice) => {
49421
+ const outcome = showReplayCard(sessionID, envoyNoticeText(failureNoticeFields(notice)), notice.envelope, btwEvents.has(notice.eventId) ? "inert" : "card");
49422
+ if (outcome === "failed")
49423
+ throw new Error("the session it names is closed");
49424
+ return outcome;
49425
+ },
49024
49426
  failureNoticeFailed: (notice, error) => {
49025
49427
  logger3.warn("envoy: a message this session was not shown could not be reported", {
49026
49428
  eventID: notice.eventId,
@@ -49057,7 +49459,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
49057
49459
  frame.nak();
49058
49460
  return;
49059
49461
  }
49060
- await deliver(frame.subject, frame.subject, frame.data, "", Date.now(), frame);
49462
+ await deliver(owner.sessionID, frame.subject, frame.subject, frame.data, "", Date.now(), frame);
49061
49463
  };
49062
49464
  const createRelay = (id, entries, ledger) => {
49063
49465
  let persistedFollows = "";
@@ -49179,6 +49581,9 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
49179
49581
  let agentStreamControl;
49180
49582
  let agentStreamControlSession = "";
49181
49583
  let agentStreamCommandsRefreshedOnWatchAt = -Infinity;
49584
+ let agentStreamContextRefreshedAt = -Infinity;
49585
+ let agentStreamContextTrailing;
49586
+ let agentStreamContextHeld;
49182
49587
  let agentStreamViewerAttached = false;
49183
49588
  const refreshAgentStreamCommands = (session) => {
49184
49589
  if (typeof pi.sendUserInput !== "function")
@@ -49223,6 +49628,60 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
49223
49628
  });
49224
49629
  }
49225
49630
  };
49631
+ const CONTEXT_FRAME_INTERVAL_MS = Number(process.env.ENVOY_CONTEXT_FRAME_INTERVAL_MS ?? "") || 2000;
49632
+ const publishAgentStreamContext = (session, usage) => {
49633
+ agentStreamContextRefreshedAt = Date.now();
49634
+ try {
49635
+ agentStream.setContext(agentStreamFramesSubject(session), usage);
49636
+ } catch (error) {
49637
+ logger3.warn("envoy: could not publish the agent stream's context frame", {
49638
+ error: messageFor(error),
49639
+ sessionID: session
49640
+ });
49641
+ }
49642
+ };
49643
+ const refreshAgentStreamContext = (session) => {
49644
+ if (session === "")
49645
+ return;
49646
+ const context = activeSessionContext;
49647
+ if (context === undefined || typeof context.getContextUsage !== "function")
49648
+ return;
49649
+ let usage;
49650
+ try {
49651
+ usage = context.getContextUsage();
49652
+ } catch (error) {
49653
+ logger3.warn("envoy: could not refresh agent stream context", {
49654
+ error: messageFor(error),
49655
+ sessionID: session
49656
+ });
49657
+ return;
49658
+ }
49659
+ const waited = Date.now() - agentStreamContextRefreshedAt;
49660
+ if (waited >= CONTEXT_FRAME_INTERVAL_MS) {
49661
+ clearTimeout(agentStreamContextTrailing);
49662
+ agentStreamContextTrailing = undefined;
49663
+ agentStreamContextHeld = undefined;
49664
+ publishAgentStreamContext(session, usage);
49665
+ return;
49666
+ }
49667
+ agentStreamContextHeld = { session, usage };
49668
+ if (agentStreamContextTrailing !== undefined)
49669
+ return;
49670
+ agentStreamContextTrailing = setTimeout(() => {
49671
+ agentStreamContextTrailing = undefined;
49672
+ const held = agentStreamContextHeld;
49673
+ agentStreamContextHeld = undefined;
49674
+ if (held !== undefined)
49675
+ publishAgentStreamContext(held.session, held.usage);
49676
+ }, CONTEXT_FRAME_INTERVAL_MS - waited);
49677
+ agentStreamContextTrailing.unref?.();
49678
+ };
49679
+ const forgetAgentStreamContext = () => {
49680
+ clearTimeout(agentStreamContextTrailing);
49681
+ agentStreamContextTrailing = undefined;
49682
+ agentStreamContextHeld = undefined;
49683
+ agentStreamContextRefreshedAt = -Infinity;
49684
+ };
49226
49685
  const pumpAgentStreamControl = async (subscription, session) => {
49227
49686
  try {
49228
49687
  for await (const message of subscription) {
@@ -49287,6 +49746,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
49287
49746
  agentStream.reset();
49288
49747
  agentStreamViewerAttached = false;
49289
49748
  agentStreamCommandsRefreshedOnWatchAt = -Infinity;
49749
+ forgetAgentStreamContext();
49290
49750
  }
49291
49751
  agentStreamControlSession = session;
49292
49752
  const connected = await connect();
@@ -49321,14 +49781,22 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
49321
49781
  if (!shuttingDown)
49322
49782
  cardWake.messageEnd(message, context);
49323
49783
  recordAgentStreamMessage(message, false);
49784
+ refreshAgentStreamContext(sessionID);
49324
49785
  cardAges.written(message, context.sessionManager.getSessionId());
49325
49786
  await unwritten.written(message);
49326
49787
  });
49327
- pi.on("session_compact", async (_event, context) => cardWake.noteIfIdle(context));
49328
- pi.on("auto_compaction_end", async (event) => cardWake.autoCompactionEnd(event));
49788
+ pi.on("session_compact", async (_event, context) => {
49789
+ cardWake.noteIfIdle(context);
49790
+ refreshAgentStreamContext(sessionID);
49791
+ });
49792
+ pi.on("auto_compaction_end", async (event) => {
49793
+ cardWake.autoCompactionEnd(event);
49794
+ refreshAgentStreamContext(sessionID);
49795
+ });
49329
49796
  pi.on("auto_retry_end", async (event) => cardWake.autoRetryEnd(event));
49330
49797
  pi.on("turn_start", async () => {
49331
49798
  refreshAgentStreamSettings(sessionID);
49799
+ refreshAgentStreamContext(sessionID);
49332
49800
  });
49333
49801
  pi.on("retry_fallback_applied", async () => {
49334
49802
  refreshAgentStreamSettings(sessionID);
@@ -49652,7 +50120,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
49652
50120
  if (registrationState.establishedFor() !== host) {
49653
50121
  if ((process.env.DISPATCH_SESSION_ID ?? "") !== host) {
49654
50122
  bindDispatchSession(host, context.ui);
49655
- procmgr.refreshShellConfigCache();
50123
+ procmgr2.refreshShellConfigCache();
49656
50124
  }
49657
50125
  tellIdChanged(host);
49658
50126
  if (host !== lastHeard)
@@ -49935,6 +50403,8 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
49935
50403
  shuttingDown = true;
49936
50404
  tmuxPlaces.shutDown();
49937
50405
  cardWake.cancel();
50406
+ for (const running of runningShellCommands.values())
50407
+ running.stop();
49938
50408
  if (publishedInterface !== undefined) {
49939
50409
  const bound = publishedInterface.roleClaim.instances.indexOf(claimInstance);
49940
50410
  if (bound !== -1)
@@ -49983,6 +50453,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
49983
50453
  agentStreamControl = undefined;
49984
50454
  agentStreamControlSession = "";
49985
50455
  const liveSessionID = context.sessionManager.getSessionId();
50456
+ forgetAgentStreamContext();
49986
50457
  forgetShownPictures(sessionID);
49987
50458
  if (liveSessionID !== sessionID)
49988
50459
  forgetShownPictures(liveSessionID);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sjawhar/pi-envoy",
3
- "version": "16.48.0",
3
+ "version": "16.49.0",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "omp": {