@sjawhar/pi-envoy 13.5.1 → 13.6.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
@@ -30383,7 +30383,7 @@ var dispatchToolSpecs = [
30383
30383
  {
30384
30384
  name: "dispatch_doc_read",
30385
30385
  example: { issue: "DSP-1" },
30386
- description: "Read a live document or a named document version, or the text of an uploaded file at its latest or named version. " + "Do not use it for issue status, asks, or events; " + "use dispatch read instead. Supply ref, issue, or project plus artifact; issue plus an omitted artifact reads the primary document. " + "A live read returns its document token for an optional dispatch doc-edit precondition. With blocks it lists the live document's blocks instead of its markdown, in document order: each block's id, type, token, anchored comments and asks, and opening words, and under a table each row by the index delete_row takes and each cell by its row and the column delete_column takes; block ids, block tokens and those indexes are what dispatch doc-edit takes. " + "After the markdown it prints every open thread anchored on the document in full: an open ask with its id and question and each reply's author, time and text, and a comment thread with its root's id, author, quote and text and each reply's author, time and text, in order; a resolved thread, and an ask that is answered or resolved, is not printed. " + "A picture (an uploaded PNG, JPEG, GIF or WebP of at most 3,750,000 bytes, 5 MB once base64-encoded) comes back as an image you see, with its name, type, size and version, every time you ask, including one a read already showed this session; " + "any other file that is not UTF-8 text is described, with the route that serves its bytes. " + OWNER_REFERENCE,
30386
+ description: "Read a live document or a named document version, or the text of an uploaded file at its latest or named version. " + "Do not use it for issue status, asks, or events; " + "use dispatch read instead. Supply ref, issue, or project plus artifact; issue plus an omitted artifact reads the primary document. " + "A live read returns its document token for an optional dispatch doc-edit precondition. With blocks it lists the live document's blocks instead of its markdown, in document order: each block's id, type, token, anchored comments and asks, and opening words, and under a table each row by the index delete_row takes and each cell by its row and the column delete_column takes; block ids, block tokens and those indexes are what dispatch doc-edit takes. " + "After the markdown it prints every open thread anchored on the document in full: an open ask with its id and question and each reply's author, time and text, and a comment thread with its root's id, author, time, quote and text and each reply's author, time and text, in order; a resolved thread, and an ask that is answered or resolved, is not printed. " + "A picture (an uploaded PNG, JPEG, GIF or WebP of at most 3,750,000 bytes, 5 MB once base64-encoded) comes back as an image you see, with its name, type, size and version, every time you ask, including one a read already showed this session; " + "any other file that is not UTF-8 text is described, with the route that serves its bytes. " + OWNER_REFERENCE,
30387
30387
  arguments: (z) => ({
30388
30388
  issue: z.string().describe(ISSUE_REFERENCE).optional(),
30389
30389
  project: z.string().describe("Project key owning the document.").optional(),
@@ -30543,6 +30543,13 @@ var dispatchToolSpecs = [
30543
30543
  }),
30544
30544
  strict: true
30545
30545
  },
30546
+ {
30547
+ name: "dispatch_answers",
30548
+ example: {},
30549
+ description: "List every answer and comment a person wrote to this session in the last 72 hours, newest first, each in full: " + "answers to its asks, replies on its asks and in its comment threads, comments on its documents and on issues routed to it, " + "mentions of it, messages to it and replies to its messages. Each item names its time, its writer, what it is, its " + "dispatch:// reference and its issue or document, an answer's question and choices, and the words, never cut. " + "Run it when the list of people's answers on a model request says it left older items out. " + "It reads this session's id from CLAUDE_CODE_SESSION_ID under Claude Code and DISPATCH_SESSION_ID elsewhere, so a subagent reads its parent's.",
30550
+ arguments: () => ({}),
30551
+ strict: true
30552
+ },
30546
30553
  {
30547
30554
  name: "dispatch_whoami",
30548
30555
  example: {},
@@ -32037,6 +32044,12 @@ class DispatchClient {
32037
32044
  async openAsksForProject(project) {
32038
32045
  return this.#json("GET", ["api", "v1", "asks", "open"], undefined, { project });
32039
32046
  }
32047
+ async sessionAnswers(sessionID, options = {}) {
32048
+ return this.#json("GET", ["api", "v1", "agents", sessionID, "answers"], undefined, {
32049
+ ...options.since === undefined ? {} : { since: options.since },
32050
+ ...options.maxChars === undefined ? {} : { max_chars: options.maxChars }
32051
+ }, options.signal);
32052
+ }
32040
32053
  async listAgents() {
32041
32054
  return this.#json("GET", ["api", "v1", "agents"]);
32042
32055
  }
@@ -32265,12 +32278,12 @@ class DispatchClient {
32265
32278
  throw error;
32266
32279
  }
32267
32280
  }
32268
- async#json(method, path, body, query) {
32269
- return (await this.#jsonAnswer(method, path, body, query)).payload;
32281
+ async#json(method, path, body, query, signal) {
32282
+ return (await this.#jsonAnswer(method, path, body, query, signal)).payload;
32270
32283
  }
32271
- async#jsonAnswer(method, path, body, query) {
32284
+ async#jsonAnswer(method, path, body, query, signal) {
32272
32285
  const url = this.#url(path, query);
32273
- const response = await this.#send(method, url, body === undefined ? undefined : { content: JSON.stringify(body), type: "application/json" });
32286
+ const response = await this.#send(method, url, body === undefined ? undefined : { content: JSON.stringify(body), type: "application/json" }, undefined, signal);
32274
32287
  return { status: response.status, payload: await this.#response(method, url, response) };
32275
32288
  }
32276
32289
  async#upload(path, input) {
@@ -32293,7 +32306,7 @@ class DispatchClient {
32293
32306
  const response = await this.#send(method, url, { content, type });
32294
32307
  return this.#response(method, url, response);
32295
32308
  }
32296
- async#send(method, url, body, accept = "application/json") {
32309
+ async#send(method, url, body, accept = "application/json", signal) {
32297
32310
  const headers = {
32298
32311
  Accept: accept,
32299
32312
  Authorization: `Bearer ${this.token}`
@@ -32304,7 +32317,7 @@ class DispatchClient {
32304
32317
  return this.fetchImpl(url, {
32305
32318
  method,
32306
32319
  headers,
32307
- signal: this.#signal,
32320
+ signal: signal === undefined ? this.#signal : AbortSignal.any([this.#signal, signal]),
32308
32321
  ...body === undefined ? {} : { body: body.content }
32309
32322
  });
32310
32323
  }
@@ -32487,6 +32500,9 @@ class DispatchClient {
32487
32500
  }
32488
32501
 
32489
32502
  // ../envoy-client/src/dispatch-owner.ts
32503
+ function ownerTitle(owner) {
32504
+ return "issue" in owner ? `${owner.issue.key}: ${owner.issue.title}` : `${owner.document.project} / ${owner.document.name}`;
32505
+ }
32490
32506
  function dispatchIssueRef(key) {
32491
32507
  return `dispatch://${key}`;
32492
32508
  }
@@ -33132,6 +33148,7 @@ function parseDispatchFrame(rawPayload) {
33132
33148
  return {
33133
33149
  event: targeted.data.event,
33134
33150
  notify: wireFrame.event.notify,
33151
+ quiet: wireFrame.event.quiet,
33135
33152
  delivery: targeted.data.delivery
33136
33153
  };
33137
33154
  }
@@ -33165,6 +33182,7 @@ function parseDispatchFrame(rawPayload) {
33165
33182
  return {
33166
33183
  event: parsed.data,
33167
33184
  notify: wireEvent.notify,
33185
+ quiet: wireEvent.quiet,
33168
33186
  delivery: undefined
33169
33187
  };
33170
33188
  }
@@ -33221,7 +33239,8 @@ function renderInbound(raw, sessionID, subject) {
33221
33239
  } else {
33222
33240
  const frame = parseDispatchFrame(envelope.payload);
33223
33241
  if ("event" in frame) {
33224
- if (frame.notify === false && topic?.startsWith(DISPATCH_TOPIC_PREFIX) === true) {
33242
+ const quiet = frame.quiet === undefined ? frame.notify === false : frame.quiet === true;
33243
+ if (quiet && topic?.startsWith(DISPATCH_TOPIC_PREFIX) === true) {
33225
33244
  return { skip: true, content: "", envelope };
33226
33245
  }
33227
33246
  if (frame.event.actor.kind === "session" && frame.event.actor.id === sessionID) {
@@ -33734,7 +33753,7 @@ function runCommand(command, env, cwd) {
33734
33753
  rmSync2(directory, { recursive: true, force: true });
33735
33754
  }
33736
33755
  }
33737
- function fileValue(value, field, filePath, env) {
33756
+ function fileValue(value, field, filePath, env, commands = "run") {
33738
33757
  if (!value.startsWith("!")) {
33739
33758
  if (!sendable(value)) {
33740
33759
  throw new Error(`${filePath}: ${field} holds whitespace or a control character`);
@@ -33745,7 +33764,11 @@ function fileValue(value, field, filePath, env) {
33745
33764
  const cwd = path.dirname(path.resolve(filePath));
33746
33765
  const key = JSON.stringify([command, filePath, cwd]);
33747
33766
  let outcome = commandOutcomes.get(key);
33748
- if (outcome === undefined || "failure" in outcome && !outcome.timedOut && Date.now() - outcome.at >= FAILURE_KEPT_MS) {
33767
+ if (commands === "kept") {
33768
+ if (outcome === undefined) {
33769
+ throw new Error(`${filePath}: ${field}'s command has not run in this process yet, and this read does not run it`);
33770
+ }
33771
+ } else if (outcome === undefined || "failure" in outcome && !outcome.timedOut && Date.now() - outcome.at >= FAILURE_KEPT_MS) {
33749
33772
  outcome = { ...runCommand(command, env, cwd), at: Date.now() };
33750
33773
  commandOutcomes.set(key, outcome);
33751
33774
  }
@@ -33887,7 +33910,7 @@ function bearerSource(env, section, written) {
33887
33910
  const bearer = written();
33888
33911
  return bearer === undefined ? { kind: "none" } : { kind: "file", ...bearer };
33889
33912
  }
33890
- function fileBearer(bearer, url, section, env) {
33913
+ function fileBearer(bearer, url, section, env, commands = "run") {
33891
33914
  const named = httpUrl2(url)?.origin;
33892
33915
  const paired = httpUrl2(bearer.server)?.origin;
33893
33916
  if (named !== paired) {
@@ -33899,7 +33922,7 @@ function fileBearer(bearer, url, section, env) {
33899
33922
  if (bearer.token === "") {
33900
33923
  throw new Error(`${bearer.field} in ${bearer.path} must be a non-empty bearer token`);
33901
33924
  }
33902
- return fileValue(bearer.token, bearer.field, bearer.path, env);
33925
+ return fileValue(bearer.token, bearer.field, bearer.path, env, commands);
33903
33926
  }
33904
33927
 
33905
33928
  // ../envoy-client/src/dispatch-config.ts
@@ -33934,7 +33957,30 @@ function writtenToken(config, checkout) {
33934
33957
  checkout: false
33935
33958
  };
33936
33959
  }
33937
- function dispatchSettings(env, config) {
33960
+ function dispatchSettings(env, config, options = {}) {
33961
+ const target = dispatchTarget(env, config);
33962
+ if (!target.enabled)
33963
+ return target;
33964
+ const { url, source } = target;
33965
+ let token;
33966
+ try {
33967
+ token = source.kind === "variable" ? source.token : fileBearer(source, url, "DISPATCH", env, options.commands);
33968
+ } catch (error) {
33969
+ return offWithError(messageFor(error));
33970
+ }
33971
+ const publicUrl = nonEmpty(env.DISPATCH_PUBLIC_URL);
33972
+ const publicParsed = publicUrl === undefined ? undefined : httpUrl2(publicUrl);
33973
+ if (publicUrl !== undefined && (publicParsed === undefined || publicParsed.port === "0")) {
33974
+ return offWithError("DISPATCH_PUBLIC_URL must be an http or https URL");
33975
+ }
33976
+ return {
33977
+ enabled: true,
33978
+ url,
33979
+ token,
33980
+ ...publicUrl === undefined ? {} : { publicUrl: publicUrl.replace(/\/+$/, "") }
33981
+ };
33982
+ }
33983
+ function dispatchTarget(env, config) {
33938
33984
  if (config.kind === "failed")
33939
33985
  return offWithError(config.error);
33940
33986
  const explicitUrl = nonEmpty(env.DISPATCH_URL);
@@ -33957,27 +34003,17 @@ function dispatchSettings(env, config) {
33957
34003
  if (explicitUrl !== undefined && httpUrl2(explicitUrl) === undefined) {
33958
34004
  return offWithError("DISPATCH_URL must be an http or https URL");
33959
34005
  }
34006
+ let source;
33960
34007
  try {
33961
- const source = checkout !== null && checkoutServer !== undefined ? checkoutPair(checkout, checkoutServer) : bearerSource(env, "DISPATCH", () => writtenToken(config, checkout));
33962
- if (source.kind === "none") {
33963
- return offWithError(explicitUrl === undefined ? `${config.path}: dispatch is enabled and no token is: set dispatch.token, or DISPATCH_TOKEN or DISPATCH_TOKEN_FILE` : `DISPATCH_URL is set and no token is: set DISPATCH_TOKEN or DISPATCH_TOKEN_FILE, or dispatch.token in ${config.path}`);
33964
- }
33965
- const url = (explicitUrl ?? (source.kind === "file" ? source.server : own.serverUrl ?? DEFAULT_SERVER_URL)).replace(/\/+$/, "");
33966
- const token = source.kind === "variable" ? source.token : fileBearer(source, url, "DISPATCH", env);
33967
- const publicUrl = nonEmpty(env.DISPATCH_PUBLIC_URL);
33968
- const publicParsed = publicUrl === undefined ? undefined : httpUrl2(publicUrl);
33969
- if (publicUrl !== undefined && (publicParsed === undefined || publicParsed.port === "0")) {
33970
- return offWithError("DISPATCH_PUBLIC_URL must be an http or https URL");
33971
- }
33972
- return {
33973
- enabled: true,
33974
- url,
33975
- token,
33976
- ...publicUrl === undefined ? {} : { publicUrl: publicUrl.replace(/\/+$/, "") }
33977
- };
34008
+ source = checkout !== null && checkoutServer !== undefined ? checkoutPair(checkout, checkoutServer) : bearerSource(env, "DISPATCH", () => writtenToken(config, checkout));
33978
34009
  } catch (error) {
33979
34010
  return offWithError(messageFor(error));
33980
34011
  }
34012
+ if (source.kind === "none") {
34013
+ return offWithError(explicitUrl === undefined ? `${config.path}: dispatch is enabled and no token is: set dispatch.token, or DISPATCH_TOKEN or DISPATCH_TOKEN_FILE` : `DISPATCH_URL is set and no token is: set DISPATCH_TOKEN or DISPATCH_TOKEN_FILE, or dispatch.token in ${config.path}`);
34014
+ }
34015
+ const url = (explicitUrl ?? (source.kind === "file" ? source.server : own.serverUrl ?? DEFAULT_SERVER_URL)).replace(/\/+$/, "");
34016
+ return { enabled: true, url, source };
33981
34017
  }
33982
34018
  function activeDispatchSettings(resolution) {
33983
34019
  if (resolution.enabled)
@@ -34293,23 +34329,51 @@ async function readPictures(client, addresses, shown) {
34293
34329
  return { lines, images, shown: showing };
34294
34330
  }
34295
34331
 
34332
+ // ../envoy-client/src/dispatch-session-directory.ts
34333
+ import { randomUUID } from "crypto";
34334
+ import { renameSync as renameSync2, rmSync as rmSync3, writeFileSync as writeFileSync2 } from "fs";
34335
+ import { homedir as homedir2 } from "os";
34336
+ import { join as join4 } from "path";
34337
+ var SESSION_ID = /^[A-Za-z0-9._-]{1,128}$/;
34338
+ var PRIVATE_FILE2 = 384;
34339
+ function sessionStateRoot(env) {
34340
+ const stateDir = env["DISPATCH_STATE_DIR"];
34341
+ if (stateDir)
34342
+ return stateDir;
34343
+ return join4(env["XDG_STATE_HOME"] || join4(homedir2(), ".local", "state"), "dispatch");
34344
+ }
34345
+ function sessionDirectory(env, sessionId) {
34346
+ if (!SESSION_ID.test(sessionId) || sessionId === "." || sessionId === "..") {
34347
+ throw new Error(`dispatch: the session id ${JSON.stringify(sessionId)} is not 1-128 letters, digits, ".", "_" or "-"`);
34348
+ }
34349
+ return join4(sessionStateRoot(env), "sessions", sessionId);
34350
+ }
34351
+ function writeAtomically2(path, text) {
34352
+ const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
34353
+ try {
34354
+ writeFileSync2(temporary, text, { mode: PRIVATE_FILE2 });
34355
+ renameSync2(temporary, path);
34356
+ } catch (error) {
34357
+ rmSync3(temporary, { force: true });
34358
+ throw error;
34359
+ }
34360
+ }
34361
+
34296
34362
  // ../envoy-client/src/dispatch-session-state.ts
34297
34363
  import {
34298
34364
  appendFileSync,
34299
34365
  closeSync as closeSync3,
34300
34366
  fstatSync,
34301
- mkdirSync as mkdirSync2,
34367
+ mkdirSync as mkdirSync3,
34302
34368
  openSync as openSync3,
34303
34369
  readdirSync as readdirSync2,
34304
- readFileSync as readFileSync5,
34370
+ readFileSync as readFileSync6,
34305
34371
  readSync,
34306
- renameSync as renameSync2,
34307
- rmSync as rmSync3,
34372
+ rmSync as rmSync4,
34308
34373
  statSync as statSync3,
34309
- writeFileSync as writeFileSync2
34374
+ writeFileSync as writeFileSync3
34310
34375
  } from "fs";
34311
- import { homedir as homedir2 } from "os";
34312
- import { join as join4 } from "path";
34376
+ import { join as join6 } from "path";
34313
34377
 
34314
34378
  // ../envoy-client/src/dispatch-cwd.ts
34315
34379
  import { execFile } from "child_process";
@@ -34352,6 +34416,242 @@ function subscriptionRemovedTopics(raw, sessionID) {
34352
34416
  return parsedPayload.data.topics ?? [];
34353
34417
  }
34354
34418
 
34419
+ // ../envoy-client/src/session-answers.ts
34420
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync5 } from "fs";
34421
+ import { join as join5 } from "path";
34422
+ var SESSION_ANSWERS_WINDOW_MS = 72 * 3600000;
34423
+ var SESSION_ANSWERS_MAX_CHARS = 8000;
34424
+ var SESSION_ANSWERS_DEADLINE_MS = 800;
34425
+ var READ_TIMEOUT_MS = 1e4;
34426
+ var NO_ROUTE_BACKOFF_MS = 5 * 60000;
34427
+ var QUESTION_MAX = 200;
34428
+ var SESSION_ANSWERS_MARKER = "[Dispatch: what people wrote to this session in the last 72 hours, newest first, word for word. Reference, not a new request.]";
34429
+ var FAILURE_MARKER = "[Dispatch: people's answers from the last 72 hours could not be read (";
34430
+ var NO_ANSWERS_ROUTE_REASON = "this Dispatch build has no answers route";
34431
+ var RELATION_PHRASES = {
34432
+ answered_your_ask: "answered your ask",
34433
+ replied_on_your_ask: "replied on your ask",
34434
+ replied_in_a_comment_thread: "replied in a comment thread",
34435
+ commented_on_a_document: "commented on a document",
34436
+ commented_on_an_issue: "commented on an issue",
34437
+ mentioned_you: "mentioned you",
34438
+ sent_you_a_message: "sent you a message",
34439
+ replied_to_your_message: "replied to your message"
34440
+ };
34441
+ function isSessionAnswersText(text) {
34442
+ return text.startsWith(SESSION_ANSWERS_MARKER) || text.startsWith(FAILURE_MARKER);
34443
+ }
34444
+ function isNoAnswersRoute(error) {
34445
+ return error instanceof DispatchServiceError && error.status === 404;
34446
+ }
34447
+ function renderSessionAnswerItem(item) {
34448
+ const relation = `${RELATION_PHRASES[item.relation]}${item.replaced === true ? " (replaces an earlier answer)" : ""}`;
34449
+ const head = [item.at, `user ${item.author.id}`, relation];
34450
+ if (item.edited_at !== undefined)
34451
+ head.push(`edited ${item.edited_at}`);
34452
+ const owner = item.owner === null ? undefined : ownerTitle(item.owner);
34453
+ const where = item.ref === null ? `Direct message ${item.id}, on no issue` : owner === undefined ? item.ref : `${item.ref} \xB7 ${owner}`;
34454
+ const lines = [head.join(" \xB7 "), where];
34455
+ if (item.ask !== undefined) {
34456
+ const question = item.ask.question.replace(/\s+/g, " ").trim();
34457
+ lines.push(`Question: ${question.length > QUESTION_MAX ? `${question.slice(0, QUESTION_MAX)}\u2026` : question}`);
34458
+ }
34459
+ if (item.kind === "answer") {
34460
+ const selected = item.selected ?? [];
34461
+ lines.push(`Selected: ${selected.length === 0 ? "none" : selected.join(", ")}`);
34462
+ }
34463
+ if (item.text !== "")
34464
+ lines.push(item.text);
34465
+ return lines.join(`
34466
+ `);
34467
+ }
34468
+ function withinWindow(items, now) {
34469
+ const start = now - SESSION_ANSWERS_WINDOW_MS;
34470
+ return items.filter((item) => Date.parse(item.at) >= start);
34471
+ }
34472
+ var MAX_CHARS_TEXT = SESSION_ANSWERS_MAX_CHARS.toLocaleString("en-US");
34473
+ function leftOutLine(count) {
34474
+ return `${count} older ${count === 1 ? "item" : "items"} left out to stay under ${MAX_CHARS_TEXT} characters: run \`dispatch answers\` to read every one in full.`;
34475
+ }
34476
+ function renderSessionAnswers(items, options) {
34477
+ const shown = withinWindow(items, Number(options.now));
34478
+ const unsent = shown.length === items.length ? Math.max(0, (options.total ?? items.length) - items.length) : 0;
34479
+ const count = shown.length + unsent;
34480
+ if (count === 0)
34481
+ return;
34482
+ const header = options.cached === undefined ? SESSION_ANSWERS_MARKER : `${SESSION_ANSWERS_MARKER}
34483
+ As read at ${options.cached.readAt}; this read failed: ${failureSentence(options.cached.reason)}`;
34484
+ const blocks = [];
34485
+ let length = header.length;
34486
+ for (const item of shown) {
34487
+ const block = renderSessionAnswerItem(item);
34488
+ const after = count - blocks.length - 1;
34489
+ const needed = length + 2 + block.length + (after === 0 ? 0 : 2 + leftOutLine(after).length);
34490
+ if (needed >= SESSION_ANSWERS_MAX_CHARS)
34491
+ break;
34492
+ blocks.push(block);
34493
+ length += 2 + block.length;
34494
+ }
34495
+ const leftOut = count - blocks.length;
34496
+ return [header, ...blocks, ...leftOut === 0 ? [] : [leftOutLine(leftOut)]].join(`
34497
+
34498
+ `);
34499
+ }
34500
+ function failureSentence(reason) {
34501
+ const text = reason.replace(/\s+/g, " ").trim();
34502
+ return /[.?!]$/.test(text) ? text : `${text}.`;
34503
+ }
34504
+ function sessionAnswersFailureLine(reason) {
34505
+ return `${FAILURE_MARKER}${reason.replace(/\s+/g, " ").trim()}); run \`dispatch answers\`.]`;
34506
+ }
34507
+ var STATE_KEY = Symbol.for("legion.pi-envoy.session-answers.v2");
34508
+ var processGlobal2 = globalThis;
34509
+ var state = processGlobal2[STATE_KEY] ?? {
34510
+ sessions: new Map,
34511
+ noRouteUntil: new Map
34512
+ };
34513
+ processGlobal2[STATE_KEY] = state;
34514
+ var CACHE_FILE = "answers.json";
34515
+ function readCacheFile(directory, url) {
34516
+ try {
34517
+ const value = JSON.parse(readFileSync5(join5(directory, CACHE_FILE), "utf-8"));
34518
+ if (typeof value === "object" && value !== null && "dispatch_url" in value && typeof value.dispatch_url === "string" && value.dispatch_url === url && "read_at" in value && typeof value.read_at === "string" && "total" in value && typeof value.total === "number" && "items" in value && Array.isArray(value.items)) {
34519
+ return {
34520
+ dispatch_url: value.dispatch_url,
34521
+ read_at: value.read_at,
34522
+ total: value.total,
34523
+ items: value.items
34524
+ };
34525
+ }
34526
+ } catch {}
34527
+ return;
34528
+ }
34529
+ async function settleWithin(promise, ms, signal) {
34530
+ if (signal?.aborted === true)
34531
+ return "aborted";
34532
+ let timer;
34533
+ let onAbort;
34534
+ const stop = new Promise((resolve) => {
34535
+ timer = setTimeout(() => resolve("deadline"), ms);
34536
+ onAbort = () => resolve("aborted");
34537
+ signal?.addEventListener("abort", onAbort, { once: true });
34538
+ });
34539
+ try {
34540
+ return await Promise.race([promise, stop]);
34541
+ } finally {
34542
+ clearTimeout(timer);
34543
+ if (onAbort !== undefined)
34544
+ signal?.removeEventListener("abort", onAbort);
34545
+ }
34546
+ }
34547
+ async function readSessionAnswers(options) {
34548
+ const now = options.now ?? Date.now;
34549
+ const { dispatch, session } = options;
34550
+ if (!dispatch.enabled && dispatch.error === null) {
34551
+ return { text: undefined, source: "off", reason: dispatch.notice };
34552
+ }
34553
+ let directory;
34554
+ try {
34555
+ directory = sessionDirectory(options.env, session);
34556
+ } catch {}
34557
+ const entries = state.sessions.get(session) ?? new Map;
34558
+ state.sessions.set(session, entries);
34559
+ const carry = (cache, reason) => {
34560
+ const text = cache === undefined ? undefined : renderSessionAnswers(cache.items, {
34561
+ now: now(),
34562
+ total: cache.total,
34563
+ cached: { readAt: cache.read_at, reason }
34564
+ });
34565
+ if (cache === undefined || text === undefined) {
34566
+ return { text: sessionAnswersFailureLine(reason), source: "failure", reason };
34567
+ }
34568
+ return { text, source: "cache", readAt: cache.read_at, reason };
34569
+ };
34570
+ if (!dispatch.enabled) {
34571
+ const url = options.dispatchUrl;
34572
+ if (url === undefined)
34573
+ return carry(undefined, dispatch.error);
34574
+ const cache = entries.get(url)?.cache ?? (directory === undefined ? undefined : readCacheFile(directory, url));
34575
+ return carry(cache, dispatch.error);
34576
+ }
34577
+ const { url } = dispatch;
34578
+ const current = entries.get(url) ?? {
34579
+ cache: undefined,
34580
+ inFlight: undefined,
34581
+ overdue: false
34582
+ };
34583
+ entries.set(url, current);
34584
+ if (current.cache === undefined && directory !== undefined) {
34585
+ current.cache = readCacheFile(directory, url);
34586
+ }
34587
+ if ((state.noRouteUntil.get(url) ?? 0) > now()) {
34588
+ return carry(current.cache, NO_ANSWERS_ROUTE_REASON);
34589
+ }
34590
+ if (current.inFlight !== undefined && current.overdue) {
34591
+ return carry(current.cache, "an earlier read is still waiting on Dispatch");
34592
+ }
34593
+ let read = current.inFlight;
34594
+ if (read === undefined) {
34595
+ const client = new DispatchClient(url, dispatch.token, options.fetchImpl ?? fetch);
34596
+ const started = client.sessionAnswers(session, {
34597
+ maxChars: SESSION_ANSWERS_MAX_CHARS,
34598
+ signal: AbortSignal.timeout(READ_TIMEOUT_MS)
34599
+ }).then((response) => {
34600
+ if (!Array.isArray(response?.items) || typeof response.total !== "number") {
34601
+ return { failure: "Dispatch answered with something that is not an answers list" };
34602
+ }
34603
+ const cache = {
34604
+ dispatch_url: url,
34605
+ read_at: new Date(now()).toISOString(),
34606
+ total: response.total,
34607
+ items: response.items
34608
+ };
34609
+ current.cache = cache;
34610
+ if (directory !== undefined) {
34611
+ try {
34612
+ mkdirSync2(directory, { recursive: true, mode: 448 });
34613
+ writeAtomically2(join5(directory, CACHE_FILE), JSON.stringify(cache));
34614
+ } catch {}
34615
+ }
34616
+ return { cache };
34617
+ }, (error) => {
34618
+ if (isNoAnswersRoute(error)) {
34619
+ state.noRouteUntil.set(url, now() + NO_ROUTE_BACKOFF_MS);
34620
+ return { failure: NO_ANSWERS_ROUTE_REASON };
34621
+ }
34622
+ return { failure: messageFor(error) };
34623
+ });
34624
+ read = started.finally(() => {
34625
+ if (current.inFlight === read) {
34626
+ current.inFlight = undefined;
34627
+ current.overdue = false;
34628
+ }
34629
+ });
34630
+ current.inFlight = read;
34631
+ current.overdue = false;
34632
+ }
34633
+ const deadlineMs = options.deadlineMs ?? SESSION_ANSWERS_DEADLINE_MS;
34634
+ const outcome = await settleWithin(read, deadlineMs, options.signal);
34635
+ if (outcome === "deadline") {
34636
+ if (current.inFlight === read)
34637
+ current.overdue = true;
34638
+ return carry(current.cache, `Dispatch did not answer within ${deadlineMs} ms`);
34639
+ }
34640
+ if (outcome === "aborted") {
34641
+ return carry(current.cache, "the request was cancelled before Dispatch answered");
34642
+ }
34643
+ if ("failure" in outcome)
34644
+ return carry(current.cache, outcome.failure);
34645
+ return {
34646
+ text: renderSessionAnswers(outcome.cache.items, {
34647
+ now: now(),
34648
+ total: outcome.cache.total
34649
+ }),
34650
+ source: "fresh",
34651
+ readAt: outcome.cache.read_at
34652
+ };
34653
+ }
34654
+
34355
34655
  // ../envoy-client/src/dispatch-execute.ts
34356
34656
  var triageAdviceShown = new Set;
34357
34657
  var refGrammarProblem = "ref must be a valid dispatch:// reference such as dispatch://KEY-1, " + "dispatch://KEY-1/ask/<uuid>, dispatch://KEY-1/comment/<uuid>, " + "dispatch://KEY-1/message/<uuid>, dispatch://KEY-1/artifact/<slug>, " + "dispatch://PROJECT/artifact/<document-ref> (an artifact id, slug, or filename), " + "dispatch://KEY-1/spec#b-<block id>, dispatch://KEY-1/artifact/<slug>#b-<block id> or " + "dispatch://PROJECT/artifact/<slug>#b-<block id> (one block of a document, its id " + "percent-encoded, optionally pinned to a version of the document with @v<N> after it; for " + "dispatch read), dispatch://KEY-1/comment/<uuid>#b-<block id>, " + "dispatch://PROJECT/artifact/<slug>/comment/<uuid>#b-<block id> or " + "dispatch://KEY-1/message/<uuid>#b-<block id> (one block of a comment or message, a " + "comment's optionally pinned to a revision of the comment with @v<N> after it; for dispatch " + "read), or " + "dispatch://agent/<session id>/artifact/<slug> (a picture in a conversation on the Agents page, " + "for dispatch doc-read); a dashboard URL on this Dispatch server is accepted too";
@@ -34361,32 +34661,13 @@ function asObject(value) {
34361
34661
  }
34362
34662
 
34363
34663
  // ../envoy-client/src/dispatch-session-state.ts
34364
- var SESSION_ID = /^[A-Za-z0-9._-]{1,128}$/;
34365
34664
  var PRIVATE_DIR2 = 448;
34366
- var PRIVATE_FILE2 = 384;
34367
34665
  var IDLE_SESSION_MS = 14 * 86400000;
34368
- function sessionStateRoot(env) {
34369
- const stateDir = env["DISPATCH_STATE_DIR"];
34370
- if (stateDir)
34371
- return stateDir;
34372
- return join4(env["XDG_STATE_HOME"] || join4(homedir2(), ".local", "state"), "dispatch");
34373
- }
34374
- function sessionDirectory(env, sessionId) {
34375
- if (!SESSION_ID.test(sessionId) || sessionId === "." || sessionId === "..") {
34376
- throw new Error(`dispatch: the session id ${JSON.stringify(sessionId)} is not 1-128 letters, digits, ".", "_" or "-"`);
34377
- }
34378
- return join4(sessionStateRoot(env), "sessions", sessionId);
34379
- }
34380
34666
  function ensureDirectory(dir) {
34381
- mkdirSync2(dir, { recursive: true, mode: PRIVATE_DIR2 });
34382
- }
34383
- function writeAtomically2(path, text) {
34384
- const temporary = `${path}.${process.pid}.${Date.now()}.tmp`;
34385
- writeFileSync2(temporary, text, { mode: PRIVATE_FILE2 });
34386
- renameSync2(temporary, path);
34667
+ mkdirSync3(dir, { recursive: true, mode: PRIVATE_DIR2 });
34387
34668
  }
34388
34669
  function readResultsSince(dir, offset, onMalformed) {
34389
- const path = join4(dir, "results.jsonl");
34670
+ const path = join6(dir, "results.jsonl");
34390
34671
  let fd;
34391
34672
  try {
34392
34673
  fd = openSync3(path, "r");
@@ -34433,7 +34714,7 @@ function linesBefore(fd, offset) {
34433
34714
  }
34434
34715
  function resultsEnd(dir) {
34435
34716
  try {
34436
- return statSync3(join4(dir, "results.jsonl")).size;
34717
+ return statSync3(join6(dir, "results.jsonl")).size;
34437
34718
  } catch (error) {
34438
34719
  if (hasErrnoCode(error, "ENOENT"))
34439
34720
  return 0;
@@ -34442,7 +34723,7 @@ function resultsEnd(dir) {
34442
34723
  }
34443
34724
  function writeSessionTitle(dir, title) {
34444
34725
  ensureDirectory(dir);
34445
- writeAtomically2(join4(dir, "title"), title);
34726
+ writeAtomically2(join6(dir, "title"), title);
34446
34727
  }
34447
34728
 
34448
34729
  // ../envoy-client/src/envoy-settings.ts
@@ -35675,7 +35956,7 @@ function sessionDispatchSettings(file, env, options) {
35675
35956
  return { dispatch: offWithError(file.error), warnings: [], missing: null };
35676
35957
  const config = readEnvoyConfig(file.path, env, options);
35677
35958
  return {
35678
- dispatch: dispatchSettings(env, config),
35959
+ dispatch: dispatchSettings(env, config, { commands: options.commands }),
35679
35960
  warnings: config.kind === "read" ? config.warnings : [],
35680
35961
  missing: config.kind === "read" ? config.missing : null
35681
35962
  };
@@ -36383,7 +36664,7 @@ var import_nats2 = __toESM(require_mod4(), 1);
36383
36664
 
36384
36665
  // package.json
36385
36666
  var name = "@sjawhar/pi-envoy";
36386
- var version2 = "13.5.1";
36667
+ var version2 = "13.6.0";
36387
36668
 
36388
36669
  // src/agent-stream.ts
36389
36670
  var encoder2 = new TextEncoder;
@@ -36705,7 +36986,7 @@ class AgentStreamPublisher {
36705
36986
  }
36706
36987
 
36707
36988
  // src/card-wake.ts
36708
- import { randomUUID } from "crypto";
36989
+ import { randomUUID as randomUUID2 } from "crypto";
36709
36990
  var STARTUP_CARD_CAP_MS = 30000;
36710
36991
  var STARTUP_TURN_CAP_MS = 30000;
36711
36992
  var STARTUP_TURN_POLL_MS = 1000;
@@ -36778,7 +37059,7 @@ class CardWake {
36778
37059
  const setup = idle === false && !this.#runActive;
36779
37060
  const wake = startup ? "startup" : setup || targetedAside ? undefined : "fold";
36780
37061
  const details = {
36781
- envoyCard: randomUUID(),
37062
+ envoyCard: randomUUID2(),
36782
37063
  ...wake !== undefined && { wake }
36783
37064
  };
36784
37065
  if (startup) {
@@ -36994,6 +37275,21 @@ function transcriptPictures(entries) {
36994
37275
  return [...shown];
36995
37276
  }
36996
37277
 
37278
+ // src/context-message.ts
37279
+ function leadingText(message, role) {
37280
+ if (typeof message !== "object" || message === null || !("role" in message) || message.role !== role || !("content" in message) || !Array.isArray(message.content)) {
37281
+ return;
37282
+ }
37283
+ const [first] = message.content;
37284
+ if (typeof first === "object" && first !== null && "text" in first && typeof first.text === "string") {
37285
+ return first.text;
37286
+ }
37287
+ return;
37288
+ }
37289
+ function userTextMessage(text) {
37290
+ return { role: "user", content: [{ type: "text", text }], timestamp: 0 };
37291
+ }
37292
+
36997
37293
  // src/dispatch-first.ts
36998
37294
  function withDispatchFirst(messages, context) {
36999
37295
  let index = 0;
@@ -37003,18 +37299,10 @@ function withDispatchFirst(messages, context) {
37003
37299
  break;
37004
37300
  index += 1;
37005
37301
  }
37006
- const present = messages[index];
37007
- if (typeof present === "object" && present !== null && "role" in present && present.role === "user" && "content" in present && Array.isArray(present.content)) {
37008
- const [first] = present.content;
37009
- if (typeof first === "object" && first !== null && "text" in first && typeof first.text === "string" && first.text.startsWith(DISPATCH_FIRST_MARKER)) {
37010
- return;
37011
- }
37302
+ if (leadingText(messages[index], "user")?.startsWith(DISPATCH_FIRST_MARKER) === true) {
37303
+ return;
37012
37304
  }
37013
- return [
37014
- ...messages.slice(0, index),
37015
- { role: "user", content: [{ type: "text", text: context }], timestamp: 0 },
37016
- ...messages.slice(index)
37017
- ];
37305
+ return [...messages.slice(0, index), userTextMessage(context), ...messages.slice(index)];
37018
37306
  }
37019
37307
 
37020
37308
  // src/dispatch-user-turn.ts
@@ -37303,6 +37591,99 @@ function opensAsk({
37303
37591
  }
37304
37592
  }
37305
37593
 
37594
+ // src/session-answers-context.ts
37595
+ var SIDE_TURN_NOTICE = "Ephemeral side-channel turn; reuses current conversation context.";
37596
+ var HANDOFF_PROMPT = `<critical>
37597
+ Write a handoff document for another instance of yourself.`;
37598
+ var DECIDED_KEY = Symbol.for("legion.pi-envoy.session-answers-requests.v1");
37599
+ var processGlobal3 = globalThis;
37600
+ var decided = processGlobal3[DECIDED_KEY] ?? new WeakSet;
37601
+ processGlobal3[DECIDED_KEY] = decided;
37602
+ function hostText(message, role) {
37603
+ return typeof message === "object" && message !== null && "attribution" in message && message.attribution === "agent" ? leadingText(message, role) : undefined;
37604
+ }
37605
+ function endsWithSessionAnswers(messages) {
37606
+ const text = leadingText(messages.at(-1), "user");
37607
+ return text !== undefined && isSessionAnswersText(text);
37608
+ }
37609
+ function isSideTurn(messages) {
37610
+ if (hostText(messages.at(-1), "user") === undefined)
37611
+ return false;
37612
+ for (let index = messages.length - 2;index >= 0; index -= 1) {
37613
+ const message = messages[index];
37614
+ const role = typeof message === "object" && message !== null && "role" in message ? message.role : undefined;
37615
+ if (role !== "user" && role !== "assistant") {
37616
+ return hostText(message, "developer")?.includes(SIDE_TURN_NOTICE) === true;
37617
+ }
37618
+ }
37619
+ return false;
37620
+ }
37621
+ function entryMessage2(entry) {
37622
+ if (typeof entry !== "object" || entry === null || !("type" in entry))
37623
+ return;
37624
+ if (entry.type === "message") {
37625
+ return "message" in entry && typeof entry.message === "object" && entry.message !== null ? entry.message : undefined;
37626
+ }
37627
+ const role = entry.type === "custom_message" ? "custom" : entry.type === "branch_summary" ? "branchSummary" : undefined;
37628
+ if (role === undefined)
37629
+ return;
37630
+ const timestamp = "timestamp" in entry && typeof entry.timestamp === "string" ? new Date(entry.timestamp).getTime() : undefined;
37631
+ return { role, timestamp };
37632
+ }
37633
+ function branchPosition(messages, entries) {
37634
+ const last = messages.at(-1);
37635
+ if (typeof last !== "object" || last === null || !("timestamp" in last) || !("role" in last)) {
37636
+ return { at: "absent" };
37637
+ }
37638
+ let later = false;
37639
+ let tip;
37640
+ for (let index = entries.length - 1;index >= 0; index -= 1) {
37641
+ const entry = entries[index];
37642
+ const message = entryMessage2(entry);
37643
+ if (message === undefined)
37644
+ continue;
37645
+ tip ??= typeof entry === "object" && entry !== null && "id" in entry ? String(entry.id) : "";
37646
+ if (message.role === last.role && message.timestamp === last.timestamp) {
37647
+ return later ? { at: "before" } : { at: "last", tip };
37648
+ }
37649
+ const failed = message.role === "assistant" && (message.stopReason === "error" || message.stopReason === "aborted");
37650
+ if (!failed)
37651
+ later = true;
37652
+ }
37653
+ return { at: "absent" };
37654
+ }
37655
+ var CONVERSIONS_KEY = Symbol.for("legion.pi-envoy.session-answers-conversions.v1");
37656
+ var conversionsGlobal = globalThis;
37657
+ var conversions = conversionsGlobal[CONVERSIONS_KEY] ?? new WeakMap;
37658
+ conversionsGlobal[CONVERSIONS_KEY] = conversions;
37659
+ async function withSessionAnswers(messages, request) {
37660
+ if (decided.has(messages) || endsWithSessionAnswers(messages))
37661
+ return;
37662
+ decided.add(messages);
37663
+ if (isSideTurn(messages) || hostText(messages.at(-1), "user")?.startsWith(HANDOFF_PROMPT) === true) {
37664
+ return;
37665
+ }
37666
+ const position = branchPosition(messages, request.branch());
37667
+ const previous = conversions.get(request.session);
37668
+ if (position.at === "before") {
37669
+ conversions.set(request.session, "cut");
37670
+ return;
37671
+ }
37672
+ const key = position.at === "last" ? [
37673
+ position.tip,
37674
+ ...messages.map((message) => typeof message === "object" && message !== null ? `${"role" in message ? String(message.role) : ""}@${"timestamp" in message ? String(message.timestamp) : ""}` : "")
37675
+ ].join(`
37676
+ `) : undefined;
37677
+ conversions.set(request.session, { key, afterCut: previous === "cut" });
37678
+ if (key !== undefined && typeof previous === "object" && previous.key === key && !previous.afterCut && request.compacting()) {
37679
+ return;
37680
+ }
37681
+ const text = await request.read();
37682
+ if (text === undefined)
37683
+ return;
37684
+ return [...messages, userTextMessage(text)];
37685
+ }
37686
+
37306
37687
  // src/side-turn.ts
37307
37688
  function btwPrompt(question) {
37308
37689
  return [
@@ -41420,10 +41801,39 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
41420
41801
  }
41421
41802
  registerEnvoyWhoamiCommand(pi, replyAddress);
41422
41803
  }
41804
+ const sessionAnswersText = async (context) => {
41805
+ const session = await replyAddress(context, context.sessionManager.getSessionId());
41806
+ if (session === "")
41807
+ return;
41808
+ try {
41809
+ const read = await readSessionAnswers({
41810
+ session,
41811
+ dispatch: sessionDispatchSettings(CONFIG_FILE, process.env, {
41812
+ cwd: process.cwd(),
41813
+ commands: "kept"
41814
+ }).dispatch,
41815
+ env: process.env
41816
+ });
41817
+ return read.text;
41818
+ } catch (error) {
41819
+ logger3.warn(`envoy: people's answers could not be read: ${messageFor(error)}`);
41820
+ return sessionAnswersFailureLine(messageFor(error));
41821
+ }
41822
+ };
41423
41823
  if (atStart.dispatch.enabled) {
41424
- pi.on("context", async (event) => {
41425
- const messages = withDispatchFirst(event.messages, DISPATCH_FIRST_CONTEXT);
41426
- return messages === undefined ? undefined : { messages };
41824
+ pi.on("context", async (event, context) => {
41825
+ const withSkill = withDispatchFirst(event.messages, DISPATCH_FIRST_CONTEXT);
41826
+ const messages = await withSessionAnswers(withSkill ?? event.messages, {
41827
+ branch: () => context.sessionManager.getBranch?.() ?? [],
41828
+ session: context.sessionManager,
41829
+ compacting: () => {
41830
+ const live = liveAgentSession(context.sessionManager.getSessionId());
41831
+ return live !== undefined && (("isCompacting" in live) && live.isCompacting === true || ("compactionSpeculation" in live) && live.compactionSpeculation === "running");
41832
+ },
41833
+ read: () => sessionAnswersText(context)
41834
+ });
41835
+ const result = messages ?? withSkill;
41836
+ return result === undefined ? undefined : { messages: result };
41427
41837
  });
41428
41838
  }
41429
41839
  pi.on("before_agent_start", async (event, context) => {