@codeforbreakfast/commy-mcp 0.26.5 → 0.26.6

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.
Files changed (2) hide show
  1. package/package.json +2 -2
  2. package/server.js +161 -112
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@codeforbreakfast/commy-mcp",
3
- "version": "0.26.5",
4
- "description": "commy MCP server — the inter-agent communication substrate, runnable on node via npx.",
3
+ "version": "0.26.6",
4
+ "description": "commy MCP server — the inter-agent communication substrate, runnable on node.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
7
7
  "bin": "./server.js",
package/server.js CHANGED
@@ -12139,6 +12139,7 @@ var forEachSequentialDiscard = /* @__PURE__ */ dual(2, (self, f) => suspend(() =
12139
12139
  }
12140
12140
  });
12141
12141
  }));
12142
+ var if_ = /* @__PURE__ */ dual((args) => typeof args[0] === "boolean" || isEffect(args[0]), (self, options) => isEffect(self) ? flatMap7(self, (b) => b ? options.onTrue() : options.onFalse()) : self ? options.onTrue() : options.onFalse());
12142
12143
  var interrupt2 = /* @__PURE__ */ flatMap7(fiberId, (fiberId) => interruptWith(fiberId));
12143
12144
  var interruptWith = (fiberId) => failCause(interrupt(fiberId));
12144
12145
  var interruptible2 = (self) => {
@@ -15133,6 +15134,7 @@ var option3 = (self) => matchEffect(self, {
15133
15134
  onFailure: () => succeed(none2()),
15134
15135
  onSuccess: (a) => succeed(some2(a))
15135
15136
  });
15137
+ var orElseFail = /* @__PURE__ */ dual(2, (self, evaluate) => orElse2(self, () => failSync(evaluate)));
15136
15138
  var orElseSucceed = /* @__PURE__ */ dual(2, (self, evaluate) => orElse2(self, () => sync(evaluate)));
15137
15139
  var patchFiberRefs = (patch) => updateFiberRefs((fiberId, fiberRefs) => pipe(patch, patch6(fiberId, fiberRefs)));
15138
15140
  var promise = (evaluate) => evaluate.length >= 1 ? async_((resolve, signal) => {
@@ -19678,8 +19680,10 @@ var option4 = option3;
19678
19680
  var either4 = either2;
19679
19681
  var exit2 = exit;
19680
19682
  var intoDeferred2 = intoDeferred;
19683
+ var if_2 = if_;
19681
19684
  var filterOrElse2 = filterOrElse;
19682
19685
  var when2 = when;
19686
+ var whenEffect2 = whenEffect;
19683
19687
  var flatMap10 = flatMap7;
19684
19688
  var andThen4 = andThen2;
19685
19689
  var flatten5 = flatten3;
@@ -19704,6 +19708,7 @@ var logError2 = logError;
19704
19708
  var annotateLogs2 = annotateLogs;
19705
19709
  var orDie2 = orDie;
19706
19710
  var orElse6 = orElse2;
19711
+ var orElseFail2 = orElseFail;
19707
19712
  var orElseSucceed2 = orElseSucceed;
19708
19713
  var runtime4 = runtime3;
19709
19714
  var unsafeMakeSemaphore2 = unsafeMakeSemaphore;
@@ -37522,7 +37527,8 @@ var wrapBotHttp = (inner, resolveDirectory, selfUserId) => ({
37522
37527
  },
37523
37528
  patch: (path, schema, body) => inner.patch(path, schema, body),
37524
37529
  delete: (path, schema, body) => inner.delete(path, schema, body),
37525
- uploadRaw: (filename, data) => inner.uploadRaw(filename, data)
37530
+ uploadRaw: (filename, data) => inner.uploadRaw(filename, data),
37531
+ downloadRaw: (realmPath) => inner.downloadRaw(realmPath)
37526
37532
  });
37527
37533
 
37528
37534
  // packages/zulip/channel-description.ts
@@ -38159,21 +38165,18 @@ var RATE_LIMIT_RETRY_BUDGET_MS = toMillis(RATE_LIMIT_RETRY_BUDGET);
38159
38165
  var DEFAULT_RATE_LIMIT_WAIT_MS = 1000;
38160
38166
  var MIN_RATE_LIMIT_WAIT_MS = 100;
38161
38167
  var isRateLimited = (err) => err.status === 429;
38162
- var rateLimitSchedule = () => makeWithState2({ waitedMs: 0 }, (now, err, state) => {
38163
- const remaining = RATE_LIMIT_RETRY_BUDGET_MS - state.waitedMs;
38168
+ var rateLimitSchedule = () => makeWithState2(none2(), (now, err, state) => {
38169
+ const firstRefusedAt = getOrElse2(state, () => now);
38170
+ const waitedMs = now - firstRefusedAt;
38171
+ const remaining = RATE_LIMIT_RETRY_BUDGET_MS - waitedMs;
38164
38172
  if (!isRateLimited(err) || remaining <= 0) {
38165
- return succeed8([
38166
- state,
38167
- millis(state.waitedMs),
38168
- done6
38169
- ]);
38173
+ return succeed8([state, millis(waitedMs), done6]);
38170
38174
  }
38171
38175
  const requested = err.retryAfter === undefined ? DEFAULT_RATE_LIMIT_WAIT_MS : Math.max(err.retryAfter * 1000, MIN_RATE_LIMIT_WAIT_MS);
38172
38176
  const waitMs = Math.min(requested, remaining);
38173
- const nextState = { waitedMs: state.waitedMs + waitMs };
38174
38177
  return succeed8([
38175
- nextState,
38176
- millis(nextState.waitedMs),
38178
+ some2(firstRefusedAt),
38179
+ millis(waitedMs + waitMs),
38177
38180
  continueWith2(after2(now + waitMs))
38178
38181
  ]);
38179
38182
  });
@@ -38208,6 +38211,7 @@ var classifyEnvelope = (text, status, url) => {
38208
38211
  });
38209
38212
  };
38210
38213
  var isCredentialRejected = (err) => err.status === 401;
38214
+ var isAccessRefused = (err) => err.status === 403;
38211
38215
  var TRANSPORT_FAILURE_STATUS = 0;
38212
38216
  var isTransientZulipError = (err) => err.status === TRANSPORT_FAILURE_STATUS || err.status === 429 || err.status === 502 || err.status === 503 || err.status === 504;
38213
38217
  var transportError = (url, cause) => new ZulipApiError({
@@ -38317,7 +38321,8 @@ var sanitiseShortName = (name) => {
38317
38321
  const collapsed = name.toLowerCase().replace(SHORT_NAME_PATTERN, "-");
38318
38322
  return collapsed.replace(/^-+|-+$/g, "") || "bot";
38319
38323
  };
38320
- var ACQUIRE_MINT_TIMEOUT = sum(RATE_LIMIT_RETRY_BUDGET, seconds(30));
38324
+ var MAX_MINT_ROUND_TRIP_CALLS = 3;
38325
+ var ACQUIRE_MINT_TIMEOUT = sum(times(RATE_LIMIT_RETRY_BUDGET, MAX_MINT_ROUND_TRIP_CALLS), seconds(30));
38321
38326
  var userSchema = Struct({
38322
38327
  user_id: Int,
38323
38328
  email: String$,
@@ -38476,7 +38481,8 @@ var zulipAdapter = (config) => gen2(function* () {
38476
38481
  post: (path, schema, body) => recordRejection(inner.post(path, schema, body)),
38477
38482
  patch: (path, schema, body) => recordRejection(inner.patch(path, schema, body)),
38478
38483
  delete: (path, schema, body) => recordRejection(inner.delete(path, schema, body)),
38479
- uploadRaw: (filename, data) => recordRejection(inner.uploadRaw(filename, data))
38484
+ uploadRaw: (filename, data) => recordRejection(inner.uploadRaw(filename, data)),
38485
+ downloadRaw: (realmPath) => recordRejection(inner.downloadRaw(realmPath))
38480
38486
  });
38481
38487
  const requireBound = () => get16(boundRef).pipe(map18(getOrThrowWith2(() => new Error("zulipAdapter: not acquired — call identity.acquire(name) first"))));
38482
38488
  const bindOnDemand = config.bindOnDemand ?? get16(boundRef).pipe(flatMap10(match2({
@@ -39097,7 +39103,7 @@ var zulipAdapter = (config) => gen2(function* () {
39097
39103
  inbox,
39098
39104
  history,
39099
39105
  directory,
39100
- downloadFile: (ref) => decodeUserUploadPath(ref).pipe(flatMap10((urlPath) => minterHttp.downloadRaw(urlPath).pipe(map18((raw) => ({ ...raw, filename: basename(urlPath) })))), mapError2((cause) => new AttachmentError({ operation: "download", cause }))),
39106
+ downloadFile: (ref) => decodeUserUploadPath(ref).pipe(flatMap10((urlPath) => minterHttp.downloadRaw(urlPath).pipe(catchIf2(isAccessRefused, (refused) => ownerHttp().pipe(orElseFail2(() => refused), flatMap10((http) => http.downloadRaw(urlPath)))), map18((raw) => ({ ...raw, filename: basename(urlPath) })))), mapError2((cause) => new AttachmentError({ operation: "download", cause }))),
39101
39107
  uploadFile: (filename, data) => boundHttp().pipe(flatMap10((http) => http.uploadRaw(filename, data)), flatMap10((upload) => decodeAttachmentRef(upload.url).pipe(map18((ref) => ({
39102
39108
  ref,
39103
39109
  filename: upload.filename,
@@ -39167,8 +39173,117 @@ class ResumeOutcome extends Tag2("commy/mcp/ResumeOutcome")() {
39167
39173
  }
39168
39174
  var ResumeOutcomeLive = effect(ResumeOutcome, make25());
39169
39175
 
39176
+ // packages/mcp/ensure-bound.ts
39177
+ var createEnsureBound = (deps) => map18(make27({ kind: "idle" }), (stateRef) => {
39178
+ const acquire = gen2(function* () {
39179
+ const fresh = yield* make25();
39180
+ const decision = yield* modify4(stateRef, (state) => {
39181
+ if (state.kind === "acquired") {
39182
+ return [{ kind: "have", identity: state.identity }, state];
39183
+ }
39184
+ if (state.kind === "pending") {
39185
+ return [{ kind: "await", deferred: state.deferred }, state];
39186
+ }
39187
+ return [
39188
+ { kind: "run", deferred: fresh },
39189
+ { kind: "pending", deferred: fresh }
39190
+ ];
39191
+ });
39192
+ if (decision.kind === "have")
39193
+ return decision.identity;
39194
+ if (decision.kind === "await")
39195
+ return yield* _await(decision.deferred);
39196
+ return yield* deps.acquire(deps.name).pipe(onExit3((exit) => set5(stateRef, match9(exit, {
39197
+ onFailure: () => ({ kind: "idle" }),
39198
+ onSuccess: (identity) => ({ kind: "acquired", identity })
39199
+ })).pipe(zipRight3(done2(decision.deferred, exit)))), tap2((acquired) => deps.afterAcquire === undefined ? _void : deps.afterAcquire(acquired).pipe(onError2(() => set5(stateRef, { kind: "idle" })))));
39200
+ });
39201
+ const ensureBound = () => acquire;
39202
+ ensureBound.current = () => {
39203
+ const state = runSync(get11(stateRef));
39204
+ return state.kind === "acquired" ? state.identity : undefined;
39205
+ };
39206
+ return ensureBound;
39207
+ });
39208
+
39209
+ // packages/mcp/identity-cache.ts
39210
+ var createSingleIdentityCache = (deps) => {
39211
+ const ensureBound = deps.ensureBound;
39212
+ return {
39213
+ ensureBoundFor: () => succeed8(ensureBound),
39214
+ ensureBoundIfUnclaimed: () => succeedSome2(ensureBound),
39215
+ boundIdentityIds: () => {
39216
+ const current = ensureBound.current();
39217
+ return current === undefined ? new Set : new Set([current.identity.id]);
39218
+ },
39219
+ releaseAllBound: () => _void
39220
+ };
39221
+ };
39222
+ var seatMoved = () => new UnboundEphemeralSession({
39223
+ message: "commy: this seat has moved to a newer session, so work started for an " + "earlier session no longer binds."
39224
+ });
39225
+ var unboundStub = Object.assign(() => fail9(new UnboundEphemeralSession({
39226
+ message: "commy: ephemeral mode requires a session_id; the plugin hook " + "should inject it from PreToolUse stdin. For non-CC clients, pass " + "session_id explicitly in the tool call arguments."
39227
+ })), {
39228
+ current: () => {
39229
+ return;
39230
+ }
39231
+ });
39232
+ var createEphemeralIdentityCache = (deps) => map18(all6([
39233
+ make49(undefined),
39234
+ makeSemaphore2(1),
39235
+ make27(none2())
39236
+ ]), ([slotRef, adapterTurn, adapterHolds]) => {
39237
+ const deriveBotName = (sessionId, project) => composeBotName({
39238
+ sessionId,
39239
+ ...project !== undefined ? { project } : {}
39240
+ });
39241
+ const afterAcquireFor = (project, sessionId) => (acquired) => deps.onAcquire !== undefined ? deps.onAcquire(acquired, project, sessionId) : _void;
39242
+ const bindAdapter = (superseded, name) => adapterTurn.withPermits(1)(if_2(get11(superseded), {
39243
+ onTrue: () => fail9(seatMoved()),
39244
+ onFalse: () => whenEffect2(deps.release(), get11(adapterHolds).pipe(map18(exists((held) => held !== name)))).pipe(zipRight3(set5(adapterHolds, some2(name))), zipRight3(deps.acquire(name)))
39245
+ }));
39246
+ const mintSlot = (sessionId, project, prior) => gen2(function* () {
39247
+ const superseded = yield* make27(false);
39248
+ const ensureBound = yield* createEnsureBound({
39249
+ acquire: (name) => bindAdapter(superseded, name),
39250
+ name: deriveBotName(sessionId, project),
39251
+ afterAcquire: afterAcquireFor(project, sessionId)
39252
+ });
39253
+ if (prior !== undefined)
39254
+ yield* set5(prior.superseded, true);
39255
+ return [ensureBound, { sessionId, ensureBound, superseded }];
39256
+ });
39257
+ const releaseBoundSlot = updateEffect2(slotRef, (slot) => as3(slot !== undefined && slot.ensureBound.current() !== undefined ? deps.release().pipe(zipRight3(set5(adapterHolds, none2()))) : _void, undefined));
39258
+ return {
39259
+ ensureBoundFor: (sessionId, project) => sessionId === undefined ? succeed8(unboundStub) : modifyEffect2(slotRef, (slot) => {
39260
+ if (slot !== undefined && slot.sessionId === sessionId) {
39261
+ return succeed8([slot.ensureBound, slot]);
39262
+ }
39263
+ return mintSlot(sessionId, project, slot);
39264
+ }),
39265
+ ensureBoundIfUnclaimed: (sessionId, project) => sessionId === undefined ? succeedSome2(unboundStub) : modifyEffect2(slotRef, (slot) => {
39266
+ if (slot === undefined) {
39267
+ return mintSlot(sessionId, project, undefined).pipe(map18(([ensureBound, minted]) => [some2(ensureBound), minted]));
39268
+ }
39269
+ return succeed8([
39270
+ slot.sessionId === sessionId ? some2(slot.ensureBound) : none2(),
39271
+ slot
39272
+ ]);
39273
+ }),
39274
+ boundIdentityIds: () => {
39275
+ const slot = runSync(get16(slotRef));
39276
+ if (slot === undefined)
39277
+ return new Set;
39278
+ const current = slot.ensureBound.current();
39279
+ return current === undefined ? new Set : new Set([current.identity.id]);
39280
+ },
39281
+ releaseAllBound: () => releaseBoundSlot
39282
+ };
39283
+ });
39284
+
39170
39285
  // packages/mcp/session-context.ts
39171
- var empty35 = { sessionId: undefined, project: undefined };
39286
+ var empty35 = { sessionId: undefined, project: undefined, mayTakeSeat: false };
39172
39287
  var CurrentSessionContext = unsafeMake7(empty35);
39173
39288
  var currentSessionContext = get13(CurrentSessionContext);
39174
39289
  var withSessionContext = (effect, context) => locally(effect, CurrentSessionContext, context);
@@ -39184,7 +39299,8 @@ var bindThrough = (ref) => get11(ref).pipe(flatMap10(match2({
39184
39299
  onSome: (binder) => binder
39185
39300
  })));
39186
39301
  var installBinder = (ref, binder) => set5(ref, some2(binder));
39187
- var binderFor = (identityCache) => currentSessionContext.pipe(flatMap10((ctx) => identityCache.ensureBoundFor(ctx.sessionId, ctx.project)), flatMap10((ensureBound) => ensureBound()));
39302
+ var binderFor = (identityCache) => currentSessionContext.pipe(flatMap10((ctx) => ctx.mayTakeSeat ? identityCache.ensureBoundFor(ctx.sessionId, ctx.project) : identityCache.ensureBoundIfUnclaimed(ctx.sessionId, ctx.project).pipe(map18(getOrElse2(() => seatTaken)))), flatMap10((ensureBound) => ensureBound()));
39303
+ var seatTaken = () => fail9(seatMoved());
39188
39304
 
39189
39305
  // packages/mcp/session-id.ts
39190
39306
  class SessionId extends Tag2("commy/mcp/SessionId")() {
@@ -39624,39 +39740,6 @@ var stateBaseConfig2 = nonEmptyString2("XDG_STATE_HOME").pipe(withDefault2(join7
39624
39740
  var cursorDirConfig = stateBaseConfig2.pipe(map14((base) => join7(base, STATE_SEGMENT2, "cursors")));
39625
39741
  var FileCursorStoreLive = effect(CursorStoreTag, all6([FileSystem, orDie2(cursorDirConfig)]).pipe(map18(([fs, dir]) => createFileCursorStore({ dir, fs }))));
39626
39742
 
39627
- // packages/mcp/ensure-bound.ts
39628
- var createEnsureBound = (deps) => map18(make27({ kind: "idle" }), (stateRef) => {
39629
- const acquire = gen2(function* () {
39630
- const fresh = yield* make25();
39631
- const decision = yield* modify4(stateRef, (state) => {
39632
- if (state.kind === "acquired") {
39633
- return [{ kind: "have", identity: state.identity }, state];
39634
- }
39635
- if (state.kind === "pending") {
39636
- return [{ kind: "await", deferred: state.deferred }, state];
39637
- }
39638
- return [
39639
- { kind: "run", deferred: fresh },
39640
- { kind: "pending", deferred: fresh }
39641
- ];
39642
- });
39643
- if (decision.kind === "have")
39644
- return decision.identity;
39645
- if (decision.kind === "await")
39646
- return yield* _await(decision.deferred);
39647
- return yield* deps.acquire(deps.name).pipe(onExit3((exit) => set5(stateRef, match9(exit, {
39648
- onFailure: () => ({ kind: "idle" }),
39649
- onSuccess: (identity) => ({ kind: "acquired", identity })
39650
- })).pipe(zipRight3(done2(decision.deferred, exit)))), tap2((acquired) => deps.afterAcquire === undefined ? _void : deps.afterAcquire(acquired).pipe(onError2(() => set5(stateRef, { kind: "idle" })))));
39651
- });
39652
- const ensureBound = () => acquire;
39653
- ensureBound.current = () => {
39654
- const state = runSync(get11(stateRef));
39655
- return state.kind === "acquired" ? state.identity : undefined;
39656
- };
39657
- return ensureBound;
39658
- });
39659
-
39660
39743
  // packages/mcp/event-pump.ts
39661
39744
  var originatorId = (event) => value3(event).pipe(discriminatorsExhaustive2("kind")({
39662
39745
  "message-posted": (message) => message.message.sender.id,
@@ -39769,58 +39852,6 @@ var channelNotifier = (mcp) => (payload) => {
39769
39852
  return;
39770
39853
  });
39771
39854
  };
39772
-
39773
- // packages/mcp/identity-cache.ts
39774
- var createSingleIdentityCache = (deps) => {
39775
- const ensureBound = deps.ensureBound;
39776
- return {
39777
- ensureBoundFor: () => succeed8(ensureBound),
39778
- boundIdentityIds: () => {
39779
- const current = ensureBound.current();
39780
- return current === undefined ? new Set : new Set([current.identity.id]);
39781
- },
39782
- releaseAllBound: () => _void
39783
- };
39784
- };
39785
- var unboundStub = Object.assign(() => fail9(new UnboundEphemeralSession({
39786
- message: "commy: ephemeral mode requires a session_id; the plugin hook " + "should inject it from PreToolUse stdin. For non-CC clients, pass " + "session_id explicitly in the tool call arguments."
39787
- })), { current: () => {
39788
- return;
39789
- } });
39790
- var createEphemeralIdentityCache = (deps) => map18(make49(undefined), (slotRef) => {
39791
- const deriveBotName = (sessionId, project) => composeBotName({
39792
- sessionId,
39793
- ...project !== undefined ? { project } : {}
39794
- });
39795
- const afterAcquireFor = (project, sessionId) => (acquired) => deps.onAcquire !== undefined ? deps.onAcquire(acquired, project, sessionId) : _void;
39796
- const acquireForTransition = (priorEnsure) => (n) => priorEnsure.current() !== undefined ? deps.release().pipe(zipRight3(deps.acquire(n))) : deps.acquire(n);
39797
- const mintSlot = (sessionId, project, prior) => {
39798
- const name = deriveBotName(sessionId, project);
39799
- const acquire = prior !== undefined ? acquireForTransition(prior.ensureBound) : deps.acquire;
39800
- return createEnsureBound({
39801
- acquire,
39802
- name,
39803
- afterAcquire: afterAcquireFor(project, sessionId)
39804
- }).pipe(map18((ensureBound) => [ensureBound, { sessionId, ensureBound }]));
39805
- };
39806
- const releaseBoundSlot = updateEffect2(slotRef, (slot) => as3(slot !== undefined && slot.ensureBound.current() !== undefined ? deps.release() : _void, undefined));
39807
- return {
39808
- ensureBoundFor: (sessionId, project) => sessionId === undefined ? succeed8(unboundStub) : modifyEffect2(slotRef, (slot) => {
39809
- if (slot !== undefined && slot.sessionId === sessionId) {
39810
- return succeed8([slot.ensureBound, slot]);
39811
- }
39812
- return mintSlot(sessionId, project, slot);
39813
- }),
39814
- boundIdentityIds: () => {
39815
- const slot = runSync(get16(slotRef));
39816
- if (slot === undefined)
39817
- return new Set;
39818
- const current = slot.ensureBound.current();
39819
- return current === undefined ? new Set : new Set([current.identity.id]);
39820
- },
39821
- releaseAllBound: () => releaseBoundSlot
39822
- };
39823
- });
39824
39855
  // node_modules/.bun/@modelcontextprotocol+sdk@1.32.2/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js
39825
39856
  function isZ4Schema(s) {
39826
39857
  const schema = s;
@@ -41255,7 +41286,7 @@ class Server extends Protocol {
41255
41286
  }
41256
41287
 
41257
41288
  // packages/mcp/mcp-server.ts
41258
- var PLUGIN_VERSION = "0.26.5";
41289
+ var PLUGIN_VERSION = "0.26.6";
41259
41290
  var COMMY_INSTRUCTIONS = `**Substrate.** commy is the inter-agent channel: agents and humans coordinate here. If you run it alongside other agent-messaging tools, keep one substrate canonical and don't fan the same message across all of them.
41260
41291
 
41261
41292
  **Channels.** Each project has one channel: \`#<project-slug>\` where the slug is resolved per session as \`COMMY_PROJECT\` env > git remote \`origin\` basename > git root basename, lowercased with \`_\`, \`/\` and other punctuation turned into \`-\`. The slug is the whole name and is never shortened; your bot name may carry a shortened form of it, so don't read your channel off your bot name. Sessions launched outside a git repo (e.g. \`/tmp\`, \`$HOME\`) have no project channel and should post to \`#general\` instead. Don't invent a channel name from a metaphor — never post to a literal \`#home\`, \`#project\`, or \`#<project>\`. Use \`list_channels\` to enumerate what actually exists in the realm; posting to a non-existent channel throws \`UnknownChannel\` rather than silently routing to Notification Bot.
@@ -41623,7 +41654,8 @@ var buildToolDefs = (deps, cache) => {
41623
41654
  const sessionId = readSessionId(args);
41624
41655
  return runEdge(projectForArgs(args).pipe(flatMap10((project) => feedSession(sessionId).pipe(zipRight3(withSessionContext(effect, {
41625
41656
  sessionId,
41626
- project: getOrUndefined2(project)
41657
+ project: getOrUndefined2(project),
41658
+ mayTakeSeat: true
41627
41659
  }))))));
41628
41660
  };
41629
41661
  const narrowWhileSubscribing = (intent, substrateSubscribe) => suspend4(() => {
@@ -42342,6 +42374,7 @@ var buildIdentityCache = (adapter, botName, ephemeralOnAcquire) => {
42342
42374
  var EDITING_PROBE_TIMEOUT = seconds(5);
42343
42375
  var signInRetrySchedule = exponential3(millis(250)).pipe(union9(spaced2(seconds(30))));
42344
42376
  var isTransientIdentityFailure = (err) => err instanceof IdentityError && err.transient;
42377
+ var retryWhileUnreachable = (signIn, attempt) => signIn.pipe(tapError2((err) => isTransientIdentityFailure(err) ? logWarning2(`commy plugin: ${attempt} could not reach the realm: ${err.message}`) : _void), retry({ schedule: signInRetrySchedule, while: isTransientIdentityFailure }));
42345
42378
  var makeProgram = (params = {}) => scoped2(gen2(function* () {
42346
42379
  const parsed = yield* parseEnv;
42347
42380
  const adapter = yield* SubstrateAdapter;
@@ -42400,7 +42433,11 @@ var makeProgram = (params = {}) => scoped2(gen2(function* () {
42400
42433
  isBound: () => identityCache.boundIdentityIds().size > 0,
42401
42434
  narrowSet,
42402
42435
  inbox: adapter.inbox
42403
- }), { sessionId: getOrUndefined2(sessionId), project: launchProject })), catchAll2((err) => logError2(`commy plugin: could not rebuild the subscription set: ${isError(err) ? err.message : String(err)}`).pipe(zipRight3(sync4(() => narrowSet.load(none2()))))), provide2(loggerLayer), ensuring2(succeed3(narrowSetRebuilt, undefined)));
42436
+ }), {
42437
+ sessionId: getOrUndefined2(sessionId),
42438
+ project: launchProject,
42439
+ mayTakeSeat: false
42440
+ })), catchAll2((err) => logError2(`commy plugin: could not rebuild the subscription set: ${isError(err) ? err.message : String(err)}`).pipe(zipRight3(sync4(() => narrowSet.load(none2()))))), provide2(loggerLayer), ensuring2(succeed3(narrowSetRebuilt, undefined)));
42404
42441
  const seedDefaults = (project) => registerType2Defaults !== undefined ? registerType2Defaults(project) : _void;
42405
42442
  const seedIfFresh = (sessionId, project) => parsed.botName !== undefined ? _void : seedDefaultsIfFresh({ subscriptionStore, registerDefaults: seedDefaults }, project).pipe(catchAll2((err) => logError2(`commy plugin: subscription seed check failed for ${sessionId}: ${isError(err) ? err.message : String(err)}`).pipe(zipRight3(seedDefaults(project)))), provide2(loggerLayer));
42406
42443
  const ensureSessionSubscriptions = (sessionId, project) => seedIfFresh(sessionId, project);
@@ -42412,7 +42449,7 @@ var makeProgram = (params = {}) => scoped2(gen2(function* () {
42412
42449
  parsed,
42413
42450
  loggerLayer
42414
42451
  };
42415
- const ephemeralOnAcquire = parsed.botName === undefined ? (acquired, project, sessionId) => seedSubscriptionsOnMint(acquired, seedDeps).pipe(catchAll2((err) => logError2(`commy plugin: COMMY_SUBSCRIBE seeding failed at mint: ${isError(err) ? err.message : String(err)}`)), provide2(loggerLayer), zipRight3(ensureSessionSubscriptions(sessionId, project)), zipRight3(_await(resumeOutcome)), flatMap10((queueReplayed) => {
42452
+ const catchUpUnlessReplayed = (acquired, queueReplayed) => suspend4(() => {
42416
42453
  if (queueReplayed)
42417
42454
  return _void;
42418
42455
  const identityId = acquired.identity.id;
@@ -42430,7 +42467,17 @@ var makeProgram = (params = {}) => scoped2(gen2(function* () {
42430
42467
  botIdentityId: identityId,
42431
42468
  windowSeconds
42432
42469
  }).pipe(catchAllCause2(logCatchUpFailure("ephemeral channels"))) : _void));
42433
- }), provide2(loggerLayer)) : undefined;
42470
+ }).pipe(provide2(loggerLayer));
42471
+ const programScope = yield* scope2;
42472
+ const waitingCatchUp = yield* make27(none2());
42473
+ const startCatchUp = (acquired) => getAndSet2(waitingCatchUp, none2()).pipe(flatMap10(match2({
42474
+ onNone: () => _void,
42475
+ onSome: (fiber) => asVoid2(interrupt5(fiber))
42476
+ })), zipRight3(poll(resumeOutcome)), flatMap10(match2({
42477
+ onSome: (verdict) => flatMap10(verdict, (queueReplayed) => catchUpUnlessReplayed(acquired, queueReplayed)),
42478
+ onNone: () => _await(resumeOutcome).pipe(flatMap10((queueReplayed) => catchUpUnlessReplayed(acquired, queueReplayed)), forkIn2(programScope), flatMap10((fiber) => set5(waitingCatchUp, some2(fiber))))
42479
+ })));
42480
+ const ephemeralOnAcquire = parsed.botName === undefined ? (acquired, project, sessionId) => seedSubscriptionsOnMint(acquired, seedDeps).pipe(catchAll2((err) => logError2(`commy plugin: COMMY_SUBSCRIBE seeding failed at mint: ${isError(err) ? err.message : String(err)}`)), provide2(loggerLayer), zipRight3(ensureSessionSubscriptions(sessionId, project)), zipRight3(startCatchUp(acquired))) : undefined;
42434
42481
  const identityCache = yield* buildIdentityCache(adapter, parsed.botName, ephemeralOnAcquire);
42435
42482
  yield* installBinder(yield* SessionBinder, binderFor(identityCache));
42436
42483
  const releasePersistent = parsed.botName !== undefined;
@@ -42441,11 +42488,9 @@ var makeProgram = (params = {}) => scoped2(gen2(function* () {
42441
42488
  })));
42442
42489
  const withBootSubscribeContext = (seed) => withSessionContext(seed, {
42443
42490
  sessionId: getOrUndefined2(bootSessionId),
42444
- project: launchProject
42491
+ project: launchProject,
42492
+ mayTakeSeat: false
42445
42493
  }).pipe(catchIf2(isBindError, (cause) => logWarning2(`commy plugin: boot-time subscribe could not bind an identity, so no ` + `subscriptions were applied yet — this seat will not receive channel traffic ` + `until it acts. ${isError(cause) ? cause.message : String(cause)}`).pipe(provide2(loggerLayer), as3([]))));
42446
- if (parsed.botName === undefined && parsed.subscribe !== undefined) {
42447
- yield* withBootSubscribeContext(binderFor(identityCache).pipe(as3([])));
42448
- }
42449
42494
  narrowSet.beginBuffering();
42450
42495
  const toolsCache = registerTools(mcp, {
42451
42496
  adapter,
@@ -42493,7 +42538,7 @@ var makeProgram = (params = {}) => scoped2(gen2(function* () {
42493
42538
  };
42494
42539
  const signInPersistentSeat = (botName) => gen2(function* () {
42495
42540
  const ensureBound = yield* identityCache.ensureBoundFor(undefined);
42496
- const acquired = yield* ensureBound().pipe(tapError2((err) => isTransientIdentityFailure(err) ? logWarning2(`commy plugin: acquire("${botName}") could not reach the realm: ${err.message}`) : _void), retry({ schedule: signInRetrySchedule, while: isTransientIdentityFailure }), catchAllCause2((cause) => {
42541
+ const acquired = yield* retryWhileUnreachable(ensureBound(), `acquire("${botName}")`).pipe(catchAllCause2((cause) => {
42497
42542
  const err = squash(cause);
42498
42543
  return fail9(new BootError({ message: isError(err) ? err.message : String(err) }));
42499
42544
  }), tapError2((bootErr) => logError2(`commy plugin: acquire("${botName}") failed: ${bootErr.message}`)));
@@ -42518,6 +42563,10 @@ var makeProgram = (params = {}) => scoped2(gen2(function* () {
42518
42563
  }).pipe(catchAllCause2(logCatchUpFailure("channels")));
42519
42564
  }
42520
42565
  });
42566
+ const signInEphemeralSeat = withBootSubscribeContext(retryWhileUnreachable(identityCache.ensureBoundIfUnclaimed(getOrUndefined2(bootSessionId), launchProject).pipe(flatMap10(match2({
42567
+ onNone: () => _void,
42568
+ onSome: (ensureBound) => asVoid2(ensureBound())
42569
+ }))), "boot-time sign-in").pipe(as3([])));
42521
42570
  const serve = gen2(function* () {
42522
42571
  const pump = yield* startEventPump({
42523
42572
  inbox: adapter.inbox,
@@ -42540,7 +42589,7 @@ var makeProgram = (params = {}) => scoped2(gen2(function* () {
42540
42589
  yield* forkScoped2(rebuildNarrowSet);
42541
42590
  yield* pump.done;
42542
42591
  });
42543
- yield* raceFirst2(parsed.botName === undefined ? serve : signInPersistentSeat(parsed.botName).pipe(zipRight3(serve)), params.shutdownSignal ?? never3);
42592
+ yield* raceFirst2(parsed.botName !== undefined ? signInPersistentSeat(parsed.botName).pipe(zipRight3(serve)) : parsed.subscribe !== undefined ? signInEphemeralSeat.pipe(zipRight3(serve)) : serve, params.shutdownSignal ?? never3);
42544
42593
  }));
42545
42594
  var AppLayer = mergeAll5(ZulipAdapterLive, FileCursorStoreLive, FileSubscriptionStoreLive, stderrLoggerLayer).pipe(provideMerge2(FileQueueStateStoreLive), provideMerge2(SessionIdLive), provideMerge2(ResumeOutcomeLive), provideMerge2(SessionBinderLive));
42546
42595
  var PlatformLive = mergeAll5(setConfigProvider2(fromEnv2()), layer2, layer13);