@sjawhar/pi-envoy 15.6.0 → 16.0.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
@@ -397,16 +397,34 @@ gated write only when it consumes one, so a write sent any other way is refused
397
397
 
398
398
  - **The record.** While the gate is bound, pi-envoy keeps one owner-only file for its process in
399
399
  the `askgate/` directory of the CLI's state directory of each session id it binds
400
- (`<state>/sessions/<id>/askgate/<pid>-<start>.json`, where `<state>` is `DISPATCH_STATE_DIR`,
401
- else `$XDG_STATE_HOME/dispatch`, else `~/.local/state/dispatch`). It names the Oh My Pi process,
402
- its Linux start time, and the process's owner-only marker store. Each process writes and removes
403
- only its own file, so two processes that bind one session never drop each other. pi-envoy sets
400
+ (`<state>/sessions/<id>/askgate/<pid>-<start>-<ns>.json`, where `<state>` is
401
+ `DISPATCH_STATE_DIR`, else `$XDG_STATE_HOME/dispatch`, else `~/.local/state/dispatch`). It names
402
+ the Oh My Pi process, its Linux start time, its pid namespace (the inode `/proc/self/ns/pid`
403
+ names), and the process's owner-only marker store. Each process writes and removes only its own
404
+ file, so two processes that bind one session never drop each other. pi-envoy sets
404
405
  `DISPATCH_STATE_DIR` in the session's environment when it is not set, so a command that changes
405
406
  `HOME` or `XDG_STATE_HOME` still finds the record. A record of a session the process switched
406
407
  away from stays until the process exits, since a shell or an eval kernel started before the
407
408
  switch still acts as that session. A record whose process is gone, or whose pid another process
408
409
  now holds, is inert, and the CLI's session pruning keeps a directory whose record is live. A
409
410
  record pi-envoy cannot write is a notice in the session, at start or at a switch.
411
+ - **Other pid namespaces.** One state directory can serve processes of several pid namespaces: the
412
+ host's and those of the containers that mount the host's state directory, each with a pid
413
+ namespace of its own. A pid and a start time name a process only in the namespace they were read
414
+ in, so the CLI looks up by pid only an owner of its own namespace. An owner of another one counts
415
+ live while its marker store changed within the last two hours; the process touches its store
416
+ every ten minutes while it keeps a record, so a live one never looks gone from another namespace.
417
+ The process also makes its store again, empty, before each write of its own file, so a store that
418
+ another process removed is back by the gate's next call. A record written by an older pi-envoy
419
+ names no namespace and is still looked up by pid in the reader's own. The pruning keeps a store
420
+ such a pi-envoy named for 14 days rather than two hours, since its process may be a live one of
421
+ another namespace, which touches its store only when it mints a marker, and it keeps a session
422
+ directory whose record names a store that is still there. A process of another namespace that
423
+ reads the record (the host's CLI, for a box's session) is never that session's own agent, whose
424
+ calls run in its process's namespace, so it reads such an owner live only by its store. Every
425
+ `dispatch` command that shares the state directory must be this release or later (pi-envoy's,
426
+ and the copy Claude Code sessions run): an earlier one reads a namespaced owner by pid, and its
427
+ pruning can still remove a box session's idle directory.
410
428
  - **The marker.** The gate mints one file in the store for each literal call it lets run, created
411
429
  owner-only and exclusively. It binds the exact argument vector the CLI receives and, behind a
412
430
  review or a deliberate pass (a rebuttal, a breaker trip), the digest of the arguments the dry
@@ -417,7 +435,8 @@ gated write only when it consumes one, so a write sent any other way is refused
417
435
  its marker until
418
436
  shutdown, and a marker older than two hours, longer than any tool's time limit, is refused and
419
437
  removed. The process removes its store when it exits; the CLI's daily session pruning removes
420
- the store of a process that is gone and that nothing changed for two hours.
438
+ the store of a process that is gone and that nothing changed for two hours, which for a process
439
+ of another pid namespace is how it is known to be gone.
421
440
  - **The check.** After `--help`, `--dry-run` and the session and Dispatch settings, and before a
422
441
  gated write posts, the CLI reads the session's record. With a live one it reads each file the
423
442
  argv names once and consumes one matching marker by unlinking it: exactly one process wins, so a
package/dist/dispatch.js CHANGED
@@ -961,10 +961,12 @@ import {
961
961
  openSync,
962
962
  readdirSync,
963
963
  readFileSync,
964
+ readlinkSync,
964
965
  renameSync,
965
966
  rmSync,
966
967
  statSync,
967
968
  unlinkSync,
969
+ utimesSync,
968
970
  writeFileSync
969
971
  } from "fs";
970
972
  import { isAbsolute, join, resolve } from "path";
@@ -980,6 +982,7 @@ function hasErrnoCode(error, code) {
980
982
  // ../envoy-client/src/askgate-marker.ts
981
983
  var ASKGATE_RECORD = "askgate";
982
984
  var MARKER_MAX_AGE_MS = 2 * 60 * 60000;
985
+ var STORE_BEAT_MS = 10 * 60000;
983
986
  var MARKERS = "markers";
984
987
  var ALWAYS_GATED = {
985
988
  dispatch_ask: true,
@@ -1044,7 +1047,25 @@ function processStart(pid) {
1044
1047
  return null;
1045
1048
  }
1046
1049
  }
1047
- function ownerLive(owner) {
1050
+ var ownNamespace;
1051
+ function pidNamespace() {
1052
+ if (ownNamespace === undefined) {
1053
+ try {
1054
+ ownNamespace = /^pid:\[([0-9]+)\]$/.exec(readlinkSync("/proc/self/ns/pid"))?.[1] ?? null;
1055
+ } catch {
1056
+ ownNamespace = null;
1057
+ }
1058
+ }
1059
+ return ownNamespace;
1060
+ }
1061
+ function ownerLive(owner, now) {
1062
+ if (owner.ns !== null && owner.ns !== pidNamespace()) {
1063
+ try {
1064
+ return now - storeTouched(owner.store) <= MARKER_MAX_AGE_MS;
1065
+ } catch {
1066
+ return false;
1067
+ }
1068
+ }
1048
1069
  if (owner.start !== null)
1049
1070
  return processStart(owner.pid) === owner.start;
1050
1071
  try {
@@ -1054,11 +1075,11 @@ function ownerLive(owner) {
1054
1075
  return !hasErrnoCode(error, "ESRCH");
1055
1076
  }
1056
1077
  }
1057
- function isOwner(value) {
1078
+ function isOwnerText(value) {
1058
1079
  if (typeof value !== "object" || value === null)
1059
1080
  return false;
1060
- const { pid, start, store } = value;
1061
- return typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0 && (start === null || typeof start === "string") && typeof store === "string" && store.startsWith("/");
1081
+ const { pid, start, ns, store } = value;
1082
+ return typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0 && (start === null || typeof start === "string") && (ns === undefined || ns === null || typeof ns === "string" && /^[0-9]+$/.test(ns)) && typeof store === "string" && store.startsWith("/");
1062
1083
  }
1063
1084
  function parseOwner(text) {
1064
1085
  let data;
@@ -1067,16 +1088,16 @@ function parseOwner(text) {
1067
1088
  } catch {
1068
1089
  return;
1069
1090
  }
1070
- if (!isOwner(data) || !("v" in data) || data.v !== 2)
1091
+ if (!isOwnerText(data) || data.v !== 2)
1071
1092
  return;
1072
- const { pid, start, store, mode } = data;
1093
+ const { pid, start, ns, store, mode } = data;
1073
1094
  return {
1074
- owner: { pid, start, store },
1095
+ owner: { pid, start, ns: ns ?? null, store },
1075
1096
  mode: mode === "block" ? "block" : "warn"
1076
1097
  };
1077
1098
  }
1078
1099
  var OWNER_FILE = ".json";
1079
- var STORE_NAME = /^([1-9][0-9]*)(?:-([0-9]+))?$/;
1100
+ var STORE_NAME = /^([1-9][0-9]*)(?:-([0-9]+)(?:-([0-9]+))?)?$/;
1080
1101
  function storeTouched(store) {
1081
1102
  const own = statSync(store).mtimeMs;
1082
1103
  try {
@@ -1087,6 +1108,7 @@ function storeTouched(store) {
1087
1108
  throw error;
1088
1109
  }
1089
1110
  }
1111
+ var UNNAMESPACED_STORE_MAX_AGE_MS = 14 * 86400000;
1090
1112
  function sweepStores(root, now) {
1091
1113
  const parent = join(root, "askgate");
1092
1114
  let names;
@@ -1101,15 +1123,42 @@ function sweepStores(root, now) {
1101
1123
  continue;
1102
1124
  const store = join(parent, name);
1103
1125
  try {
1104
- if (ownerLive({ pid: Number(match[1]), start: match[2] ?? null, store }))
1126
+ const owner = { pid: Number(match[1]), start: match[2] ?? null, ns: match[3] ?? null, store };
1127
+ if (ownerLive(owner, now))
1105
1128
  continue;
1106
- if (now - storeTouched(store) <= MARKER_MAX_AGE_MS)
1129
+ const unnamespaced = owner.start !== null && owner.ns === null;
1130
+ const keep = unnamespaced ? UNNAMESPACED_STORE_MAX_AGE_MS : MARKER_MAX_AGE_MS;
1131
+ if (now - storeTouched(store) <= keep)
1107
1132
  continue;
1108
1133
  rmSync(store, { recursive: true, force: true });
1109
1134
  } catch {}
1110
1135
  }
1111
1136
  }
1112
- function askgateState(dir) {
1137
+ function recordNamesStore(dir) {
1138
+ const record = join(dir, ASKGATE_RECORD);
1139
+ let names;
1140
+ try {
1141
+ names = readdirSync(record);
1142
+ } catch (error) {
1143
+ return !hasErrnoCode(error, "ENOENT");
1144
+ }
1145
+ for (const name of names) {
1146
+ if (!name.endsWith(OWNER_FILE))
1147
+ continue;
1148
+ try {
1149
+ const parsed = parseOwner(readFileSync(join(record, name), "utf-8"));
1150
+ if (parsed === undefined)
1151
+ return true;
1152
+ statSync(parsed.owner.store);
1153
+ return true;
1154
+ } catch (error) {
1155
+ if (!hasErrnoCode(error, "ENOENT"))
1156
+ return true;
1157
+ }
1158
+ }
1159
+ return false;
1160
+ }
1161
+ function askgateState(dir, now = Date.now()) {
1113
1162
  const record = join(dir, ASKGATE_RECORD);
1114
1163
  let names;
1115
1164
  try {
@@ -1135,8 +1184,9 @@ function askgateState(dir) {
1135
1184
  const parsed = parseOwner(text);
1136
1185
  if (parsed === undefined)
1137
1186
  return { kind: "broken", problem: `${file}, is not an AskGate record` };
1138
- if (ownerLive(parsed.owner))
1187
+ if (ownerLive(parsed.owner, now)) {
1139
1188
  live.push({ file, store: parsed.owner.store, mode: parsed.mode });
1189
+ }
1140
1190
  }
1141
1191
  if (live.length === 0)
1142
1192
  return { kind: "off" };
@@ -21493,7 +21543,8 @@ function pruneSessions(root, now) {
21493
21543
  continue;
21494
21544
  const dir = join3(sessions, entry.name);
21495
21545
  try {
21496
- if (now - statSync2(dir).mtimeMs > IDLE_SESSION_MS && askgateState(dir).kind === "off") {
21546
+ const idle = now - statSync2(dir).mtimeMs > IDLE_SESSION_MS;
21547
+ if (idle && askgateState(dir, now).kind === "off" && !recordNamesStore(dir)) {
21497
21548
  rmSync3(dir, { recursive: true, force: true });
21498
21549
  }
21499
21550
  } catch (error) {
@@ -21515,7 +21566,7 @@ import {
21515
21566
  mkdtempSync,
21516
21567
  openSync as openSync3,
21517
21568
  readFileSync as readFileSync4,
21518
- readlinkSync,
21569
+ readlinkSync as readlinkSync2,
21519
21570
  rmSync as rmSync4,
21520
21571
  statSync as statSync3
21521
21572
  } from "fs";
@@ -21742,7 +21793,7 @@ function describeSchemaIssue(filePath, error) {
21742
21793
  }
21743
21794
  function danglingLink(filePath) {
21744
21795
  try {
21745
- return lstatSync(filePath).isSymbolicLink() ? readlinkSync(filePath) : null;
21796
+ return lstatSync(filePath).isSymbolicLink() ? readlinkSync2(filePath) : null;
21746
21797
  } catch {
21747
21798
  return null;
21748
21799
  }
package/dist/envoy.js CHANGED
@@ -30997,10 +30997,12 @@ import {
30997
30997
  openSync,
30998
30998
  readdirSync,
30999
30999
  readFileSync,
31000
+ readlinkSync,
31000
31001
  renameSync,
31001
31002
  rmSync,
31002
31003
  statSync,
31003
31004
  unlinkSync,
31005
+ utimesSync,
31004
31006
  writeFileSync
31005
31007
  } from "fs";
31006
31008
  import { isAbsolute, join, resolve } from "path";
@@ -31016,6 +31018,7 @@ function hasErrnoCode(error, code) {
31016
31018
  // ../envoy-client/src/askgate-marker.ts
31017
31019
  var ASKGATE_RECORD = "askgate";
31018
31020
  var MARKER_MAX_AGE_MS = 2 * 60 * 60000;
31021
+ var STORE_BEAT_MS = 10 * 60000;
31019
31022
  var PRIVATE_DIR = 448;
31020
31023
  var PRIVATE_FILE = 384;
31021
31024
  var MARKERS = "markers";
@@ -31082,17 +31085,38 @@ function processStart(pid) {
31082
31085
  return null;
31083
31086
  }
31084
31087
  }
31085
- function ownerName(pid, start) {
31086
- return start === null ? String(pid) : `${pid}-${start}`;
31088
+ var ownNamespace;
31089
+ function pidNamespace() {
31090
+ if (ownNamespace === undefined) {
31091
+ try {
31092
+ ownNamespace = /^pid:\[([0-9]+)\]$/.exec(readlinkSync("/proc/self/ns/pid"))?.[1] ?? null;
31093
+ } catch {
31094
+ ownNamespace = null;
31095
+ }
31096
+ }
31097
+ return ownNamespace;
31098
+ }
31099
+ function ownerName({ pid, start, ns }) {
31100
+ if (start === null)
31101
+ return String(pid);
31102
+ return ns === null ? `${pid}-${start}` : `${pid}-${start}-${ns}`;
31087
31103
  }
31088
- function askgateStore(root, pid, start) {
31089
- return join(root, "askgate", ownerName(pid, start));
31104
+ function askgateStore(root, pid, start, ns = null) {
31105
+ return join(root, "askgate", ownerName({ pid, start, ns }));
31090
31106
  }
31091
31107
  function selfOwner(root) {
31092
31108
  const start = processStart(process.pid);
31093
- return { pid: process.pid, start, store: askgateStore(root, process.pid, start) };
31109
+ const ns = pidNamespace();
31110
+ return { pid: process.pid, start, ns, store: askgateStore(root, process.pid, start, ns) };
31094
31111
  }
31095
- function ownerLive(owner) {
31112
+ function ownerLive(owner, now) {
31113
+ if (owner.ns !== null && owner.ns !== pidNamespace()) {
31114
+ try {
31115
+ return now - storeTouched(owner.store) <= MARKER_MAX_AGE_MS;
31116
+ } catch {
31117
+ return false;
31118
+ }
31119
+ }
31096
31120
  if (owner.start !== null)
31097
31121
  return processStart(owner.pid) === owner.start;
31098
31122
  try {
@@ -31102,11 +31126,11 @@ function ownerLive(owner) {
31102
31126
  return !hasErrnoCode(error, "ESRCH");
31103
31127
  }
31104
31128
  }
31105
- function isOwner(value) {
31129
+ function isOwnerText(value) {
31106
31130
  if (typeof value !== "object" || value === null)
31107
31131
  return false;
31108
- const { pid, start, store } = value;
31109
- return typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0 && (start === null || typeof start === "string") && typeof store === "string" && store.startsWith("/");
31132
+ const { pid, start, ns, store } = value;
31133
+ return typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0 && (start === null || typeof start === "string") && (ns === undefined || ns === null || typeof ns === "string" && /^[0-9]+$/.test(ns)) && typeof store === "string" && store.startsWith("/");
31110
31134
  }
31111
31135
  function parseOwner(text) {
31112
31136
  let data;
@@ -31115,11 +31139,11 @@ function parseOwner(text) {
31115
31139
  } catch {
31116
31140
  return;
31117
31141
  }
31118
- if (!isOwner(data) || !("v" in data) || data.v !== 2)
31142
+ if (!isOwnerText(data) || data.v !== 2)
31119
31143
  return;
31120
- const { pid, start, store, mode } = data;
31144
+ const { pid, start, ns, store, mode } = data;
31121
31145
  return {
31122
- owner: { pid, start, store },
31146
+ owner: { pid, start, ns: ns ?? null, store },
31123
31147
  mode: mode === "block" ? "block" : "warn"
31124
31148
  };
31125
31149
  }
@@ -31130,9 +31154,10 @@ function writeAtomically(file, text) {
31130
31154
  }
31131
31155
  var OWNER_FILE = ".json";
31132
31156
  function ownerFile(dir, owner) {
31133
- return join(dir, ASKGATE_RECORD, `${ownerName(owner.pid, owner.start)}${OWNER_FILE}`);
31157
+ return join(dir, ASKGATE_RECORD, `${ownerName(owner)}${OWNER_FILE}`);
31134
31158
  }
31135
- function writeAskgateRecord(dir, owner, mode) {
31159
+ function writeAskgateRecord(dir, owner, mode, now = Date.now()) {
31160
+ keepStore(owner.store, now);
31136
31161
  const record = join(dir, ASKGATE_RECORD);
31137
31162
  mkdirSync(record, { recursive: true, mode: PRIVATE_DIR });
31138
31163
  const own = ownerFile(dir, owner);
@@ -31147,12 +31172,15 @@ function writeAskgateRecord(dir, owner, mode) {
31147
31172
  } catch {
31148
31173
  continue;
31149
31174
  }
31150
- if (other !== undefined && other.owner.start !== null && !ownerLive(other.owner)) {
31175
+ const gone = other !== undefined && other.owner.start !== null && other.owner.ns !== null && other.owner.ns === pidNamespace() && !ownerLive(other.owner, now);
31176
+ if (gone) {
31151
31177
  rmSync(file, { force: true });
31152
31178
  }
31153
31179
  }
31154
31180
  }
31155
- function setRecordMode(dir, owner, mode) {
31181
+ function setRecordMode(dir, owner, mode, now = Date.now()) {
31182
+ keepStore(owner.store, now);
31183
+ mkdirSync(join(dir, ASKGATE_RECORD), { recursive: true, mode: PRIVATE_DIR });
31156
31184
  writeAtomically(ownerFile(dir, owner), ownerText(owner, mode));
31157
31185
  }
31158
31186
  function recordedOwnerMode(dir, owner) {
@@ -31163,7 +31191,8 @@ function recordedOwnerMode(dir, owner) {
31163
31191
  }
31164
31192
  }
31165
31193
  function ownerText(owner, mode) {
31166
- return JSON.stringify({ v: 2, pid: owner.pid, start: owner.start, store: owner.store, mode });
31194
+ const { pid, start, ns, store } = owner;
31195
+ return JSON.stringify({ v: 2, pid, start, ns, store, mode });
31167
31196
  }
31168
31197
  function dropAskgateRecord(dir, owner) {
31169
31198
  rmSync(ownerFile(dir, owner), { force: true });
@@ -31171,9 +31200,25 @@ function dropAskgateRecord(dir, owner) {
31171
31200
  function openStore(store) {
31172
31201
  mkdirSync(join(store, MARKERS), { recursive: true, mode: PRIVATE_DIR });
31173
31202
  }
31203
+ function keepStore(store, now) {
31204
+ openStore(store);
31205
+ const at = new Date(now);
31206
+ utimesSync(store, at, at);
31207
+ }
31174
31208
  function closeStore(store) {
31175
31209
  rmSync(store, { recursive: true, force: true });
31176
31210
  }
31211
+ function storeTouched(store) {
31212
+ const own = statSync(store).mtimeMs;
31213
+ try {
31214
+ return Math.max(own, statSync(join(store, MARKERS)).mtimeMs);
31215
+ } catch (error) {
31216
+ if (hasErrnoCode(error, "ENOENT"))
31217
+ return own;
31218
+ throw error;
31219
+ }
31220
+ }
31221
+ var UNNAMESPACED_STORE_MAX_AGE_MS = 14 * 86400000;
31177
31222
  function sweepMarkers(dir, now) {
31178
31223
  for (const name of readdirSync(dir)) {
31179
31224
  const file = join(dir, name);
@@ -33881,7 +33926,7 @@ import {
33881
33926
  mkdtempSync,
33882
33927
  openSync as openSync2,
33883
33928
  readFileSync as readFileSync3,
33884
- readlinkSync,
33929
+ readlinkSync as readlinkSync2,
33885
33930
  rmSync as rmSync2,
33886
33931
  statSync as statSync2
33887
33932
  } from "fs";
@@ -34108,7 +34153,7 @@ function describeSchemaIssue(filePath, error) {
34108
34153
  }
34109
34154
  function danglingLink(filePath) {
34110
34155
  try {
34111
- return lstatSync(filePath).isSymbolicLink() ? readlinkSync(filePath) : null;
34156
+ return lstatSync(filePath).isSymbolicLink() ? readlinkSync2(filePath) : null;
34112
34157
  } catch {
34113
34158
  return null;
34114
34159
  }
@@ -37914,7 +37959,7 @@ var envoyToolSpecs = [
37914
37959
  },
37915
37960
  {
37916
37961
  name: "envoy_publish",
37917
- description: `Publish an Envoy message to a notifications. topic. ${STORED_DELIVERY} A role or built-in topic is delivered as its guide says; a role message errs when its holder did not confirm it within the listener's window. A team or ad-hoc topic (such as notifications.team.deploy-squad.all) reaches every session subscribed to it when you publish, and is not kept for a session that subscribes later. The listener confirms it with each other session that holds its own NATS connection and registered the topic, and errs naming each session that did not confirm; a session that stopped without unregistering stays registered for up to 5 minutes and is named in that time, and a named session is not a failed delivery to the other sessions. A session that holds its own NATS connection receives such a live topic directly, yours included; a session the listener delivers to over a serve port is not confirmed and receives it through its machine's listener when that listener subscribes to every topic (ENVOY_SUBSCRIBE_ALL_TOPICS=1; the shared hub's listener does not). ${DELIVERY_CONTRACT}`,
37962
+ description: `Publish an Envoy message to a notifications. topic. ${STORED_DELIVERY} A role or built-in topic is delivered as its guide says; a role message errs when its holder did not confirm it within the listener's window. A team or ad-hoc topic (such as notifications.team.deploy-squad.all) reaches every session subscribed to it when you publish, and is not kept for a session that subscribes later. The listener confirms it with each other session that holds its own NATS connection and registered the topic, and errs naming each session that did not confirm; a session that stopped without unregistering stays registered for up to 5 minutes and is named in that time, and a named session is not a failed delivery to the other sessions. A session that holds its own NATS connection receives such a live topic directly, yours included. ${DELIVERY_CONTRACT}`,
37918
37963
  arguments: (schema) => ({ topic: schema.string(), ...messageArguments(schema) }),
37919
37964
  operation: EnvoyToolOperation.publish
37920
37965
  },
@@ -38282,7 +38327,7 @@ var import_nats2 = __toESM(require_mod4(), 1);
38282
38327
 
38283
38328
  // package.json
38284
38329
  var name = "@sjawhar/pi-envoy";
38285
- var version2 = "15.6.0";
38330
+ var version2 = "16.0.0";
38286
38331
  var package_default = {
38287
38332
  name,
38288
38333
  version: version2,
@@ -44140,6 +44185,7 @@ function envoyExtension(pi) {
44140
44185
  }
44141
44186
  const askgateOwner = askgateFile === null ? undefined : selfOwner(sessionStateRoot(process.env));
44142
44187
  const askgateRecords = new Set;
44188
+ let askgateBeat;
44143
44189
  const serverClock = new ServerClock(() => Date.now());
44144
44190
  const active = envoy.enabled ? {
44145
44191
  settings: envoy,
@@ -44289,10 +44335,20 @@ function envoyExtension(pi) {
44289
44335
  if (askgateOwner !== undefined) {
44290
44336
  const dir = sessionDirectory(process.env, id);
44291
44337
  try {
44292
- openStore(askgateOwner.store);
44293
44338
  const recorded = recordedOwnerMode(dir, askgateOwner);
44294
44339
  writeAskgateRecord(dir, askgateOwner, process.env.OMP_ASKGATE?.trim() === "block" || recorded === "block" ? "block" : "warn");
44295
44340
  askgateRecords.add(dir);
44341
+ if (askgateBeat === undefined) {
44342
+ const { store } = askgateOwner;
44343
+ askgateBeat = setInterval(() => {
44344
+ try {
44345
+ keepStore(store, Date.now());
44346
+ } catch (error) {
44347
+ logger3.warn(`AskGate could not touch its marker store ${store}: ${messageFor(error)}`);
44348
+ }
44349
+ }, STORE_BEAT_MS);
44350
+ askgateBeat.unref();
44351
+ }
44296
44352
  } catch (error) {
44297
44353
  const notice = `AskGate could not write its record for session ${id} (${messageFor(error)}), so the dispatch CLI does not ask for AskGate's marker there: a Dispatch write AskGate cannot read posts unreviewed.`;
44298
44354
  logger3.warn(notice);
@@ -44712,6 +44768,8 @@ ${REPLAYED_BTW_NOTE}`, "inert", identity, claim);
44712
44768
  let shuttingDown = false;
44713
44769
  const intentionallyClosed = new Set;
44714
44770
  const awaitingRetry = new Set;
44771
+ const SUBSCRIBE_FLUSH_TIMEOUT_MS = 1e4;
44772
+ const unconfirmed = new Map;
44715
44773
  const closeIntentionally = (topic) => {
44716
44774
  const subscription = subscriptions.get(topic);
44717
44775
  if (subscription === undefined) {
@@ -44760,7 +44818,7 @@ ${REPLAYED_BTW_NOTE}`, "inert", identity, claim);
44760
44818
  awaitingRetry.add(topic);
44761
44819
  setTimeout(() => {
44762
44820
  awaitingRetry.delete(topic);
44763
- if (shuttingDown || subscriptions.has(topic))
44821
+ if (shuttingDown || subscriptions.has(topic) && !unconfirmed.has(topic))
44764
44822
  return;
44765
44823
  if (intentionallyClosed.delete(topic))
44766
44824
  return;
@@ -44772,19 +44830,62 @@ ${REPLAYED_BTW_NOTE}`, "inert", identity, claim);
44772
44830
  };
44773
44831
  retry(RESUBSCRIBE_DELAY_MS);
44774
44832
  };
44833
+ const within = async (promise, ms, what) => {
44834
+ const expired = Promise.withResolvers();
44835
+ const timer = setTimeout(() => expired.reject(new Error(`${what} timed out after ${ms} ms`)), ms);
44836
+ try {
44837
+ return await Promise.race([promise, expired.promise]);
44838
+ } finally {
44839
+ clearTimeout(timer);
44840
+ }
44841
+ };
44775
44842
  const subscribe = async (topic, connect = ensureConnection) => {
44776
- const subjects = expandSubscriptionTopics([topic]).filter((candidate) => !subscriptions.has(candidate));
44777
- if (subjects.length === 0)
44843
+ const subjects = expandSubscriptionTopics([topic]);
44844
+ const fresh = subjects.filter((candidate) => !subscriptions.has(candidate));
44845
+ const confirming = subjects.filter((candidate) => !subscriptions.has(candidate) || unconfirmed.has(candidate));
44846
+ if (confirming.length === 0)
44778
44847
  return false;
44779
44848
  const activeConnection = await connect();
44780
- for (const subject of subjects) {
44849
+ for (const subject of fresh) {
44781
44850
  const subscription = activeConnection.subscribe(subject);
44782
44851
  intentionallyClosed.delete(subject);
44783
44852
  subscriptions.set(subject, subscription);
44784
44853
  pump(subject, subscription);
44785
44854
  }
44855
+ const pending = confirming.flatMap((subject) => {
44856
+ const subscription = subscriptions.get(subject);
44857
+ return subscription === undefined ? [] : [[subject, subscription]];
44858
+ });
44859
+ for (const [subject, subscription] of pending)
44860
+ unconfirmed.set(subject, subscription);
44861
+ await within(activeConnection.flush(), SUBSCRIBE_FLUSH_TIMEOUT_MS, `confirming the subscription to ${topic}`);
44862
+ for (const [subject, subscription] of pending) {
44863
+ if (unconfirmed.get(subject) === subscription && subscriptions.get(subject) === subscription) {
44864
+ unconfirmed.delete(subject);
44865
+ }
44866
+ }
44786
44867
  return true;
44787
44868
  };
44869
+ const confirmPending = async (connect = ensureConnection) => {
44870
+ for (const [subject, subscription] of unconfirmed) {
44871
+ if (subscriptions.get(subject) !== subscription)
44872
+ unconfirmed.delete(subject);
44873
+ }
44874
+ const pending = [...unconfirmed];
44875
+ if (pending.length === 0)
44876
+ return;
44877
+ const activeConnection = await connect();
44878
+ await within(activeConnection.flush(), SUBSCRIBE_FLUSH_TIMEOUT_MS, `confirming the subscriptions to ${pending.map(([subject]) => subject).join(", ")}`);
44879
+ for (const [subject, subscription] of pending) {
44880
+ if (unconfirmed.get(subject) === subscription && subscriptions.get(subject) === subscription) {
44881
+ unconfirmed.delete(subject);
44882
+ }
44883
+ }
44884
+ };
44885
+ const agentSubjectUnconfirmed = (session) => {
44886
+ const own = agentSubject(session);
44887
+ return subscriptions.has(own) && unconfirmed.has(own);
44888
+ };
44788
44889
  const noteInbox = (envelope) => {
44789
44890
  inbox.unshift({
44790
44891
  event_id: envelope.event_id ?? "unknown",
@@ -44993,6 +45094,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
44993
45094
  });
44994
45095
  let agentStreamControl;
44995
45096
  let agentStreamControlSession = "";
45097
+ let agentStreamControlConfirmed = false;
44996
45098
  let agentStreamCommandsRefreshedOnWatchAt = -Infinity;
44997
45099
  let agentStreamViewerAttached = false;
44998
45100
  const refreshAgentStreamCommands = (session) => {
@@ -45094,20 +45196,30 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
45094
45196
  }, RESUBSCRIBE_DELAY_MS);
45095
45197
  };
45096
45198
  const watchAgentStream = async (session, connect = ensureConnection) => {
45097
- if (agentStreamControlSession === session && agentStreamControl !== undefined)
45098
- return;
45099
- agentStreamControl?.unsubscribe();
45100
- agentStreamControl = undefined;
45101
- if (agentStreamControlSession !== session) {
45102
- agentStream.reset();
45103
- agentStreamViewerAttached = false;
45104
- agentStreamCommandsRefreshedOnWatchAt = -Infinity;
45105
- }
45106
- agentStreamControlSession = session;
45107
- const connected = await connect();
45108
- const subscription = connected.subscribe(agentStreamControlSubject(session));
45109
- agentStreamControl = subscription;
45110
- pumpAgentStreamControl(subscription, session);
45199
+ let subscription = agentStreamControlSession === session ? agentStreamControl : undefined;
45200
+ let connected;
45201
+ if (subscription !== undefined) {
45202
+ if (agentStreamControlConfirmed)
45203
+ return;
45204
+ connected = await connect();
45205
+ } else {
45206
+ agentStreamControl?.unsubscribe();
45207
+ agentStreamControl = undefined;
45208
+ if (agentStreamControlSession !== session) {
45209
+ agentStream.reset();
45210
+ agentStreamViewerAttached = false;
45211
+ agentStreamCommandsRefreshedOnWatchAt = -Infinity;
45212
+ }
45213
+ agentStreamControlSession = session;
45214
+ connected = await connect();
45215
+ subscription = connected.subscribe(agentStreamControlSubject(session));
45216
+ agentStreamControl = subscription;
45217
+ agentStreamControlConfirmed = false;
45218
+ pumpAgentStreamControl(subscription, session);
45219
+ }
45220
+ await within(connected.flush(), SUBSCRIBE_FLUSH_TIMEOUT_MS, `confirming the agent stream control subscription for ${session}`);
45221
+ if (agentStreamControl === subscription)
45222
+ agentStreamControlConfirmed = true;
45111
45223
  };
45112
45224
  const recordAgentStreamMessage = (message, streaming) => {
45113
45225
  if (sessionID === "")
@@ -45177,7 +45289,7 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
45177
45289
  const topics = [
45178
45290
  ...new Set([
45179
45291
  own,
45180
- ...[...subscriptions.keys()].filter((subject) => !registrationState.isRoleBound(subject) && !reachesPrivateStreamSubject(own, subject))
45292
+ ...[...subscriptions.keys()].filter((subject) => !unconfirmed.has(subject) && !registrationState.isRoleBound(subject) && !reachesPrivateStreamSubject(own, subject))
45181
45293
  ])
45182
45294
  ];
45183
45295
  if (asking !== undefined)
@@ -45197,6 +45309,9 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
45197
45309
  };
45198
45310
  const sendRegistration = (send) => {
45199
45311
  const registeringFor = sessionID;
45312
+ if (agentSubjectUnconfirmed(registeringFor)) {
45313
+ return Promise.reject(new Error(`the server has not confirmed this session's subscription to ${agentSubject(registeringFor)}, so the session is not registered until it does`));
45314
+ }
45200
45315
  const asking = relay?.sessionID === registeringFor && relay.subscription !== undefined ? relay : undefined;
45201
45316
  const input = registrationInput(asking);
45202
45317
  return send(input).then((result) => {
@@ -45403,10 +45518,18 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
45403
45518
  inboundFailure = error;
45404
45519
  }
45405
45520
  }
45521
+ let confirmFailure;
45522
+ if (inbound && inboundFailure === undefined) {
45523
+ await confirmPending(handle.connect).catch((error) => {
45524
+ confirmFailure = error;
45525
+ });
45526
+ }
45406
45527
  handle.check();
45407
45528
  const registration = await sendRegistration(handle.register).then(() => {
45408
45529
  return;
45409
- }, (error) => ({ error }));
45530
+ }, (error) => ({
45531
+ error: agentSubjectUnconfirmed(host) ? inboundFailure ?? confirmFailure ?? error : error
45532
+ }));
45410
45533
  handle.check();
45411
45534
  if (registration === undefined) {
45412
45535
  handle.markEstablished(host);
@@ -45662,6 +45785,8 @@ ${REPLAYED_BTW_NOTE}`, frame.envelope, "inert");
45662
45785
  } catch {}
45663
45786
  }
45664
45787
  askgateRecords.clear();
45788
+ clearInterval(askgateBeat);
45789
+ askgateBeat = undefined;
45665
45790
  closeStore(askgateOwner.store);
45666
45791
  }
45667
45792
  const deadline = Promise.withResolvers();
@@ -67,6 +67,6 @@ Every topic starts with `notifications.`.
67
67
 
68
68
  - Send to one session with `envoy_send`, to the one session that holds a named duty with a role, and to a group with a team topic.
69
69
  - Publish to a role with `envoy_publish(topic="notifications.role.<role>", ...)`; never subscribe to a role topic, because the listener forwards a role message to its holder only. A publish returns once the holder's session confirmed it, with the live `holder`. An unheld role returns an error, and so does a holder that did not confirm the message within about 4 seconds; that error names the holder, and you see it after about 8 seconds, because the client tries once more. `envoy_role_get(role=...)` finds the holder first. The stream keeps the forward on the holder's inbox, so the holder's session gets it once from its own durable consumer, also after a restart or a reconnect.
70
- - For a team, the group subscribes to `notifications.team.<name>.>`, and any member publishes to `notifications.team.<name>.all`. Envoy treats any other `notifications.` topic that no source in the table uses the same way. It reaches every session subscribed when it is published (yours too, when you subscribe, unless you are a serve-port session, which receives it only through a listener run with `ENVOY_SUBSCRIBE_ALL_TOPICS=1` and never its own publish). The listener also asks each other session that holds its own NATS connection and registered the topic (every session that follows it with `envoy_subscribe`) to confirm the message; your own session is never asked. A publish returns an error naming each such session that did not confirm within about 4 seconds, and you see it after about 8 seconds, because the client tries once more. A session named with `receipt_timeout` still gets the message: the listener kept a copy in that session's inbox, which the session reads back once its connection returns. A session that stopped without unregistering stays registered for up to 5 minutes and is named in that time; a named session is not a failed delivery to the others. A team topic is not kept for a session that subscribes later. A topic outside `notifications.` is refused.
70
+ - For a team, the group subscribes to `notifications.team.<name>.>`, and any member publishes to `notifications.team.<name>.all`. Envoy treats any other `notifications.` topic that no source in the table uses the same way. It reaches every session subscribed when it is published, yours too when you subscribe. The listener also asks each other session that holds its own NATS connection and registered the topic (every session that follows it with `envoy_subscribe`) to confirm the message; your own session is never asked. A publish returns an error naming each such session that did not confirm within about 4 seconds, and you see it after about 8 seconds, because the client tries once more. A session named with `receipt_timeout` still gets the message: the listener kept a copy in that session's inbox, which the session reads back once its connection returns. A session that stopped without unregistering stays registered for up to 5 minutes and is named in that time; a named session is not a failed delivery to the others. A team topic is not kept for a session that subscribes later. A topic outside `notifications.` is refused.
71
71
  - How a role claim survives a resume, a fork or a dead process: `skill://envoy/references/roles.md`.
72
72
  - In a Legion pane, the plugin claims your role at session start; read `skill://envoy/references/legion.md` before you claim, release or publish to a role, or answer a role delivery failure there.
@@ -59,7 +59,6 @@ It depends on where a session takes its deliveries, not on whether the topic is
59
59
 
60
60
  - An Oh My Pi or Claude Code session takes its messages from a durable consumer the listener keeps for it on Envoy's stream and relays to it in order, acknowledging each one only once the session wrote it. So every message the stream keeps — your inbox, and each topic you follow with `envoy_subscribe` — reaches you once, whoever sent it: your own publish included, and a subagent's publish to a topic its parent follows. One published while you were restarting, disconnected or not running reaches you when you are back, up to 72 hours later. A session does not take its messages from a NATS subscription of its own; `packages/envoy/AGENTS.md`, "Session consumers", is the rule.
61
61
  - A team or other ad-hoc topic is the exception: the stream keeps none, so such a topic reaches only the sessions connected and subscribed when it is published, and nothing recovers it. The listener also forwards the message to the inbox of every other session registered on the topic with `envoy_subscribe`, and the stream keeps that copy, so a session that registered it gets it once after a restart too. What a team topic you subscribed to without registering carried meanwhile is gone.
62
- - A session the listener delivers to by push, over a serve port, does not receive its own publish, and receives a team topic only through the listener that owns it when that listener runs with `ENVOY_SUBSCRIBE_ALL_TOPICS=1` (the shared hub's listener does not). It receives the stored messages for it by the listener's push, which the listener repeats until the port accepts each one.
63
62
  - A role is not a subject its holder subscribes to: the listener finds the live holder and forwards the message to it, and drops the message when that holder is the message's source session. The stream keeps the forward on the holder's inbox, so the holder's session gets it once, also after a restart.
64
63
  - A session whose plugin, or whose listener, is of an earlier release falls back to the core path while the rollout lasts (dispatch://INFRA-771 removes it): there it receives live on its own NATS subscriptions, and recovers what the stream stored for it itself, marked as published while its connection was down. It does not recover a role message that way.
65
64
 
@@ -38,4 +38,4 @@ envoy_publish(
38
38
  )
39
39
  ```
40
40
 
41
- The subscribed session should receive it. An Oh My Pi or Claude Code session receives its own publish, so it can run both steps; a session delivered over a serve port cannot, and needs a second session to publish. Real WhatsApp delivery also needs the listener's MCP bridge configured with a `whatsapp` server (`packages/envoy/internal/mcpbridge`).
41
+ The subscribed session should receive it. An Oh My Pi or Claude Code session receives its own publish, so it can run both steps. Real WhatsApp delivery also needs the listener's MCP bridge configured with a `whatsapp` server (`packages/envoy/internal/mcpbridge`).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sjawhar/pi-envoy",
3
- "version": "15.6.0",
3
+ "version": "16.0.0",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "omp": {