@sjawhar/pi-envoy 15.1.2 → 15.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -105,8 +105,8 @@ set -g set-clipboard on
105
105
 
106
106
  A session with Dispatch configured — a top-level session, a Legion pane or a `task` subagent —
107
107
  sends two extra user messages with every model request of its conversation. At the head, after
108
- any compaction summary, it sends the `dispatch-first` skill, whose text never changes. At the
109
- tail, after the request's last message, it sends what people wrote to the session in the last 72
108
+ any compaction summary, it sends the `dispatch-first` skill, whose text never changes. It also
109
+ sends what people wrote to the session in the last 72
110
110
  hours that Dispatch delivered to it: answers to its asks, replies on them and in its comment
111
111
  threads, comments on its documents and routed issues, mentions, and messages, newest first and
112
112
  word for word. A subagent reads its parent's list. The list stays under 8,000 characters (at most 7,999): the oldest
@@ -119,9 +119,15 @@ own `404 NOT_FOUND` "no route for …". Against that Dispatch a request carries
119
119
  `dispatch answers` cannot read it either; a list read before from it is still carried, its
120
120
  left-out line naming no command; the log says once per session that the Dispatch has no answers
121
121
  route; and that Dispatch is not asked again for 5 minutes. Any other answer, a proxy's 404 page or
122
- a 200 that is no answers list included, is a failed read. The list sits at the tail so that a
123
- change in it costs only its own tokens: the cached conversation before it is sent byte for byte as
124
- before.
122
+ a 200 that is no answers list included, is a failed read.
123
+
124
+ The list goes after the request's last message only on the request where it first shows an item,
125
+ or new words in one. On every request after that it stays right after the message it followed
126
+ there, so the request ends with its own last message and the model does not take a list with
127
+ nothing new in it for a new turn; it keeps that place when it only loses items or its header
128
+ changes. After a compaction summarizes that message, or in a new process, the list goes after the
129
+ last message once more. It is never at the head, so a change in it costs only the bytes after it,
130
+ and a list that keeps its place is inside the cached prefix of the next request.
125
131
 
126
132
  Oh My Pi also builds requests that are not turns of the conversation from it; those carry the
127
133
  skill but no list, and wait on no read: a side turn (a Dispatch BTW, the stop-time self-check,
package/dist/dispatch.js CHANGED
@@ -14979,7 +14979,7 @@ var messageValidation = {
14979
14979
  },
14980
14980
  message: "issue is required unless in_reply_to names a message delivered to this session, which is the one message with no issue."
14981
14981
  };
14982
- var readOwner = documentOwnerValidation(true);
14982
+ var readOwner = documentOwnerValidation(false);
14983
14983
  var readValidation = {
14984
14984
  check: (value) => {
14985
14985
  const input = value;
@@ -14987,7 +14987,7 @@ var readValidation = {
14987
14987
  return readOwner.check(value);
14988
14988
  return input.issue === undefined && input.project === undefined && input.artifact === undefined && input.ref === undefined;
14989
14989
  },
14990
- message: `${readOwner.message} message stands alone: it names the conversation, so name no issue, project, artifact, or ref with it.`
14990
+ message: "Exactly one of issue and project is required; project alone lists its documents, and with artifact names one. " + "message stands alone: it names the conversation, so name no issue, project, artifact, or ref with it."
14991
14991
  };
14992
14992
  var ISSUE_COMPONENTS_MODES = ["inherit", "explicit", "none"];
14993
14993
  function componentsArgument(z) {
@@ -15246,7 +15246,7 @@ var dispatchToolSpecs = [
15246
15246
  body: z.string({ max: DISPATCH_BODY_MAX }).describe(`Review comment, at most ${DISPATCH_BODY_MAX} characters.`),
15247
15247
  reply_to: z.string().describe("A comment id (uuid); replying to any comment in a thread continues that thread (an " + "ask's clarification thread included). A block reference to one block of the comment " + "(dispatch://KEY/comment/<id>#b-<block id>) replies to that comment and names the " + "passage the reply answers. To reply to an ask, use reply_to_ask with the ask id, or " + "with a reference to one of its parts, instead.").optional(),
15248
15248
  reply_to_ask: z.string().describe("Optional ask id to reply to, threading this comment under that question. A block " + "reference to one part of the ask (dispatch://KEY/ask/<id>#b-<part id>, the id an " + "option or the answer carries) threads under that ask and names the part the reply " + "answers. Mutually exclusive with reply_to.").optional(),
15249
- turn: z.enum(["agent", "human"]).describe("Only with reply_to_ask: who holds the turn after this reply. agent: a progress note - " + "you keep the turn and the ask stays 'Waiting on agents' for the human; human (default): " + "you need the human to act - the ask returns to 'Waiting on you'.").optional(),
15249
+ turn: z.enum(["agent", "human"]).describe("Only with reply_to_ask: who holds the turn after this reply. agent: a progress note - " + "you keep the turn and the ask stays 'Waiting on agents' for the human; human (default): " + "you need the human to act - the ask returns to 'Waiting on you'. human does not " + "apply to an approval request a newer version moved: it stays with you until dispatch " + "request-approval hands it back at the current version.").optional(),
15250
15250
  images: imagesArgument(z, "the issue (or the project document's project)", `the ${DISPATCH_BODY_MAX}-character body limit`)
15251
15251
  }),
15252
15252
  validation: commentValidation
@@ -15292,7 +15292,7 @@ var dispatchToolSpecs = [
15292
15292
  ops: [{ op: "delete_column", block: "table-123", index: 1 }],
15293
15293
  precondition: { blocks: [{ id: "table-123", token: "sha256:current-table-token" }] }
15294
15294
  },
15295
- description: "Apply deterministic document edits: replace or delete quoted text, insert markdown at an anchor, retype an identified paragraph or typed block into a schema-declared typed block, delete or move a whole block by its id, or delete a table row or column in place. " + "Do not use it for review feedback or for reading; use dispatch comment, dispatch suggest, or dispatch doc-read instead. " + `For replace, delete, and quote anchors, find text as rendered: inline Markdown (**bold**, \`code\`) is tolerated and must be balanced; a leading '# ' matches a heading at any level. replace is inline: with is the new text of the matched span, so a marker of a different kind from the block's own stays literal text ('4. Design' written into a heading). A with that opens with a marker of the same kind as the matched block's own would write it twice and is INVALID_OP - including prose that merely looks like one ('1999. was a year' into an ordered item), which you write as text by escaping it ('1999\\. was a year'). The exception is a heading rename whose find carried a heading marker: replace(find="## Old", with="## New") gives '## New', and a different level applies only when find named the heading's actual level (find "## Old" with "### New" makes it an h3), since '# ' selects a heading without naming its level. A task item (\`- [ ]\` / \`- [x]\`) is ticked the same way: when find matches from the start of the item's text and with opens with '[x] ' or '[ ] ', the opening sets the item's box and the rest is its new text (replace(find="Write it", with="[x] Write it") ticks it); the same opening over a plain list item or a paragraph stays literal text. Any non-empty with that renders to no text - a line indented four spaces or a tab, which markdown reads as a code block, or whitespace alone - is INVALID_OP rather than a silent deletion; pass an empty with to delete the matched text on purpose - a list item, quote, typed block or footnote definition left holding only the emptied paragraph keeps it. ` + "with cannot open a new block: after a hard line break inside with (two trailing spaces, or a backslash, before the newline) a heading, bullet, '1.'/'1)' ordered, or '>' blockquote marker is INVALID_OP too, since that line would stay escaped text inside the matched block - use insert, plus delete for what it replaces, to add the block. A hard break in with is itself INVALID_OP when the matched text is in a heading or a table cell, which are written on one line. In a table cell, with is the cell's text: write a | in it bare, in code too, since code whose text has an odd run of backslashes right before a | cannot be stored in a cell and is INVALID_OP, naming the cell. " + "A delete whose find is a block's entire text removes the block (a list emptied of its items goes too); delete with block removes any block by id, and move with block relocates one. A delete or retype that would take an ask block out of the document while its ask is open is refused, with nothing sent. delete_row and delete_column take a table block and a zero-based index, preserving the table block id and refusing to remove cells with open asks or unresolved comments. " + `Insert and move anchors also accept "start", "end", "heading:<exact heading text>", and "block:<id>"; dispatch doc-read --blocks lists every block's id, type, opening words and token, and each table's rows and cells with the indexes delete_row and delete_column take (GET /api/v1/artifacts/{artifact UUID}/blocks serves the same list). ` + "Optionally require the state just read: precondition selects exactly one of a document token from dispatch doc-read, or block {id, token} values from dispatch doc-read --blocks. A block guard must include every block the batch changes; Dispatch resolves quote targets and rejects an uncovered batch rather than applying it. Use a document token for insert or move, which depend on document order. Prefer block tokens when the covered content blocks are independent sections. Tokens include inline marks, so a fresh human comment also makes a stale edit fail. PRECONDITION_FAILED means re-read; EDIT_QUEUE_FULL means back off before retrying. " + "The result carries the document token this edit produced, so a chain of guarded edits passes each result's token as the next edit's precondition with no dispatch doc-read between them. " + "A batch that leaves the document exactly as it was mints no version, named or not, and the result says nothing changed and names each operation that did nothing. " + "A change a browser removes while the edit is in flight is never reported as applied: EDIT_LOST_TO_CONCURRENT_CHANGE means the write was refused and nothing was written, so re-read the document and decide again, as with PRECONDITION_FAILED; lost_ops on a successful result names operations whose text the live document no longer has, because the deletion landed after the version was written. " + "One replace per paragraph: more new paragraphs go in one insert after the last one you rewrote, since two inserts at one anchor come out reversed; read the passage back with dispatch doc-read afterwards. " + "Each decision block the edit adds gets the related-item check dispatch ask gets, waiting at most five seconds for all of them together: the result prints, after its first line, `Decision block <id>:` and what that check found, that it found nothing, or that it was not made and why. " + "A block id written as {#id} longer than 256 bytes is stored, but its block is no graph node, so no reference reaches it. " + `The spec holds requirements, design, and decisions - never progress, status, or timestamps; a record of open items or progress is a document of its own. ${OWNER_REFERENCE} ${SPEC_WRITING_POINTER}`,
15295
+ description: "Apply deterministic document edits: replace or delete quoted text, insert markdown at an anchor, retype an identified paragraph or typed block into a schema-declared typed block, delete or move a whole block by its id, or delete a table row or column in place. " + "Do not use it for review feedback or for reading; use dispatch comment, dispatch suggest, or dispatch doc-read instead. " + "For replace, delete, and quote anchors, find text as rendered: inline Markdown (**bold**, `code`) is tolerated and must be balanced; a leading '# ' matches a heading at any level. A find that opens with a list marker ('- ', '5. ', with an optional '[ ] ' or '[x] ' after it) and matches no text as written selects an item of that kind of list whose text starts with the rest, its number not matched and a box matching only a task item in that state. A find or quote anchor stays inside one block, and in a table inside one cell: ' | ' is the boundary markdown writes between two cells, not text a cell holds, so a quote that runs across cells is refused, naming the cells; change several cells with one operation per cell in the same batch, and anchor on one cell's text. replace is inline: with is the new text of the matched span, so a marker of a different kind from the block's own stays literal text ('4. Design' written into a heading). A with that opens with a marker of the same kind as the matched block's own would write it twice and is INVALID_OP - including prose that merely looks like one ('1999. was a year' into an ordered item), which you write as text by escaping it ('1999\\. was a year'). The exceptions are an item a find's list marker selected (it matched no text as written): replace(find=\"5. Old\", with=\"5. New\") gives the item the text 'New' under its own number, and a with that is the marker alone is INVALID_OP; and a heading rename whose find carried a heading marker: replace(find=\"## Old\", with=\"## New\") gives '## New', where a different level applies only when find named the heading's actual level (find \"## Old\" with \"### New\" makes it an h3), since '# ' selects a heading without naming its level. A task item (`- [ ]` / `- [x]`) is ticked the same way: when find matches from the start of the item's text and with opens with '[x] ' or '[ ] ', the opening sets the item's box and the rest is its new text (replace(find=\"Write it\", with=\"[x] Write it\") ticks it); the same opening over a plain list item or a paragraph stays literal text. Any non-empty with that renders to no text - a line indented four spaces or a tab, which markdown reads as a code block, or whitespace alone - is INVALID_OP rather than a silent deletion; pass an empty with to delete the matched text on purpose - a list item, quote, typed block or footnote definition left holding only the emptied paragraph keeps it. " + "with cannot open a new block: after a hard line break inside with (two trailing spaces, or a backslash, before the newline) a heading, bullet, '1.'/'1)' ordered, or '>' blockquote marker is INVALID_OP too, since that line would stay escaped text inside the matched block - use insert, plus delete for what it replaces, to add the block. A hard break in with is itself INVALID_OP when the matched text is in a heading or a table cell, which are written on one line. In a table cell, with is the cell's text: write a | in it bare, in code too, since code whose text has an odd run of backslashes right before a | cannot be stored in a cell and is INVALID_OP, naming the cell. " + "A delete whose find is a block's entire text removes the block (a list emptied of its items goes too); delete with block removes any block by id, and move with block relocates one. A delete or retype that would take an ask block out of the document while its ask is open is refused, with nothing sent. delete_row and delete_column take a table block and a zero-based index, preserving the table block id and refusing to remove cells with open asks or unresolved comments. " + `Insert and move anchors also accept "start", "end", "heading:<exact heading text>", and "block:<id>"; dispatch doc-read --blocks lists every block's id, type, opening words and token, and each table's rows and cells with the indexes delete_row and delete_column take (GET /api/v1/artifacts/{artifact UUID}/blocks serves the same list). ` + "Optionally require the state just read: precondition selects exactly one of a document token from dispatch doc-read, or block {id, token} values from dispatch doc-read --blocks. A block guard must include every block the batch changes; Dispatch resolves quote targets and rejects an uncovered batch rather than applying it. Use a document token for insert or move, which depend on document order. Prefer block tokens when the covered content blocks are independent sections. Tokens include inline marks, so a fresh human comment also makes a stale edit fail. PRECONDITION_FAILED means re-read; EDIT_QUEUE_FULL means back off before retrying. " + "The result carries the document token this edit produced, so a chain of guarded edits passes each result's token as the next edit's precondition with no dispatch doc-read between them. " + "A batch that leaves the document exactly as it was mints no version, named or not, and the result says nothing changed and names each operation that did nothing. " + "A change a browser removes while the edit is in flight is never reported as applied: EDIT_LOST_TO_CONCURRENT_CHANGE means the write was refused and nothing was written, so re-read the document and decide again, as with PRECONDITION_FAILED; lost_ops on a successful result names operations whose text the live document no longer has, because the deletion landed after the version was written. " + "One replace per paragraph: more new paragraphs go in one insert after the last one you rewrote, since two inserts at one anchor come out reversed; read the passage back with dispatch doc-read afterwards. " + "Each decision block the edit adds gets the related-item check dispatch ask gets, waiting at most five seconds for all of them together: the result prints, after its first line, `Decision block <id>:` and what that check found, that it found nothing, or that it was not made and why. " + "A block id written as {#id} longer than 256 bytes is stored, but its block is no graph node, so no reference reaches it. " + `The spec holds requirements, design, and decisions - never progress, status, or timestamps; a record of open items or progress is a document of its own. ${OWNER_REFERENCE} ${SPEC_WRITING_POINTER}`,
15296
15296
  arguments: (z) => ({
15297
15297
  issue: z.string().describe(ISSUE_REFERENCE).optional(),
15298
15298
  project: z.string().describe("Project key owning the document.").optional(),
@@ -15370,7 +15370,7 @@ var dispatchToolSpecs = [
15370
15370
  {
15371
15371
  name: "dispatch_read",
15372
15372
  example: { issue: "DSP-1" },
15373
- description: "Read an issue or document summary, targeted ask, or targeted comment reply chain, or the conversation " + "a message belongs to. Do not use it for document contents; use dispatch doc-read instead. Supply ref, issue, " + "issue plus artifact (one of its documents), or project plus artifact; or message alone, which reads a human's direct message to this session and every " + "reply to it (they belong to no issue). A document summary names its issue, reference, versions and approval. " + "An anchored comment or ask also says where its quote sits, as `Position:`: the block's path from the top, " + "and in a table the row (0 is the header), the cells before the anchored one, and the column's header; " + "`Position: unavailable (<code>)` when Dispatch could not read the document: `DOC_SERVICE_UNAVAILABLE` " + "(try again shortly), `DOC_SCHEMA` (the document needs repair), `DOCUMENT_UNLOADABLE` (the document " + "needs a rebuild) or `INTERNAL`. " + "An issue read carries a `Progress:` line, `tasks 3/7, children 2/5`: its spec's task-list items " + "(`- [ ]` / `- [x]`, nested lists included) and its direct children, each done of total and each only " + "when it has any (`Progress: none` otherwise). " + `An issue read, and its dispatch://KEY/log, lists the issue's last ${DEFAULT_ISSUE_READ_EVENTS} events, oldest first; ` + "--events N lists the last N, and --all-events every one. " + "Every read ends with `Referenced by:` (what cites or hangs off this node, each with its dispatch:// address, " + "an excerpt, and when) and `Links:` (what it cites), so tracing provenance is one call. " + "A block read prints `Block:`, `Document:`, `Changed in version:` and `Text:`, then those two sections; a pinned one adds " + "the block's text at that version and whether it is unchanged, changed or removed since, and an absent block, unpinned, " + "reads `No block <id> in <document>.` " + "The pictures the shown messages, asks and comments embed come back as images you see, newest first, at most 8 " + "and 10 MiB of them per read, each a PNG, JPEG, GIF or WebP of at most 3,750,000 bytes (5 MB of base64); a `Pictures:` section names each " + "one shown, in order, and the rest by reference, for dispatch doc-read. A picture this session was already shown is named, not sent again " + "(every request carries the session's history, and the provider refuses one over 32 MB); dispatch doc-read shows it again. " + OWNER_REFERENCE,
15373
+ description: "Read an issue or document summary, targeted ask, or targeted comment reply chain, or the conversation " + "a message belongs to. Do not use it for document contents; use dispatch doc-read instead. Supply ref, issue, " + "issue plus artifact (one of its documents), project plus artifact, or project alone, which lists the project's documents on no issue and nothing more; or message alone, which reads a human's direct message to this session and every " + "reply to it (they belong to no issue). A document summary names its issue, reference, versions and approval. " + "An issue read lists every document, picture and file the issue holds under `Documents:`, each by slug, filename and kind. " + "An anchored comment or ask also says where its quote sits, as `Position:`: the block's path from the top, " + "and in a table the row (0 is the header), the cells before the anchored one, and the column's header; " + "`Position: unavailable (<code>)` when Dispatch could not read the document: `DOC_SERVICE_UNAVAILABLE` " + "(try again shortly), `DOC_SCHEMA` (the document needs repair), `DOCUMENT_UNLOADABLE` (the document " + "needs a rebuild) or `INTERNAL`. " + "An issue read carries a `Progress:` line, `tasks 3/7, children 2/5`: its spec's task-list items " + "(`- [ ]` / `- [x]`, nested lists included) and its direct children, each done of total and each only " + "when it has any (`Progress: none` otherwise). " + `An issue read, and its dispatch://KEY/log, lists the issue's last ${DEFAULT_ISSUE_READ_EVENTS} events, oldest first; ` + "--events N lists the last N, and --all-events every one. " + "Every read ends with `Referenced by:` (what cites or hangs off this node, each with its dispatch:// address, " + "an excerpt, and when) and `Links:` (what it cites), so tracing provenance is one call. " + "A block read prints `Block:`, `Document:`, `Changed in version:` and `Text:`, then those two sections; a pinned one adds " + "the block's text at that version and whether it is unchanged, changed or removed since, and an absent block, unpinned, " + "reads `No block <id> in <document>.` " + "The pictures the shown messages, asks and comments embed come back as images you see, newest first, at most 8 " + "and 10 MiB of them per read, each a PNG, JPEG, GIF or WebP of at most 3,750,000 bytes (5 MB of base64); a `Pictures:` section names each " + "one shown, in order, and the rest by reference, for dispatch doc-read. A picture this session was already shown is named, not sent again " + "(every request carries the session's history, and the provider refuses one over 32 MB); dispatch doc-read shows it again. " + OWNER_REFERENCE,
15374
15374
  arguments: (z) => ({
15375
15375
  issue: z.string().describe(ISSUE_REFERENCE).optional(),
15376
15376
  project: z.string().describe("Project key owning the document.").optional(),
@@ -19268,7 +19268,7 @@ async function resolveArtifact(client, owner, artifactReference, { canonical = f
19268
19268
  const artifacts = routed === undefined ? unlinked : [routed, ...unlinked.filter((candidate) => candidate.id !== routed.id)];
19269
19269
  return {
19270
19270
  owner,
19271
- artifact: artifactByReference(artifacts, artifactReference, "project", canonical)
19271
+ artifact: artifactByReference(artifacts, artifactReference, owner, canonical)
19272
19272
  };
19273
19273
  }
19274
19274
  const issue = await client.getIssue(owner.issue);
@@ -19276,10 +19276,13 @@ async function resolveArtifact(client, owner, artifactReference, { canonical = f
19276
19276
  if (artifactReference === undefined || artifactReference === "spec") {
19277
19277
  artifact = issue.artifacts.find((candidate) => candidate.primary || candidate.id === issue.primary_artifact_id);
19278
19278
  } else {
19279
- artifact = artifactByReference(issue.artifacts, artifactReference, "issue", canonical);
19279
+ artifact = artifactByReference(issue.artifacts, artifactReference, { kind: "issue", issue: issue.key }, canonical);
19280
19280
  }
19281
19281
  if (!artifact) {
19282
- throw new DocumentNotFoundError(documentReferenceProblem(artifactReference ?? "spec", issue.artifacts, "issue"));
19282
+ throw new DocumentNotFoundError(documentReferenceProblem(artifactReference ?? "spec", issue.artifacts, {
19283
+ kind: "issue",
19284
+ issue: issue.key
19285
+ }));
19283
19286
  }
19284
19287
  return { owner, issue, artifact };
19285
19288
  }
@@ -19300,15 +19303,85 @@ async function documentTargets(client, resolution) {
19300
19303
  }
19301
19304
  var documentHintLimit = 8;
19302
19305
  function documentReferenceProblem(reference, documents, owner, ambiguous = false) {
19303
- const hints = documents.slice(0, documentHintLimit).map((document) => `${document.slug} (${document.name})`);
19306
+ const scope = owner.kind;
19307
+ const busy = !ambiguous && documents.length > documentHintLimit;
19308
+ const hints = (busy ? documentsNearest(reference, documents) : documents).slice(0, documentHintLimit).map((document) => `${document.slug} (${document.name})`);
19304
19309
  const list = hints.length === 0 ? "none" : hints.join(", ");
19305
- return ambiguous ? `"${reference}" names ${documents.length} documents on this ${owner}; use a slug: ${list}` : `document "${reference}" not found by slug; this ${owner}'s documents: ${list}`;
19310
+ if (busy) {
19311
+ const read = owner.kind === "issue" ? `dispatch read --issue ${owner.issue}` : `dispatch read --project ${owner.project}`;
19312
+ const counted = documents.every((document) => (document.kind ?? "doc") === "doc") ? "documents" : "documents and files";
19313
+ return `document "${reference}" not found by slug; this ${scope}'s ${documents.length} ${counted} include: ${list}; ${read} lists them all`;
19314
+ }
19315
+ return ambiguous ? `"${reference}" names ${documents.length} documents on this ${scope}; use a slug: ${list}` : `document "${reference}" not found by slug; this ${scope}'s documents: ${list}`;
19316
+ }
19317
+ function documentsNearest(reference, documents) {
19318
+ return documents.map((document, index) => ({
19319
+ document,
19320
+ index,
19321
+ ...documentCloseness(reference, document.slug, document.name)
19322
+ })).sort((a, b) => {
19323
+ if (a.near !== b.near)
19324
+ return a.near ? -1 : 1;
19325
+ if (a.near && a.distance !== b.distance)
19326
+ return a.distance - b.distance;
19327
+ return b.index - a.index;
19328
+ }).map(({ document }) => document);
19329
+ }
19330
+ function documentListLines(documents) {
19331
+ return documents.length === 0 ? ["- none"] : documents.map((document) => `- ${document.slug} (${document.name}, ${document.kind})`);
19332
+ }
19333
+ function documentCloseness(reference, slug, name) {
19334
+ const wanted = [...reference.replace(/[A-Z]/g, (letter) => letter.toLowerCase())];
19335
+ const limit = Math.max(2, Math.floor(wanted.length / 3));
19336
+ let distance = Number.POSITIVE_INFINITY;
19337
+ for (const candidate of [slug, name]) {
19338
+ const label = [...candidate.replace(/[A-Z]/g, (letter) => letter.toLowerCase())];
19339
+ let edits = boundedEditDistance(wanted, label, limit);
19340
+ if (wanted.length >= 4 && label.join("").includes(wanted.join("")) || label.length >= 4 && wanted.join("").includes(label.join(""))) {
19341
+ edits = Math.abs(label.length - wanted.length);
19342
+ } else if (edits > limit) {
19343
+ continue;
19344
+ }
19345
+ distance = Math.min(distance, edits);
19346
+ }
19347
+ return distance === Number.POSITIVE_INFINITY ? { distance: limit + 1, near: false } : { distance, near: true };
19348
+ }
19349
+ function boundedEditDistance(a, b, limit) {
19350
+ if (Math.abs(a.length - b.length) > limit)
19351
+ return limit + 1;
19352
+ let previous = Array.from({ length: b.length + 1 }, (_, j) => j);
19353
+ let current = new Array(b.length + 1).fill(0);
19354
+ for (let i = 1;i <= a.length; i++) {
19355
+ current[0] = i;
19356
+ let smallest = i;
19357
+ for (let j = 1;j <= b.length; j++) {
19358
+ const substitution = previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1);
19359
+ current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, substitution);
19360
+ smallest = Math.min(smallest, current[j]);
19361
+ }
19362
+ if (smallest > limit)
19363
+ return limit + 1;
19364
+ [previous, current] = [current, previous];
19365
+ }
19366
+ return Math.min(previous[b.length], limit + 1);
19306
19367
  }
19307
19368
  var askHintLimit = 8;
19308
19369
  function askIDInputProblem(asks, scope) {
19309
19370
  const hints = asks.slice(0, askHintLimit).map((ask) => `${ask.id.slice(0, 8)}\u2026 ${textHead(ask.question)}`);
19310
19371
  return `ask IDs are UUIDs; use the full ask ID; ${scope} open asks: ${hints.length === 0 ? "none" : hints.join(", ")}`;
19311
19372
  }
19373
+ async function movedApprovalLine(client, askID) {
19374
+ const ask = (await client.getAsk(askID).catch(() => {
19375
+ return;
19376
+ }))?.ask;
19377
+ const approval = ask?.approval;
19378
+ if (ask?.kind !== "approval" || approval === undefined)
19379
+ return;
19380
+ if (approval.requested_version >= approval.version)
19381
+ return;
19382
+ const owner = ask.issue_key === null ? `--project ${ask.approval_artifact?.project ?? "<project>"} --artifact ${approval.artifact_id}` : ask.approval_artifact?.primary === true ? `--issue ${ask.issue_key}` : `--issue ${ask.issue_key} --artifact ${approval.artifact_id}`;
19383
+ return `The reply did not hand the ask to the human: it is the approval request for ${approval.name} ` + `at version ${approval.requested_version}, and ${approval.name} is now version ${approval.version}. ` + "No reply hands a moved approval request back. Once the human has agreed to every point in " + `version ${approval.version}, run: dispatch request-approval ${owner} --summary ` + `'<what changed since version ${approval.requested_version}>'`;
19384
+ }
19312
19385
  async function invalidReplyToAskProblem(client, owner, resolved) {
19313
19386
  if (owner.kind === "issue") {
19314
19387
  const issue = resolved?.issue ?? await client.getIssue(owner.issue);
@@ -19465,6 +19538,8 @@ function issueSummary(issue, events, references, graph, linkBase, titles) {
19465
19538
  ...specApproval === undefined ? [] : [`Spec ${specApproval.replace(/^Approval/, "approval")}`],
19466
19539
  "External links:",
19467
19540
  ...issue.external_links.length === 0 ? ["- none"] : issue.external_links.map((link) => `- ${link.url}${link.kind === undefined ? "" : ` (${link.kind})`}`),
19541
+ "Documents:",
19542
+ ...documentListLines(issue.artifacts ?? []),
19468
19543
  "Open asks:",
19469
19544
  ...asks.length === 0 ? ["- none"] : asks.map((ask) => `- ${ask.id}: ${ask.question}`),
19470
19545
  "References:",
@@ -20713,9 +20788,11 @@ async function executeDispatchTool(input) {
20713
20788
  });
20714
20789
  if (replyToAsk !== undefined) {
20715
20790
  const askState = comment.ask_waiting_on === undefined ? "" : `; ask now waiting on ${comment.ask_waiting_on}`;
20791
+ const moved = requestedTurn !== "agent" && comment.ask_waiting_on === "agent" ? await movedApprovalLine(client, replyToAsk) : undefined;
20716
20792
  return {
20717
20793
  text: [
20718
20794
  `Replied on ask ${replyToAsk} (comment ${comment.id}${askState}). ${await followsAsk(commentOwner, input.subscriptions)}`,
20795
+ ...moved === undefined ? [] : [moved],
20719
20796
  ...adviceLines
20720
20797
  ].join(`
20721
20798
  `),
@@ -21186,6 +21263,19 @@ ${handoff.body}`,
21186
21263
  }
21187
21264
  };
21188
21265
  }
21266
+ const projectOwner = documentOwner();
21267
+ if (projectOwner.kind === "project" && optionalString(args, "artifact") === undefined) {
21268
+ const documents = await client.listProjectArtifacts(projectOwner.project, true);
21269
+ return {
21270
+ text: [
21271
+ `Project: ${projectOwner.project}`,
21272
+ "Documents:",
21273
+ ...documentListLines(documents)
21274
+ ].join(`
21275
+ `),
21276
+ details: { project: projectOwner.project }
21277
+ };
21278
+ }
21189
21279
  const documentReference = optionalString(args, "artifact");
21190
21280
  if (documentOwner().kind === "project" || documentReference !== undefined) {
21191
21281
  const resolved = await resolveDocument(documentOwner(), documentReference);
package/dist/envoy.js CHANGED
@@ -30099,7 +30099,7 @@ var messageValidation = {
30099
30099
  },
30100
30100
  message: "issue is required unless in_reply_to names a message delivered to this session, which is the one message with no issue."
30101
30101
  };
30102
- var readOwner = documentOwnerValidation(true);
30102
+ var readOwner = documentOwnerValidation(false);
30103
30103
  var readValidation = {
30104
30104
  check: (value) => {
30105
30105
  const input = value;
@@ -30107,7 +30107,7 @@ var readValidation = {
30107
30107
  return readOwner.check(value);
30108
30108
  return input.issue === undefined && input.project === undefined && input.artifact === undefined && input.ref === undefined;
30109
30109
  },
30110
- message: `${readOwner.message} message stands alone: it names the conversation, so name no issue, project, artifact, or ref with it.`
30110
+ message: "Exactly one of issue and project is required; project alone lists its documents, and with artifact names one. " + "message stands alone: it names the conversation, so name no issue, project, artifact, or ref with it."
30111
30111
  };
30112
30112
  var ISSUE_COMPONENTS_MODES = ["inherit", "explicit", "none"];
30113
30113
  function componentsArgument(z) {
@@ -30366,7 +30366,7 @@ var dispatchToolSpecs = [
30366
30366
  body: z.string({ max: DISPATCH_BODY_MAX }).describe(`Review comment, at most ${DISPATCH_BODY_MAX} characters.`),
30367
30367
  reply_to: z.string().describe("A comment id (uuid); replying to any comment in a thread continues that thread (an " + "ask's clarification thread included). A block reference to one block of the comment " + "(dispatch://KEY/comment/<id>#b-<block id>) replies to that comment and names the " + "passage the reply answers. To reply to an ask, use reply_to_ask with the ask id, or " + "with a reference to one of its parts, instead.").optional(),
30368
30368
  reply_to_ask: z.string().describe("Optional ask id to reply to, threading this comment under that question. A block " + "reference to one part of the ask (dispatch://KEY/ask/<id>#b-<part id>, the id an " + "option or the answer carries) threads under that ask and names the part the reply " + "answers. Mutually exclusive with reply_to.").optional(),
30369
- turn: z.enum(["agent", "human"]).describe("Only with reply_to_ask: who holds the turn after this reply. agent: a progress note - " + "you keep the turn and the ask stays 'Waiting on agents' for the human; human (default): " + "you need the human to act - the ask returns to 'Waiting on you'.").optional(),
30369
+ turn: z.enum(["agent", "human"]).describe("Only with reply_to_ask: who holds the turn after this reply. agent: a progress note - " + "you keep the turn and the ask stays 'Waiting on agents' for the human; human (default): " + "you need the human to act - the ask returns to 'Waiting on you'. human does not " + "apply to an approval request a newer version moved: it stays with you until dispatch " + "request-approval hands it back at the current version.").optional(),
30370
30370
  images: imagesArgument(z, "the issue (or the project document's project)", `the ${DISPATCH_BODY_MAX}-character body limit`)
30371
30371
  }),
30372
30372
  validation: commentValidation
@@ -30412,7 +30412,7 @@ var dispatchToolSpecs = [
30412
30412
  ops: [{ op: "delete_column", block: "table-123", index: 1 }],
30413
30413
  precondition: { blocks: [{ id: "table-123", token: "sha256:current-table-token" }] }
30414
30414
  },
30415
- description: "Apply deterministic document edits: replace or delete quoted text, insert markdown at an anchor, retype an identified paragraph or typed block into a schema-declared typed block, delete or move a whole block by its id, or delete a table row or column in place. " + "Do not use it for review feedback or for reading; use dispatch comment, dispatch suggest, or dispatch doc-read instead. " + `For replace, delete, and quote anchors, find text as rendered: inline Markdown (**bold**, \`code\`) is tolerated and must be balanced; a leading '# ' matches a heading at any level. replace is inline: with is the new text of the matched span, so a marker of a different kind from the block's own stays literal text ('4. Design' written into a heading). A with that opens with a marker of the same kind as the matched block's own would write it twice and is INVALID_OP - including prose that merely looks like one ('1999. was a year' into an ordered item), which you write as text by escaping it ('1999\\. was a year'). The exception is a heading rename whose find carried a heading marker: replace(find="## Old", with="## New") gives '## New', and a different level applies only when find named the heading's actual level (find "## Old" with "### New" makes it an h3), since '# ' selects a heading without naming its level. A task item (\`- [ ]\` / \`- [x]\`) is ticked the same way: when find matches from the start of the item's text and with opens with '[x] ' or '[ ] ', the opening sets the item's box and the rest is its new text (replace(find="Write it", with="[x] Write it") ticks it); the same opening over a plain list item or a paragraph stays literal text. Any non-empty with that renders to no text - a line indented four spaces or a tab, which markdown reads as a code block, or whitespace alone - is INVALID_OP rather than a silent deletion; pass an empty with to delete the matched text on purpose - a list item, quote, typed block or footnote definition left holding only the emptied paragraph keeps it. ` + "with cannot open a new block: after a hard line break inside with (two trailing spaces, or a backslash, before the newline) a heading, bullet, '1.'/'1)' ordered, or '>' blockquote marker is INVALID_OP too, since that line would stay escaped text inside the matched block - use insert, plus delete for what it replaces, to add the block. A hard break in with is itself INVALID_OP when the matched text is in a heading or a table cell, which are written on one line. In a table cell, with is the cell's text: write a | in it bare, in code too, since code whose text has an odd run of backslashes right before a | cannot be stored in a cell and is INVALID_OP, naming the cell. " + "A delete whose find is a block's entire text removes the block (a list emptied of its items goes too); delete with block removes any block by id, and move with block relocates one. A delete or retype that would take an ask block out of the document while its ask is open is refused, with nothing sent. delete_row and delete_column take a table block and a zero-based index, preserving the table block id and refusing to remove cells with open asks or unresolved comments. " + `Insert and move anchors also accept "start", "end", "heading:<exact heading text>", and "block:<id>"; dispatch doc-read --blocks lists every block's id, type, opening words and token, and each table's rows and cells with the indexes delete_row and delete_column take (GET /api/v1/artifacts/{artifact UUID}/blocks serves the same list). ` + "Optionally require the state just read: precondition selects exactly one of a document token from dispatch doc-read, or block {id, token} values from dispatch doc-read --blocks. A block guard must include every block the batch changes; Dispatch resolves quote targets and rejects an uncovered batch rather than applying it. Use a document token for insert or move, which depend on document order. Prefer block tokens when the covered content blocks are independent sections. Tokens include inline marks, so a fresh human comment also makes a stale edit fail. PRECONDITION_FAILED means re-read; EDIT_QUEUE_FULL means back off before retrying. " + "The result carries the document token this edit produced, so a chain of guarded edits passes each result's token as the next edit's precondition with no dispatch doc-read between them. " + "A batch that leaves the document exactly as it was mints no version, named or not, and the result says nothing changed and names each operation that did nothing. " + "A change a browser removes while the edit is in flight is never reported as applied: EDIT_LOST_TO_CONCURRENT_CHANGE means the write was refused and nothing was written, so re-read the document and decide again, as with PRECONDITION_FAILED; lost_ops on a successful result names operations whose text the live document no longer has, because the deletion landed after the version was written. " + "One replace per paragraph: more new paragraphs go in one insert after the last one you rewrote, since two inserts at one anchor come out reversed; read the passage back with dispatch doc-read afterwards. " + "Each decision block the edit adds gets the related-item check dispatch ask gets, waiting at most five seconds for all of them together: the result prints, after its first line, `Decision block <id>:` and what that check found, that it found nothing, or that it was not made and why. " + "A block id written as {#id} longer than 256 bytes is stored, but its block is no graph node, so no reference reaches it. " + `The spec holds requirements, design, and decisions - never progress, status, or timestamps; a record of open items or progress is a document of its own. ${OWNER_REFERENCE} ${SPEC_WRITING_POINTER}`,
30415
+ description: "Apply deterministic document edits: replace or delete quoted text, insert markdown at an anchor, retype an identified paragraph or typed block into a schema-declared typed block, delete or move a whole block by its id, or delete a table row or column in place. " + "Do not use it for review feedback or for reading; use dispatch comment, dispatch suggest, or dispatch doc-read instead. " + "For replace, delete, and quote anchors, find text as rendered: inline Markdown (**bold**, `code`) is tolerated and must be balanced; a leading '# ' matches a heading at any level. A find that opens with a list marker ('- ', '5. ', with an optional '[ ] ' or '[x] ' after it) and matches no text as written selects an item of that kind of list whose text starts with the rest, its number not matched and a box matching only a task item in that state. A find or quote anchor stays inside one block, and in a table inside one cell: ' | ' is the boundary markdown writes between two cells, not text a cell holds, so a quote that runs across cells is refused, naming the cells; change several cells with one operation per cell in the same batch, and anchor on one cell's text. replace is inline: with is the new text of the matched span, so a marker of a different kind from the block's own stays literal text ('4. Design' written into a heading). A with that opens with a marker of the same kind as the matched block's own would write it twice and is INVALID_OP - including prose that merely looks like one ('1999. was a year' into an ordered item), which you write as text by escaping it ('1999\\. was a year'). The exceptions are an item a find's list marker selected (it matched no text as written): replace(find=\"5. Old\", with=\"5. New\") gives the item the text 'New' under its own number, and a with that is the marker alone is INVALID_OP; and a heading rename whose find carried a heading marker: replace(find=\"## Old\", with=\"## New\") gives '## New', where a different level applies only when find named the heading's actual level (find \"## Old\" with \"### New\" makes it an h3), since '# ' selects a heading without naming its level. A task item (`- [ ]` / `- [x]`) is ticked the same way: when find matches from the start of the item's text and with opens with '[x] ' or '[ ] ', the opening sets the item's box and the rest is its new text (replace(find=\"Write it\", with=\"[x] Write it\") ticks it); the same opening over a plain list item or a paragraph stays literal text. Any non-empty with that renders to no text - a line indented four spaces or a tab, which markdown reads as a code block, or whitespace alone - is INVALID_OP rather than a silent deletion; pass an empty with to delete the matched text on purpose - a list item, quote, typed block or footnote definition left holding only the emptied paragraph keeps it. " + "with cannot open a new block: after a hard line break inside with (two trailing spaces, or a backslash, before the newline) a heading, bullet, '1.'/'1)' ordered, or '>' blockquote marker is INVALID_OP too, since that line would stay escaped text inside the matched block - use insert, plus delete for what it replaces, to add the block. A hard break in with is itself INVALID_OP when the matched text is in a heading or a table cell, which are written on one line. In a table cell, with is the cell's text: write a | in it bare, in code too, since code whose text has an odd run of backslashes right before a | cannot be stored in a cell and is INVALID_OP, naming the cell. " + "A delete whose find is a block's entire text removes the block (a list emptied of its items goes too); delete with block removes any block by id, and move with block relocates one. A delete or retype that would take an ask block out of the document while its ask is open is refused, with nothing sent. delete_row and delete_column take a table block and a zero-based index, preserving the table block id and refusing to remove cells with open asks or unresolved comments. " + `Insert and move anchors also accept "start", "end", "heading:<exact heading text>", and "block:<id>"; dispatch doc-read --blocks lists every block's id, type, opening words and token, and each table's rows and cells with the indexes delete_row and delete_column take (GET /api/v1/artifacts/{artifact UUID}/blocks serves the same list). ` + "Optionally require the state just read: precondition selects exactly one of a document token from dispatch doc-read, or block {id, token} values from dispatch doc-read --blocks. A block guard must include every block the batch changes; Dispatch resolves quote targets and rejects an uncovered batch rather than applying it. Use a document token for insert or move, which depend on document order. Prefer block tokens when the covered content blocks are independent sections. Tokens include inline marks, so a fresh human comment also makes a stale edit fail. PRECONDITION_FAILED means re-read; EDIT_QUEUE_FULL means back off before retrying. " + "The result carries the document token this edit produced, so a chain of guarded edits passes each result's token as the next edit's precondition with no dispatch doc-read between them. " + "A batch that leaves the document exactly as it was mints no version, named or not, and the result says nothing changed and names each operation that did nothing. " + "A change a browser removes while the edit is in flight is never reported as applied: EDIT_LOST_TO_CONCURRENT_CHANGE means the write was refused and nothing was written, so re-read the document and decide again, as with PRECONDITION_FAILED; lost_ops on a successful result names operations whose text the live document no longer has, because the deletion landed after the version was written. " + "One replace per paragraph: more new paragraphs go in one insert after the last one you rewrote, since two inserts at one anchor come out reversed; read the passage back with dispatch doc-read afterwards. " + "Each decision block the edit adds gets the related-item check dispatch ask gets, waiting at most five seconds for all of them together: the result prints, after its first line, `Decision block <id>:` and what that check found, that it found nothing, or that it was not made and why. " + "A block id written as {#id} longer than 256 bytes is stored, but its block is no graph node, so no reference reaches it. " + `The spec holds requirements, design, and decisions - never progress, status, or timestamps; a record of open items or progress is a document of its own. ${OWNER_REFERENCE} ${SPEC_WRITING_POINTER}`,
30416
30416
  arguments: (z) => ({
30417
30417
  issue: z.string().describe(ISSUE_REFERENCE).optional(),
30418
30418
  project: z.string().describe("Project key owning the document.").optional(),
@@ -30490,7 +30490,7 @@ var dispatchToolSpecs = [
30490
30490
  {
30491
30491
  name: "dispatch_read",
30492
30492
  example: { issue: "DSP-1" },
30493
- description: "Read an issue or document summary, targeted ask, or targeted comment reply chain, or the conversation " + "a message belongs to. Do not use it for document contents; use dispatch doc-read instead. Supply ref, issue, " + "issue plus artifact (one of its documents), or project plus artifact; or message alone, which reads a human's direct message to this session and every " + "reply to it (they belong to no issue). A document summary names its issue, reference, versions and approval. " + "An anchored comment or ask also says where its quote sits, as `Position:`: the block's path from the top, " + "and in a table the row (0 is the header), the cells before the anchored one, and the column's header; " + "`Position: unavailable (<code>)` when Dispatch could not read the document: `DOC_SERVICE_UNAVAILABLE` " + "(try again shortly), `DOC_SCHEMA` (the document needs repair), `DOCUMENT_UNLOADABLE` (the document " + "needs a rebuild) or `INTERNAL`. " + "An issue read carries a `Progress:` line, `tasks 3/7, children 2/5`: its spec's task-list items " + "(`- [ ]` / `- [x]`, nested lists included) and its direct children, each done of total and each only " + "when it has any (`Progress: none` otherwise). " + `An issue read, and its dispatch://KEY/log, lists the issue's last ${DEFAULT_ISSUE_READ_EVENTS} events, oldest first; ` + "--events N lists the last N, and --all-events every one. " + "Every read ends with `Referenced by:` (what cites or hangs off this node, each with its dispatch:// address, " + "an excerpt, and when) and `Links:` (what it cites), so tracing provenance is one call. " + "A block read prints `Block:`, `Document:`, `Changed in version:` and `Text:`, then those two sections; a pinned one adds " + "the block's text at that version and whether it is unchanged, changed or removed since, and an absent block, unpinned, " + "reads `No block <id> in <document>.` " + "The pictures the shown messages, asks and comments embed come back as images you see, newest first, at most 8 " + "and 10 MiB of them per read, each a PNG, JPEG, GIF or WebP of at most 3,750,000 bytes (5 MB of base64); a `Pictures:` section names each " + "one shown, in order, and the rest by reference, for dispatch doc-read. A picture this session was already shown is named, not sent again " + "(every request carries the session's history, and the provider refuses one over 32 MB); dispatch doc-read shows it again. " + OWNER_REFERENCE,
30493
+ description: "Read an issue or document summary, targeted ask, or targeted comment reply chain, or the conversation " + "a message belongs to. Do not use it for document contents; use dispatch doc-read instead. Supply ref, issue, " + "issue plus artifact (one of its documents), project plus artifact, or project alone, which lists the project's documents on no issue and nothing more; or message alone, which reads a human's direct message to this session and every " + "reply to it (they belong to no issue). A document summary names its issue, reference, versions and approval. " + "An issue read lists every document, picture and file the issue holds under `Documents:`, each by slug, filename and kind. " + "An anchored comment or ask also says where its quote sits, as `Position:`: the block's path from the top, " + "and in a table the row (0 is the header), the cells before the anchored one, and the column's header; " + "`Position: unavailable (<code>)` when Dispatch could not read the document: `DOC_SERVICE_UNAVAILABLE` " + "(try again shortly), `DOC_SCHEMA` (the document needs repair), `DOCUMENT_UNLOADABLE` (the document " + "needs a rebuild) or `INTERNAL`. " + "An issue read carries a `Progress:` line, `tasks 3/7, children 2/5`: its spec's task-list items " + "(`- [ ]` / `- [x]`, nested lists included) and its direct children, each done of total and each only " + "when it has any (`Progress: none` otherwise). " + `An issue read, and its dispatch://KEY/log, lists the issue's last ${DEFAULT_ISSUE_READ_EVENTS} events, oldest first; ` + "--events N lists the last N, and --all-events every one. " + "Every read ends with `Referenced by:` (what cites or hangs off this node, each with its dispatch:// address, " + "an excerpt, and when) and `Links:` (what it cites), so tracing provenance is one call. " + "A block read prints `Block:`, `Document:`, `Changed in version:` and `Text:`, then those two sections; a pinned one adds " + "the block's text at that version and whether it is unchanged, changed or removed since, and an absent block, unpinned, " + "reads `No block <id> in <document>.` " + "The pictures the shown messages, asks and comments embed come back as images you see, newest first, at most 8 " + "and 10 MiB of them per read, each a PNG, JPEG, GIF or WebP of at most 3,750,000 bytes (5 MB of base64); a `Pictures:` section names each " + "one shown, in order, and the rest by reference, for dispatch doc-read. A picture this session was already shown is named, not sent again " + "(every request carries the session's history, and the provider refuses one over 32 MB); dispatch doc-read shows it again. " + OWNER_REFERENCE,
30494
30494
  arguments: (z) => ({
30495
30495
  issue: z.string().describe(ISSUE_REFERENCE).optional(),
30496
30496
  project: z.string().describe("Project key owning the document.").optional(),
@@ -36641,15 +36641,26 @@ function withinWindow(items, now) {
36641
36641
  const start = now - SESSION_ANSWERS_WINDOW_MS;
36642
36642
  return items.filter((item) => Date.parse(item.at) >= start);
36643
36643
  }
36644
+ function sessionAnswersWords(items) {
36645
+ return items.map((item) => JSON.stringify([
36646
+ item.kind,
36647
+ item.id,
36648
+ item.author.id,
36649
+ item.at,
36650
+ item.edited_at ?? null,
36651
+ item.selected ?? null,
36652
+ item.text
36653
+ ]));
36654
+ }
36644
36655
  var MAX_CHARS_TEXT = SESSION_ANSWERS_MAX_CHARS.toLocaleString("en-US");
36645
36656
  function leftOutLine(count, namesCommand) {
36646
36657
  const counted = `${count} older ${count === 1 ? "item" : "items"} left out to stay under ${MAX_CHARS_TEXT} characters`;
36647
36658
  return namesCommand ? `${counted}: run \`dispatch answers\` to read every one in full.` : `${counted}.`;
36648
36659
  }
36649
- function renderSessionAnswers(items, options) {
36650
- const shown = withinWindow(items, Number(options.now));
36651
- const unsent = shown.length === items.length ? Math.max(0, (options.total ?? items.length) - items.length) : 0;
36652
- const count = shown.length + unsent;
36660
+ function renderShown(items, options) {
36661
+ const inWindow = withinWindow(items, Number(options.now));
36662
+ const unsent = inWindow.length === items.length ? Math.max(0, (options.total ?? items.length) - items.length) : 0;
36663
+ const count = inWindow.length + unsent;
36653
36664
  if (count === 0)
36654
36665
  return;
36655
36666
  const header = options.cached === undefined ? SESSION_ANSWERS_MARKER : `${SESSION_ANSWERS_MARKER}
@@ -36657,7 +36668,7 @@ As read at ${options.cached.readAt}; this read failed: ${failureSentence(options
36657
36668
  const namesCommand = options.withoutCommand !== true;
36658
36669
  const blocks = [];
36659
36670
  let length = header.length;
36660
- for (const item of shown) {
36671
+ for (const item of inWindow) {
36661
36672
  const block = renderSessionAnswerItem(item);
36662
36673
  const after = count - blocks.length - 1;
36663
36674
  const needed = length + 2 + block.length + (after === 0 ? 0 : 2 + leftOutLine(after, namesCommand).length);
@@ -36667,9 +36678,14 @@ As read at ${options.cached.readAt}; this read failed: ${failureSentence(options
36667
36678
  length += 2 + block.length;
36668
36679
  }
36669
36680
  const leftOut = count - blocks.length;
36670
- return [header, ...blocks, ...leftOut === 0 ? [] : [leftOutLine(leftOut, namesCommand)]].join(`
36681
+ const text = [
36682
+ header,
36683
+ ...blocks,
36684
+ ...leftOut === 0 ? [] : [leftOutLine(leftOut, namesCommand)]
36685
+ ].join(`
36671
36686
 
36672
36687
  `);
36688
+ return { text, shown: inWindow.slice(0, blocks.length) };
36673
36689
  }
36674
36690
  function failureSentence(reason) {
36675
36691
  const text = reason.replace(/\s+/g, " ").trim();
@@ -36731,18 +36747,24 @@ async function readSessionAnswers(options) {
36731
36747
  const entries = state.sessions.get(session) ?? new Map;
36732
36748
  state.sessions.set(session, entries);
36733
36749
  const carry = (cache, reason, noRoute = false) => {
36734
- const text = cache === undefined ? undefined : renderSessionAnswers(cache.items, {
36750
+ const rendered = cache === undefined ? undefined : renderShown(cache.items, {
36735
36751
  now: now(),
36736
36752
  total: cache.total,
36737
36753
  cached: { readAt: cache.read_at, reason },
36738
36754
  withoutCommand: noRoute
36739
36755
  });
36740
- if (cache === undefined || text === undefined) {
36756
+ if (cache === undefined || rendered === undefined) {
36741
36757
  if (noRoute)
36742
36758
  return { text: undefined, source: "unavailable", reason };
36743
36759
  return { text: sessionAnswersFailureLine(reason), source: "failure", reason };
36744
36760
  }
36745
- return { text, source: "cache", readAt: cache.read_at, reason };
36761
+ return {
36762
+ text: rendered.text,
36763
+ source: "cache",
36764
+ readAt: cache.read_at,
36765
+ words: sessionAnswersWords(rendered.shown),
36766
+ reason
36767
+ };
36746
36768
  };
36747
36769
  if (!dispatch.enabled) {
36748
36770
  const url = options.dispatchUrl;
@@ -36832,13 +36854,12 @@ async function readSessionAnswers(options) {
36832
36854
  return noRoute();
36833
36855
  if ("failure" in outcome)
36834
36856
  return carry(current.cache, outcome.failure);
36857
+ const rendered = renderShown(outcome.cache.items, { now: now(), total: outcome.cache.total });
36835
36858
  return {
36836
- text: renderSessionAnswers(outcome.cache.items, {
36837
- now: now(),
36838
- total: outcome.cache.total
36839
- }),
36859
+ text: rendered?.text,
36840
36860
  source: "fresh",
36841
- readAt: outcome.cache.read_at
36861
+ readAt: outcome.cache.read_at,
36862
+ words: sessionAnswersWords(rendered?.shown ?? [])
36842
36863
  };
36843
36864
  }
36844
36865
 
@@ -37191,7 +37212,7 @@ async function resolveArtifact(client, owner, artifactReference, { canonical = f
37191
37212
  const artifacts = routed === undefined ? unlinked : [routed, ...unlinked.filter((candidate) => candidate.id !== routed.id)];
37192
37213
  return {
37193
37214
  owner,
37194
- artifact: artifactByReference(artifacts, artifactReference, "project", canonical)
37215
+ artifact: artifactByReference(artifacts, artifactReference, owner, canonical)
37195
37216
  };
37196
37217
  }
37197
37218
  const issue = await client.getIssue(owner.issue);
@@ -37199,10 +37220,13 @@ async function resolveArtifact(client, owner, artifactReference, { canonical = f
37199
37220
  if (artifactReference === undefined || artifactReference === "spec") {
37200
37221
  artifact = issue.artifacts.find((candidate) => candidate.primary || candidate.id === issue.primary_artifact_id);
37201
37222
  } else {
37202
- artifact = artifactByReference(issue.artifacts, artifactReference, "issue", canonical);
37223
+ artifact = artifactByReference(issue.artifacts, artifactReference, { kind: "issue", issue: issue.key }, canonical);
37203
37224
  }
37204
37225
  if (!artifact) {
37205
- throw new DocumentNotFoundError(documentReferenceProblem(artifactReference ?? "spec", issue.artifacts, "issue"));
37226
+ throw new DocumentNotFoundError(documentReferenceProblem(artifactReference ?? "spec", issue.artifacts, {
37227
+ kind: "issue",
37228
+ issue: issue.key
37229
+ }));
37206
37230
  }
37207
37231
  return { owner, issue, artifact };
37208
37232
  }
@@ -37223,9 +37247,64 @@ async function documentTargets(client, resolution) {
37223
37247
  }
37224
37248
  var documentHintLimit = 8;
37225
37249
  function documentReferenceProblem(reference, documents, owner, ambiguous = false) {
37226
- const hints = documents.slice(0, documentHintLimit).map((document) => `${document.slug} (${document.name})`);
37250
+ const scope = owner.kind;
37251
+ const busy = !ambiguous && documents.length > documentHintLimit;
37252
+ const hints = (busy ? documentsNearest(reference, documents) : documents).slice(0, documentHintLimit).map((document) => `${document.slug} (${document.name})`);
37227
37253
  const list = hints.length === 0 ? "none" : hints.join(", ");
37228
- return ambiguous ? `"${reference}" names ${documents.length} documents on this ${owner}; use a slug: ${list}` : `document "${reference}" not found by slug; this ${owner}'s documents: ${list}`;
37254
+ if (busy) {
37255
+ const read = owner.kind === "issue" ? `dispatch read --issue ${owner.issue}` : `dispatch read --project ${owner.project}`;
37256
+ const counted = documents.every((document) => (document.kind ?? "doc") === "doc") ? "documents" : "documents and files";
37257
+ return `document "${reference}" not found by slug; this ${scope}'s ${documents.length} ${counted} include: ${list}; ${read} lists them all`;
37258
+ }
37259
+ return ambiguous ? `"${reference}" names ${documents.length} documents on this ${scope}; use a slug: ${list}` : `document "${reference}" not found by slug; this ${scope}'s documents: ${list}`;
37260
+ }
37261
+ function documentsNearest(reference, documents) {
37262
+ return documents.map((document, index) => ({
37263
+ document,
37264
+ index,
37265
+ ...documentCloseness(reference, document.slug, document.name)
37266
+ })).sort((a, b) => {
37267
+ if (a.near !== b.near)
37268
+ return a.near ? -1 : 1;
37269
+ if (a.near && a.distance !== b.distance)
37270
+ return a.distance - b.distance;
37271
+ return b.index - a.index;
37272
+ }).map(({ document }) => document);
37273
+ }
37274
+ function documentCloseness(reference, slug, name) {
37275
+ const wanted = [...reference.replace(/[A-Z]/g, (letter) => letter.toLowerCase())];
37276
+ const limit = Math.max(2, Math.floor(wanted.length / 3));
37277
+ let distance = Number.POSITIVE_INFINITY;
37278
+ for (const candidate of [slug, name]) {
37279
+ const label = [...candidate.replace(/[A-Z]/g, (letter) => letter.toLowerCase())];
37280
+ let edits = boundedEditDistance(wanted, label, limit);
37281
+ if (wanted.length >= 4 && label.join("").includes(wanted.join("")) || label.length >= 4 && wanted.join("").includes(label.join(""))) {
37282
+ edits = Math.abs(label.length - wanted.length);
37283
+ } else if (edits > limit) {
37284
+ continue;
37285
+ }
37286
+ distance = Math.min(distance, edits);
37287
+ }
37288
+ return distance === Number.POSITIVE_INFINITY ? { distance: limit + 1, near: false } : { distance, near: true };
37289
+ }
37290
+ function boundedEditDistance(a, b, limit) {
37291
+ if (Math.abs(a.length - b.length) > limit)
37292
+ return limit + 1;
37293
+ let previous = Array.from({ length: b.length + 1 }, (_, j) => j);
37294
+ let current = new Array(b.length + 1).fill(0);
37295
+ for (let i = 1;i <= a.length; i++) {
37296
+ current[0] = i;
37297
+ let smallest = i;
37298
+ for (let j = 1;j <= b.length; j++) {
37299
+ const substitution = previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1);
37300
+ current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, substitution);
37301
+ smallest = Math.min(smallest, current[j]);
37302
+ }
37303
+ if (smallest > limit)
37304
+ return limit + 1;
37305
+ [previous, current] = [current, previous];
37306
+ }
37307
+ return Math.min(previous[b.length], limit + 1);
37229
37308
  }
37230
37309
  async function liveBlocks(client, artifact) {
37231
37310
  const before = await client.docRead(artifact.id);
@@ -38201,7 +38280,7 @@ var import_nats2 = __toESM(require_mod4(), 1);
38201
38280
 
38202
38281
  // package.json
38203
38282
  var name = "@sjawhar/pi-envoy";
38204
- var version2 = "15.1.2";
38283
+ var version2 = "15.2.0";
38205
38284
  var package_default = {
38206
38285
  name,
38207
38286
  version: version2,
@@ -39883,6 +39962,14 @@ function endsWithSessionAnswers(messages) {
39883
39962
  const text = leadingText(messages.at(-1), "user");
39884
39963
  return text !== undefined && isSessionAnswersText(text);
39885
39964
  }
39965
+ function messageKey(message) {
39966
+ if (typeof message !== "object" || message === null)
39967
+ return "";
39968
+ const role = "role" in message ? String(message.role) : "";
39969
+ const timestamp = "timestamp" in message ? String(message.timestamp) : "";
39970
+ const call = "toolCallId" in message ? `#${String(message.toolCallId)}` : "";
39971
+ return `${role}@${timestamp}${call}`;
39972
+ }
39886
39973
  function isSideTurn(messages) {
39887
39974
  if (hostText(messages.at(-1), "user") === undefined)
39888
39975
  return false;
@@ -39907,11 +39994,21 @@ function entryMessage2(entry) {
39907
39994
  const timestamp = "timestamp" in entry && typeof entry.timestamp === "string" ? new Date(entry.timestamp).getTime() : undefined;
39908
39995
  return { role, timestamp };
39909
39996
  }
39997
+ function failedCalls(message) {
39998
+ if (message.role !== "assistant" || message.stopReason !== "error" && message.stopReason !== "aborted") {
39999
+ return [];
40000
+ }
40001
+ return (Array.isArray(message.content) ? message.content : []).flatMap((block) => typeof block === "object" && block !== null && ("type" in block) && block.type === "toolCall" && ("id" in block) ? [String(block.id)] : []);
40002
+ }
39910
40003
  function branchPosition(messages, entries) {
39911
40004
  const last = messages.at(-1);
39912
40005
  if (typeof last !== "object" || last === null || !("timestamp" in last) || !("role" in last)) {
39913
40006
  return { at: "absent" };
39914
40007
  }
40008
+ const dropped = new Set(entries.flatMap((entry) => {
40009
+ const message = entryMessage2(entry);
40010
+ return message === undefined ? [] : failedCalls(message);
40011
+ }));
39915
40012
  let later = false;
39916
40013
  let tip;
39917
40014
  for (let index = entries.length - 1;index >= 0; index -= 1) {
@@ -39923,7 +40020,7 @@ function branchPosition(messages, entries) {
39923
40020
  if (message.role === last.role && message.timestamp === last.timestamp) {
39924
40021
  return later ? { at: "before" } : { at: "last", tip };
39925
40022
  }
39926
- const failed = message.role === "assistant" && (message.stopReason === "error" || message.stopReason === "aborted");
40023
+ const failed = message.role === "assistant" && (message.stopReason === "error" || message.stopReason === "aborted") || message.role === "toolResult" && dropped.has(String(message.toolCallId));
39927
40024
  if (!failed)
39928
40025
  later = true;
39929
40026
  }
@@ -39933,10 +40030,39 @@ var CONVERSIONS_KEY = Symbol.for("legion.pi-envoy.session-answers-conversions.v1
39933
40030
  var conversionsGlobal = globalThis;
39934
40031
  var conversions = conversionsGlobal[CONVERSIONS_KEY] ?? new WeakMap;
39935
40032
  conversionsGlobal[CONVERSIONS_KEY] = conversions;
40033
+ var PLACEMENTS_KEY = Symbol.for("legion.pi-envoy.session-answers-placements.v1");
40034
+ var placementsGlobal = globalThis;
40035
+ var placements = placementsGlobal[PLACEMENTS_KEY] ?? new WeakMap;
40036
+ placementsGlobal[PLACEMENTS_KEY] = placements;
40037
+ function showsNew(shown, next) {
40038
+ if (shown.words === undefined || next.words === undefined)
40039
+ return shown.text !== next.text;
40040
+ const before = new Set(shown.words);
40041
+ return next.words.some((word) => !before.has(word));
40042
+ }
40043
+ function placeList(messages, carried, request, compacting) {
40044
+ const list = userTextMessage(carried.text);
40045
+ if (compacting)
40046
+ return [...messages, list];
40047
+ const sessions = placements.get(request.session) ?? new Map;
40048
+ placements.set(request.session, sessions);
40049
+ const placed = sessions.get(request.id);
40050
+ if (placed !== undefined && !showsNew(placed.carried, carried)) {
40051
+ const index = messages.findLastIndex((message) => messageKey(message) === placed.after);
40052
+ if (index >= 0) {
40053
+ sessions.set(request.id, { after: placed.after, carried });
40054
+ return [...messages.slice(0, index + 1), list, ...messages.slice(index + 1)];
40055
+ }
40056
+ }
40057
+ sessions.set(request.id, { after: messageKey(messages.at(-1)), carried });
40058
+ return [...messages, list];
40059
+ }
39936
40060
  async function withSessionAnswers(messages, request) {
39937
- if (decided.has(messages) || endsWithSessionAnswers(messages))
40061
+ if (decided.has(messages))
39938
40062
  return;
39939
40063
  decided.add(messages);
40064
+ if (endsWithSessionAnswers(messages))
40065
+ return placedLegacy(messages, request);
39940
40066
  if (isSideTurn(messages) || hostText(messages.at(-1), "user")?.startsWith(HANDOFF_PROMPT) === true) {
39941
40067
  return;
39942
40068
  }
@@ -39946,19 +40072,30 @@ async function withSessionAnswers(messages, request) {
39946
40072
  conversions.set(request.session, "cut");
39947
40073
  return;
39948
40074
  }
39949
- const key = position.at === "last" ? [
39950
- position.tip,
39951
- ...messages.map((message) => typeof message === "object" && message !== null ? `${"role" in message ? String(message.role) : ""}@${"timestamp" in message ? String(message.timestamp) : ""}` : "")
39952
- ].join(`
40075
+ const key = position.at === "last" ? [position.tip, ...messages.map(messageKey)].join(`
39953
40076
  `) : undefined;
39954
40077
  conversions.set(request.session, { key, afterCut: previous === "cut" });
39955
40078
  if (key !== undefined && typeof previous === "object" && previous.key === key && !previous.afterCut && request.compacting()) {
39956
40079
  return;
39957
40080
  }
39958
- const text = await request.read();
39959
- if (text === undefined)
40081
+ const carried = await request.read();
40082
+ if (carried === undefined)
40083
+ return;
40084
+ const placed = placeList(messages, carried, request, previous === "cut" || request.compacting());
40085
+ decided.add(placed);
40086
+ return placed;
40087
+ }
40088
+ function placedLegacy(messages, request) {
40089
+ const last = messages.at(-1);
40090
+ const text = leadingText(last, "user");
40091
+ const added = typeof last === "object" && last !== null && "timestamp" in last && last.timestamp === 0;
40092
+ if (text === undefined || !added)
39960
40093
  return;
39961
- return [...messages, userTextMessage(text)];
40094
+ const recorded = conversions.get(request.session);
40095
+ const compacting = typeof recorded === "object" && recorded.afterCut || request.compacting();
40096
+ const placed = placeList(messages.slice(0, -1), { text }, request, compacting);
40097
+ decided.add(placed);
40098
+ return placed;
39962
40099
  }
39963
40100
 
39964
40101
  // src/side-turn.ts
@@ -45573,10 +45710,10 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
45573
45710
  });
45574
45711
  if (read.notice !== undefined)
45575
45712
  logger3.warn(`envoy: ${read.notice}`);
45576
- return read.text;
45713
+ return read.text === undefined ? undefined : { text: read.text, words: read.words ?? [] };
45577
45714
  } catch (error) {
45578
45715
  logger3.warn(`envoy: people's answers could not be read: ${messageFor(error)}`);
45579
- return sessionAnswersFailureLine(messageFor(error));
45716
+ return { text: sessionAnswersFailureLine(messageFor(error)), words: [] };
45580
45717
  }
45581
45718
  };
45582
45719
  if (atStart.dispatch.enabled || inbound) {
@@ -45588,6 +45725,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
45588
45725
  const messages = await withSessionAnswers(withSkill ?? aged ?? event.messages, {
45589
45726
  branch: () => context.sessionManager.getBranch?.() ?? [],
45590
45727
  session: context.sessionManager,
45728
+ id: context.sessionManager.getSessionId(),
45591
45729
  compacting: () => {
45592
45730
  const live = liveAgentSession(context.sessionManager.getSessionId());
45593
45731
  return live !== undefined && (("isCompacting" in live) && live.isCompacting === true || ("compactionSpeculation" in live) && live.compactionSpeculation === "running");
@@ -25,12 +25,12 @@ Which machines, files or people, the numbers, then "A happens to X, or B to Y?"
25
25
  ```
26
26
 
27
27
  - In Legion, fix a clear defect in code your tree uses, hand others to the controller, and ask about decisions (`skill://legion-worker/references/findings.md`).
28
- - An open ask is the request; never repeat it in each message.
28
+ - An open ask is the request; never repeat it per message.
29
29
  - Change an open ask's block with `dispatch edit-ask`, or `doc-edit`'s `replace` or `move`. An answered ask is fixed: ask anew.
30
- - Answer a person's reply to an open ask with `dispatch comment --reply-to-ask`; `--turn agent` for a note that needs nothing from them.
30
+ - Reply on an open ask with `dispatch comment --reply-to-ask`; `--turn agent` for a note needing nothing. An approval request a newer version moved needs `request-approval` again.
31
31
  - When an answer's option and text disagree, the text wins.
32
32
  - An ask block has a block id, for `doc-edit`, and an ask id, for the ask commands. `dispatch read --ref dispatch://KEY/ask/<id>` takes either.
33
- - An ask reaches the issue's assignee. On an unassigned issue, name who must answer.
33
+ - An ask reaches the issue's assignee; if none, name who answers.
34
34
 
35
35
  ## Choosing what to work on
36
36
 
@@ -47,8 +47,7 @@ A claim, or `dispatch issue-update --route session:<your id>` (`--route ''` on r
47
47
 
48
48
  ## Close what you opened
49
49
 
50
- - An ask you opened is yours until answered or resolved. `dispatch resolve-ask` it that turn once anything makes it needless: another answer, a later write, work dropped.
51
- - Retract an ask a new one replaces.
50
+ - Resolve your open ask (`dispatch resolve-ask`) the turn it turns needless: another answer, a later write, dropped work, a replacement. If a person said keep it open, say why in its thread; they close it.
52
51
 
53
52
  ## Structure over stream
54
53
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sjawhar/pi-envoy",
3
- "version": "15.1.2",
3
+ "version": "15.2.0",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "omp": {