@sjawhar/claude-envoy 5.1.3 → 5.2.1

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.
@@ -2,5 +2,5 @@
2
2
  "name": "claude-envoy",
3
3
  "description": "Put Envoy events into the Claude Code session's own conversation and expose Envoy MCP tools.",
4
4
  "mcpServers": "./.mcp.json",
5
- "version": "5.1.3"
5
+ "version": "5.2.1"
6
6
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-envoy",
3
- "version": "5.1.3",
3
+ "version": "5.2.1",
4
4
  "description": "Put Envoy events into the Claude Code session's own conversation and expose Envoy MCP tools.",
5
5
  "mcpServers": {}
6
6
  }
@@ -14116,16 +14116,45 @@ function preconditionKept(value) {
14116
14116
  const precondition = input.precondition;
14117
14117
  return typeof precondition.document === "string" !== Array.isArray(precondition.blocks);
14118
14118
  }
14119
+ var REPLACE_OP_KEYS = {
14120
+ op: true,
14121
+ find: true,
14122
+ with: true,
14123
+ occurrence: true
14124
+ };
14125
+ var REPLACE_OP_RULE = 'A replace names with and takes find, with and occurrence alone: with "" deletes the match on purpose, and a replace without with, or with its new text under another key such as markdown, would delete the match too.';
14126
+ function replaceOpsProblem(value) {
14127
+ if (typeof value !== "object" || value === null || !("ops" in value))
14128
+ return;
14129
+ const ops = value.ops;
14130
+ if (!Array.isArray(ops))
14131
+ return;
14132
+ const problems = [];
14133
+ ops.forEach((op, index) => {
14134
+ if (typeof op !== "object" || op === null || !("op" in op) || op.op !== "replace")
14135
+ return;
14136
+ const foreign = Object.entries(op).filter(([key, held]) => REPLACE_OP_KEYS[key] !== true && held !== undefined).map(([key]) => key);
14137
+ if (foreign.length > 0) {
14138
+ problems.push(`ops[${index}] is a replace carrying ${foreign.join(" and ")}, which replace does not take: it takes find, with and occurrence, and its new text goes in with.`);
14139
+ }
14140
+ if (!("with" in op) || op.with === undefined) {
14141
+ problems.push(`ops[${index}] is a replace with no with, which would delete the text find matches: write the new text in with, or with "" to delete it on purpose.`);
14142
+ }
14143
+ });
14144
+ return problems.length === 0 ? undefined : problems.join(" ");
14145
+ }
14119
14146
  function documentEditProblem(value) {
14147
+ const replaceProblem = replaceOpsProblem(value);
14120
14148
  return brokenParts([
14121
14149
  [documentEditOwner.check(value), documentEditOwner.message],
14122
- [preconditionKept(value), PRECONDITION_RULE]
14150
+ [preconditionKept(value), PRECONDITION_RULE],
14151
+ [replaceProblem === undefined, replaceProblem ?? REPLACE_OP_RULE]
14123
14152
  ]);
14124
14153
  }
14125
14154
  var documentEditValidation = {
14126
14155
  check: (value) => documentEditProblem(value) === undefined,
14127
- message: `${documentEditOwner.message} ${PRECONDITION_RULE}`,
14128
- refusal: (value) => documentEditProblem(value) ?? `${documentEditOwner.message} ${PRECONDITION_RULE}`
14156
+ message: `${documentEditOwner.message} ${PRECONDITION_RULE} ${REPLACE_OP_RULE}`,
14157
+ refusal: (value) => documentEditProblem(value) ?? `${documentEditOwner.message} ${PRECONDITION_RULE} ${REPLACE_OP_RULE}`
14129
14158
  };
14130
14159
  var commentOwner = documentOwnerValidation(true);
14131
14160
  var COMMENT_TURN_RULE = "turn requires reply_to_ask: turn says who holds an open ask's thread after the reply. Pass reply_to_ask with the open ask's id, or drop turn.";
@@ -14594,7 +14623,7 @@ var dispatchToolSpecs = [
14594
14623
  ops: z.array(z.object({
14595
14624
  op: z.enum(DOC_EDIT_OPS).describe("Edit operation."),
14596
14625
  find: z.string().describe("Text of the target as rendered, for replace or delete; inline markdown (**bold**, `code`) is tolerated and must be balanced; a leading '# ' matches a heading. A delete of a block's entire text removes the block.").optional(),
14597
- with: z.string().describe("Replacement text for replace: inside a code block, the code's literal text as sent (line breaks at its end do not survive a read); elsewhere parsed as markdown, as insert's markdown is. Text that parses to one paragraph is written inside the matched block, where a backslash escape keeps prose that merely looks like a marker, a leading '[x] ' or '[ ] ' over a task item's text matched from its start sets the item's checkbox, and any non-empty value that renders to no text is refused - only an empty value deletes the match. Text that parses to blocks ('---' over a paragraph, a list, a table, two paragraphs) writes those blocks where the match sits, fitted as the editor fits them, and is refused, with the document unchanged, where the block holding the match cannot hold them: a heading, any cell of a table, and a typed block whose content rule they break. A leading marker of the same kind as the matched block's own is refused either way, since the block renders it already, unless it is a heading rename (where a level named by find is what lets with change it) or an item find's own marker selected. A CR LF or a lone carriage return in it is written as a line feed.").optional(),
14626
+ with: z.string().describe("Replacement text for replace, which every replace names: an empty value deletes the match on purpose. A replace takes op, find, with and occurrence alone, and one without with, or carrying any other key whatever it holds, is refused before it is sent, and by the server with 400 REPLACE_FIELDS, the document unchanged. Inside a code block, with is the code's literal text as sent (line breaks at its end do not survive a read); elsewhere parsed as markdown, as insert's markdown is. Text that parses to one paragraph is written inside the matched block, where a backslash escape keeps prose that merely looks like a marker, a leading '[x] ' or '[ ] ' over a task item's text matched from its start sets the item's checkbox, and any non-empty value that renders to no text is refused - only an empty value deletes the match. Text that parses to blocks ('---' over a paragraph, a list, a table, two paragraphs) writes those blocks where the match sits, fitted as the editor fits them, and is refused, with the document unchanged, where the block holding the match cannot hold them: a heading, any cell of a table, and a typed block whose content rule they break. A leading marker of the same kind as the matched block's own is refused either way, since the block renders it already, unless it is a heading rename (where a level named by find is what lets with change it) or an item find's own marker selected. A CR LF or a lone carriage return in it is written as a line feed.").optional(),
14598
14627
  occurrence: z.number({ int: true, min: 0 }).describe("Optional zero-based match occurrence.").optional(),
14599
14628
  markdown: z.string().describe("Markdown to insert; a CR LF or a lone carriage return in it is written as a line feed.").optional(),
14600
14629
  after: z.string().describe(`Insert or move after this anchor: a quote of the neighbouring block's text, or one of "start", "end", "heading:<exact heading text>", "block:<id>".`).optional(),
package/dist/dispatch.js CHANGED
@@ -15413,16 +15413,45 @@ function preconditionKept(value) {
15413
15413
  const precondition = input.precondition;
15414
15414
  return typeof precondition.document === "string" !== Array.isArray(precondition.blocks);
15415
15415
  }
15416
+ var REPLACE_OP_KEYS = {
15417
+ op: true,
15418
+ find: true,
15419
+ with: true,
15420
+ occurrence: true
15421
+ };
15422
+ var REPLACE_OP_RULE = 'A replace names with and takes find, with and occurrence alone: with "" deletes the match on purpose, and a replace without with, or with its new text under another key such as markdown, would delete the match too.';
15423
+ function replaceOpsProblem(value) {
15424
+ if (typeof value !== "object" || value === null || !("ops" in value))
15425
+ return;
15426
+ const ops = value.ops;
15427
+ if (!Array.isArray(ops))
15428
+ return;
15429
+ const problems = [];
15430
+ ops.forEach((op, index) => {
15431
+ if (typeof op !== "object" || op === null || !("op" in op) || op.op !== "replace")
15432
+ return;
15433
+ const foreign = Object.entries(op).filter(([key, held]) => REPLACE_OP_KEYS[key] !== true && held !== undefined).map(([key]) => key);
15434
+ if (foreign.length > 0) {
15435
+ problems.push(`ops[${index}] is a replace carrying ${foreign.join(" and ")}, which replace does not take: it takes find, with and occurrence, and its new text goes in with.`);
15436
+ }
15437
+ if (!("with" in op) || op.with === undefined) {
15438
+ problems.push(`ops[${index}] is a replace with no with, which would delete the text find matches: write the new text in with, or with "" to delete it on purpose.`);
15439
+ }
15440
+ });
15441
+ return problems.length === 0 ? undefined : problems.join(" ");
15442
+ }
15416
15443
  function documentEditProblem(value) {
15444
+ const replaceProblem = replaceOpsProblem(value);
15417
15445
  return brokenParts([
15418
15446
  [documentEditOwner.check(value), documentEditOwner.message],
15419
- [preconditionKept(value), PRECONDITION_RULE]
15447
+ [preconditionKept(value), PRECONDITION_RULE],
15448
+ [replaceProblem === undefined, replaceProblem ?? REPLACE_OP_RULE]
15420
15449
  ]);
15421
15450
  }
15422
15451
  var documentEditValidation = {
15423
15452
  check: (value) => documentEditProblem(value) === undefined,
15424
- message: `${documentEditOwner.message} ${PRECONDITION_RULE}`,
15425
- refusal: (value) => documentEditProblem(value) ?? `${documentEditOwner.message} ${PRECONDITION_RULE}`
15453
+ message: `${documentEditOwner.message} ${PRECONDITION_RULE} ${REPLACE_OP_RULE}`,
15454
+ refusal: (value) => documentEditProblem(value) ?? `${documentEditOwner.message} ${PRECONDITION_RULE} ${REPLACE_OP_RULE}`
15426
15455
  };
15427
15456
  var commentOwner = documentOwnerValidation(true);
15428
15457
  var COMMENT_TURN_RULE = "turn requires reply_to_ask: turn says who holds an open ask's thread after the reply. Pass reply_to_ask with the open ask's id, or drop turn.";
@@ -15891,7 +15920,7 @@ var dispatchToolSpecs = [
15891
15920
  ops: z.array(z.object({
15892
15921
  op: z.enum(DOC_EDIT_OPS).describe("Edit operation."),
15893
15922
  find: z.string().describe("Text of the target as rendered, for replace or delete; inline markdown (**bold**, `code`) is tolerated and must be balanced; a leading '# ' matches a heading. A delete of a block's entire text removes the block.").optional(),
15894
- with: z.string().describe("Replacement text for replace: inside a code block, the code's literal text as sent (line breaks at its end do not survive a read); elsewhere parsed as markdown, as insert's markdown is. Text that parses to one paragraph is written inside the matched block, where a backslash escape keeps prose that merely looks like a marker, a leading '[x] ' or '[ ] ' over a task item's text matched from its start sets the item's checkbox, and any non-empty value that renders to no text is refused - only an empty value deletes the match. Text that parses to blocks ('---' over a paragraph, a list, a table, two paragraphs) writes those blocks where the match sits, fitted as the editor fits them, and is refused, with the document unchanged, where the block holding the match cannot hold them: a heading, any cell of a table, and a typed block whose content rule they break. A leading marker of the same kind as the matched block's own is refused either way, since the block renders it already, unless it is a heading rename (where a level named by find is what lets with change it) or an item find's own marker selected. A CR LF or a lone carriage return in it is written as a line feed.").optional(),
15923
+ with: z.string().describe("Replacement text for replace, which every replace names: an empty value deletes the match on purpose. A replace takes op, find, with and occurrence alone, and one without with, or carrying any other key whatever it holds, is refused before it is sent, and by the server with 400 REPLACE_FIELDS, the document unchanged. Inside a code block, with is the code's literal text as sent (line breaks at its end do not survive a read); elsewhere parsed as markdown, as insert's markdown is. Text that parses to one paragraph is written inside the matched block, where a backslash escape keeps prose that merely looks like a marker, a leading '[x] ' or '[ ] ' over a task item's text matched from its start sets the item's checkbox, and any non-empty value that renders to no text is refused - only an empty value deletes the match. Text that parses to blocks ('---' over a paragraph, a list, a table, two paragraphs) writes those blocks where the match sits, fitted as the editor fits them, and is refused, with the document unchanged, where the block holding the match cannot hold them: a heading, any cell of a table, and a typed block whose content rule they break. A leading marker of the same kind as the matched block's own is refused either way, since the block renders it already, unless it is a heading rename (where a level named by find is what lets with change it) or an item find's own marker selected. A CR LF or a lone carriage return in it is written as a line feed.").optional(),
15895
15924
  occurrence: z.number({ int: true, min: 0 }).describe("Optional zero-based match occurrence.").optional(),
15896
15925
  markdown: z.string().describe("Markdown to insert; a CR LF or a lone carriage return in it is written as a line feed.").optional(),
15897
15926
  after: z.string().describe(`Insert or move after this anchor: a quote of the neighbouring block's text, or one of "start", "end", "heading:<exact heading text>", "block:<id>".`).optional(),
@@ -36916,16 +36916,45 @@ function preconditionKept(value) {
36916
36916
  const precondition = input.precondition;
36917
36917
  return typeof precondition.document === "string" !== Array.isArray(precondition.blocks);
36918
36918
  }
36919
+ var REPLACE_OP_KEYS = {
36920
+ op: true,
36921
+ find: true,
36922
+ with: true,
36923
+ occurrence: true
36924
+ };
36925
+ var REPLACE_OP_RULE = 'A replace names with and takes find, with and occurrence alone: with "" deletes the match on purpose, and a replace without with, or with its new text under another key such as markdown, would delete the match too.';
36926
+ function replaceOpsProblem(value) {
36927
+ if (typeof value !== "object" || value === null || !("ops" in value))
36928
+ return;
36929
+ const ops = value.ops;
36930
+ if (!Array.isArray(ops))
36931
+ return;
36932
+ const problems = [];
36933
+ ops.forEach((op, index) => {
36934
+ if (typeof op !== "object" || op === null || !("op" in op) || op.op !== "replace")
36935
+ return;
36936
+ const foreign = Object.entries(op).filter(([key, held]) => REPLACE_OP_KEYS[key] !== true && held !== undefined).map(([key]) => key);
36937
+ if (foreign.length > 0) {
36938
+ problems.push(`ops[${index}] is a replace carrying ${foreign.join(" and ")}, which replace does not take: it takes find, with and occurrence, and its new text goes in with.`);
36939
+ }
36940
+ if (!("with" in op) || op.with === undefined) {
36941
+ problems.push(`ops[${index}] is a replace with no with, which would delete the text find matches: write the new text in with, or with "" to delete it on purpose.`);
36942
+ }
36943
+ });
36944
+ return problems.length === 0 ? undefined : problems.join(" ");
36945
+ }
36919
36946
  function documentEditProblem(value) {
36947
+ const replaceProblem = replaceOpsProblem(value);
36920
36948
  return brokenParts([
36921
36949
  [documentEditOwner.check(value), documentEditOwner.message],
36922
- [preconditionKept(value), PRECONDITION_RULE]
36950
+ [preconditionKept(value), PRECONDITION_RULE],
36951
+ [replaceProblem === undefined, replaceProblem ?? REPLACE_OP_RULE]
36923
36952
  ]);
36924
36953
  }
36925
36954
  var documentEditValidation = {
36926
36955
  check: (value) => documentEditProblem(value) === undefined,
36927
- message: `${documentEditOwner.message} ${PRECONDITION_RULE}`,
36928
- refusal: (value) => documentEditProblem(value) ?? `${documentEditOwner.message} ${PRECONDITION_RULE}`
36956
+ message: `${documentEditOwner.message} ${PRECONDITION_RULE} ${REPLACE_OP_RULE}`,
36957
+ refusal: (value) => documentEditProblem(value) ?? `${documentEditOwner.message} ${PRECONDITION_RULE} ${REPLACE_OP_RULE}`
36929
36958
  };
36930
36959
  var commentOwner = documentOwnerValidation(true);
36931
36960
  var COMMENT_TURN_RULE = "turn requires reply_to_ask: turn says who holds an open ask's thread after the reply. Pass reply_to_ask with the open ask's id, or drop turn.";
@@ -37394,7 +37423,7 @@ var dispatchToolSpecs = [
37394
37423
  ops: z.array(z.object({
37395
37424
  op: z.enum(DOC_EDIT_OPS).describe("Edit operation."),
37396
37425
  find: z.string().describe("Text of the target as rendered, for replace or delete; inline markdown (**bold**, `code`) is tolerated and must be balanced; a leading '# ' matches a heading. A delete of a block's entire text removes the block.").optional(),
37397
- with: z.string().describe("Replacement text for replace: inside a code block, the code's literal text as sent (line breaks at its end do not survive a read); elsewhere parsed as markdown, as insert's markdown is. Text that parses to one paragraph is written inside the matched block, where a backslash escape keeps prose that merely looks like a marker, a leading '[x] ' or '[ ] ' over a task item's text matched from its start sets the item's checkbox, and any non-empty value that renders to no text is refused - only an empty value deletes the match. Text that parses to blocks ('---' over a paragraph, a list, a table, two paragraphs) writes those blocks where the match sits, fitted as the editor fits them, and is refused, with the document unchanged, where the block holding the match cannot hold them: a heading, any cell of a table, and a typed block whose content rule they break. A leading marker of the same kind as the matched block's own is refused either way, since the block renders it already, unless it is a heading rename (where a level named by find is what lets with change it) or an item find's own marker selected. A CR LF or a lone carriage return in it is written as a line feed.").optional(),
37426
+ with: z.string().describe("Replacement text for replace, which every replace names: an empty value deletes the match on purpose. A replace takes op, find, with and occurrence alone, and one without with, or carrying any other key whatever it holds, is refused before it is sent, and by the server with 400 REPLACE_FIELDS, the document unchanged. Inside a code block, with is the code's literal text as sent (line breaks at its end do not survive a read); elsewhere parsed as markdown, as insert's markdown is. Text that parses to one paragraph is written inside the matched block, where a backslash escape keeps prose that merely looks like a marker, a leading '[x] ' or '[ ] ' over a task item's text matched from its start sets the item's checkbox, and any non-empty value that renders to no text is refused - only an empty value deletes the match. Text that parses to blocks ('---' over a paragraph, a list, a table, two paragraphs) writes those blocks where the match sits, fitted as the editor fits them, and is refused, with the document unchanged, where the block holding the match cannot hold them: a heading, any cell of a table, and a typed block whose content rule they break. A leading marker of the same kind as the matched block's own is refused either way, since the block renders it already, unless it is a heading rename (where a level named by find is what lets with change it) or an item find's own marker selected. A CR LF or a lone carriage return in it is written as a line feed.").optional(),
37398
37427
  occurrence: z.number({ int: true, min: 0 }).describe("Optional zero-based match occurrence.").optional(),
37399
37428
  markdown: z.string().describe("Markdown to insert; a CR LF or a lone carriage return in it is written as a line feed.").optional(),
37400
37429
  after: z.string().describe(`Insert or move after this anchor: a quote of the neighbouring block's text, or one of "start", "end", "heading:<exact heading text>", "block:<id>".`).optional(),
@@ -60481,7 +60510,7 @@ var import_nats5 = __toESM(require_mod4(), 1);
60481
60510
 
60482
60511
  // package.json
60483
60512
  var name2 = "@sjawhar/claude-envoy";
60484
- var version2 = "5.1.3";
60513
+ var version2 = "5.2.1";
60485
60514
  var legion = {
60486
60515
  daemonApiVersion: 205
60487
60516
  };
@@ -68009,15 +68038,16 @@ function codexServersDirectory(stateDirectory, codexPid) {
68009
68038
  return join18(stateDirectory, "codex-servers", String(codexPid));
68010
68039
  }
68011
68040
  var ENTRY_NAME = /^(\d+)\.json$/;
68041
+ var TEMPORARY_NAME = /^\.\d+\.\d+\.tmp$/;
68012
68042
  function entryName(entry) {
68013
68043
  return `${entry.seq}.json`;
68014
68044
  }
68015
- async function registerServer(directory, pid, started) {
68045
+ async function registerServer(directory, pid, started, list = (path) => readdir6(path)) {
68016
68046
  await mkdir6(directory, { mode: 448, recursive: true });
68017
68047
  const temporary = join18(directory, `.${pid}.${process.hrtime.bigint()}.tmp`);
68018
68048
  await writeFile4(temporary, JSON.stringify({ pid, started }), { mode: 384 });
68019
68049
  try {
68020
- let seq = Math.max(0, ...(await entryNames(directory)).map(({ seq: taken }) => taken)) + 1;
68050
+ let seq = Math.max(0, ...numbered(await list(directory)).map(({ seq: taken }) => taken)) + 1;
68021
68051
  for (;; ) {
68022
68052
  try {
68023
68053
  await place(temporary, join18(directory, entryName({ seq })), pid, started);
@@ -68048,7 +68078,12 @@ async function place(temporary, target, pid, started) {
68048
68078
  await writeFile4(target, JSON.stringify({ pid, started }), { flag: "wx", mode: 384 });
68049
68079
  }
68050
68080
  async function unregisterServer(directory, self2) {
68051
- await rm6(join18(directory, entryName(self2)), { force: true });
68081
+ const file = join18(directory, entryName(self2));
68082
+ const named = await readFile8(file, "utf8").then(serverOf, () => {
68083
+ return;
68084
+ });
68085
+ if (named?.pid === self2.pid && named.started === self2.started)
68086
+ await rm6(file, { force: true });
68052
68087
  }
68053
68088
  var startedOf = new Map;
68054
68089
  var SYSTEM_PROBE = {
@@ -68076,95 +68111,141 @@ function serverAlive(entry, probe = SYSTEM_PROBE) {
68076
68111
  const now = probe.started(entry.pid);
68077
68112
  return entry.started === null || now === undefined || now === entry.started;
68078
68113
  }
68079
- async function entryNames(directory) {
68080
- let names;
68081
- try {
68082
- names = await readdir6(directory);
68083
- } catch {
68084
- return [];
68085
- }
68114
+ function numbered(names) {
68086
68115
  return names.flatMap((name) => {
68087
68116
  const match = ENTRY_NAME.exec(name);
68088
68117
  return match === null ? [] : [{ name, seq: Number(match[1]) }];
68089
68118
  });
68090
68119
  }
68120
+ function serverOf(text) {
68121
+ let parsed;
68122
+ try {
68123
+ parsed = JSON.parse(text);
68124
+ } catch {
68125
+ return;
68126
+ }
68127
+ if (typeof parsed?.pid !== "number")
68128
+ return;
68129
+ return { pid: parsed.pid, started: typeof parsed.started === "string" ? parsed.started : null };
68130
+ }
68091
68131
  var UNREADABLE_ENTRY_MS = 5000;
68092
- async function readEntries(directory, now = Date.now) {
68093
- const entries = [];
68094
- for (const { name, seq } of await entryNames(directory)) {
68132
+ async function readEntries(directory, probe, now = Date.now) {
68133
+ let names;
68134
+ try {
68135
+ names = await readdir6(directory);
68136
+ } catch (error) {
68137
+ if (hasErrnoCode(error, "ENOENT"))
68138
+ return { entries: [], publishing: false, held: new Map };
68139
+ throw error;
68140
+ }
68141
+ let publishing = false;
68142
+ for (const name of names.filter((each) => TEMPORARY_NAME.test(each))) {
68095
68143
  let text;
68096
68144
  try {
68097
68145
  text = await readFile8(join18(directory, name), "utf8");
68098
68146
  } catch {
68099
- continue;
68147
+ publishing = true;
68148
+ break;
68100
68149
  }
68101
- let parsed;
68150
+ const server = serverOf(text);
68151
+ if (server !== undefined && serverAlive(server, probe)) {
68152
+ publishing = true;
68153
+ break;
68154
+ }
68155
+ }
68156
+ const entries = [];
68157
+ const held = new Map;
68158
+ for (const { name, seq } of numbered(names)) {
68159
+ let text;
68102
68160
  try {
68103
- parsed = JSON.parse(text);
68161
+ text = await readFile8(join18(directory, name), "utf8");
68104
68162
  } catch {
68105
- parsed = undefined;
68163
+ continue;
68106
68164
  }
68107
- if (typeof parsed?.pid !== "number") {
68165
+ const server = serverOf(text);
68166
+ if (server === undefined) {
68108
68167
  const written = await stat6(join18(directory, name)).then((info) => info.mtimeMs, () => {
68109
68168
  return;
68110
68169
  });
68111
- if (written === undefined || now() - written > UNREADABLE_ENTRY_MS)
68170
+ if (written === undefined)
68112
68171
  continue;
68113
- return;
68172
+ if (now() - written <= UNREADABLE_ENTRY_MS)
68173
+ return;
68174
+ held.set(seq, text);
68175
+ continue;
68114
68176
  }
68115
- entries.push({
68116
- pid: parsed.pid,
68117
- seq,
68118
- started: typeof parsed.started === "string" ? parsed.started : null
68119
- });
68177
+ held.set(seq, text);
68178
+ entries.push({ ...server, seq });
68120
68179
  }
68121
- return entries;
68180
+ return { entries, publishing, held };
68122
68181
  }
68123
68182
  async function currentOwner(directory, probe = SYSTEM_PROBE) {
68124
- const entries = await readEntries(directory);
68125
- if (entries === undefined)
68183
+ const seen = await readEntries(directory, probe);
68184
+ if (seen === undefined)
68126
68185
  return;
68127
- const live = entries.filter((entry) => serverAlive(entry, probe));
68186
+ const live = seen.entries.filter((entry) => serverAlive(entry, probe));
68128
68187
  live.sort((a, b) => a.seq - b.seq);
68129
- return live[0];
68188
+ const owner = live[0];
68189
+ if (owner === undefined || !seen.publishing)
68190
+ return owner;
68191
+ for (let seq = 1;seq < owner.seq; seq++) {
68192
+ const text = seen.held.get(seq);
68193
+ if (text === undefined)
68194
+ return;
68195
+ const now = await readFile8(join18(directory, entryName({ seq })), "utf8").catch(() => {
68196
+ return;
68197
+ });
68198
+ if (now !== text)
68199
+ return;
68200
+ }
68201
+ return owner;
68130
68202
  }
68131
68203
  function waitForOwnership(directory, pid, started, signal, published = () => {
68132
68204
  return;
68133
- }, pollMs = 1000, probe = SYSTEM_PROBE) {
68205
+ }, pollMs = 1000, probe = SYSTEM_PROBE, warn = (text) => void process.stderr.write(`envoy-channel: ${text}
68206
+ `)) {
68134
68207
  return new Promise((done) => {
68135
68208
  let self2;
68136
68209
  let timer;
68210
+ let failing = false;
68137
68211
  const look = async () => {
68138
68212
  if (signal.aborted)
68139
68213
  return done(undefined);
68140
- const entries = await readEntries(directory);
68141
- if (entries !== undefined && (self2 === undefined || !entries.some((entry) => entry.seq === self2?.seq))) {
68142
- if (self2 !== undefined)
68143
- await unregisterServer(directory, self2);
68214
+ const seen = await readEntries(directory, probe);
68215
+ const had = self2;
68216
+ if (seen !== undefined && !seen.entries.some((entry) => entry.seq === had?.seq && entry.pid === pid && entry.started === started)) {
68217
+ self2 = undefined;
68218
+ if (had !== undefined)
68219
+ await unregisterServer(directory, had);
68144
68220
  self2 = await registerServer(directory, pid, started);
68145
68221
  published(self2);
68146
68222
  }
68147
68223
  const owner = await currentOwner(directory, probe);
68224
+ failing = false;
68148
68225
  if (owner?.pid === pid)
68149
68226
  done(self2);
68150
68227
  else
68151
- timer = setTimeout(() => void look().catch(retry), pollMs);
68228
+ next();
68152
68229
  };
68153
- const retry = () => {
68154
- timer = setTimeout(() => void look().catch(retry), pollMs);
68230
+ const next = () => {
68231
+ timer = setTimeout(() => void look().catch(failed), pollMs);
68232
+ };
68233
+ const failed = (error) => {
68234
+ if (!failing) {
68235
+ warn(`this plugin server could not read or publish its entry in ${directory}, so it stands by and tries again: ${messageFor(error)}`);
68236
+ }
68237
+ failing = true;
68238
+ next();
68155
68239
  };
68156
68240
  signal.addEventListener("abort", () => {
68157
68241
  if (timer !== undefined)
68158
68242
  clearTimeout(timer);
68159
68243
  done(undefined);
68160
68244
  });
68161
- look().catch(retry);
68245
+ look().catch(failed);
68162
68246
  });
68163
68247
  }
68164
68248
  async function stillOwner(directory, self2, probe = SYSTEM_PROBE) {
68165
- const entries = await readEntries(directory);
68166
- if (entries === undefined)
68167
- return true;
68168
68249
  const owner = await currentOwner(directory, probe);
68169
68250
  return owner === undefined || owner.pid === self2.pid;
68170
68251
  }
@@ -14320,16 +14320,45 @@ function preconditionKept(value) {
14320
14320
  const precondition = input.precondition;
14321
14321
  return typeof precondition.document === "string" !== Array.isArray(precondition.blocks);
14322
14322
  }
14323
+ var REPLACE_OP_KEYS = {
14324
+ op: true,
14325
+ find: true,
14326
+ with: true,
14327
+ occurrence: true
14328
+ };
14329
+ var REPLACE_OP_RULE = 'A replace names with and takes find, with and occurrence alone: with "" deletes the match on purpose, and a replace without with, or with its new text under another key such as markdown, would delete the match too.';
14330
+ function replaceOpsProblem(value) {
14331
+ if (typeof value !== "object" || value === null || !("ops" in value))
14332
+ return;
14333
+ const ops = value.ops;
14334
+ if (!Array.isArray(ops))
14335
+ return;
14336
+ const problems = [];
14337
+ ops.forEach((op, index) => {
14338
+ if (typeof op !== "object" || op === null || !("op" in op) || op.op !== "replace")
14339
+ return;
14340
+ const foreign = Object.entries(op).filter(([key, held]) => REPLACE_OP_KEYS[key] !== true && held !== undefined).map(([key]) => key);
14341
+ if (foreign.length > 0) {
14342
+ problems.push(`ops[${index}] is a replace carrying ${foreign.join(" and ")}, which replace does not take: it takes find, with and occurrence, and its new text goes in with.`);
14343
+ }
14344
+ if (!("with" in op) || op.with === undefined) {
14345
+ problems.push(`ops[${index}] is a replace with no with, which would delete the text find matches: write the new text in with, or with "" to delete it on purpose.`);
14346
+ }
14347
+ });
14348
+ return problems.length === 0 ? undefined : problems.join(" ");
14349
+ }
14323
14350
  function documentEditProblem(value) {
14351
+ const replaceProblem = replaceOpsProblem(value);
14324
14352
  return brokenParts([
14325
14353
  [documentEditOwner.check(value), documentEditOwner.message],
14326
- [preconditionKept(value), PRECONDITION_RULE]
14354
+ [preconditionKept(value), PRECONDITION_RULE],
14355
+ [replaceProblem === undefined, replaceProblem ?? REPLACE_OP_RULE]
14327
14356
  ]);
14328
14357
  }
14329
14358
  var documentEditValidation = {
14330
14359
  check: (value) => documentEditProblem(value) === undefined,
14331
- message: `${documentEditOwner.message} ${PRECONDITION_RULE}`,
14332
- refusal: (value) => documentEditProblem(value) ?? `${documentEditOwner.message} ${PRECONDITION_RULE}`
14360
+ message: `${documentEditOwner.message} ${PRECONDITION_RULE} ${REPLACE_OP_RULE}`,
14361
+ refusal: (value) => documentEditProblem(value) ?? `${documentEditOwner.message} ${PRECONDITION_RULE} ${REPLACE_OP_RULE}`
14333
14362
  };
14334
14363
  var commentOwner = documentOwnerValidation(true);
14335
14364
  var COMMENT_TURN_RULE = "turn requires reply_to_ask: turn says who holds an open ask's thread after the reply. Pass reply_to_ask with the open ask's id, or drop turn.";
@@ -14798,7 +14827,7 @@ var dispatchToolSpecs = [
14798
14827
  ops: z.array(z.object({
14799
14828
  op: z.enum(DOC_EDIT_OPS).describe("Edit operation."),
14800
14829
  find: z.string().describe("Text of the target as rendered, for replace or delete; inline markdown (**bold**, `code`) is tolerated and must be balanced; a leading '# ' matches a heading. A delete of a block's entire text removes the block.").optional(),
14801
- with: z.string().describe("Replacement text for replace: inside a code block, the code's literal text as sent (line breaks at its end do not survive a read); elsewhere parsed as markdown, as insert's markdown is. Text that parses to one paragraph is written inside the matched block, where a backslash escape keeps prose that merely looks like a marker, a leading '[x] ' or '[ ] ' over a task item's text matched from its start sets the item's checkbox, and any non-empty value that renders to no text is refused - only an empty value deletes the match. Text that parses to blocks ('---' over a paragraph, a list, a table, two paragraphs) writes those blocks where the match sits, fitted as the editor fits them, and is refused, with the document unchanged, where the block holding the match cannot hold them: a heading, any cell of a table, and a typed block whose content rule they break. A leading marker of the same kind as the matched block's own is refused either way, since the block renders it already, unless it is a heading rename (where a level named by find is what lets with change it) or an item find's own marker selected. A CR LF or a lone carriage return in it is written as a line feed.").optional(),
14830
+ with: z.string().describe("Replacement text for replace, which every replace names: an empty value deletes the match on purpose. A replace takes op, find, with and occurrence alone, and one without with, or carrying any other key whatever it holds, is refused before it is sent, and by the server with 400 REPLACE_FIELDS, the document unchanged. Inside a code block, with is the code's literal text as sent (line breaks at its end do not survive a read); elsewhere parsed as markdown, as insert's markdown is. Text that parses to one paragraph is written inside the matched block, where a backslash escape keeps prose that merely looks like a marker, a leading '[x] ' or '[ ] ' over a task item's text matched from its start sets the item's checkbox, and any non-empty value that renders to no text is refused - only an empty value deletes the match. Text that parses to blocks ('---' over a paragraph, a list, a table, two paragraphs) writes those blocks where the match sits, fitted as the editor fits them, and is refused, with the document unchanged, where the block holding the match cannot hold them: a heading, any cell of a table, and a typed block whose content rule they break. A leading marker of the same kind as the matched block's own is refused either way, since the block renders it already, unless it is a heading rename (where a level named by find is what lets with change it) or an item find's own marker selected. A CR LF or a lone carriage return in it is written as a line feed.").optional(),
14802
14831
  occurrence: z.number({ int: true, min: 0 }).describe("Optional zero-based match occurrence.").optional(),
14803
14832
  markdown: z.string().describe("Markdown to insert; a CR LF or a lone carriage return in it is written as a line feed.").optional(),
14804
14833
  after: z.string().describe(`Insert or move after this anchor: a quote of the neighbouring block's text, or one of "start", "end", "heading:<exact heading text>", "block:<id>".`).optional(),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sjawhar/claude-envoy",
3
- "version": "5.1.3",
3
+ "version": "5.2.1",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Claude Code plugin for Legion's Envoy bus",
6
6
  "type": "module",
@@ -1,5 +1,6 @@
1
1
  import { link, mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises"
2
2
  import { join } from "node:path"
3
+ import { hasErrnoCode, messageFor } from "@legion/envoy-client/errors"
3
4
  import { processStarted } from "./codex-session-record"
4
5
 
5
6
  /**
@@ -12,12 +13,18 @@ import { processStarted } from "./codex-session-record"
12
13
  *
13
14
  * So each server publishes an entry, `codex-servers/<codex pid>/<seq>.json`, taking the next free
14
15
  * sequence number by linking a fully written temporary file into place (`link` fails when the
15
- * name exists), so two live entries never hold one number and the order is the order they
16
- * published in, whatever the clock says. The owner is the live entry with the lowest number. No
17
- * server removes another's entry, so a name a server judged dead and a name a later server took
18
- * are never confused; the `SessionStart` hook removes a dead codex process's entries. Every server
19
- * reads the same entries and reaches the same answer. The others stand by, serving their thread's
20
- * `dispatch` calls, until every server that published before them is gone.
16
+ * name exists), so two live entries never hold one number, whatever the clock says. The owner is
17
+ * the live entry with the lowest number. A server reads the directory before it links, and a
18
+ * server that stops removes its entry, so a server held between the two can take a number freed
19
+ * meanwhile, below an entry published after its read, even a number freed while another server
20
+ * was looking. Its temporary file is there all that time, and while a server that still runs has
21
+ * one there, no owner is decided unless every number below it is taken by an entry still there,
22
+ * unchanged, after the look found its server gone, which no server can remove any more
23
+ * (`currentOwner`). So, while every entry is readable, no server owns while another does. No
24
+ * server removes another's entry (`unregisterServer`), so a name a server judged dead and a name a
25
+ * later server took are never confused; the `SessionStart` hook removes a dead codex process's
26
+ * entries. Every server reads the same entries and reaches the same answer. The others stand by,
27
+ * serving their thread's `dispatch` calls, until every server ahead of them is gone.
21
28
  */
22
29
  export interface CodexServerEntry {
23
30
  /** The publication number: lower owns. */
@@ -36,26 +43,34 @@ export function codexServersDirectory(stateDirectory: string, codexPid: number):
36
43
 
37
44
  const ENTRY_NAME = /^(\d+)\.json$/
38
45
 
46
+ /** A server's temporary file (`registerServer`): `.<pid>.<n>.tmp`. */
47
+ const TEMPORARY_NAME = /^\.\d+\.\d+\.tmp$/
48
+
39
49
  function entryName(entry: { readonly seq: number }): string {
40
50
  return `${entry.seq}.json`
41
51
  }
42
52
 
43
53
  /**
44
- * Publishes an entry for server `pid`, at the lowest number above every entry there, and answers
45
- * it. The entry is written whole to a temporary file and linked into place, and `link` fails when
46
- * the name exists, so a server that loses a number to another takes the next one, and a reader
47
- * never sees a half-written entry.
54
+ * Publishes an entry for server `pid`, at the lowest free number above every entry there, and
55
+ * answers it. The entry is written whole to a temporary file and linked into place, and `link`
56
+ * fails when the name exists, so a server that loses a number to another takes the next one, and a
57
+ * reader never sees a half-written entry. The temporary file is there from before the directory is
58
+ * read until the entry is placed, so no owner is decided meanwhile above a number the server could
59
+ * take (`currentOwner`). A listing that fails is no empty one: its failure stands, rather than a
60
+ * number read off nothing. `list` reads the directory; production passes nothing, and a test wraps
61
+ * the read to hold a server right after it, as one the scheduler stalls there.
48
62
  */
49
63
  export async function registerServer(
50
64
  directory: string,
51
65
  pid: number,
52
66
  started: string | null,
67
+ list: (directory: string) => Promise<string[]> = (path) => readdir(path),
53
68
  ): Promise<CodexServerEntry> {
54
69
  await mkdir(directory, { mode: 0o700, recursive: true })
55
70
  const temporary = join(directory, `.${pid}.${process.hrtime.bigint()}.tmp`)
56
71
  await writeFile(temporary, JSON.stringify({ pid, started }), { mode: 0o600 })
57
72
  try {
58
- let seq = Math.max(0, ...(await entryNames(directory)).map(({ seq: taken }) => taken)) + 1
73
+ let seq = Math.max(0, ...numbered(await list(directory)).map(({ seq: taken }) => taken)) + 1
59
74
  for (;;) {
60
75
  try {
61
76
  await place(temporary, join(directory, entryName({ seq })), pid, started)
@@ -98,9 +113,14 @@ async function place(
98
113
  await writeFile(target, JSON.stringify({ pid, started }), { flag: "wx", mode: 0o600 })
99
114
  }
100
115
 
101
- /** Removes `self`'s entry. */
116
+ /**
117
+ * Removes `self`'s entry, when the file at its number still names `self`. A server whose entry was
118
+ * removed, and whose number another server then took, so leaves that server's entry alone.
119
+ */
102
120
  export async function unregisterServer(directory: string, self: CodexServerEntry): Promise<void> {
103
- await rm(join(directory, entryName(self)), { force: true })
121
+ const file = join(directory, entryName(self))
122
+ const named = await readFile(file, "utf8").then(serverOf, () => undefined)
123
+ if (named?.pid === self.pid && named.started === self.started) await rm(file, { force: true })
104
124
  }
105
125
 
106
126
  /** How a liveness check reads a process: `kill(pid, 0)` and its start. */
@@ -138,88 +158,151 @@ function gone(pid: number, probe: ProcessProbe): boolean {
138
158
  * when both starts can be read and differ (the pid was used again); a start that cannot be read
139
159
  * now, as when `ps` fails, says nothing either way, so a live owner is never judged gone for it.
140
160
  */
141
- export function serverAlive(entry: CodexServerEntry, probe: ProcessProbe = SYSTEM_PROBE): boolean {
161
+ export function serverAlive(
162
+ entry: Pick<CodexServerEntry, "pid" | "started">,
163
+ probe: ProcessProbe = SYSTEM_PROBE,
164
+ ): boolean {
142
165
  if (gone(entry.pid, probe)) return false
143
166
  const now = probe.started(entry.pid)
144
167
  return entry.started === null || now === undefined || now === entry.started
145
168
  }
146
169
 
147
- async function entryNames(directory: string): Promise<{ seq: number; name: string }[]> {
148
- let names: string[]
149
- try {
150
- names = await readdir(directory)
151
- } catch {
152
- return []
153
- }
170
+ /** The numbered entries among a listing's `names`. */
171
+ function numbered(names: readonly string[]): { seq: number; name: string }[] {
154
172
  return names.flatMap((name) => {
155
173
  const match = ENTRY_NAME.exec(name)
156
174
  return match === null ? [] : [{ name, seq: Number(match[1]) }]
157
175
  })
158
176
  }
159
177
 
178
+ /** The server a file names, or undefined while the file is still empty or half-written. */
179
+ function serverOf(text: string): Pick<CodexServerEntry, "pid" | "started"> | undefined {
180
+ let parsed: { pid?: unknown; started?: unknown } | undefined
181
+ try {
182
+ parsed = JSON.parse(text) as { pid?: unknown; started?: unknown }
183
+ } catch {
184
+ return undefined
185
+ }
186
+ if (typeof parsed?.pid !== "number") return undefined
187
+ return { pid: parsed.pid, started: typeof parsed.started === "string" ? parsed.started : null }
188
+ }
189
+
160
190
  /** How long a numbered entry may stay unreadable before it counts as dead: one small write takes
161
191
  * far less, so an entry still empty after this was left by a server killed in that write. */
162
192
  const UNREADABLE_ENTRY_MS = 5_000
163
193
 
164
- /** The entries `directory` holds, or undefined when one of them could not be read yet: a numbered
165
- * file that is still empty or half-written (placed by an exclusive create where the file system
166
- * has no hard links), which no look may decide past. Such a file older than
167
- * `UNREADABLE_ENTRY_MS` counts as dead, so a server killed in that write blocks no owner for
168
- * long. */
194
+ /**
195
+ * One look at `directory`, from one listing of it, or undefined when an entry could not be read
196
+ * yet: a numbered file that is still empty or half-written (placed by an exclusive create where
197
+ * the file system has no hard links), which no look may decide past. Such a file older than
198
+ * `UNREADABLE_ENTRY_MS` counts as dead, so a server killed in that write blocks no owner for long.
199
+ * A directory that is not there is an empty look; a listing that fails for any other reason
200
+ * rejects, since a look read off nothing would have a server publish again, or decide, on entries
201
+ * it never saw.
202
+ *
203
+ * `publishing` says a server that still runs is publishing: its whole temporary file is in the
204
+ * listing, or was and is gone now, its entry placed after the listing. That server has read the
205
+ * directory and not yet placed its entry, and the number it read may have been freed since. A
206
+ * temporary file still empty or half-written says nothing: its server reads the directory only
207
+ * once the file is whole, so it reads every entry placed by then and takes a number above them
208
+ * all. `held` maps each number a file held in this look to the text read from it.
209
+ */
169
210
  async function readEntries(
170
211
  directory: string,
212
+ probe: ProcessProbe,
171
213
  now: () => number = Date.now,
172
- ): Promise<CodexServerEntry[] | undefined> {
173
- const entries: CodexServerEntry[] = []
174
- for (const { name, seq } of await entryNames(directory)) {
214
+ ): Promise<
215
+ | { entries: CodexServerEntry[]; publishing: boolean; held: ReadonlyMap<number, string> }
216
+ | undefined
217
+ > {
218
+ let names: string[]
219
+ try {
220
+ names = await readdir(directory)
221
+ } catch (error) {
222
+ if (hasErrnoCode(error, "ENOENT")) return { entries: [], publishing: false, held: new Map() }
223
+ throw error
224
+ }
225
+ let publishing = false
226
+ for (const name of names.filter((each) => TEMPORARY_NAME.test(each))) {
175
227
  let text: string
176
228
  try {
177
229
  text = await readFile(join(directory, name), "utf8")
178
230
  } catch {
179
- continue // Removed meanwhile.
231
+ publishing = true // Its entry was placed after the listing, which does not hold it.
232
+ break
180
233
  }
181
- let parsed: { pid?: unknown; started?: unknown } | undefined
234
+ const server = serverOf(text)
235
+ if (server !== undefined && serverAlive(server, probe)) {
236
+ publishing = true
237
+ break
238
+ }
239
+ }
240
+ const entries: CodexServerEntry[] = []
241
+ const held = new Map<number, string>()
242
+ for (const { name, seq } of numbered(names)) {
243
+ let text: string
182
244
  try {
183
- parsed = JSON.parse(text) as { pid?: unknown; started?: unknown }
245
+ text = await readFile(join(directory, name), "utf8")
184
246
  } catch {
185
- parsed = undefined
247
+ continue // Removed meanwhile.
186
248
  }
187
- if (typeof parsed?.pid !== "number") {
249
+ const server = serverOf(text)
250
+ if (server === undefined) {
188
251
  const written = await stat(join(directory, name)).then(
189
252
  (info) => info.mtimeMs,
190
253
  () => undefined,
191
254
  )
192
- if (written === undefined || now() - written > UNREADABLE_ENTRY_MS) continue
193
- return undefined
255
+ if (written === undefined) continue // Removed meanwhile.
256
+ if (now() - written <= UNREADABLE_ENTRY_MS) return undefined
257
+ held.set(seq, text)
258
+ continue
194
259
  }
195
- entries.push({
196
- pid: parsed.pid,
197
- seq,
198
- started: typeof parsed.started === "string" ? parsed.started : null,
199
- })
260
+ held.set(seq, text)
261
+ entries.push({ ...server, seq })
200
262
  }
201
- return entries
263
+ return { entries, publishing, held }
202
264
  }
203
265
 
204
- /** The live server that owns the session: the live entry with the lowest number; undefined when
205
- * there is none, or when an entry could not be read yet and no answer can be given. */
266
+ /**
267
+ * The live server that owns the session: the live entry with the lowest number; undefined when
268
+ * there is none, or when an entry could not be read yet, and no answer can be given. It rejects
269
+ * when the directory cannot be listed (`readEntries`).
270
+ *
271
+ * While a server that still runs is publishing (`readEntries`), it may take any number below the
272
+ * owner's that is free, so the answer is undefined unless every such number is taken by the file
273
+ * this look read, still there unchanged once the look has found that file's server gone. A server
274
+ * removes its own entry as it stops, so a file read before the look found its server gone may have
275
+ * gone since; one still there after that is a dead server's, which nothing removes while this
276
+ * codex process runs.
277
+ */
206
278
  export async function currentOwner(
207
279
  directory: string,
208
280
  probe: ProcessProbe = SYSTEM_PROBE,
209
281
  ): Promise<CodexServerEntry | undefined> {
210
- const entries = await readEntries(directory)
211
- if (entries === undefined) return undefined
212
- const live = entries.filter((entry) => serverAlive(entry, probe))
282
+ const seen = await readEntries(directory, probe)
283
+ if (seen === undefined) return undefined
284
+ const live = seen.entries.filter((entry) => serverAlive(entry, probe))
213
285
  live.sort((a, b) => a.seq - b.seq)
214
- return live[0]
286
+ const owner = live[0]
287
+ if (owner === undefined || !seen.publishing) return owner
288
+ for (let seq = 1; seq < owner.seq; seq++) {
289
+ const text = seen.held.get(seq)
290
+ if (text === undefined) return undefined // Free: the server publishing may take it.
291
+ const now = await readFile(join(directory, entryName({ seq })), "utf8").catch(() => undefined)
292
+ if (now !== text) return undefined // Freed, or taken, since this look read it.
293
+ }
294
+ return owner
215
295
  }
216
296
 
217
297
  /**
218
298
  * Resolves with `self`'s entry once it owns the session, looking every `pollMs`, or undefined when
219
299
  * `signal` aborts. It publishes the entry first, and tells `published` each entry it publishes, so
220
300
  * a server that stops while it stands by removes its own. A look that finds the entry gone (a
221
- * failed write, or a directory someone removed) publishes it again, at the back of the order,
222
- * after removing the one it had. The server owns when the owner is any entry of its own pid.
301
+ * failed write, a directory someone removed, or another server's entry at its number) publishes it
302
+ * again, at the back of the order, after removing the one it had if that is still its own. The
303
+ * server owns when the owner is any entry of its own pid. A look that fails (a directory it cannot
304
+ * list, an entry it cannot write) changes nothing and is tried again at the next look; `warn` is
305
+ * told once when looks start to fail, and again only after one has succeeded.
223
306
  */
224
307
  export function waitForOwnership(
225
308
  directory: string,
@@ -229,45 +312,63 @@ export function waitForOwnership(
229
312
  published: (entry: CodexServerEntry) => void = () => undefined,
230
313
  pollMs = 1_000,
231
314
  probe: ProcessProbe = SYSTEM_PROBE,
315
+ warn: (text: string) => void = (text) => void process.stderr.write(`envoy-channel: ${text}\n`),
232
316
  ): Promise<CodexServerEntry | undefined> {
233
317
  return new Promise((done) => {
234
318
  let self: CodexServerEntry | undefined
235
319
  let timer: ReturnType<typeof setTimeout> | undefined
320
+ /** Whether the last look failed, so looks that keep failing are told once. */
321
+ let failing = false
236
322
  const look = async (): Promise<void> => {
237
323
  if (signal.aborted) return done(undefined)
238
- const entries = await readEntries(directory)
324
+ const seen = await readEntries(directory, probe)
325
+ const had = self
239
326
  if (
240
- entries !== undefined &&
241
- (self === undefined || !entries.some((entry) => entry.seq === self?.seq))
327
+ seen !== undefined &&
328
+ !seen.entries.some(
329
+ (entry) => entry.seq === had?.seq && entry.pid === pid && entry.started === started,
330
+ )
242
331
  ) {
243
- if (self !== undefined) await unregisterServer(directory, self)
332
+ // Cleared first, so a publish that fails leaves no number this server no longer holds.
333
+ self = undefined
334
+ if (had !== undefined) await unregisterServer(directory, had)
244
335
  self = await registerServer(directory, pid, started)
245
336
  published(self)
246
337
  }
247
338
  const owner = await currentOwner(directory, probe)
339
+ failing = false
248
340
  if (owner?.pid === pid) done(self)
249
- else timer = setTimeout(() => void look().catch(retry), pollMs)
341
+ else next()
250
342
  }
251
- const retry = (): void => {
252
- timer = setTimeout(() => void look().catch(retry), pollMs)
343
+ const next = (): void => {
344
+ timer = setTimeout(() => void look().catch(failed), pollMs)
345
+ }
346
+ const failed = (error: unknown): void => {
347
+ if (!failing) {
348
+ warn(
349
+ `this plugin server could not read or publish its entry in ${directory}, so it stands by and tries again: ${messageFor(error)}`,
350
+ )
351
+ }
352
+ failing = true
353
+ next()
253
354
  }
254
355
  signal.addEventListener("abort", () => {
255
356
  if (timer !== undefined) clearTimeout(timer)
256
357
  done(undefined)
257
358
  })
258
- void look().catch(retry)
359
+ void look().catch(failed)
259
360
  })
260
361
  }
261
362
 
262
- /** Whether `self` still owns the session. The owner re-checks every few seconds and warns when it
263
- * finds another owner, which the order of publication rules out while every entry is readable. */
363
+ /** Whether `self` still owns the session: true too when no owner can be decided now. The owner
364
+ * re-checks every few seconds and warns when it finds another owner, which the order of
365
+ * publication rules out while every entry is readable. It rejects when the directory cannot be
366
+ * listed. */
264
367
  export async function stillOwner(
265
368
  directory: string,
266
369
  self: CodexServerEntry,
267
370
  probe: ProcessProbe = SYSTEM_PROBE,
268
371
  ): Promise<boolean> {
269
- const entries = await readEntries(directory)
270
- if (entries === undefined) return true
271
372
  const owner = await currentOwner(directory, probe)
272
373
  return owner === undefined || owner.pid === self.pid
273
374
  }