@sjawhar/claude-envoy 4.15.2 → 4.15.4
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/.claude-plugin/plugin.json +1 -1
- package/.omp-plugin/plugin.json +1 -1
- package/README.md +8 -0
- package/dist/envoy-channel.js +772 -348
- package/package.json +2 -2
- package/src/agent-stream-runner.ts +83 -95
- package/src/channel-connection.ts +306 -0
- package/src/channel-topics.ts +17 -10
- package/src/codex/codex-agent-stream.ts +43 -64
- package/src/codex/codex-server.ts +57 -17
- package/src/control-subscription.ts +166 -0
- package/src/envoy-channel-server.ts +447 -222
package/dist/envoy-channel.js
CHANGED
|
@@ -13365,8 +13365,17 @@ var require_protocol = __commonJS(function(exports) {
|
|
|
13365
13365
|
this.connectError = (err) => {
|
|
13366
13366
|
pong.reject(err);
|
|
13367
13367
|
};
|
|
13368
|
-
|
|
13369
|
-
this.transport
|
|
13368
|
+
const transport = (0, transport_1.newTransport)();
|
|
13369
|
+
this.transport = transport;
|
|
13370
|
+
const errorBefore = this.lastError;
|
|
13371
|
+
transport.closed().then((_err) => __awaiter(this, undefined, undefined, function* () {
|
|
13372
|
+
if (transport !== this.transport) {
|
|
13373
|
+
return;
|
|
13374
|
+
}
|
|
13375
|
+
if (!this.connected) {
|
|
13376
|
+
pong.reject(this.lastError !== errorBefore && this.lastError ? this.lastError : transport.closeError || core_1.NatsError.errorForCode(core_1.ErrorCode.Disconnect));
|
|
13377
|
+
return;
|
|
13378
|
+
}
|
|
13370
13379
|
this.connected = false;
|
|
13371
13380
|
if (!this.isClosed()) {
|
|
13372
13381
|
yield this.disconnected(this.transport.closeError || this.lastError);
|
|
@@ -13454,6 +13463,9 @@ var require_protocol = __commonJS(function(exports) {
|
|
|
13454
13463
|
if (timer) {
|
|
13455
13464
|
timer.cancel();
|
|
13456
13465
|
}
|
|
13466
|
+
if (this._closed) {
|
|
13467
|
+
throw core_1.NatsError.errorForCode(core_1.ErrorCode.ConnectionClosed);
|
|
13468
|
+
}
|
|
13457
13469
|
this.connected = true;
|
|
13458
13470
|
this.connectError = undefined;
|
|
13459
13471
|
this.sendSubscriptions();
|
|
@@ -13474,6 +13486,9 @@ var require_protocol = __commonJS(function(exports) {
|
|
|
13474
13486
|
_doDial(srv) {
|
|
13475
13487
|
return __awaiter(this, undefined, undefined, function* () {
|
|
13476
13488
|
const { resolve } = this.options;
|
|
13489
|
+
if (this.options.abandonSignal && this.options.abandonSignal.aborted) {
|
|
13490
|
+
throw core_1.NatsError.errorForCode(core_1.ErrorCode.Timeout);
|
|
13491
|
+
}
|
|
13477
13492
|
const alts = yield srv.resolve({
|
|
13478
13493
|
fn: (0, transport_1.getResolveFn)(),
|
|
13479
13494
|
debug: this.options.debug,
|
|
@@ -13482,6 +13497,12 @@ var require_protocol = __commonJS(function(exports) {
|
|
|
13482
13497
|
});
|
|
13483
13498
|
let lastErr = null;
|
|
13484
13499
|
for (const a of alts) {
|
|
13500
|
+
if (this._closed) {
|
|
13501
|
+
throw lastErr || core_1.NatsError.errorForCode(core_1.ErrorCode.ConnectionClosed);
|
|
13502
|
+
}
|
|
13503
|
+
if (this.options.abandonSignal && this.options.abandonSignal.aborted) {
|
|
13504
|
+
throw lastErr || core_1.NatsError.errorForCode(core_1.ErrorCode.Timeout);
|
|
13505
|
+
}
|
|
13485
13506
|
try {
|
|
13486
13507
|
lastErr = null;
|
|
13487
13508
|
this.dispatchStatus({ type: core_1.DebugEvents.Reconnecting, data: a.toString() });
|
|
@@ -56064,11 +56085,291 @@ class StdioServerTransport {
|
|
|
56064
56085
|
}
|
|
56065
56086
|
|
|
56066
56087
|
// src/codex/codex-server.ts
|
|
56067
|
-
var
|
|
56088
|
+
var import_nats6 = __toESM(require_mod4(), 1);
|
|
56068
56089
|
|
|
56069
56090
|
// codex/package.json
|
|
56070
56091
|
var name = "@sjawhar/codex-envoy";
|
|
56071
56092
|
|
|
56093
|
+
// ../envoy-client/src/nats-connection.ts
|
|
56094
|
+
var import_nats2 = __toESM(require_mod4(), 1);
|
|
56095
|
+
var import_nats3 = __toESM(require_nats(), 1);
|
|
56096
|
+
var import_servers = __toESM(require_servers(), 1);
|
|
56097
|
+
import { setTimeout as delay } from "timers/promises";
|
|
56098
|
+
|
|
56099
|
+
// ../envoy-client/src/nats-auth.ts
|
|
56100
|
+
var import_nats = __toESM(require_mod4(), 1);
|
|
56101
|
+
var seedKeys = import_nats.nkeys;
|
|
56102
|
+
function natsAuthOptions(credential) {
|
|
56103
|
+
switch (credential.kind) {
|
|
56104
|
+
case "none":
|
|
56105
|
+
return {};
|
|
56106
|
+
case "broker":
|
|
56107
|
+
return { authenticator: credential.broker.authenticator };
|
|
56108
|
+
case "seed": {
|
|
56109
|
+
const { seed } = credential;
|
|
56110
|
+
const bytes = new TextEncoder().encode(seed.value);
|
|
56111
|
+
let publicKey;
|
|
56112
|
+
try {
|
|
56113
|
+
publicKey = seedKeys.fromSeed(bytes).getPublicKey();
|
|
56114
|
+
} catch (error) {
|
|
56115
|
+
throw new Error(`${seed.source} does not hold a valid nkey seed: ${messageFor(error)}`);
|
|
56116
|
+
}
|
|
56117
|
+
if (!publicKey.startsWith("U")) {
|
|
56118
|
+
throw new Error(`${seed.source} holds an nkey seed that is not a user's (public key ${publicKey})`);
|
|
56119
|
+
}
|
|
56120
|
+
return { authenticator: import_nats.nkeyAuthenticator(bytes) };
|
|
56121
|
+
}
|
|
56122
|
+
}
|
|
56123
|
+
}
|
|
56124
|
+
|
|
56125
|
+
// ../envoy-client/src/nats-connection.ts
|
|
56126
|
+
var NATS_PING_INTERVAL_MS = 1e4;
|
|
56127
|
+
var NATS_MAX_PINGS_OUT = 2;
|
|
56128
|
+
var NATS_DIAL_TIMEOUT_MS = 1e4;
|
|
56129
|
+
function natsConnectionOptions(input) {
|
|
56130
|
+
return {
|
|
56131
|
+
servers: [...input.servers],
|
|
56132
|
+
name: input.name,
|
|
56133
|
+
...natsAuthOptions(input.credential),
|
|
56134
|
+
timeout: NATS_DIAL_TIMEOUT_MS,
|
|
56135
|
+
reconnect: true,
|
|
56136
|
+
maxReconnectAttempts: -1,
|
|
56137
|
+
reconnectTimeWait: 2000,
|
|
56138
|
+
pingInterval: NATS_PING_INTERVAL_MS,
|
|
56139
|
+
maxPingOut: NATS_MAX_PINGS_OUT,
|
|
56140
|
+
...input.credential.kind === "broker" ? { ignoreAuthErrorAbort: true } : {}
|
|
56141
|
+
};
|
|
56142
|
+
}
|
|
56143
|
+
function natsServersForLog(setting, count) {
|
|
56144
|
+
return count === 1 ? `the server ${setting} names` : `the ${count} servers ${setting} names`;
|
|
56145
|
+
}
|
|
56146
|
+
function natsDialFailure(named, error, presenting) {
|
|
56147
|
+
const credential = presenting === undefined ? "" : ` presenting ${presenting}`;
|
|
56148
|
+
return `could not connect to NATS at ${named}${credential}: ${natsFailureReason(error)}`;
|
|
56149
|
+
}
|
|
56150
|
+
var NATS_DIAL_PLAN = {
|
|
56151
|
+
firstDelayMs: 250,
|
|
56152
|
+
maxDelayMs: 4000,
|
|
56153
|
+
budgetMs: 25000
|
|
56154
|
+
};
|
|
56155
|
+
var NATS_MIN_REDIAL_BOUND_MS = 500;
|
|
56156
|
+
|
|
56157
|
+
class NatsDialBoundError extends LoggableError {
|
|
56158
|
+
}
|
|
56159
|
+
var AUTHORIZATION_REFUSALS = {
|
|
56160
|
+
[import_nats2.ErrorCode.AuthorizationViolation]: true,
|
|
56161
|
+
[import_nats2.ErrorCode.AuthenticationExpired]: true,
|
|
56162
|
+
[import_nats2.ErrorCode.AccountExpired]: true
|
|
56163
|
+
};
|
|
56164
|
+
var NEVER_CURED = {
|
|
56165
|
+
[import_nats2.ErrorCode.BadAuthentication]: true,
|
|
56166
|
+
[import_nats2.ErrorCode.BadCreds]: true,
|
|
56167
|
+
[import_nats2.ErrorCode.InvalidOption]: true,
|
|
56168
|
+
[import_nats2.ErrorCode.NotFunction]: true,
|
|
56169
|
+
[import_nats2.ErrorCode.ServerOptionNotAvailable]: true,
|
|
56170
|
+
[import_nats2.ErrorCode.WssRequired]: true,
|
|
56171
|
+
[import_nats2.ErrorCode.Tls]: true
|
|
56172
|
+
};
|
|
56173
|
+
function redialCures(error, options) {
|
|
56174
|
+
if (error instanceof NatsDialBoundError)
|
|
56175
|
+
return true;
|
|
56176
|
+
if (!(error instanceof Error) || !("code" in error) || typeof error.code !== "string")
|
|
56177
|
+
return false;
|
|
56178
|
+
const { code } = error;
|
|
56179
|
+
if (AUTHORIZATION_REFUSALS[code] === true)
|
|
56180
|
+
return options.ignoreAuthErrorAbort === true;
|
|
56181
|
+
return NEVER_CURED[code] !== true && !code.startsWith("ERR_");
|
|
56182
|
+
}
|
|
56183
|
+
async function connectNats(connect, options, plan, hooks = {}) {
|
|
56184
|
+
const started = performance.now();
|
|
56185
|
+
const elapsed = () => performance.now() - started;
|
|
56186
|
+
const timeout = options.timeout ?? NATS_DIAL_TIMEOUT_MS;
|
|
56187
|
+
const servers = Array.isArray(options.servers) ? Math.max(1, options.servers.length) : 1;
|
|
56188
|
+
let delayMs = plan.firstDelayMs;
|
|
56189
|
+
let failed;
|
|
56190
|
+
for (let attempt = 1;; attempt += 1) {
|
|
56191
|
+
if (hooks.stopped?.() === true) {
|
|
56192
|
+
throw failed ?? new LoggableError("the NATS dial was stopped before it began");
|
|
56193
|
+
}
|
|
56194
|
+
const bound = Math.max(1, Math.round(Math.min(timeout, attempt === 1 ? hooks.firstBoundMs ?? timeout : plan.budgetMs - elapsed())));
|
|
56195
|
+
try {
|
|
56196
|
+
const nc = await boundedDial(connect, {
|
|
56197
|
+
...options,
|
|
56198
|
+
timeout: Math.min(bound, Math.max(NATS_MIN_REDIAL_BOUND_MS, Math.floor(bound / servers)))
|
|
56199
|
+
}, bound);
|
|
56200
|
+
keepWholeTimeout(nc, timeout);
|
|
56201
|
+
return nc;
|
|
56202
|
+
} catch (error) {
|
|
56203
|
+
failed = error;
|
|
56204
|
+
const waitEnds = elapsed() + delayMs;
|
|
56205
|
+
if (!redialCures(error, options) || waitEnds + NATS_MIN_REDIAL_BOUND_MS > plan.budgetMs || hooks.stopped?.() === true) {
|
|
56206
|
+
throw error;
|
|
56207
|
+
}
|
|
56208
|
+
hooks.onRetry?.(error, delayMs, attempt);
|
|
56209
|
+
await delay(delayMs);
|
|
56210
|
+
if (plan.budgetMs - elapsed() < NATS_MIN_REDIAL_BOUND_MS)
|
|
56211
|
+
throw error;
|
|
56212
|
+
delayMs = Math.min(delayMs * 2, plan.maxDelayMs);
|
|
56213
|
+
}
|
|
56214
|
+
}
|
|
56215
|
+
}
|
|
56216
|
+
function keepWholeTimeout(nc, timeout) {
|
|
56217
|
+
if (!(nc instanceof import_nats3.NatsConnectionImpl))
|
|
56218
|
+
return;
|
|
56219
|
+
const opened = nc.options;
|
|
56220
|
+
opened.timeout = timeout;
|
|
56221
|
+
delete opened.abandonSignal;
|
|
56222
|
+
}
|
|
56223
|
+
async function boundedDial(connect, options, boundMs) {
|
|
56224
|
+
const abandon = new AbortController;
|
|
56225
|
+
const withAbandon = {
|
|
56226
|
+
...options,
|
|
56227
|
+
abandonSignal: abandon.signal
|
|
56228
|
+
};
|
|
56229
|
+
const dialing = connect(withAbandon);
|
|
56230
|
+
const expired = Promise.withResolvers();
|
|
56231
|
+
const timer = setTimeout(() => {
|
|
56232
|
+
abandon.abort();
|
|
56233
|
+
expired.reject(new NatsDialBoundError(`the NATS dial did not complete within ${boundMs} ms`));
|
|
56234
|
+
}, boundMs);
|
|
56235
|
+
try {
|
|
56236
|
+
return await Promise.race([dialing, expired.promise]);
|
|
56237
|
+
} catch (error) {
|
|
56238
|
+
dialing.then((late) => late.close()).catch(() => {
|
|
56239
|
+
return;
|
|
56240
|
+
});
|
|
56241
|
+
throw error;
|
|
56242
|
+
} finally {
|
|
56243
|
+
clearTimeout(timer);
|
|
56244
|
+
}
|
|
56245
|
+
}
|
|
56246
|
+
|
|
56247
|
+
// src/channel-connection.ts
|
|
56248
|
+
var import_nats4 = __toESM(require_mod4(), 1);
|
|
56249
|
+
var START_STOPPING = "the channel server stopped before its NATS subscriptions reached the server";
|
|
56250
|
+
function sessionAdmission(first) {
|
|
56251
|
+
let current = first;
|
|
56252
|
+
let pending;
|
|
56253
|
+
return {
|
|
56254
|
+
admit: (session) => {
|
|
56255
|
+
current = session;
|
|
56256
|
+
if (pending?.session !== session)
|
|
56257
|
+
return;
|
|
56258
|
+
pending.wait.resolve();
|
|
56259
|
+
pending = undefined;
|
|
56260
|
+
},
|
|
56261
|
+
admitted: (session) => {
|
|
56262
|
+
if (session === current)
|
|
56263
|
+
return Promise.resolve();
|
|
56264
|
+
if (pending?.session !== session) {
|
|
56265
|
+
pending = { session, wait: Promise.withResolvers() };
|
|
56266
|
+
}
|
|
56267
|
+
return pending.wait.promise;
|
|
56268
|
+
}
|
|
56269
|
+
};
|
|
56270
|
+
}
|
|
56271
|
+
function admittingMoves(admission, identity) {
|
|
56272
|
+
return (follow) => follow === undefined || admission === undefined ? undefined : async () => {
|
|
56273
|
+
const forSession = identity.id;
|
|
56274
|
+
await follow();
|
|
56275
|
+
admission.admit(forSession);
|
|
56276
|
+
};
|
|
56277
|
+
}
|
|
56278
|
+
var CREDENTIAL_NAMES = {
|
|
56279
|
+
broker: "the session's broker token",
|
|
56280
|
+
seed: "an nkey seed",
|
|
56281
|
+
none: "no credential"
|
|
56282
|
+
};
|
|
56283
|
+
var CHANNEL_DIAL_PLAN = {
|
|
56284
|
+
...NATS_DIAL_PLAN,
|
|
56285
|
+
budgetMs: Number.POSITIVE_INFINITY
|
|
56286
|
+
};
|
|
56287
|
+
async function dialChannelNats(inbound, name, warn, dial = import_nats4.connect, signal, plan = CHANNEL_DIAL_PLAN) {
|
|
56288
|
+
const stopped = Promise.withResolvers();
|
|
56289
|
+
const onAbort = () => stopped.resolve("stopping");
|
|
56290
|
+
if (signal?.aborted === true)
|
|
56291
|
+
onAbort();
|
|
56292
|
+
signal?.addEventListener("abort", onAbort);
|
|
56293
|
+
const unlessStopped = async (waited) => {
|
|
56294
|
+
const outcome = await Promise.race([
|
|
56295
|
+
waited.then((value) => ({ value }), (error) => ({ error })),
|
|
56296
|
+
stopped.promise
|
|
56297
|
+
]);
|
|
56298
|
+
if (outcome === "stopping")
|
|
56299
|
+
throw new Error(START_STOPPING);
|
|
56300
|
+
if ("error" in outcome)
|
|
56301
|
+
throw outcome.error;
|
|
56302
|
+
return outcome.value;
|
|
56303
|
+
};
|
|
56304
|
+
try {
|
|
56305
|
+
const { natsCredential } = inbound;
|
|
56306
|
+
const failed = (error) => natsDialFailure(natsServersForLog(inbound.natsServersSetting, inbound.natsUrls.length), error, CREDENTIAL_NAMES[natsCredential.kind]);
|
|
56307
|
+
const broker = natsCredential.kind === "broker" ? natsCredential.broker : undefined;
|
|
56308
|
+
await unlessStopped(broker?.ready({ life: signal ?? new AbortController().signal }) ?? Promise.resolve());
|
|
56309
|
+
const dialing = connectNats(dial, natsConnectionOptions({ servers: inbound.natsUrls, name, credential: natsCredential }), plan, {
|
|
56310
|
+
stopped: () => signal?.aborted === true,
|
|
56311
|
+
onRetry: (error, delayMs) => warn(`${failed(error)}; dialing again in ${delayMs} ms`, error)
|
|
56312
|
+
});
|
|
56313
|
+
let connection;
|
|
56314
|
+
try {
|
|
56315
|
+
connection = await unlessStopped(dialing);
|
|
56316
|
+
} catch (error) {
|
|
56317
|
+
if (signal?.aborted === true) {
|
|
56318
|
+
dialing.then((late) => late.close()).catch(() => {
|
|
56319
|
+
return;
|
|
56320
|
+
});
|
|
56321
|
+
throw new Error(START_STOPPING);
|
|
56322
|
+
}
|
|
56323
|
+
throw new LoggableError(failed(error));
|
|
56324
|
+
}
|
|
56325
|
+
if (broker === undefined)
|
|
56326
|
+
return { connection, stop: () => {} };
|
|
56327
|
+
return {
|
|
56328
|
+
connection,
|
|
56329
|
+
stop: keepNatsCredential(connection, broker, warn),
|
|
56330
|
+
followSession: () => followNatsCredential(connection, broker)
|
|
56331
|
+
};
|
|
56332
|
+
} finally {
|
|
56333
|
+
signal?.removeEventListener("abort", onAbort);
|
|
56334
|
+
}
|
|
56335
|
+
}
|
|
56336
|
+
var START_DRAIN_BOUND_MS = 2000;
|
|
56337
|
+
async function closeUnstartedConnection(connection) {
|
|
56338
|
+
await Promise.race([connection.drain().catch(() => {
|
|
56339
|
+
return;
|
|
56340
|
+
}), Bun.sleep(START_DRAIN_BOUND_MS)]);
|
|
56341
|
+
await connection.close().catch(() => {
|
|
56342
|
+
return;
|
|
56343
|
+
});
|
|
56344
|
+
}
|
|
56345
|
+
function channelReopener(options) {
|
|
56346
|
+
return async (failed) => {
|
|
56347
|
+
options.swapKeeper(() => {
|
|
56348
|
+
return;
|
|
56349
|
+
});
|
|
56350
|
+
const next = await dialChannelNats(options.inbound, options.name, (text, dialError) => {
|
|
56351
|
+
process.stderr.write(`envoy-channel: ${text}
|
|
56352
|
+
`);
|
|
56353
|
+
if (dialError !== undefined)
|
|
56354
|
+
failed(dialError);
|
|
56355
|
+
}, import_nats4.connect, options.signal);
|
|
56356
|
+
if (options.signal.aborted) {
|
|
56357
|
+
next.stop();
|
|
56358
|
+
next.connection.close().catch(() => {
|
|
56359
|
+
return;
|
|
56360
|
+
});
|
|
56361
|
+
throw new Error(START_STOPPING);
|
|
56362
|
+
}
|
|
56363
|
+
options.swapKeeper(next.stop);
|
|
56364
|
+
options.useConnection(next.connection);
|
|
56365
|
+
const followSession = options.admitting(next.followSession);
|
|
56366
|
+
return {
|
|
56367
|
+
connection: next.connection,
|
|
56368
|
+
...followSession === undefined ? {} : { followSession }
|
|
56369
|
+
};
|
|
56370
|
+
};
|
|
56371
|
+
}
|
|
56372
|
+
|
|
56072
56373
|
// src/claude-session.ts
|
|
56073
56374
|
function configuredValue(value) {
|
|
56074
56375
|
return value !== undefined && value.trim().length > 0 ? value : undefined;
|
|
@@ -56089,6 +56390,7 @@ function claudeProjectDirectory(environment, fallback) {
|
|
|
56089
56390
|
// src/envoy-channel-server.ts
|
|
56090
56391
|
import { unwatchFile, watchFile } from "fs";
|
|
56091
56392
|
import { rm as rm2 } from "fs/promises";
|
|
56393
|
+
import { setImmediate as nextTurn } from "timers/promises";
|
|
56092
56394
|
|
|
56093
56395
|
// ../envoy-client/src/delivery-ledger.ts
|
|
56094
56396
|
var DELIVERY_LEDGER_TTL_MS = DELIVERY_DUPLICATE_WINDOW_MS;
|
|
@@ -56805,7 +57107,13 @@ function inboundUnavailableNoticeText(why) {
|
|
|
56805
57107
|
detail: "The listener gave this session no durable consumer, which is the only path an Envoy message reaches it by, so it receives none. Everything else works, and the session registers again at every heartbeat; what the stream stored meanwhile arrives once a registration is accepted."
|
|
56806
57108
|
});
|
|
56807
57109
|
}
|
|
56808
|
-
function
|
|
57110
|
+
function inboundRestoredNoticeText() {
|
|
57111
|
+
return envoyNoticeText({
|
|
57112
|
+
notice: "Envoy inbound restored",
|
|
57113
|
+
detail: "The listener accepted this session's registration and gave it its durable consumer, so Envoy messages reach it again, the ones the stream stored during the outage first."
|
|
57114
|
+
});
|
|
57115
|
+
}
|
|
57116
|
+
function inboundUnavailable(tell, restored) {
|
|
56809
57117
|
let told = false;
|
|
56810
57118
|
return {
|
|
56811
57119
|
refused(error) {
|
|
@@ -56815,12 +57123,19 @@ function inboundUnavailable(tell) {
|
|
|
56815
57123
|
tell(messageFor(error));
|
|
56816
57124
|
},
|
|
56817
57125
|
accepted() {
|
|
57126
|
+
if (!told)
|
|
57127
|
+
return;
|
|
56818
57128
|
told = false;
|
|
57129
|
+
restored();
|
|
56819
57130
|
}
|
|
56820
57131
|
};
|
|
56821
57132
|
}
|
|
57133
|
+
|
|
57134
|
+
class NoRelaySubjectError extends Error {
|
|
57135
|
+
}
|
|
56822
57136
|
function registerWithRelay({
|
|
56823
57137
|
relay,
|
|
57138
|
+
relayMissing,
|
|
56824
57139
|
ownAgentSubject,
|
|
56825
57140
|
followed,
|
|
56826
57141
|
roles,
|
|
@@ -56829,7 +57144,7 @@ function registerWithRelay({
|
|
|
56829
57144
|
answered
|
|
56830
57145
|
}) {
|
|
56831
57146
|
if (relay === undefined) {
|
|
56832
|
-
const refused = new
|
|
57147
|
+
const refused = new NoRelaySubjectError(`this session holds no relay subject, so the listener can give it no consumer and it can receive nothing${relayMissing === undefined ? "" : `, because its relay subject could not be opened: ${relayMissing}`}`);
|
|
56833
57148
|
outage.refused(refused);
|
|
56834
57149
|
return Promise.reject(refused);
|
|
56835
57150
|
}
|
|
@@ -56845,59 +57160,6 @@ function registerWithRelay({
|
|
|
56845
57160
|
});
|
|
56846
57161
|
}
|
|
56847
57162
|
|
|
56848
|
-
// ../envoy-client/src/nats-connection.ts
|
|
56849
|
-
var import_servers = __toESM(require_servers(), 1);
|
|
56850
|
-
|
|
56851
|
-
// ../envoy-client/src/nats-auth.ts
|
|
56852
|
-
var import_nats = __toESM(require_mod4(), 1);
|
|
56853
|
-
var seedKeys = import_nats.nkeys;
|
|
56854
|
-
function natsAuthOptions(credential) {
|
|
56855
|
-
switch (credential.kind) {
|
|
56856
|
-
case "none":
|
|
56857
|
-
return {};
|
|
56858
|
-
case "broker":
|
|
56859
|
-
return { authenticator: credential.broker.authenticator };
|
|
56860
|
-
case "seed": {
|
|
56861
|
-
const { seed } = credential;
|
|
56862
|
-
const bytes = new TextEncoder().encode(seed.value);
|
|
56863
|
-
let publicKey;
|
|
56864
|
-
try {
|
|
56865
|
-
publicKey = seedKeys.fromSeed(bytes).getPublicKey();
|
|
56866
|
-
} catch (error) {
|
|
56867
|
-
throw new Error(`${seed.source} does not hold a valid nkey seed: ${messageFor(error)}`);
|
|
56868
|
-
}
|
|
56869
|
-
if (!publicKey.startsWith("U")) {
|
|
56870
|
-
throw new Error(`${seed.source} holds an nkey seed that is not a user's (public key ${publicKey})`);
|
|
56871
|
-
}
|
|
56872
|
-
return { authenticator: import_nats.nkeyAuthenticator(bytes) };
|
|
56873
|
-
}
|
|
56874
|
-
}
|
|
56875
|
-
}
|
|
56876
|
-
|
|
56877
|
-
// ../envoy-client/src/nats-connection.ts
|
|
56878
|
-
var NATS_PING_INTERVAL_MS = 1e4;
|
|
56879
|
-
var NATS_MAX_PINGS_OUT = 2;
|
|
56880
|
-
function natsConnectionOptions(input) {
|
|
56881
|
-
return {
|
|
56882
|
-
servers: [...input.servers],
|
|
56883
|
-
name: input.name,
|
|
56884
|
-
...natsAuthOptions(input.credential),
|
|
56885
|
-
reconnect: true,
|
|
56886
|
-
maxReconnectAttempts: -1,
|
|
56887
|
-
reconnectTimeWait: 2000,
|
|
56888
|
-
pingInterval: NATS_PING_INTERVAL_MS,
|
|
56889
|
-
maxPingOut: NATS_MAX_PINGS_OUT,
|
|
56890
|
-
...input.credential.kind === "broker" ? { ignoreAuthErrorAbort: true } : {}
|
|
56891
|
-
};
|
|
56892
|
-
}
|
|
56893
|
-
function natsServersForLog(setting, count) {
|
|
56894
|
-
return count === 1 ? `the server ${setting} names` : `the ${count} servers ${setting} names`;
|
|
56895
|
-
}
|
|
56896
|
-
function natsDialFailure(named, error, presenting) {
|
|
56897
|
-
const credential = presenting === undefined ? "" : ` presenting ${presenting}`;
|
|
56898
|
-
return `could not connect to NATS at ${named}${credential}: ${natsFailureReason(error)}`;
|
|
56899
|
-
}
|
|
56900
|
-
|
|
56901
57163
|
// ../envoy-client/src/slack-post.ts
|
|
56902
57164
|
import { BlockList, isIP } from "net";
|
|
56903
57165
|
var SLACK_BOT_TOKEN_SECRET = "LEGION_SLACK_BOT_TOKEN";
|
|
@@ -58575,13 +58837,13 @@ async function findHandoffReport(input) {
|
|
|
58575
58837
|
}
|
|
58576
58838
|
|
|
58577
58839
|
// src/envoy-channel-server.ts
|
|
58578
|
-
var
|
|
58840
|
+
var import_nats5 = __toESM(require_mod4(), 1);
|
|
58579
58841
|
|
|
58580
58842
|
// package.json
|
|
58581
58843
|
var name2 = "@sjawhar/claude-envoy";
|
|
58582
|
-
var version2 = "4.15.
|
|
58844
|
+
var version2 = "4.15.4";
|
|
58583
58845
|
var legion = {
|
|
58584
|
-
daemonApiVersion:
|
|
58846
|
+
daemonApiVersion: 189
|
|
58585
58847
|
};
|
|
58586
58848
|
|
|
58587
58849
|
// ../pi-shared/src/agent-stream.ts
|
|
@@ -59271,20 +59533,118 @@ function rememberBoundedEntry(remembered, key, value, max) {
|
|
|
59271
59533
|
}
|
|
59272
59534
|
}
|
|
59273
59535
|
|
|
59274
|
-
// src/
|
|
59536
|
+
// src/control-subscription.ts
|
|
59275
59537
|
var encoder4 = new TextEncoder;
|
|
59276
59538
|
var decoder4 = new TextDecoder;
|
|
59539
|
+
var RESUBSCRIBE_MS = 1000;
|
|
59540
|
+
function controlSubscription(options) {
|
|
59541
|
+
let connection = options.connection;
|
|
59542
|
+
let subscription;
|
|
59543
|
+
let stopped = false;
|
|
59544
|
+
const pump = async (taken, forSession) => {
|
|
59545
|
+
try {
|
|
59546
|
+
for await (const message of taken) {
|
|
59547
|
+
try {
|
|
59548
|
+
const parsed = JSON.parse(decoder4.decode(message.data));
|
|
59549
|
+
if (typeof parsed !== "object" || parsed === null)
|
|
59550
|
+
continue;
|
|
59551
|
+
const request = parsed;
|
|
59552
|
+
if (request.type !== "replay" && request.type !== "watch")
|
|
59553
|
+
continue;
|
|
59554
|
+
const reply = message.reply;
|
|
59555
|
+
const answer = options.answer(request, reply !== undefined, forSession);
|
|
59556
|
+
if (answer === undefined || reply === undefined)
|
|
59557
|
+
continue;
|
|
59558
|
+
connection.publish(reply, encoder4.encode(answer));
|
|
59559
|
+
} catch (error) {
|
|
59560
|
+
options.warn(`a live view control message failed \u2014 ${messageFor(error)}`);
|
|
59561
|
+
}
|
|
59562
|
+
}
|
|
59563
|
+
} catch {}
|
|
59564
|
+
if (subscription === taken)
|
|
59565
|
+
subscription = undefined;
|
|
59566
|
+
if (stopped || options.session() !== forSession)
|
|
59567
|
+
return;
|
|
59568
|
+
const retry = setTimeout(() => {
|
|
59569
|
+
if (stopped || options.session() !== forSession || subscription !== undefined)
|
|
59570
|
+
return;
|
|
59571
|
+
subscribeWhenAdmitted(forSession);
|
|
59572
|
+
}, RESUBSCRIBE_MS);
|
|
59573
|
+
retry.unref();
|
|
59574
|
+
};
|
|
59575
|
+
function subscribe() {
|
|
59576
|
+
if (stopped || connection.isClosed())
|
|
59577
|
+
return;
|
|
59578
|
+
subscription?.unsubscribe();
|
|
59579
|
+
const forSession = options.session();
|
|
59580
|
+
const taken = connection.subscribe(agentStreamControlSubject(forSession));
|
|
59581
|
+
subscription = taken;
|
|
59582
|
+
pump(taken, forSession);
|
|
59583
|
+
}
|
|
59584
|
+
function subscribeWhenAdmitted(forSession) {
|
|
59585
|
+
const admitted = options.admitted?.(forSession);
|
|
59586
|
+
if (admitted === undefined) {
|
|
59587
|
+
subscribe();
|
|
59588
|
+
return;
|
|
59589
|
+
}
|
|
59590
|
+
admitted.then(() => {
|
|
59591
|
+
if (!stopped && options.session() === forSession && subscription === undefined)
|
|
59592
|
+
subscribe();
|
|
59593
|
+
});
|
|
59594
|
+
}
|
|
59595
|
+
return {
|
|
59596
|
+
get stopped() {
|
|
59597
|
+
return stopped;
|
|
59598
|
+
},
|
|
59599
|
+
publish(subject, payload) {
|
|
59600
|
+
if (!stopped && !connection.isClosed())
|
|
59601
|
+
connection.publish(subject, encoder4.encode(payload));
|
|
59602
|
+
},
|
|
59603
|
+
start() {
|
|
59604
|
+
subscribeWhenAdmitted(options.session());
|
|
59605
|
+
},
|
|
59606
|
+
moved() {
|
|
59607
|
+
subscription?.unsubscribe();
|
|
59608
|
+
subscription = undefined;
|
|
59609
|
+
subscribeWhenAdmitted(options.session());
|
|
59610
|
+
},
|
|
59611
|
+
useConnection(next) {
|
|
59612
|
+
connection = next;
|
|
59613
|
+
if (stopped)
|
|
59614
|
+
return;
|
|
59615
|
+
subscription?.unsubscribe();
|
|
59616
|
+
subscription = undefined;
|
|
59617
|
+
subscribeWhenAdmitted(options.session());
|
|
59618
|
+
},
|
|
59619
|
+
stop() {
|
|
59620
|
+
if (stopped)
|
|
59621
|
+
return;
|
|
59622
|
+
stopped = true;
|
|
59623
|
+
subscription?.unsubscribe();
|
|
59624
|
+
subscription = undefined;
|
|
59625
|
+
}
|
|
59626
|
+
};
|
|
59627
|
+
}
|
|
59628
|
+
|
|
59629
|
+
// src/agent-stream-runner.ts
|
|
59277
59630
|
var AGENT_STREAM_CALL_TIMEOUT_MS = 5000;
|
|
59278
|
-
var AGENT_STREAM_RESUBSCRIBE_MS = 1000;
|
|
59279
59631
|
var AGENT_STREAM_SEEN_ROWS_MAX = 512;
|
|
59280
59632
|
function startAgentStream(options) {
|
|
59281
|
-
const {
|
|
59633
|
+
const { link } = options;
|
|
59282
59634
|
const now = options.now ?? Date.now;
|
|
59283
59635
|
const warn = options.warn ?? ((text) => void process.stderr.write(`envoy-channel: ${text}
|
|
59284
59636
|
`));
|
|
59637
|
+
let session = options.sessionId;
|
|
59638
|
+
const control = controlSubscription({
|
|
59639
|
+
connection: options.connection,
|
|
59640
|
+
session: () => session,
|
|
59641
|
+
...options.admitted === undefined ? {} : { admitted: options.admitted },
|
|
59642
|
+
warn,
|
|
59643
|
+
answer: answerControl
|
|
59644
|
+
});
|
|
59285
59645
|
const publisher = new AgentStreamPublisher({
|
|
59286
59646
|
now,
|
|
59287
|
-
publish: (subject, payload) =>
|
|
59647
|
+
publish: (subject, payload) => control.publish(subject, payload)
|
|
59288
59648
|
});
|
|
59289
59649
|
const stream = createClaudeAgentStream({
|
|
59290
59650
|
isPane: options.isPane === true,
|
|
@@ -59295,9 +59655,6 @@ function startAgentStream(options) {
|
|
|
59295
59655
|
...options.runsUnreadPrompt === undefined ? {} : { runsUnreadPrompt: options.runsUnreadPrompt },
|
|
59296
59656
|
...options.tagFor === undefined ? {} : { tagFor: options.tagFor }
|
|
59297
59657
|
});
|
|
59298
|
-
let session = options.sessionId;
|
|
59299
|
-
let subscription;
|
|
59300
|
-
let stopped = false;
|
|
59301
59658
|
let model;
|
|
59302
59659
|
let configRows;
|
|
59303
59660
|
let listedCommands;
|
|
@@ -59322,7 +59679,7 @@ function startAgentStream(options) {
|
|
|
59322
59679
|
publisher.setCommands(framesSubject(), listedCommands);
|
|
59323
59680
|
};
|
|
59324
59681
|
const refreshSettings = () => {
|
|
59325
|
-
if (stopped || readingSettings || !link.connected())
|
|
59682
|
+
if (control.stopped || readingSettings || !link.connected())
|
|
59326
59683
|
return;
|
|
59327
59684
|
readingSettings = true;
|
|
59328
59685
|
Promise.all([
|
|
@@ -59331,7 +59688,7 @@ function startAgentStream(options) {
|
|
|
59331
59688
|
]).then(([answeredModel, rows]) => {
|
|
59332
59689
|
model = answeredModel;
|
|
59333
59690
|
configRows = rows;
|
|
59334
|
-
if (!stopped)
|
|
59691
|
+
if (!control.stopped)
|
|
59335
59692
|
publishSettings();
|
|
59336
59693
|
}).catch((error) => {
|
|
59337
59694
|
warn(`the live view could not read this session's model \u2014 ${messageFor(error)}`);
|
|
@@ -59340,12 +59697,12 @@ function startAgentStream(options) {
|
|
|
59340
59697
|
});
|
|
59341
59698
|
};
|
|
59342
59699
|
const refreshCommands = () => {
|
|
59343
|
-
if (stopped || readingCommands || !link.connected())
|
|
59700
|
+
if (control.stopped || readingCommands || !link.connected())
|
|
59344
59701
|
return;
|
|
59345
59702
|
readingCommands = true;
|
|
59346
59703
|
link.request("command.list", undefined, { timeoutMs: AGENT_STREAM_CALL_TIMEOUT_MS }).then((commands) => {
|
|
59347
59704
|
listedCommands = claudeAgentStreamCommands(commands);
|
|
59348
|
-
if (!stopped)
|
|
59705
|
+
if (!control.stopped)
|
|
59349
59706
|
publishCommands();
|
|
59350
59707
|
}).catch((error) => {
|
|
59351
59708
|
warn(`the live view could not read this session's commands \u2014 ${messageFor(error)}`);
|
|
@@ -59353,58 +59710,23 @@ function startAgentStream(options) {
|
|
|
59353
59710
|
readingCommands = false;
|
|
59354
59711
|
});
|
|
59355
59712
|
};
|
|
59356
|
-
|
|
59357
|
-
|
|
59358
|
-
|
|
59359
|
-
|
|
59360
|
-
|
|
59361
|
-
|
|
59362
|
-
|
|
59363
|
-
|
|
59364
|
-
|
|
59365
|
-
|
|
59366
|
-
|
|
59367
|
-
|
|
59368
|
-
|
|
59369
|
-
|
|
59370
|
-
commandsRefreshedOnWatchAt = now();
|
|
59371
|
-
}
|
|
59372
|
-
const reply = message.reply;
|
|
59373
|
-
const answer = request.type === "replay" && reply !== undefined ? JSON.stringify(publisher.replay(forSession)) : undefined;
|
|
59374
|
-
const arming = !publisher.watched;
|
|
59375
|
-
publisher.noteViewer();
|
|
59376
|
-
viewerAttached = true;
|
|
59377
|
-
if (arming)
|
|
59378
|
-
publisher.publishState(agentStreamFramesSubject(forSession));
|
|
59379
|
-
if (answer === undefined || reply === undefined)
|
|
59380
|
-
continue;
|
|
59381
|
-
connection.publish(reply, encoder4.encode(answer));
|
|
59382
|
-
} catch (error) {
|
|
59383
|
-
warn(`a live view control message failed \u2014 ${messageFor(error)}`);
|
|
59384
|
-
}
|
|
59385
|
-
}
|
|
59386
|
-
} catch {}
|
|
59387
|
-
if (subscription === taken)
|
|
59388
|
-
subscription = undefined;
|
|
59389
|
-
if (stopped || session !== forSession)
|
|
59390
|
-
return;
|
|
59391
|
-
const retry = setTimeout(() => {
|
|
59392
|
-
if (stopped || session !== forSession)
|
|
59393
|
-
return;
|
|
59394
|
-
subscribe();
|
|
59395
|
-
}, AGENT_STREAM_RESUBSCRIBE_MS);
|
|
59396
|
-
retry.unref();
|
|
59397
|
-
};
|
|
59398
|
-
function subscribe() {
|
|
59399
|
-
if (stopped)
|
|
59400
|
-
return;
|
|
59401
|
-
subscription?.unsubscribe();
|
|
59402
|
-
const taken = connection.subscribe(agentStreamControlSubject(session));
|
|
59403
|
-
subscription = taken;
|
|
59404
|
-
pump(taken, session);
|
|
59713
|
+
function answerControl(request, replying, forSession) {
|
|
59714
|
+
refreshSettings();
|
|
59715
|
+
if (request.type === "replay" || !viewerAttached || now() - commandsRefreshedOnWatchAt >= AGENT_STREAM_WATCH_INTERVAL_MS) {
|
|
59716
|
+
refreshCommands();
|
|
59717
|
+
if (request.type === "watch" && viewerAttached)
|
|
59718
|
+
commandsRefreshedOnWatchAt = now();
|
|
59719
|
+
}
|
|
59720
|
+
const answer = request.type === "replay" && replying ? JSON.stringify(publisher.replay(forSession)) : undefined;
|
|
59721
|
+
const arming = !publisher.watched;
|
|
59722
|
+
publisher.noteViewer();
|
|
59723
|
+
viewerAttached = true;
|
|
59724
|
+
if (arming)
|
|
59725
|
+
publisher.publishState(agentStreamFramesSubject(forSession));
|
|
59726
|
+
return answer;
|
|
59405
59727
|
}
|
|
59406
|
-
|
|
59407
|
-
if (stopped || !options.followsSessionId || next === session)
|
|
59728
|
+
const moveTo = (next) => {
|
|
59729
|
+
if (control.stopped || !options.followsSessionId || next === session)
|
|
59408
59730
|
return;
|
|
59409
59731
|
session = next;
|
|
59410
59732
|
publisher.reset();
|
|
@@ -59413,17 +59735,9 @@ function startAgentStream(options) {
|
|
|
59413
59735
|
commandsRefreshedOnWatchAt = Number.NEGATIVE_INFINITY;
|
|
59414
59736
|
publishSettings();
|
|
59415
59737
|
publishCommands();
|
|
59416
|
-
|
|
59417
|
-
|
|
59418
|
-
|
|
59419
|
-
if (admitted === undefined)
|
|
59420
|
-
subscribe();
|
|
59421
|
-
else
|
|
59422
|
-
admitted.then(() => {
|
|
59423
|
-
if (!stopped && session === next)
|
|
59424
|
-
subscribe();
|
|
59425
|
-
});
|
|
59426
|
-
});
|
|
59738
|
+
control.moved();
|
|
59739
|
+
};
|
|
59740
|
+
link.onSessionId(moveTo);
|
|
59427
59741
|
const reading = (async () => {
|
|
59428
59742
|
for await (const event of link.events) {
|
|
59429
59743
|
if (!primed) {
|
|
@@ -59444,23 +59758,26 @@ function startAgentStream(options) {
|
|
|
59444
59758
|
reading.catch((error) => {
|
|
59445
59759
|
warn(`the live view stopped reading this session's events \u2014 ${messageFor(error)}`);
|
|
59446
59760
|
});
|
|
59447
|
-
|
|
59761
|
+
control.start();
|
|
59448
59762
|
return {
|
|
59449
59763
|
refresh() {
|
|
59450
59764
|
refreshSettings();
|
|
59451
59765
|
},
|
|
59452
59766
|
pickedEffort(effort) {
|
|
59453
|
-
if (stopped)
|
|
59767
|
+
if (control.stopped)
|
|
59454
59768
|
return;
|
|
59455
59769
|
stream.pickedEffort(effort);
|
|
59456
59770
|
publishSettings();
|
|
59457
59771
|
},
|
|
59458
59772
|
stop() {
|
|
59459
|
-
|
|
59460
|
-
|
|
59461
|
-
|
|
59462
|
-
|
|
59463
|
-
|
|
59773
|
+
control.stop();
|
|
59774
|
+
},
|
|
59775
|
+
useConnection(next) {
|
|
59776
|
+
control.useConnection(next);
|
|
59777
|
+
},
|
|
59778
|
+
sessionAdopted(previous, next) {
|
|
59779
|
+
if (session === previous)
|
|
59780
|
+
moveTo(next);
|
|
59464
59781
|
}
|
|
59465
59782
|
};
|
|
59466
59783
|
}
|
|
@@ -59508,24 +59825,25 @@ function createChannelTopics(connection, options = {}) {
|
|
|
59508
59825
|
return [...following];
|
|
59509
59826
|
},
|
|
59510
59827
|
isClosed() {
|
|
59511
|
-
return connection.isClosed();
|
|
59828
|
+
return connection().isClosed();
|
|
59512
59829
|
},
|
|
59513
59830
|
async close() {
|
|
59514
59831
|
following.clear();
|
|
59515
|
-
|
|
59832
|
+
const held = connection();
|
|
59833
|
+
if (held.isClosed())
|
|
59516
59834
|
return;
|
|
59517
59835
|
const timeout = Promise.withResolvers();
|
|
59518
59836
|
const timer = setTimeout(timeout.resolve, drainTimeoutMs);
|
|
59519
59837
|
try {
|
|
59520
|
-
await Promise.race([
|
|
59838
|
+
await Promise.race([held.drain(), timeout.promise]);
|
|
59521
59839
|
} catch (error) {
|
|
59522
59840
|
report("draining the broker connection failed", error);
|
|
59523
59841
|
}
|
|
59524
59842
|
clearTimeout(timer);
|
|
59525
|
-
if (
|
|
59843
|
+
if (held.isClosed())
|
|
59526
59844
|
return;
|
|
59527
59845
|
try {
|
|
59528
|
-
await
|
|
59846
|
+
await held.close();
|
|
59529
59847
|
} catch (error) {
|
|
59530
59848
|
report("closing the broker connection failed", error);
|
|
59531
59849
|
}
|
|
@@ -59765,7 +60083,7 @@ function installedPluginVersion(bundlePath) {
|
|
|
59765
60083
|
// src/legion-claim.ts
|
|
59766
60084
|
import { readdir as readdir3, stat as stat2 } from "fs/promises";
|
|
59767
60085
|
import { join as join10 } from "path";
|
|
59768
|
-
import { setTimeout as
|
|
60086
|
+
import { setTimeout as delay2 } from "timers/promises";
|
|
59769
60087
|
|
|
59770
60088
|
// ../pi-shared/src/stall-limits.ts
|
|
59771
60089
|
var DEFAULT_STALL_LIMITS = {
|
|
@@ -60676,7 +60994,7 @@ async function waitForTranscript(configDir, sessionID, signal, pollMs = 100) {
|
|
|
60676
60994
|
if (await isFile(file))
|
|
60677
60995
|
return file;
|
|
60678
60996
|
}
|
|
60679
|
-
await
|
|
60997
|
+
await delay2(pollMs, undefined, { signal });
|
|
60680
60998
|
}
|
|
60681
60999
|
}
|
|
60682
61000
|
var SAVED_MARKER_SUFFIX = ".legion-saved";
|
|
@@ -60686,7 +61004,7 @@ async function waitForSavedTranscript(transcript, signal, pollMs = 100) {
|
|
|
60686
61004
|
signal.throwIfAborted();
|
|
60687
61005
|
if (await isFile(marker))
|
|
60688
61006
|
return;
|
|
60689
|
-
await
|
|
61007
|
+
await delay2(pollMs, undefined, { signal });
|
|
60690
61008
|
}
|
|
60691
61009
|
}
|
|
60692
61010
|
function isFile(file) {
|
|
@@ -60739,7 +61057,7 @@ function startLegionClaim(deps) {
|
|
|
60739
61057
|
waited = true;
|
|
60740
61058
|
deps.log(`Envoy role ${role} is claimed under this session by the process this pane replaced; asking again every ${roleRetryMs} ms for up to ${roleWaitMs} ms, until nobody has answered for that claim inside the listener's live window`);
|
|
60741
61059
|
}
|
|
60742
|
-
await
|
|
61060
|
+
await delay2(Math.min(roleRetryMs, left), undefined, { signal: deps.signal });
|
|
60743
61061
|
}
|
|
60744
61062
|
await deps.session.rememberRole(role);
|
|
60745
61063
|
},
|
|
@@ -62578,81 +62896,28 @@ function createChannelDelivery(input) {
|
|
|
62578
62896
|
}
|
|
62579
62897
|
};
|
|
62580
62898
|
}
|
|
62581
|
-
|
|
62582
|
-
|
|
62583
|
-
|
|
62584
|
-
|
|
62585
|
-
|
|
62586
|
-
current = session;
|
|
62587
|
-
if (pending?.session !== session)
|
|
62588
|
-
return;
|
|
62589
|
-
pending.wait.resolve();
|
|
62590
|
-
pending = undefined;
|
|
62591
|
-
},
|
|
62592
|
-
admitted: (session) => {
|
|
62593
|
-
if (session === current)
|
|
62594
|
-
return Promise.resolve();
|
|
62595
|
-
if (pending?.session !== session) {
|
|
62596
|
-
pending = { session, wait: Promise.withResolvers() };
|
|
62597
|
-
}
|
|
62598
|
-
return pending.wait.promise;
|
|
62599
|
-
}
|
|
62600
|
-
};
|
|
62899
|
+
var REDIAL_FLUSH_RETRY_MS = 250;
|
|
62900
|
+
var START_CLOSED = "the NATS connection closed before its subscriptions reached the server";
|
|
62901
|
+
function lostConnectionReason(lost) {
|
|
62902
|
+
const why = lost.closeError ?? lost.dialError;
|
|
62903
|
+
return why === undefined ? "it closed and named no error" : natsFailureReason(why);
|
|
62601
62904
|
}
|
|
62602
|
-
|
|
62603
|
-
|
|
62604
|
-
|
|
62605
|
-
|
|
62606
|
-
|
|
62607
|
-
|
|
62608
|
-
const
|
|
62609
|
-
const onAbort = () => stopped.resolve("stopping");
|
|
62610
|
-
if (signal?.aborted === true)
|
|
62611
|
-
onAbort();
|
|
62612
|
-
signal?.addEventListener("abort", onAbort);
|
|
62613
|
-
const unlessStopped = async (waited) => {
|
|
62614
|
-
const outcome = await Promise.race([
|
|
62615
|
-
waited.then((value) => ({ value }), (error) => ({ error })),
|
|
62616
|
-
stopped.promise
|
|
62617
|
-
]);
|
|
62618
|
-
if (outcome === "stopping")
|
|
62619
|
-
throw new Error(START_STOPPING);
|
|
62620
|
-
if ("error" in outcome)
|
|
62621
|
-
throw outcome.error;
|
|
62622
|
-
return outcome.value;
|
|
62623
|
-
};
|
|
62905
|
+
function closedStart(closed) {
|
|
62906
|
+
return closed.error === undefined ? new Error(START_CLOSED) : new Error(`${START_CLOSED}: ${natsFailureReason(closed.error)}`);
|
|
62907
|
+
}
|
|
62908
|
+
var CLOSE_ERROR_WAIT_MS = 1000;
|
|
62909
|
+
async function closeErrorOf(connection) {
|
|
62910
|
+
const waited = Promise.withResolvers();
|
|
62911
|
+
const timer = setTimeout(() => waited.resolve(undefined), CLOSE_ERROR_WAIT_MS);
|
|
62624
62912
|
try {
|
|
62625
|
-
|
|
62626
|
-
|
|
62627
|
-
|
|
62628
|
-
|
|
62629
|
-
let connection;
|
|
62630
|
-
try {
|
|
62631
|
-
connection = await unlessStopped(dialing);
|
|
62632
|
-
} catch (error) {
|
|
62633
|
-
if (signal?.aborted === true) {
|
|
62634
|
-
dialing.then((late) => late.close()).catch(() => {
|
|
62635
|
-
return;
|
|
62636
|
-
});
|
|
62637
|
-
throw new Error(START_STOPPING);
|
|
62638
|
-
}
|
|
62639
|
-
throw new Error(natsDialFailure(natsServersForLog(inbound.natsServersSetting, inbound.natsUrls.length), error, CREDENTIAL_NAMES[natsCredential.kind]));
|
|
62640
|
-
}
|
|
62641
|
-
if (broker === undefined)
|
|
62642
|
-
return { connection, stop: () => {} };
|
|
62643
|
-
return {
|
|
62644
|
-
connection,
|
|
62645
|
-
stop: keepNatsCredential(connection, broker, warn),
|
|
62646
|
-
followSession: () => followNatsCredential(connection, broker)
|
|
62647
|
-
};
|
|
62913
|
+
return await Promise.race([
|
|
62914
|
+
connection.closed().then((error) => error, (error) => error),
|
|
62915
|
+
waited.promise
|
|
62916
|
+
]);
|
|
62648
62917
|
} finally {
|
|
62649
|
-
|
|
62918
|
+
clearTimeout(timer);
|
|
62650
62919
|
}
|
|
62651
62920
|
}
|
|
62652
|
-
var REDIAL_FLUSH_RETRY_MS = 250;
|
|
62653
|
-
var START_STOPPING = "the channel server stopped before its NATS subscriptions reached the server";
|
|
62654
|
-
var START_CLOSED = "the NATS connection closed before its subscriptions reached the server";
|
|
62655
|
-
var START_DRAIN_BOUND_MS = 2000;
|
|
62656
62921
|
async function flushThroughRedials(connection, signal) {
|
|
62657
62922
|
const ended = Promise.withResolvers();
|
|
62658
62923
|
const check = () => {
|
|
@@ -62663,30 +62928,33 @@ async function flushThroughRedials(connection, signal) {
|
|
|
62663
62928
|
};
|
|
62664
62929
|
const watch = setInterval(check, REDIAL_FLUSH_RETRY_MS);
|
|
62665
62930
|
signal?.addEventListener("abort", check);
|
|
62666
|
-
const failure = (why, error) => why === "stopping" ? new Error(START_STOPPING) : error === undefined ? new Error(START_CLOSED) : new Error(`${START_CLOSED}: ${natsFailureReason(error)}`);
|
|
62667
62931
|
try {
|
|
62668
62932
|
for (;; ) {
|
|
62669
62933
|
check();
|
|
62670
62934
|
const attempt = connection.flush().then(() => ({ flushed: true }), (error) => ({ flushed: false, error }));
|
|
62671
62935
|
const outcome = await Promise.race([attempt, ended.promise]);
|
|
62672
|
-
if (outcome === "stopping"
|
|
62673
|
-
throw
|
|
62936
|
+
if (outcome === "stopping")
|
|
62937
|
+
throw new Error(START_STOPPING);
|
|
62938
|
+
if (outcome === "closed")
|
|
62939
|
+
return { error: undefined };
|
|
62674
62940
|
if (outcome.flushed) {
|
|
62675
62941
|
if (signal?.aborted === true)
|
|
62676
|
-
throw
|
|
62942
|
+
throw new Error(START_STOPPING);
|
|
62677
62943
|
return;
|
|
62678
62944
|
}
|
|
62679
62945
|
check();
|
|
62680
62946
|
if (signal?.aborted === true)
|
|
62681
|
-
throw
|
|
62947
|
+
throw new Error(START_STOPPING);
|
|
62682
62948
|
if (connection.isClosed())
|
|
62683
|
-
|
|
62949
|
+
return { error: outcome.error };
|
|
62684
62950
|
const waited = await Promise.race([
|
|
62685
62951
|
Bun.sleep(REDIAL_FLUSH_RETRY_MS).then(() => "asked again"),
|
|
62686
62952
|
ended.promise
|
|
62687
62953
|
]);
|
|
62688
|
-
if (waited
|
|
62689
|
-
throw
|
|
62954
|
+
if (waited === "stopping")
|
|
62955
|
+
throw new Error(START_STOPPING);
|
|
62956
|
+
if (waited === "closed")
|
|
62957
|
+
return { error: outcome.error };
|
|
62690
62958
|
}
|
|
62691
62959
|
} finally {
|
|
62692
62960
|
clearInterval(watch);
|
|
@@ -62696,6 +62964,12 @@ async function flushThroughRedials(connection, signal) {
|
|
|
62696
62964
|
async function startChannelSession(options) {
|
|
62697
62965
|
const { identity } = options;
|
|
62698
62966
|
let directSubject = legacyAgentSubject(identity.id);
|
|
62967
|
+
let connection = options.connection;
|
|
62968
|
+
let followSession = options.followSession;
|
|
62969
|
+
let connectionLost;
|
|
62970
|
+
let reopening = false;
|
|
62971
|
+
const lostConnections = new WeakSet;
|
|
62972
|
+
const watchedConnections = new WeakSet;
|
|
62699
62973
|
let router;
|
|
62700
62974
|
let turns;
|
|
62701
62975
|
const delivery = createChannelDelivery({
|
|
@@ -62849,7 +63123,7 @@ async function startChannelSession(options) {
|
|
|
62849
63123
|
`);
|
|
62850
63124
|
}
|
|
62851
63125
|
},
|
|
62852
|
-
publish: (reply, body) =>
|
|
63126
|
+
publish: (reply, body) => connection.publish(reply, encoder5.encode(body)),
|
|
62853
63127
|
persist: (snapshot) => {
|
|
62854
63128
|
if (relay !== owner)
|
|
62855
63129
|
return false;
|
|
@@ -62866,11 +63140,20 @@ async function startChannelSession(options) {
|
|
|
62866
63140
|
sessionID,
|
|
62867
63141
|
delivery: consumer,
|
|
62868
63142
|
state,
|
|
62869
|
-
subscription: undefined
|
|
63143
|
+
subscription: undefined,
|
|
63144
|
+
stopped: undefined
|
|
62870
63145
|
};
|
|
62871
63146
|
relay = owner;
|
|
62872
|
-
|
|
63147
|
+
subscribeRelay(owner);
|
|
63148
|
+
};
|
|
63149
|
+
const subscribeRelay = (owner) => {
|
|
63150
|
+
if (connection.isClosed()) {
|
|
63151
|
+
owner.subscription = undefined;
|
|
63152
|
+
return;
|
|
63153
|
+
}
|
|
63154
|
+
const subscription = connection.subscribe(owner.delivery.subject);
|
|
62873
63155
|
owner.subscription = subscription;
|
|
63156
|
+
owner.stopped = undefined;
|
|
62874
63157
|
pumpRelay(owner, subscription);
|
|
62875
63158
|
};
|
|
62876
63159
|
const pumpRelay = async (owner, subscription) => {
|
|
@@ -62881,8 +63164,43 @@ async function startChannelSession(options) {
|
|
|
62881
63164
|
} catch (error) {
|
|
62882
63165
|
process.stderr.write(`envoy-channel: the relay subscription of ${owner.sessionID} stopped \u2014 ${natsFailureReason(error)}
|
|
62883
63166
|
`);
|
|
63167
|
+
if (owner.subscription !== subscription)
|
|
63168
|
+
return;
|
|
63169
|
+
owner.subscription = undefined;
|
|
63170
|
+
owner.stopped = { error };
|
|
63171
|
+
if (shuttingDown || relay !== owner)
|
|
63172
|
+
return;
|
|
63173
|
+
serialized(register).catch(() => {
|
|
63174
|
+
registrationFailed = true;
|
|
63175
|
+
});
|
|
62884
63176
|
}
|
|
62885
63177
|
};
|
|
63178
|
+
const resubscribeRelay = async () => {
|
|
63179
|
+
const owner = relay;
|
|
63180
|
+
const previous = owner?.stopped;
|
|
63181
|
+
if (owner === undefined || previous === undefined || owner.sessionID !== identity.id)
|
|
63182
|
+
return;
|
|
63183
|
+
if (connectionLost !== undefined || connection.isClosed())
|
|
63184
|
+
return;
|
|
63185
|
+
try {
|
|
63186
|
+
subscribeRelay(owner);
|
|
63187
|
+
} catch (error) {
|
|
63188
|
+
owner.stopped = { error };
|
|
63189
|
+
return;
|
|
63190
|
+
}
|
|
63191
|
+
const taken = owner.subscription;
|
|
63192
|
+
const confirmed = await withTimeout(connection.flush(), options.handoffFlushTimeoutMs ?? HANDOFF_FLUSH_TIMEOUT_MS, "flushing NATS").then(() => true, () => false);
|
|
63193
|
+
await nextTurn();
|
|
63194
|
+
if (relay !== owner || owner.subscription !== taken)
|
|
63195
|
+
return;
|
|
63196
|
+
if (!confirmed) {
|
|
63197
|
+
taken?.unsubscribe();
|
|
63198
|
+
owner.subscription = undefined;
|
|
63199
|
+
owner.stopped = previous;
|
|
63200
|
+
return;
|
|
63201
|
+
}
|
|
63202
|
+
owner.delivery.beginEpoch();
|
|
63203
|
+
};
|
|
62886
63204
|
function closeRelay() {
|
|
62887
63205
|
const owner = relay;
|
|
62888
63206
|
if (owner === undefined)
|
|
@@ -62906,7 +63224,7 @@ async function startChannelSession(options) {
|
|
|
62906
63224
|
return;
|
|
62907
63225
|
asked.delivery.answered(result.delivery);
|
|
62908
63226
|
};
|
|
62909
|
-
const followedTopics = createChannelTopics(
|
|
63227
|
+
const followedTopics = createChannelTopics(() => connection);
|
|
62910
63228
|
function unfollowRemovedTopics(topics) {
|
|
62911
63229
|
dropFromTopicsAndRegistry(topics).catch((error) => {
|
|
62912
63230
|
process.stderr.write(`envoy-channel: could not drop a removed subscription from the registry \u2014 ${messageFor(error)}; the next heartbeat reconciles it
|
|
@@ -62925,23 +63243,36 @@ async function startChannelSession(options) {
|
|
|
62925
63243
|
}));
|
|
62926
63244
|
}
|
|
62927
63245
|
const inboundOutage = inboundUnavailable((why) => {
|
|
63246
|
+
if (shuttingDown)
|
|
63247
|
+
return;
|
|
62928
63248
|
process.stderr.write(`envoy-channel: this session receives nothing (${why}); registering again every heartbeat
|
|
62929
63249
|
`);
|
|
62930
63250
|
delivery.notice(inboundUnavailableNoticeText(why)).catch((noticeError) => {
|
|
62931
63251
|
process.stderr.write(`envoy-channel: the session could not be told that it receives nothing \u2014 ${messageFor(noticeError)}
|
|
63252
|
+
`);
|
|
63253
|
+
});
|
|
63254
|
+
}, () => {
|
|
63255
|
+
if (shuttingDown)
|
|
63256
|
+
return;
|
|
63257
|
+
process.stderr.write(`envoy-channel: this session receives again: its registration was accepted
|
|
63258
|
+
`);
|
|
63259
|
+
delivery.notice(inboundRestoredNoticeText()).catch((noticeError) => {
|
|
63260
|
+
process.stderr.write(`envoy-channel: the session could not be told that it receives again \u2014 ${messageFor(noticeError)}
|
|
62932
63261
|
`);
|
|
62933
63262
|
});
|
|
62934
63263
|
});
|
|
62935
63264
|
let stampedTitle;
|
|
62936
63265
|
let stampFailureReported = false;
|
|
62937
63266
|
const register = async () => {
|
|
62938
|
-
if (
|
|
62939
|
-
|
|
63267
|
+
if (shuttingDown)
|
|
63268
|
+
return;
|
|
63269
|
+
if (handoffDeliveryPending && connectionLost === undefined) {
|
|
63270
|
+
await followSession?.();
|
|
62940
63271
|
if (shuttingDown)
|
|
62941
63272
|
return;
|
|
62942
63273
|
await restoreDelivery();
|
|
62943
63274
|
handoffDeliveryPending = false;
|
|
62944
|
-
await withTimeout(
|
|
63275
|
+
await withTimeout(connection.flush(), options.handoffFlushTimeoutMs ?? HANDOFF_FLUSH_TIMEOUT_MS, "flushing NATS").catch((error) => {
|
|
62945
63276
|
process.stderr.write(`envoy-channel: could not confirm the relay subscription of ${identity.id} \u2014 ${natsFailureReason(error)}
|
|
62946
63277
|
`);
|
|
62947
63278
|
});
|
|
@@ -62961,9 +63292,13 @@ async function startChannelSession(options) {
|
|
|
62961
63292
|
}
|
|
62962
63293
|
}
|
|
62963
63294
|
const sessionID = identity.id;
|
|
62964
|
-
const
|
|
63295
|
+
const lost = connectionLost;
|
|
63296
|
+
const stopped = relay?.stopped;
|
|
63297
|
+
const relayMissing = lost !== undefined ? lostConnectionReason(lost) : stopped === undefined ? undefined : natsFailureReason(stopped.error);
|
|
63298
|
+
const asking = relayMissing === undefined && relay?.sessionID === sessionID ? relay : undefined;
|
|
62965
63299
|
await registerWithRelay({
|
|
62966
63300
|
relay: asking?.delivery,
|
|
63301
|
+
...relayMissing === undefined ? {} : { relayMissing },
|
|
62967
63302
|
ownAgentSubject: directSubject,
|
|
62968
63303
|
followed: followedTopics.topics(),
|
|
62969
63304
|
roles: heldRole === undefined ? [] : [heldRole],
|
|
@@ -63114,13 +63449,14 @@ async function startChannelSession(options) {
|
|
|
63114
63449
|
const nextSubject = legacyAgentSubject(next);
|
|
63115
63450
|
followedTopics.follow(nextSubject);
|
|
63116
63451
|
try {
|
|
63117
|
-
await withTimeout(
|
|
63452
|
+
await withTimeout(connection.flush(), options.handoffFlushTimeoutMs ?? HANDOFF_FLUSH_TIMEOUT_MS, "flushing NATS");
|
|
63118
63453
|
await deregister(previous);
|
|
63119
63454
|
} catch (error) {
|
|
63120
63455
|
followedTopics.unfollow([nextSubject]);
|
|
63121
63456
|
throw error;
|
|
63122
63457
|
}
|
|
63123
63458
|
identity.set(next);
|
|
63459
|
+
options.adopted?.(previous, next);
|
|
63124
63460
|
forgetBrokerSession(previous);
|
|
63125
63461
|
directSubject = nextSubject;
|
|
63126
63462
|
closeRelay();
|
|
@@ -63180,18 +63516,24 @@ async function startChannelSession(options) {
|
|
|
63180
63516
|
dropRetry = undefined;
|
|
63181
63517
|
};
|
|
63182
63518
|
const heartbeat = async (fromRetry = false) => {
|
|
63183
|
-
if (shuttingDown
|
|
63519
|
+
if (shuttingDown)
|
|
63520
|
+
return;
|
|
63521
|
+
reopenConnection();
|
|
63522
|
+
if (heartbeatInFlight)
|
|
63184
63523
|
return;
|
|
63185
63524
|
heartbeatInFlight = true;
|
|
63186
63525
|
try {
|
|
63187
63526
|
await serialized(async () => {
|
|
63188
63527
|
await adoptHandoff();
|
|
63528
|
+
await resubscribeRelay();
|
|
63189
63529
|
try {
|
|
63190
63530
|
await register();
|
|
63191
63531
|
} catch (error) {
|
|
63192
63532
|
registrationFailed = true;
|
|
63193
63533
|
throw error;
|
|
63194
63534
|
}
|
|
63535
|
+
if (shuttingDown)
|
|
63536
|
+
return;
|
|
63195
63537
|
await reassertRole(registrationFailed);
|
|
63196
63538
|
await transferRole();
|
|
63197
63539
|
await syncRegisteredInterests();
|
|
@@ -63246,7 +63588,15 @@ async function startChannelSession(options) {
|
|
|
63246
63588
|
process.stderr.write(`envoy-channel: could not read the registered interests (${messageFor(error)}); the next heartbeat retries
|
|
63247
63589
|
`);
|
|
63248
63590
|
});
|
|
63249
|
-
await flushThroughRedials(
|
|
63591
|
+
const closedBeforeFlush = await flushThroughRedials(connection, options.startSignal);
|
|
63592
|
+
if (closedBeforeFlush !== undefined) {
|
|
63593
|
+
if (options.reopen === undefined)
|
|
63594
|
+
throw closedStart(closedBeforeFlush);
|
|
63595
|
+
const closeError = await closeErrorOf(connection);
|
|
63596
|
+
if (options.startSignal?.aborted === true)
|
|
63597
|
+
throw new Error(START_STOPPING);
|
|
63598
|
+
connectionClosed(connection, closeError ?? closedBeforeFlush.error);
|
|
63599
|
+
}
|
|
63250
63600
|
await serialized(async () => {
|
|
63251
63601
|
await register().catch((error) => {
|
|
63252
63602
|
registrationFailed = true;
|
|
@@ -63289,18 +63639,93 @@ async function startChannelSession(options) {
|
|
|
63289
63639
|
watchFile(handoffFile, { interval: HANDOFF_POLL_MS }, handoffFileChanged);
|
|
63290
63640
|
requestHeartbeat();
|
|
63291
63641
|
}
|
|
63292
|
-
(
|
|
63642
|
+
function connectionClosed(closed, closeError) {
|
|
63643
|
+
if (shuttingDown || closed !== connection || lostConnections.has(closed))
|
|
63644
|
+
return;
|
|
63645
|
+
lostConnections.add(closed);
|
|
63646
|
+
connectionLost = { closeError, dialError: undefined };
|
|
63647
|
+
if (relay !== undefined)
|
|
63648
|
+
relay.subscription = undefined;
|
|
63649
|
+
process.stderr.write(`envoy-channel: the NATS connection closed for good (${lostConnectionReason(connectionLost)}); ${options.reopen === undefined ? "nothing dials a new one" : "dialing a new one"}
|
|
63650
|
+
`);
|
|
63651
|
+
serialized(register).catch(() => {
|
|
63652
|
+
registrationFailed = true;
|
|
63653
|
+
});
|
|
63654
|
+
reopenConnection();
|
|
63655
|
+
}
|
|
63656
|
+
function reopenConnection() {
|
|
63657
|
+
const lost = connectionLost;
|
|
63658
|
+
const reopen = options.reopen;
|
|
63659
|
+
if (lost === undefined || reopen === undefined || reopening || shuttingDown)
|
|
63660
|
+
return;
|
|
63661
|
+
reopening = true;
|
|
63662
|
+
reopenFor(lost, reopen).finally(() => {
|
|
63663
|
+
reopening = false;
|
|
63664
|
+
if (connectionLost !== undefined && connectionLost !== lost)
|
|
63665
|
+
reopenConnection();
|
|
63666
|
+
});
|
|
63667
|
+
}
|
|
63668
|
+
async function reopenFor(lost, reopen) {
|
|
63669
|
+
let reopened;
|
|
63293
63670
|
try {
|
|
63294
|
-
|
|
63295
|
-
|
|
63296
|
-
|
|
63297
|
-
renewRelayEpoch();
|
|
63298
|
-
}
|
|
63671
|
+
reopened = await reopen((dialError) => {
|
|
63672
|
+
lost.dialError = dialError;
|
|
63673
|
+
});
|
|
63299
63674
|
} catch (error) {
|
|
63300
|
-
|
|
63675
|
+
if (shuttingDown || options.startSignal?.aborted === true)
|
|
63676
|
+
return;
|
|
63677
|
+
lost.dialError = error;
|
|
63678
|
+
process.stderr.write(`envoy-channel: gave up opening a new NATS connection (${natsFailureReason(error)}); dialing again at the next heartbeat
|
|
63301
63679
|
`);
|
|
63680
|
+
return;
|
|
63302
63681
|
}
|
|
63303
|
-
|
|
63682
|
+
const live = reopened.connection;
|
|
63683
|
+
if (shuttingDown) {
|
|
63684
|
+
live.close().catch(() => {
|
|
63685
|
+
return;
|
|
63686
|
+
});
|
|
63687
|
+
return;
|
|
63688
|
+
}
|
|
63689
|
+
connection = live;
|
|
63690
|
+
followSession = reopened.followSession;
|
|
63691
|
+
if (relay !== undefined && !handoffDeliveryPending)
|
|
63692
|
+
subscribeRelay(relay);
|
|
63693
|
+
watchConnection(live);
|
|
63694
|
+
await serialized(async () => {
|
|
63695
|
+
await withTimeout(live.flush(), options.handoffFlushTimeoutMs ?? HANDOFF_FLUSH_TIMEOUT_MS, "flushing NATS").catch((error) => {
|
|
63696
|
+
process.stderr.write(`envoy-channel: could not confirm the relay subscription on the new NATS connection \u2014 ${natsFailureReason(error)}
|
|
63697
|
+
`);
|
|
63698
|
+
});
|
|
63699
|
+
if (shuttingDown || live !== connection || live.isClosed())
|
|
63700
|
+
return;
|
|
63701
|
+
connectionLost = undefined;
|
|
63702
|
+
relay?.delivery.beginEpoch();
|
|
63703
|
+
await register();
|
|
63704
|
+
}).catch((error) => {
|
|
63705
|
+
registrationFailed = true;
|
|
63706
|
+
process.stderr.write(`envoy-channel: could not register on the new NATS connection (${messageFor(error)}); the next heartbeat retries
|
|
63707
|
+
`);
|
|
63708
|
+
});
|
|
63709
|
+
}
|
|
63710
|
+
function watchConnection(watched) {
|
|
63711
|
+
if (watchedConnections.has(watched))
|
|
63712
|
+
return;
|
|
63713
|
+
watchedConnections.add(watched);
|
|
63714
|
+
(async () => {
|
|
63715
|
+
try {
|
|
63716
|
+
for await (const status of watched.status()) {
|
|
63717
|
+
if (status.type !== "reconnect")
|
|
63718
|
+
continue;
|
|
63719
|
+
renewRelayEpoch();
|
|
63720
|
+
}
|
|
63721
|
+
} catch (error) {
|
|
63722
|
+
process.stderr.write(`envoy-channel: the NATS connection's status reader failed \u2014 ${natsFailureReason(error)}
|
|
63723
|
+
`);
|
|
63724
|
+
}
|
|
63725
|
+
})();
|
|
63726
|
+
watched.closed().then((closeError) => connectionClosed(watched, closeError), (closeError) => connectionClosed(watched, closeError));
|
|
63727
|
+
}
|
|
63728
|
+
watchConnection(connection);
|
|
63304
63729
|
return {
|
|
63305
63730
|
delivery,
|
|
63306
63731
|
topics: () => followedTopics.topics(),
|
|
@@ -63316,7 +63741,8 @@ async function startChannelSession(options) {
|
|
|
63316
63741
|
followedTopics.follow(topic);
|
|
63317
63742
|
fresh.push(topic);
|
|
63318
63743
|
}
|
|
63319
|
-
|
|
63744
|
+
if (!connection.isClosed())
|
|
63745
|
+
await connection.flush();
|
|
63320
63746
|
await serialized(register);
|
|
63321
63747
|
if (fresh.length > 0) {
|
|
63322
63748
|
await ledger.followedChanged();
|
|
@@ -63351,8 +63777,10 @@ async function startChannelSession(options) {
|
|
|
63351
63777
|
return turns?.messageOf(row);
|
|
63352
63778
|
},
|
|
63353
63779
|
async rememberRole(role) {
|
|
63354
|
-
|
|
63355
|
-
|
|
63780
|
+
await serialized(async () => {
|
|
63781
|
+
heldRole = role;
|
|
63782
|
+
await writeRoleRecord(roleStateFile(options.stateDirectory, identity.id), role);
|
|
63783
|
+
});
|
|
63356
63784
|
},
|
|
63357
63785
|
async shutdown() {
|
|
63358
63786
|
if (shuttingDown)
|
|
@@ -63714,8 +64142,13 @@ async function runEnvoyChannelServer() {
|
|
|
63714
64142
|
session = inboundOffChannelSession({ identity, stateDirectory, why: inbound.off });
|
|
63715
64143
|
} else {
|
|
63716
64144
|
starting = inbound.natsCredential.kind === "broker" ? "it waits for this session's broker token, and its stderr says what each trade came to" : "it connects to NATS";
|
|
63717
|
-
const
|
|
63718
|
-
|
|
64145
|
+
const natsName = `claude-envoy-channel-${identity.id}`;
|
|
64146
|
+
const dialled = await dialChannelNats(inbound, natsName, (text, dialError) => {
|
|
64147
|
+
if (dialError !== undefined)
|
|
64148
|
+
starting = text;
|
|
64149
|
+
process.stderr.write(`envoy-channel: ${text}
|
|
64150
|
+
`);
|
|
64151
|
+
}, import_nats5.connect, booting.signal).catch((error) => {
|
|
63719
64152
|
if (stopping)
|
|
63720
64153
|
return;
|
|
63721
64154
|
throw error;
|
|
@@ -63726,12 +64159,22 @@ async function runEnvoyChannelServer() {
|
|
|
63726
64159
|
stopNatsKeeper = dialled.stop;
|
|
63727
64160
|
starting = "it registers this session with Envoy";
|
|
63728
64161
|
const admission = dialled.followSession === undefined ? undefined : sessionAdmission(identity.id);
|
|
63729
|
-
const
|
|
63730
|
-
const followSession =
|
|
63731
|
-
|
|
63732
|
-
|
|
63733
|
-
|
|
63734
|
-
|
|
64162
|
+
const admitting = admittingMoves(admission, identity);
|
|
64163
|
+
const followSession = admitting(dialled.followSession);
|
|
64164
|
+
const reopen = channelReopener({
|
|
64165
|
+
inbound,
|
|
64166
|
+
name: natsName,
|
|
64167
|
+
signal: booting.signal,
|
|
64168
|
+
swapKeeper: (stop) => {
|
|
64169
|
+
stopNatsKeeper();
|
|
64170
|
+
stopNatsKeeper = stop;
|
|
64171
|
+
},
|
|
64172
|
+
admitting,
|
|
64173
|
+
useConnection: (next) => {
|
|
64174
|
+
connection = next;
|
|
64175
|
+
agentStream?.useConnection(next);
|
|
64176
|
+
}
|
|
64177
|
+
});
|
|
63735
64178
|
const started = await startChannelSession({
|
|
63736
64179
|
identity,
|
|
63737
64180
|
connection,
|
|
@@ -63749,6 +64192,8 @@ async function runEnvoyChannelServer() {
|
|
|
63749
64192
|
...stamping ? { stampTitle } : {},
|
|
63750
64193
|
...configuredValue(overrideSessionId) === undefined ? { handoffPid: process.ppid } : {},
|
|
63751
64194
|
...followSession === undefined ? {} : { followSession },
|
|
64195
|
+
adopted: (previous, next) => agentStream?.sessionAdopted(previous, next),
|
|
64196
|
+
reopen,
|
|
63752
64197
|
startSignal: booting.signal
|
|
63753
64198
|
}).catch((error) => {
|
|
63754
64199
|
if (stopping)
|
|
@@ -63758,13 +64203,12 @@ async function runEnvoyChannelServer() {
|
|
|
63758
64203
|
if (started === undefined)
|
|
63759
64204
|
return;
|
|
63760
64205
|
session = started;
|
|
63761
|
-
const bus = connection;
|
|
63762
64206
|
const live = session;
|
|
63763
64207
|
linked.promise.then((link) => {
|
|
63764
|
-
if (stopping)
|
|
64208
|
+
if (stopping || connection === undefined)
|
|
63765
64209
|
return;
|
|
63766
64210
|
agentStream = startAgentStream({
|
|
63767
|
-
connection
|
|
64211
|
+
connection,
|
|
63768
64212
|
followsSessionId: configuredValue(overrideSessionId) === undefined,
|
|
63769
64213
|
...admission === undefined ? {} : { admitted: (id) => admission.admitted(id) },
|
|
63770
64214
|
isPane: inbox !== undefined,
|
|
@@ -63814,15 +64258,7 @@ async function runEnvoyChannelServer() {
|
|
|
63814
64258
|
return;
|
|
63815
64259
|
});
|
|
63816
64260
|
if (session === undefined && connection !== undefined) {
|
|
63817
|
-
await
|
|
63818
|
-
connection.drain().catch(() => {
|
|
63819
|
-
return;
|
|
63820
|
-
}),
|
|
63821
|
-
Bun.sleep(START_DRAIN_BOUND_MS)
|
|
63822
|
-
]);
|
|
63823
|
-
await connection.close().catch(() => {
|
|
63824
|
-
return;
|
|
63825
|
-
});
|
|
64261
|
+
await closeUnstartedConnection(connection);
|
|
63826
64262
|
}
|
|
63827
64263
|
await server.close().catch(() => {
|
|
63828
64264
|
return;
|
|
@@ -63831,23 +64267,24 @@ async function runEnvoyChannelServer() {
|
|
|
63831
64267
|
}
|
|
63832
64268
|
|
|
63833
64269
|
// src/codex/codex-agent-stream.ts
|
|
63834
|
-
var encoder6 = new TextEncoder;
|
|
63835
|
-
var decoder5 = new TextDecoder;
|
|
63836
|
-
var RESUBSCRIBE_MS = 1000;
|
|
63837
64270
|
var EXPECTED_MAX = 16;
|
|
63838
64271
|
var CODEX_PROVIDER = "openai";
|
|
63839
64272
|
function startCodexAgentStream(options) {
|
|
63840
|
-
const { connection } = options;
|
|
63841
64273
|
const now = options.now ?? Date.now;
|
|
63842
64274
|
const warn = options.warn ?? ((text) => void process.stderr.write(`envoy-channel: ${text}
|
|
63843
64275
|
`));
|
|
64276
|
+
let session = options.sessionId;
|
|
64277
|
+
const control = controlSubscription({
|
|
64278
|
+
connection: options.connection,
|
|
64279
|
+
session: () => session,
|
|
64280
|
+
...options.admitted === undefined ? {} : { admitted: options.admitted },
|
|
64281
|
+
warn,
|
|
64282
|
+
answer: answerControl
|
|
64283
|
+
});
|
|
63844
64284
|
const publisher = new AgentStreamPublisher({
|
|
63845
64285
|
now,
|
|
63846
|
-
publish: (subject, payload) =>
|
|
64286
|
+
publish: (subject, payload) => control.publish(subject, payload)
|
|
63847
64287
|
});
|
|
63848
|
-
let session = options.sessionId;
|
|
63849
|
-
let subscription;
|
|
63850
|
-
let stopped = false;
|
|
63851
64288
|
let model;
|
|
63852
64289
|
let allocated = 0;
|
|
63853
64290
|
const expected = [];
|
|
@@ -63882,52 +64319,19 @@ function startCodexAgentStream(options) {
|
|
|
63882
64319
|
thinking: null
|
|
63883
64320
|
});
|
|
63884
64321
|
};
|
|
63885
|
-
|
|
63886
|
-
|
|
63887
|
-
|
|
63888
|
-
|
|
63889
|
-
|
|
63890
|
-
|
|
63891
|
-
|
|
63892
|
-
const request = parsed;
|
|
63893
|
-
if (request.type !== "replay" && request.type !== "watch")
|
|
63894
|
-
continue;
|
|
63895
|
-
const reply = message.reply;
|
|
63896
|
-
const answer = request.type === "replay" && reply !== undefined ? JSON.stringify(publisher.replay(forSession)) : undefined;
|
|
63897
|
-
const arming = !publisher.watched;
|
|
63898
|
-
publisher.noteViewer();
|
|
63899
|
-
if (arming)
|
|
63900
|
-
publisher.publishState(agentStreamFramesSubject(forSession));
|
|
63901
|
-
if (answer === undefined || reply === undefined)
|
|
63902
|
-
continue;
|
|
63903
|
-
connection.publish(reply, encoder6.encode(answer));
|
|
63904
|
-
} catch (error) {
|
|
63905
|
-
warn(`a live view control message failed \u2014 ${messageFor(error)}`);
|
|
63906
|
-
}
|
|
63907
|
-
}
|
|
63908
|
-
} catch {}
|
|
63909
|
-
if (subscription === taken)
|
|
63910
|
-
subscription = undefined;
|
|
63911
|
-
if (stopped || session !== forSession)
|
|
63912
|
-
return;
|
|
63913
|
-
setTimeout(() => {
|
|
63914
|
-
if (!stopped && session === forSession)
|
|
63915
|
-
subscribe();
|
|
63916
|
-
}, RESUBSCRIBE_MS).unref?.();
|
|
63917
|
-
};
|
|
63918
|
-
function subscribe() {
|
|
63919
|
-
if (stopped)
|
|
63920
|
-
return;
|
|
63921
|
-
subscription?.unsubscribe();
|
|
63922
|
-
const taken = connection.subscribe(agentStreamControlSubject(session));
|
|
63923
|
-
subscription = taken;
|
|
63924
|
-
pump(taken, session);
|
|
64322
|
+
function answerControl(request, replying, forSession) {
|
|
64323
|
+
const answer = request.type === "replay" && replying ? JSON.stringify(publisher.replay(forSession)) : undefined;
|
|
64324
|
+
const arming = !publisher.watched;
|
|
64325
|
+
publisher.noteViewer();
|
|
64326
|
+
if (arming)
|
|
64327
|
+
publisher.publishState(agentStreamFramesSubject(forSession));
|
|
64328
|
+
return answer;
|
|
63925
64329
|
}
|
|
63926
|
-
|
|
64330
|
+
control.start();
|
|
63927
64331
|
publishSettings();
|
|
63928
64332
|
return {
|
|
63929
64333
|
event(event) {
|
|
63930
|
-
if (stopped)
|
|
64334
|
+
if (control.stopped)
|
|
63931
64335
|
return;
|
|
63932
64336
|
switch (event.kind) {
|
|
63933
64337
|
case "settings":
|
|
@@ -63986,7 +64390,7 @@ function startCodexAgentStream(options) {
|
|
|
63986
64390
|
}
|
|
63987
64391
|
},
|
|
63988
64392
|
delivered(text, dispatchMessageId) {
|
|
63989
|
-
if (stopped)
|
|
64393
|
+
if (control.stopped)
|
|
63990
64394
|
return;
|
|
63991
64395
|
if (dispatchMessageId !== undefined) {
|
|
63992
64396
|
const index = expected.findIndex((entry) => entry.dispatchMessageId === dispatchMessageId);
|
|
@@ -64002,27 +64406,20 @@ function startCodexAgentStream(options) {
|
|
|
64002
64406
|
expected.shift();
|
|
64003
64407
|
},
|
|
64004
64408
|
rebind(next) {
|
|
64005
|
-
if (stopped || next === session)
|
|
64409
|
+
if (control.stopped || next === session)
|
|
64006
64410
|
return;
|
|
64007
64411
|
session = next;
|
|
64008
64412
|
publisher.reset();
|
|
64009
64413
|
expected.length = 0;
|
|
64010
64414
|
toolNames.clear();
|
|
64011
64415
|
publishSettings();
|
|
64012
|
-
|
|
64013
|
-
|
|
64014
|
-
|
|
64015
|
-
|
|
64016
|
-
subscribe();
|
|
64017
|
-
else
|
|
64018
|
-
admitted.then(() => {
|
|
64019
|
-
if (!stopped && session === next)
|
|
64020
|
-
subscribe();
|
|
64021
|
-
});
|
|
64416
|
+
control.moved();
|
|
64417
|
+
},
|
|
64418
|
+
useConnection(next) {
|
|
64419
|
+
control.useConnection(next);
|
|
64022
64420
|
},
|
|
64023
64421
|
stop() {
|
|
64024
|
-
|
|
64025
|
-
subscription?.unsubscribe();
|
|
64422
|
+
control.stop();
|
|
64026
64423
|
}
|
|
64027
64424
|
};
|
|
64028
64425
|
}
|
|
@@ -65507,17 +65904,36 @@ async function runCodexEnvoyServer() {
|
|
|
65507
65904
|
if ("off" in inbound) {
|
|
65508
65905
|
session = inboundOffChannelSession({ identity: id, stateDirectory, why: inbound.off });
|
|
65509
65906
|
} else {
|
|
65510
|
-
const
|
|
65907
|
+
const natsName = `codex-envoy-channel-${id.id}`;
|
|
65908
|
+
const dialled = await dialChannelNats(inbound, natsName, warn, import_nats6.connect, stopping.signal).catch((error) => {
|
|
65909
|
+
if (isStopping)
|
|
65910
|
+
return;
|
|
65911
|
+
throw error;
|
|
65912
|
+
});
|
|
65913
|
+
if (dialled === undefined) {
|
|
65914
|
+
await stopped.promise;
|
|
65915
|
+
return;
|
|
65916
|
+
}
|
|
65511
65917
|
connection = dialled.connection;
|
|
65512
65918
|
stopNatsKeeper = dialled.stop;
|
|
65513
65919
|
const admission = dialled.followSession === undefined ? undefined : sessionAdmission(id.id);
|
|
65514
|
-
const
|
|
65515
|
-
const followSession =
|
|
65516
|
-
|
|
65517
|
-
|
|
65518
|
-
|
|
65519
|
-
|
|
65520
|
-
|
|
65920
|
+
const admitting = admittingMoves(admission, id);
|
|
65921
|
+
const followSession = admitting(dialled.followSession);
|
|
65922
|
+
const reopen = channelReopener({
|
|
65923
|
+
inbound,
|
|
65924
|
+
name: natsName,
|
|
65925
|
+
signal: stopping.signal,
|
|
65926
|
+
swapKeeper: (stop) => {
|
|
65927
|
+
stopNatsKeeper();
|
|
65928
|
+
stopNatsKeeper = stop;
|
|
65929
|
+
},
|
|
65930
|
+
admitting,
|
|
65931
|
+
useConnection: (next) => {
|
|
65932
|
+
connection = next;
|
|
65933
|
+
stream?.useConnection(next);
|
|
65934
|
+
}
|
|
65935
|
+
});
|
|
65936
|
+
const started = await startChannelSession({
|
|
65521
65937
|
capabilities: () => CODEX_CAPABILITIES,
|
|
65522
65938
|
client,
|
|
65523
65939
|
clientInstanceID,
|
|
@@ -65547,16 +65963,29 @@ async function runCodexEnvoyServer() {
|
|
|
65547
65963
|
state,
|
|
65548
65964
|
warn
|
|
65549
65965
|
}),
|
|
65966
|
+
reopen,
|
|
65967
|
+
startSignal: stopping.signal,
|
|
65550
65968
|
stateDirectory,
|
|
65551
65969
|
title,
|
|
65552
65970
|
...dispatch.enabled ? { stampTitle } : {}
|
|
65971
|
+
}).catch((error) => {
|
|
65972
|
+
if (isStopping)
|
|
65973
|
+
return;
|
|
65974
|
+
throw error;
|
|
65553
65975
|
});
|
|
65976
|
+
if (started === undefined) {
|
|
65977
|
+
await stopped.promise;
|
|
65978
|
+
return;
|
|
65979
|
+
}
|
|
65980
|
+
session = started;
|
|
65554
65981
|
stream = startCodexAgentStream({
|
|
65555
65982
|
connection,
|
|
65556
65983
|
sessionId: id.id,
|
|
65557
65984
|
warn,
|
|
65558
65985
|
...admission === undefined ? {} : { admitted: (next) => admission.admitted(next) }
|
|
65559
65986
|
});
|
|
65987
|
+
if (isStopping)
|
|
65988
|
+
stream.stop();
|
|
65560
65989
|
}
|
|
65561
65990
|
runtime = { client, clientInstanceID, identity: id, session };
|
|
65562
65991
|
follow(bound.transcript_path);
|
|
@@ -65570,12 +65999,7 @@ async function runCodexEnvoyServer() {
|
|
|
65570
65999
|
follower?.stop();
|
|
65571
66000
|
stopNatsKeeper();
|
|
65572
66001
|
if (session === undefined && connection !== undefined) {
|
|
65573
|
-
await connection
|
|
65574
|
-
return;
|
|
65575
|
-
});
|
|
65576
|
-
await connection.close().catch(() => {
|
|
65577
|
-
return;
|
|
65578
|
-
});
|
|
66002
|
+
await closeUnstartedConnection(connection);
|
|
65579
66003
|
}
|
|
65580
66004
|
await server.close().catch(() => {
|
|
65581
66005
|
return;
|