@integrity-labs/agt-cli 0.28.1249 → 0.28.1251

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 (36) hide show
  1. package/dist/api-client-ECOBF6BM.js +39 -0
  2. package/dist/bin/agt.js +17 -15
  3. package/dist/bin/agt.js.map +1 -1
  4. package/dist/chunk-2VGFSHFP.js +471 -0
  5. package/dist/chunk-2VGFSHFP.js.map +1 -0
  6. package/dist/{chunk-COCLODTH.js → chunk-4AUE34MF.js} +162 -565
  7. package/dist/chunk-4AUE34MF.js.map +1 -0
  8. package/dist/{chunk-CMCT3LOQ.js → chunk-6KY5FKXC.js} +192 -1
  9. package/dist/chunk-6KY5FKXC.js.map +1 -0
  10. package/dist/{chunk-G5CNX4XF.js → chunk-O6WRX5FE.js} +26 -3
  11. package/dist/{chunk-G5CNX4XF.js.map → chunk-O6WRX5FE.js.map} +1 -1
  12. package/dist/{chunk-NNB7XNZA.js → chunk-OAAKFU3J.js} +2 -2
  13. package/dist/{chunk-IQ6MCAEK.js → chunk-VOMOPWFI.js} +2 -2
  14. package/dist/{claude-code-updater-EWJ6B5HX.js → claude-code-updater-2TZ4TSOB.js} +3 -3
  15. package/dist/{claude-pair-runtime-BJLV7HMD.js → claude-pair-runtime-CTJCJNK4.js} +3 -3
  16. package/dist/lib/manager-worker.js +484 -146
  17. package/dist/lib/manager-worker.js.map +1 -1
  18. package/dist/mcp/direct-chat-channel.js +5 -0
  19. package/dist/mcp/index.js +5 -0
  20. package/dist/mcp/origami.js +5 -0
  21. package/dist/mcp/slack-channel.js +5 -0
  22. package/dist/mcp/telegram-channel.js +367 -186
  23. package/dist/{persistent-session-ZTDFRERR.js → persistent-session-TBE4KP4K.js} +4 -4
  24. package/dist/persistent-session-TBE4KP4K.js.map +1 -0
  25. package/dist/{responsiveness-probe-SVSMKLYS.js → responsiveness-probe-J7DA3AB4.js} +4 -4
  26. package/dist/{session-auth-dead-K63LMSKK.js → session-auth-dead-OL5ODQRN.js} +3 -3
  27. package/package.json +1 -1
  28. package/dist/chunk-CMCT3LOQ.js.map +0 -1
  29. package/dist/chunk-COCLODTH.js.map +0 -1
  30. /package/dist/{claude-code-updater-EWJ6B5HX.js.map → api-client-ECOBF6BM.js.map} +0 -0
  31. /package/dist/{chunk-NNB7XNZA.js.map → chunk-OAAKFU3J.js.map} +0 -0
  32. /package/dist/{chunk-IQ6MCAEK.js.map → chunk-VOMOPWFI.js.map} +0 -0
  33. /package/dist/{persistent-session-ZTDFRERR.js.map → claude-code-updater-2TZ4TSOB.js.map} +0 -0
  34. /package/dist/{claude-pair-runtime-BJLV7HMD.js.map → claude-pair-runtime-CTJCJNK4.js.map} +0 -0
  35. /package/dist/{responsiveness-probe-SVSMKLYS.js.map → responsiveness-probe-J7DA3AB4.js.map} +0 -0
  36. /package/dist/{session-auth-dead-K63LMSKK.js.map → session-auth-dead-OL5ODQRN.js.map} +0 -0
@@ -2,7 +2,6 @@ import {
2
2
  hostClaudeOneShotArgs
3
3
  } from "../chunk-MM3OF6UT.js";
4
4
  import {
5
- ApiError,
6
5
  COMPUTER_USE_MCP_KEY,
7
6
  DEAD_CHANNEL_MS,
8
7
  FIRST_CONNECT_WINDOW_MS,
@@ -11,8 +10,6 @@ import {
11
10
  RestartBreaker,
12
11
  SUPERVISOR_RESTART_EXIT_CODE,
13
12
  TunnelWatcher,
14
- adoptHostKeyInProcess,
15
- api,
16
13
  atomicWriteFileSync,
17
14
  buildClaudeAgentMatcher,
18
15
  buildConnectivityProbeDeps,
@@ -31,33 +28,22 @@ import {
31
28
  diffEnvIntegrations,
32
29
  drainTranscriptFlushDeps,
33
30
  envOnlyRespawnVars,
34
- exchangeApiKey,
35
- exchangeFailureKind,
36
31
  executeConnectivityProbe,
37
32
  extractCommandNotFound,
38
33
  findMcpServersUsingVars,
39
34
  flushAgentTranscriptsOnDrain,
40
- forceNextExchange,
41
35
  gatherSessionToolBindProbe,
42
- getApiKey,
43
- getCachedClaudeAuthMode,
44
- getCachedClaudeAuthModeRaw,
45
- getHostId,
46
36
  givenUpMcpServerKeys,
47
37
  guardrailsForProvision,
48
38
  isIntegrationBucketedReason,
49
39
  isProvisioningReloadReason,
50
- isTransientAuthFailure,
51
40
  isWithinReconnectQuiesceWindow,
52
41
  liveProxyExtraHeaderVars,
53
42
  liveProxyTokenVars,
54
43
  markQuarantinedForProbe,
55
44
  migrateAgentDirToIdKeyed,
56
- mintAgentKey,
57
- mintRotatedHostKey,
58
45
  parseRmPolicy,
59
46
  pinAllowsUrgent,
60
- probeHostKey,
61
47
  provision,
62
48
  provisionAutoKanbanProgressHook,
63
49
  provisionChannelProgressHook,
@@ -77,42 +63,31 @@ import {
77
63
  reaperRestartBreakerReason,
78
64
  reconstructQuarantinedMcpServerEntry,
79
65
  redactKnownValues,
80
- requireHost,
81
66
  resolveEffectivePinRaw,
82
67
  safeWriteJsonAtomic,
83
- setConfigHash,
84
68
  shellGuard,
85
69
  tripClass,
86
70
  writeEtcEnvironment,
87
71
  writeProfileDScript
88
- } from "../chunk-COCLODTH.js";
72
+ } from "../chunk-4AUE34MF.js";
89
73
  import {
90
- CLAUDE_CODE_SECURITY_FLOOR,
91
- SELF_UPDATE_TIMEOUTS,
92
- anyPackageInstallRunning,
93
- compareVersions,
94
- effectiveSecurityFloor,
95
- ensureDiskForSelfUpdate,
96
- maybeRunDiskGuard,
97
- readDiskStat,
98
- rearmForcedDiskHoldAnnounce,
99
- runSafeCleanup,
100
- tightestDiskStat,
101
- withPackageCacheLock
102
- } from "../chunk-NNB7XNZA.js";
103
- import {
104
- rewriteSupervisorApiKey,
105
- supervisorChannelsRefusing
106
- } from "../chunk-H3JMPEH7.js";
107
- import {
108
- catchUpNote,
109
- describeCatchUp,
110
- getProjectDir as getProjectDir2,
111
- getReadyTasks,
112
- loadSchedulerState,
113
- markTaskFired,
114
- syncTasksToScheduler
115
- } from "../chunk-FIGZJ6AU.js";
74
+ ApiError,
75
+ adoptHostKeyInProcess,
76
+ api,
77
+ exchangeApiKey,
78
+ exchangeFailureKind,
79
+ forceNextExchange,
80
+ getApiKey,
81
+ getCachedClaudeAuthMode,
82
+ getCachedClaudeAuthModeRaw,
83
+ getHostId,
84
+ isTransientAuthFailure,
85
+ mintAgentKey,
86
+ mintRotatedHostKey,
87
+ probeHostKey,
88
+ requireHost,
89
+ setConfigHash
90
+ } from "../chunk-2VGFSHFP.js";
116
91
  import {
117
92
  BLOCKED_ON_PROMPT_DECISION,
118
93
  CHANNEL_SECRET_ENV_KEYS,
@@ -154,6 +129,7 @@ import {
154
129
  modelPolicyAuthComponent,
155
130
  modelPolicyEgressDomains,
156
131
  noteSessionBlockedOnPrompt,
132
+ opencodeTmuxSession,
157
133
  paneLogPath,
158
134
  parseEnvIntegrations,
159
135
  parseModelPolicy,
@@ -195,7 +171,7 @@ import {
195
171
  webFetchBaselineValue,
196
172
  webFetchRestartNeeded,
197
173
  writeEgressAllowlist
198
- } from "../chunk-G5CNX4XF.js";
174
+ } from "../chunk-O6WRX5FE.js";
199
175
  import {
200
176
  isAgentIdle,
201
177
  isStaleForToday,
@@ -206,7 +182,7 @@ import {
206
182
  subagentActivityAgeSeconds,
207
183
  subagentTranscriptDir,
208
184
  transcriptActivityAgeSeconds
209
- } from "../chunk-IQ6MCAEK.js";
185
+ } from "../chunk-VOMOPWFI.js";
210
186
  import {
211
187
  classifyUnanswerablePane,
212
188
  focusedConfirmDialogBlock,
@@ -217,6 +193,20 @@ import {
217
193
  simpleTextHash
218
194
  } from "../chunk-HYQ7VOC3.js";
219
195
  import "../chunk-6HBXEJHO.js";
196
+ import {
197
+ CLAUDE_CODE_SECURITY_FLOOR,
198
+ SELF_UPDATE_TIMEOUTS,
199
+ anyPackageInstallRunning,
200
+ compareVersions,
201
+ effectiveSecurityFloor,
202
+ ensureDiskForSelfUpdate,
203
+ maybeRunDiskGuard,
204
+ readDiskStat,
205
+ rearmForcedDiskHoldAnnounce,
206
+ runSafeCleanup,
207
+ tightestDiskStat,
208
+ withPackageCacheLock
209
+ } from "../chunk-OAAKFU3J.js";
220
210
  import {
221
211
  parsePsRows,
222
212
  reapOrphanChannelMcps
@@ -238,6 +228,7 @@ import {
238
228
  FLAG_REGISTRY,
239
229
  FORCED_UPDATE_HARD_DEADLINE_MS,
240
230
  FORCED_UPDATE_RELAX_AFTER_MS,
231
+ GROUP_CLAIMED_REPLY,
241
232
  HITL_TIER_ORDER,
242
233
  HOST_KEY_ROTATION_RETRY_MS,
243
234
  HOST_USAGE_POLL_INTERVAL_MS,
@@ -259,12 +250,14 @@ import {
259
250
  agentRulesRestartBasis,
260
251
  analyzeFailingTurnRun,
261
252
  appendDmFooter,
253
+ applyMigrationToAllowlist,
262
254
  attributeTranscriptUsageByRun,
263
255
  bannerRemedyFor,
264
256
  buildFailureCategoryPromptLines,
265
257
  buildHostUsageReading,
266
258
  buildScheduledTaskContextBlocks,
267
259
  buildSlackThirdPartyBotsEnvValue,
260
+ claimTelegramGroupLinkCode,
268
261
  classifyActor,
269
262
  classifyCursorAdvance,
270
263
  classifyOutput,
@@ -274,6 +267,7 @@ import {
274
267
  claudeHostModelFromCandidate,
275
268
  claudeModelOption,
276
269
  coerceOnboardingState,
270
+ createMigrationReportQueue,
277
271
  cursorAdvanceCounterKey,
278
272
  decideInboundAccess,
279
273
  describeOnboardingChannel,
@@ -315,6 +309,7 @@ import {
315
309
  pairToolCallBrackets,
316
310
  parseDeliverAssertion,
317
311
  parseDeliveryTarget,
312
+ parseTelegramGroupLinkStart,
318
313
  parseTranscriptUsage,
319
314
  parseUsageBanner,
320
315
  parseUsageReport,
@@ -322,6 +317,7 @@ import {
322
317
  recordBackgroundTaskLine,
323
318
  redactPaneFrame,
324
319
  remoteMcpServerKey,
320
+ reportTelegramGroupMigrationOutcome,
325
321
  resolveAgentTimezone,
326
322
  resolveAvatarEnvUrl,
327
323
  resolveChannels,
@@ -337,7 +333,7 @@ import {
337
333
  stabiliseResetInstant,
338
334
  sumTranscriptUsageInWindow,
339
335
  summarizeTranscriptActivity
340
- } from "../chunk-CMCT3LOQ.js";
336
+ } from "../chunk-6KY5FKXC.js";
341
337
  import {
342
338
  CLAUDE_CONFIG_DIR_ENV,
343
339
  claudeConfigDirFor,
@@ -345,8 +341,191 @@ import {
345
341
  effectiveClaudeJsonPath,
346
342
  seedClaudeConfigFromLegacy
347
343
  } from "../chunk-AIUIMEUS.js";
344
+ import {
345
+ rewriteSupervisorApiKey,
346
+ supervisorChannelsRefusing
347
+ } from "../chunk-H3JMPEH7.js";
348
+ import {
349
+ catchUpNote,
350
+ describeCatchUp,
351
+ getProjectDir as getProjectDir2,
352
+ getReadyTasks,
353
+ loadSchedulerState,
354
+ markTaskFired,
355
+ syncTasksToScheduler
356
+ } from "../chunk-FIGZJ6AU.js";
348
357
  import "../chunk-DGUM43GV.js";
349
358
 
359
+ // src/lib/manager-restart-gate.ts
360
+ import { execFileSync } from "child_process";
361
+ var MANAGER_RESTART_REASON = "manager-restart";
362
+ function decideManagerRestart(report) {
363
+ if (!report) return { kill: false, reason: "unknown_activity", runningBackgroundTasks: null };
364
+ if (report.state === "no_session") return { kill: true };
365
+ const running2 = typeof report.runningBackgroundTasks === "number" ? report.runningBackgroundTasks : null;
366
+ if (report.state === "mid_turn") return { kill: false, reason: "mid_turn", runningBackgroundTasks: running2 };
367
+ if (report.state === "idle_at_prompt") {
368
+ if (running2 === 0) return { kill: true };
369
+ return { kill: false, reason: running2 && running2 > 0 ? "background_tasks" : "unknown_activity", runningBackgroundTasks: running2 };
370
+ }
371
+ return { kill: false, reason: "unknown_activity", runningBackgroundTasks: running2 };
372
+ }
373
+ function laneDefersForFramework(cached, refreshed) {
374
+ return cached !== void 0 && cached !== refreshed;
375
+ }
376
+ function confirmsNoSession(err) {
377
+ const e = err;
378
+ if (!e || e.status !== 1 || e.signal) return false;
379
+ const stderr = typeof e.stderr === "string" ? e.stderr : Buffer.isBuffer(e.stderr) ? e.stderr.toString("utf8") : "";
380
+ return /can't find session|no server running|error connecting to .*\(No such file or directory\)/i.test(stderr);
381
+ }
382
+ function killAbortsRestart(killed, restartReason) {
383
+ if (killed === "timed-out") return true;
384
+ return killed === "failed" && restartReason === MANAGER_RESTART_REASON;
385
+ }
386
+ var TMUX_PROBE_TIMEOUT_MS = 3e3;
387
+ function captureAgentPane(codeName) {
388
+ const tmuxSession = `=agt-${codeName}`;
389
+ let tmuxAlive;
390
+ let screenCapture = null;
391
+ try {
392
+ execFileSync("tmux", ["has-session", "-t", tmuxSession], {
393
+ stdio: ["ignore", "ignore", "pipe"],
394
+ encoding: "utf-8",
395
+ timeout: TMUX_PROBE_TIMEOUT_MS
396
+ });
397
+ tmuxAlive = true;
398
+ } catch (err) {
399
+ tmuxAlive = confirmsNoSession(err) ? false : null;
400
+ }
401
+ if (tmuxAlive) {
402
+ try {
403
+ screenCapture = execFileSync("tmux", ["capture-pane", "-t", `${tmuxSession}:`, "-p", "-S", "-30"], {
404
+ encoding: "utf-8",
405
+ timeout: TMUX_PROBE_TIMEOUT_MS
406
+ }).trim();
407
+ } catch {
408
+ }
409
+ }
410
+ return { tmuxAlive, screenCapture };
411
+ }
412
+ var TMUX_KILL_TIMEOUT_MS = 1e4;
413
+ function killAgentPane(codeName, exec = execFileSync) {
414
+ try {
415
+ exec("tmux", ["kill-session", "-t", `=agt-${codeName}`], {
416
+ stdio: ["ignore", "ignore", "pipe"],
417
+ encoding: "utf-8",
418
+ timeout: TMUX_KILL_TIMEOUT_MS,
419
+ killSignal: "SIGKILL"
420
+ });
421
+ return "done";
422
+ } catch (err) {
423
+ if (err?.code === "ETIMEDOUT") return "timed-out";
424
+ return confirmsNoSession(err) ? "done" : "failed";
425
+ }
426
+ }
427
+
428
+ // src/lib/integration-reload-policy.ts
429
+ function restartReasonNeedsRender(reason) {
430
+ return reason != null && reason !== "manual" && reason !== MANAGER_RESTART_REASON;
431
+ }
432
+ function emptyPruneRestartsOpencode(input) {
433
+ return input.hadIntegrations && input.framework === "opencode" && input.serveHealthy;
434
+ }
435
+ function reloadAckAwaitsFreshIntegrations(reason, agentStatus) {
436
+ return reason === "integration-change" && agentRendersThisPoll(agentStatus);
437
+ }
438
+ function agentRendersThisPoll(agentStatus) {
439
+ return agentStatus !== "draft" && agentStatus !== "paused" && agentStatus !== "revoked";
440
+ }
441
+ function configReloadAction(input) {
442
+ return input.pendingRequested === input.requested ? "await-render" : "teardown";
443
+ }
444
+ function configReloadConfirmed(input) {
445
+ return input.pending && input.freshFetch && input.rendered;
446
+ }
447
+ var ConfigReloadLedger = class {
448
+ pending = /* @__PURE__ */ new Map();
449
+ confirmed = /* @__PURE__ */ new Set();
450
+ /** What the poll does with this agent's integration-change request. Records a teardown. */
451
+ service(agentId, requested) {
452
+ const action = configReloadAction({ requested, pendingRequested: this.pending.get(agentId) });
453
+ if (action === "teardown") {
454
+ this.pending.set(agentId, requested);
455
+ this.confirmed.delete(agentId);
456
+ }
457
+ return action;
458
+ }
459
+ isPending(agentId) {
460
+ return this.pending.has(agentId);
461
+ }
462
+ /** processAgent rendered fresh state for this agent's pending reload. */
463
+ confirm(agentId) {
464
+ if (this.pending.has(agentId)) this.confirmed.add(agentId);
465
+ }
466
+ /** The confirmed reloads among `agentIds`, as acks; they stop being pending. */
467
+ takeConfirmed(agentIds) {
468
+ const out = [];
469
+ for (const agentId of agentIds) {
470
+ if (!this.confirmed.has(agentId)) continue;
471
+ const requestedAt = this.pending.get(agentId);
472
+ this.confirmed.delete(agentId);
473
+ this.pending.delete(agentId);
474
+ if (requestedAt) out.push({ agentId, requestedAt });
475
+ }
476
+ return out;
477
+ }
478
+ /** The agent left this host. */
479
+ forget(agentId) {
480
+ this.pending.delete(agentId);
481
+ this.confirmed.delete(agentId);
482
+ }
483
+ };
484
+ function stampIsOlder(a, b) {
485
+ const ta = Date.parse(a);
486
+ const tb = Date.parse(b);
487
+ if (Number.isNaN(ta) || Number.isNaN(tb)) return a < b;
488
+ return ta < tb;
489
+ }
490
+ function stepConfigReload(ledger, input) {
491
+ if (!agentRendersThisPoll(input.agentStatus)) {
492
+ ledger.forget(input.agentId);
493
+ return "teardown-and-ack";
494
+ }
495
+ if (!reloadAckAwaitsFreshIntegrations(input.reason, input.agentStatus) && !ledger.isPending(input.agentId)) {
496
+ return "teardown-and-ack";
497
+ }
498
+ return ledger.service(input.agentId, input.requested) === "await-render" ? "await-render" : "teardown-await-render";
499
+ }
500
+ function orphansStillDeclared(orphanKeys, declaredAfter) {
501
+ return orphanKeys.filter((key) => Object.prototype.hasOwnProperty.call(declaredAfter, key));
502
+ }
503
+ function orphanPruneFailedLine(codeName, keys, reason) {
504
+ const servers = keys.length > 0 ? keys.map((k) => `'${k}'`).join(", ") : "(not determined: the read failed first)";
505
+ return `[hot-reload] ORPHAN_PRUNE_FAILED agent='${codeName}' servers=${servers} reason=${reason}. The integration-change reload stays pending and the session is NOT blocked, so a removed integration's tools may still be reachable until the prune succeeds (ENG-11912).`;
506
+ }
507
+ function readDeclaredServersForPrune(adapter, codeName) {
508
+ if (adapter.readMcpServersOrNull) return adapter.readMcpServersOrNull(codeName);
509
+ return adapter.readMcpServers ? adapter.readMcpServers(codeName) : null;
510
+ }
511
+ function orphanPruneOutcome(orphanKeys, declaredAfter) {
512
+ if (orphanKeys.length === 0) return { failed: false };
513
+ if (declaredAfter === null) {
514
+ return { failed: true, stuck: [...orphanKeys], reason: "the MCP config could not be re-read after removal" };
515
+ }
516
+ const stuck = orphansStillDeclared(orphanKeys, declaredAfter);
517
+ return stuck.length > 0 ? { failed: true, stuck, reason: "removal returned but the server is still declared (config write refused)" } : { failed: false };
518
+ }
519
+ var MCP_REPAIR_PENDING_HASH = "\0mcp-repair\0";
520
+ function markMcpRepairPending(hashes, agentId, unlanded) {
521
+ if (!unlanded) return false;
522
+ hashes.set(agentId, MCP_REPAIR_PENDING_HASH);
523
+ return true;
524
+ }
525
+ function staleSessionStopConfirmed(sessionState) {
526
+ return sessionState === "dead";
527
+ }
528
+
350
529
  // src/lib/manager-worker.ts
351
530
  import { createHash as createHash20 } from "crypto";
352
531
  import { readFileSync as readFileSync35, writeFileSync as writeFileSync18, mkdirSync as mkdirSync16, existsSync as existsSync19, rmSync as rmSync8, readdirSync as readdirSync14, statSync as statSync15, unlinkSync as unlinkSync6, renameSync as renameSync11, utimesSync as utimesSync4, readlinkSync as readlinkSync2 } from "fs";
@@ -1256,6 +1435,10 @@ function shouldDeferBindRemediationForFirstConnect(outcome, ctx) {
1256
1435
 
1257
1436
  // src/lib/integration-hash.ts
1258
1437
  import { createHash as createHash2 } from "crypto";
1438
+ function remoteMcpUrlOf(i) {
1439
+ const url = i.remoteMcp?.url;
1440
+ return typeof url === "string" && url ? url : null;
1441
+ }
1259
1442
  function canonicalize(value) {
1260
1443
  if (Array.isArray(value)) return value.map(canonicalize);
1261
1444
  if (value && typeof value === "object") {
@@ -1278,9 +1461,11 @@ function hashableConfig(config2) {
1278
1461
  return out;
1279
1462
  }
1280
1463
  function computeIntegrationsHash(integrations) {
1281
- const payload = integrations.map(
1282
- (i) => `${i.definition_id}:${JSON.stringify(canonicalize(i.credentials ?? {}))}:${JSON.stringify(canonicalize(hashableConfig(i.config)))}`
1283
- ).sort();
1464
+ const payload = integrations.map((i) => {
1465
+ const base = `${i.definition_id}:${JSON.stringify(canonicalize(i.credentials ?? {}))}:${JSON.stringify(canonicalize(hashableConfig(i.config)))}`;
1466
+ const url = remoteMcpUrlOf(i);
1467
+ return url ? `${base}:remote=${url}` : base;
1468
+ }).sort();
1284
1469
  return createHash2("sha256").update(JSON.stringify(payload)).digest("hex").slice(0, 16);
1285
1470
  }
1286
1471
  function computeCapabilitySurfaceHash(integrations) {
@@ -5266,75 +5451,6 @@ function buildSessionActivityReport(args) {
5266
5451
  }
5267
5452
  }
5268
5453
 
5269
- // src/lib/manager-restart-gate.ts
5270
- import { execFileSync } from "child_process";
5271
- var MANAGER_RESTART_REASON = "manager-restart";
5272
- function decideManagerRestart(report) {
5273
- if (!report) return { kill: false, reason: "unknown_activity", runningBackgroundTasks: null };
5274
- if (report.state === "no_session") return { kill: true };
5275
- const running2 = typeof report.runningBackgroundTasks === "number" ? report.runningBackgroundTasks : null;
5276
- if (report.state === "mid_turn") return { kill: false, reason: "mid_turn", runningBackgroundTasks: running2 };
5277
- if (report.state === "idle_at_prompt") {
5278
- if (running2 === 0) return { kill: true };
5279
- return { kill: false, reason: running2 && running2 > 0 ? "background_tasks" : "unknown_activity", runningBackgroundTasks: running2 };
5280
- }
5281
- return { kill: false, reason: "unknown_activity", runningBackgroundTasks: running2 };
5282
- }
5283
- function laneDefersForFramework(cached, refreshed) {
5284
- return cached !== void 0 && cached !== refreshed;
5285
- }
5286
- function confirmsNoSession(err) {
5287
- const e = err;
5288
- if (!e || e.status !== 1 || e.signal) return false;
5289
- const stderr = typeof e.stderr === "string" ? e.stderr : Buffer.isBuffer(e.stderr) ? e.stderr.toString("utf8") : "";
5290
- return /can't find session|no server running|error connecting to .*\(No such file or directory\)/i.test(stderr);
5291
- }
5292
- function killAbortsRestart(killed, restartReason) {
5293
- if (killed === "timed-out") return true;
5294
- return killed === "failed" && restartReason === MANAGER_RESTART_REASON;
5295
- }
5296
- var TMUX_PROBE_TIMEOUT_MS = 3e3;
5297
- function captureAgentPane(codeName) {
5298
- const tmuxSession = `=agt-${codeName}`;
5299
- let tmuxAlive;
5300
- let screenCapture = null;
5301
- try {
5302
- execFileSync("tmux", ["has-session", "-t", tmuxSession], {
5303
- stdio: ["ignore", "ignore", "pipe"],
5304
- encoding: "utf-8",
5305
- timeout: TMUX_PROBE_TIMEOUT_MS
5306
- });
5307
- tmuxAlive = true;
5308
- } catch (err) {
5309
- tmuxAlive = confirmsNoSession(err) ? false : null;
5310
- }
5311
- if (tmuxAlive) {
5312
- try {
5313
- screenCapture = execFileSync("tmux", ["capture-pane", "-t", `${tmuxSession}:`, "-p", "-S", "-30"], {
5314
- encoding: "utf-8",
5315
- timeout: TMUX_PROBE_TIMEOUT_MS
5316
- }).trim();
5317
- } catch {
5318
- }
5319
- }
5320
- return { tmuxAlive, screenCapture };
5321
- }
5322
- var TMUX_KILL_TIMEOUT_MS = 1e4;
5323
- function killAgentPane(codeName, exec = execFileSync) {
5324
- try {
5325
- exec("tmux", ["kill-session", "-t", `=agt-${codeName}`], {
5326
- stdio: ["ignore", "ignore", "pipe"],
5327
- encoding: "utf-8",
5328
- timeout: TMUX_KILL_TIMEOUT_MS,
5329
- killSignal: "SIGKILL"
5330
- });
5331
- return "done";
5332
- } catch (err) {
5333
- if (err?.code === "ETIMEDOUT") return "timed-out";
5334
- return confirmsNoSession(err) ? "done" : "failed";
5335
- }
5336
- }
5337
-
5338
5454
  // src/lib/workflow-run-reconciler.ts
5339
5455
  import { readdirSync as readdirSync4, readFileSync as readFileSync13, statSync as statSync4 } from "fs";
5340
5456
  import { join as join19 } from "path";
@@ -13668,9 +13784,46 @@ var BoundedSet2 = class {
13668
13784
  async function dispatchTelegramInbound(update, ctx) {
13669
13785
  const msg = update.message;
13670
13786
  const chatId = String(msg.chat.id);
13787
+ if (typeof msg.migrate_to_chat_id === "number") {
13788
+ const toChatId = String(msg.migrate_to_chat_id);
13789
+ const admittedNow = applyMigrationToAllowlist(ctx.allowedChats, chatId, toChatId);
13790
+ let reported = "none";
13791
+ if (ctx.migrationReports) {
13792
+ ctx.migrationReports.enqueue(chatId, toChatId);
13793
+ const outcomes = await ctx.migrationReports.flushDue();
13794
+ reported = outcomes.get(`${chatId}->${toChatId}`) ?? "retry";
13795
+ }
13796
+ ctx.log(
13797
+ `[telegram-ingest:${ctx.codeName}] group migrated ${redactId(chatId)} -> ${redactId(toChatId)} admitted_now=${admittedNow} reported=${reported}`
13798
+ );
13799
+ return "migrated";
13800
+ }
13671
13801
  const dedupKey = String(update.update_id);
13672
13802
  if (ctx.seen.has(dedupKey)) return "dropped_duplicate";
13673
13803
  ctx.seen.add(dedupKey);
13804
+ const groupCode = ctx.claimGroupCode ? parseTelegramGroupLinkStart({ chatType: msg.chat.type, isBot: msg.from?.is_bot, text: msg.text }) : null;
13805
+ if (groupCode && ctx.claimGroupCode) {
13806
+ let claimed = false;
13807
+ try {
13808
+ claimed = await ctx.claimGroupCode({
13809
+ code: groupCode,
13810
+ chatId,
13811
+ chatType: msg.chat.type,
13812
+ ...msg.chat.title ? { chatTitle: msg.chat.title } : {},
13813
+ ...msg.from ? { fromId: String(msg.from.id) } : {},
13814
+ ...msg.from?.first_name ? { firstName: msg.from.first_name } : {},
13815
+ ...msg.from?.last_name ? { lastName: msg.from.last_name } : {}
13816
+ });
13817
+ } catch {
13818
+ claimed = false;
13819
+ }
13820
+ if (claimed) {
13821
+ ctx.log(`[telegram-ingest:${ctx.codeName}] group-link claimed chat=${redactId(chatId)}`);
13822
+ await ctx.sendReply({ chatId, text: GROUP_CLAIMED_REPLY });
13823
+ return "group_claimed";
13824
+ }
13825
+ ctx.log(`[telegram-ingest:${ctx.codeName}] group-link not claimed chat=${redactId(chatId)}, falling through`);
13826
+ }
13674
13827
  const decision = evaluateTelegramInboundGate(msg, {
13675
13828
  allowedChats: ctx.allowedChats,
13676
13829
  peerConfig: ctx.peerConfig,
@@ -13798,13 +13951,17 @@ function startTelegramIngest(config2) {
13798
13951
  ...config2.ackReaction ? { ackReaction: config2.ackReaction } : {},
13799
13952
  ...config2.skipReaction ? { skipReaction: config2.skipReaction } : {},
13800
13953
  log: config2.log,
13801
- seen
13954
+ seen,
13955
+ ...config2.claimGroupCode ? { claimGroupCode: config2.claimGroupCode } : {},
13956
+ ...config2.migrationReports ? { migrationReports: config2.migrationReports } : {}
13802
13957
  };
13803
13958
  let stopped = false;
13804
13959
  let controller = null;
13805
13960
  let nextOffset = offsetStore.load();
13806
13961
  const pollLoop = async () => {
13807
13962
  while (!stopped) {
13963
+ if (config2.migrationReports) await config2.migrationReports.flushDue();
13964
+ if (stopped) return;
13808
13965
  try {
13809
13966
  controller = new AbortController();
13810
13967
  const timeout = AbortSignal.timeout(POLL_HTTP_TIMEOUT_MS);
@@ -13872,6 +14029,7 @@ function anySignal(signals) {
13872
14029
 
13873
14030
  // src/lib/opencode-telegram-ingest.ts
13874
14031
  var ingests2 = /* @__PURE__ */ new Map();
14032
+ var migrationQueues = /* @__PURE__ */ new Map();
13875
14033
  function fingerprint2(params) {
13876
14034
  return createHash19("sha256").update(
13877
14035
  JSON.stringify({
@@ -13944,6 +14102,46 @@ function createFileOffsetStore(codeName, log2, currentBotId) {
13944
14102
  }
13945
14103
  };
13946
14104
  }
14105
+ function createFileMigrationReportIO(codeName, log2) {
14106
+ let dir;
14107
+ let filePath;
14108
+ try {
14109
+ dir = getFramework("opencode").getAgentDir(codeName);
14110
+ filePath = join41(dir, "telegram-migration-reports-opencode.json");
14111
+ } catch {
14112
+ dir = null;
14113
+ filePath = null;
14114
+ }
14115
+ return {
14116
+ load() {
14117
+ if (!filePath) return null;
14118
+ try {
14119
+ return readFileSync32(filePath, "utf-8");
14120
+ } catch {
14121
+ return null;
14122
+ }
14123
+ },
14124
+ save(data) {
14125
+ if (!filePath || !dir) return;
14126
+ try {
14127
+ mkdirSync13(dir, { recursive: true, mode: 448 });
14128
+ atomicWriteFileSync(filePath, data, { mode: 384 });
14129
+ } catch (err) {
14130
+ log2(`[telegram-ingest:${codeName}] migration-report persist failed: ${err instanceof Error ? err.message : String(err)}`);
14131
+ }
14132
+ }
14133
+ };
14134
+ }
14135
+ var managerHostPost = async (path, body) => {
14136
+ const { api: api2, ApiError: ApiError3 } = await import("../api-client-ECOBF6BM.js");
14137
+ try {
14138
+ const json = await api2.post(path, body);
14139
+ return { status: 200, json };
14140
+ } catch (err) {
14141
+ if (err instanceof ApiError3) return { status: err.status, json: err.body };
14142
+ throw err;
14143
+ }
14144
+ };
13947
14145
  async function ensureOpencodeTelegramIngest(opts) {
13948
14146
  const { codeName, agentId, log: log2 } = opts;
13949
14147
  const readEnv = opts.readEnv ?? readChannelServerEnv;
@@ -13984,9 +14182,30 @@ async function ensureOpencodeTelegramIngest(opts) {
13984
14182
  existing.key === key ? `[telegram-ingest:${codeName}] bot identity resolved; restarting ingest` : `[telegram-ingest:${codeName}] config changed; restarting ingest`
13985
14183
  );
13986
14184
  }
14185
+ const hostPost = opts.hostPost ?? managerHostPost;
14186
+ let queued = migrationQueues.get(codeName);
14187
+ if (!queued || queued.io !== opts.migrationReportIO) {
14188
+ const target = { hostPost, agentId };
14189
+ queued = {
14190
+ io: opts.migrationReportIO,
14191
+ target,
14192
+ queue: createMigrationReportQueue({
14193
+ io: opts.migrationReportIO ?? createFileMigrationReportIO(codeName, log2),
14194
+ report: (fromChatId, toChatId) => reportTelegramGroupMigrationOutcome(target.hostPost, { agentId: target.agentId, fromChatId, toChatId }),
14195
+ log: (m) => log2(`[telegram-ingest:${codeName}] ${m}`)
14196
+ })
14197
+ };
14198
+ migrationQueues.set(codeName, queued);
14199
+ } else {
14200
+ queued.target.hostPost = hostPost;
14201
+ queued.target.agentId = agentId;
14202
+ }
14203
+ const migrationReports = queued.queue;
13987
14204
  const handle = startTelegramIngest({
13988
14205
  codeName,
13989
14206
  agentId,
14207
+ claimGroupCode: (input) => claimTelegramGroupLinkCode(hostPost, { ...input, agentId }),
14208
+ migrationReports,
13990
14209
  botToken: params.botToken,
13991
14210
  allowedChats: params.allowedChats,
13992
14211
  peerConfig: params.peerConfig,
@@ -15953,7 +16172,7 @@ var pendingDayRolloverReset = /* @__PURE__ */ new Set();
15953
16172
  var dayRolloverInboundHold = /* @__PURE__ */ new Map();
15954
16173
  var INBOUND_HOLD_EPISODE_GAP_MS = 12e4;
15955
16174
  async function channelInboundActivityAgeSecondsFor(codeName) {
15956
- const { newestPendingInboundActivityMtimeMs } = await import("../responsiveness-probe-SVSMKLYS.js");
16175
+ const { newestPendingInboundActivityMtimeMs } = await import("../responsiveness-probe-J7DA3AB4.js");
15957
16176
  const newest = newestPendingInboundActivityMtimeMs(dirname11(paneLogPath(codeName)));
15958
16177
  if (newest === null) return null;
15959
16178
  return Math.max(0, Math.floor((Date.now() - newest) / 1e3));
@@ -16726,6 +16945,7 @@ function clearAgentCaches(agentId, codeName) {
16726
16945
  integrationsFetchGate.forget(agentId);
16727
16946
  quarantinedFetchGate.forget(agentId);
16728
16947
  lastIntegrationsPayload.delete(agentId);
16948
+ configReloads.forget(agentId);
16729
16949
  integrationEgressDomainsByAgent.delete(agentId);
16730
16950
  lastQuarantinedPayload.delete(agentId);
16731
16951
  forgetRealtimeRebindState(agentId);
@@ -16768,7 +16988,7 @@ var agentRestartTimezoneInputs = /* @__PURE__ */ new Map();
16768
16988
  var lastVersionCheckAt = 0;
16769
16989
  var VERSION_CHECK_INTERVAL_MS = 5 * 60 * 1e3;
16770
16990
  var lastResponsivenessProbeAt = 0;
16771
- var agtCliVersion = true ? "0.28.1249" : "dev";
16991
+ var agtCliVersion = true ? "0.28.1251" : "dev";
16772
16992
  function resolveBrewPath(execFileSync4) {
16773
16993
  try {
16774
16994
  const out = execFileSync4("which", ["brew"], { timeout: 5e3 }).toString().trim();
@@ -18708,6 +18928,7 @@ var boardFetchGate = createFetchGate(MY_KANBAN_FETCH_TTL_MS);
18708
18928
  var RECURRING_SPAWN_INTERVAL_MS = 6e4;
18709
18929
  var RECURRING_SPAWN_GATE_KEY = "host";
18710
18930
  var recurringSpawnGate = createFetchGate(RECURRING_SPAWN_INTERVAL_MS);
18931
+ var configReloads = new ConfigReloadLedger();
18711
18932
  function forceIntegrationsFetch(agentId) {
18712
18933
  integrationsFetchGate.forceNext(agentId);
18713
18934
  quarantinedFetchGate.forceNext(agentId);
@@ -18766,7 +18987,7 @@ function flushRestartedAgentDiagnostics(hostId, codeNames) {
18766
18987
  if (codeNames.length === 0) return;
18767
18988
  void (async () => {
18768
18989
  try {
18769
- const { collectDiagnostics } = await import("../persistent-session-ZTDFRERR.js");
18990
+ const { collectDiagnostics } = await import("../persistent-session-TBE4KP4K.js");
18770
18991
  await api.post("/host/heartbeat", {
18771
18992
  host_id: hostId,
18772
18993
  agent_diagnostics: collectDiagnostics(codeNames, quarantineEntriesFor, claudeMdSizeFor, spawnOutcomeForDiagnostics, pidPressureFor, forwardedToolsFor, runtimeVersionFor, sessionActivityFor)
@@ -18909,7 +19130,7 @@ async function pollCycleInner() {
18909
19130
  }
18910
19131
  try {
18911
19132
  const { detectHostSecurity } = await import("../host-security-KQYYZZVW.js");
18912
- const { collectDiagnostics } = await import("../persistent-session-ZTDFRERR.js");
19133
+ const { collectDiagnostics } = await import("../persistent-session-TBE4KP4K.js");
18913
19134
  const diagCodeNames = [...agentState.persistentSessionAgents];
18914
19135
  const agentDiagnostics = diagCodeNames.length > 0 ? collectDiagnostics(diagCodeNames, quarantineEntriesFor, claudeMdSizeFor, spawnOutcomeForDiagnostics, pidPressureFor, forwardedToolsFor, runtimeVersionFor, sessionActivityFor) : void 0;
18915
19136
  let tailscaleHostname;
@@ -19174,7 +19395,7 @@ async function pollCycleInner() {
19174
19395
  }
19175
19396
  try {
19176
19397
  const desiredClaudeCodeVersion = hbResp?.desired_claude_code_version?.trim();
19177
- const { maybeUpdateClaudeCode, shouldRunClaudeCodeUpdater } = await import("../claude-code-updater-EWJ6B5HX.js");
19398
+ const { maybeUpdateClaudeCode, shouldRunClaudeCodeUpdater } = await import("../claude-code-updater-2TZ4TSOB.js");
19178
19399
  const securityFloor = currentSecurityFloor();
19179
19400
  claudeUpdaterInFlight = true;
19180
19401
  if (desiredClaudeCodeVersion && (claudePairLoop.busy || claudePairingInProgress())) {
@@ -19209,7 +19430,7 @@ async function pollCycleInner() {
19209
19430
  collectPanelessActivityProbes,
19210
19431
  getResponsivenessIntervalMs,
19211
19432
  occupancyQualificationClassifications
19212
- } = await import("../responsiveness-probe-SVSMKLYS.js");
19433
+ } = await import("../responsiveness-probe-J7DA3AB4.js");
19213
19434
  const probeIntervalMs = getResponsivenessIntervalMs();
19214
19435
  if (now - lastResponsivenessProbeAt > probeIntervalMs) {
19215
19436
  const probeCodeNames = [...agentState.persistentSessionAgents];
@@ -19326,7 +19547,7 @@ async function pollCycleInner() {
19326
19547
  collectResponsivenessProbes,
19327
19548
  livePendingInboundOldestAgeSeconds,
19328
19549
  parkPendingInbound
19329
- } = await import("../responsiveness-probe-SVSMKLYS.js");
19550
+ } = await import("../responsiveness-probe-J7DA3AB4.js");
19330
19551
  const { getProjectDir: wedgeProjectDir } = await import("../scheduler-engine-5PCBGRNY.js");
19331
19552
  const wedgeNow = /* @__PURE__ */ new Date();
19332
19553
  const liveAgents = agentState.persistentSessionAgents;
@@ -19612,7 +19833,7 @@ async function pollCycleInner() {
19612
19833
  }
19613
19834
  }
19614
19835
  );
19615
- const { parkPendingInbound } = await import("../responsiveness-probe-SVSMKLYS.js");
19836
+ const { parkPendingInbound } = await import("../responsiveness-probe-J7DA3AB4.js");
19616
19837
  const { parked, deadLettered } = parkPendingInbound(codeName, new Date(fatalNowMs));
19617
19838
  paneFatalStreak.delete(codeName);
19618
19839
  paneFatalRestarts.set(codeName, [...history, fatalNowMs]);
@@ -19643,7 +19864,7 @@ async function pollCycleInner() {
19643
19864
  TRANSCRIPT_MOUNT_ESCALATION_REFRESH_MS,
19644
19865
  bindSourceEscalations
19645
19866
  } = await import("../transcript-mount-health-OHE6IVJV.js");
19646
- const { transcriptBindSourcesFor, ensureTranscriptBindSources } = await import("../persistent-session-ZTDFRERR.js");
19867
+ const { transcriptBindSourcesFor, ensureTranscriptBindSources } = await import("../persistent-session-TBE4KP4K.js");
19647
19868
  const mountConfig = resolveTranscriptMountConfig();
19648
19869
  const liveAgents = agentState.persistentSessionAgents;
19649
19870
  for (const tracked of [
@@ -19808,7 +20029,7 @@ async function pollCycleInner() {
19808
20029
  }
19809
20030
  try {
19810
20031
  const { scrapeMcpFailedBannerCount } = await import("../pane-mcp-banner-scraper-VR5QGP3J.js");
19811
- const { probeSessionAuth } = await import("../session-auth-dead-K63LMSKK.js");
20032
+ const { probeSessionAuth } = await import("../session-auth-dead-OL5ODQRN.js");
19812
20033
  const observations = [];
19813
20034
  const pendingCacheCommits = [];
19814
20035
  const modelApiErrorReportingOn = hostFlagStore().getBoolean("model-api-error-reporting");
@@ -19941,12 +20162,25 @@ async function pollCycleInner() {
19941
20162
  log(
19942
20163
  `[restart] Dashboard requested restart for '${agent.code_name}' at ${requested} (reason=${restartReason ?? "manual"})`
19943
20164
  );
20165
+ if (restartReasonNeedsRender(restartReason)) forceIntegrationsFetch(agent.agent_id);
20166
+ const reloadStep = stepConfigReload(configReloads, {
20167
+ agentId: agent.agent_id,
20168
+ requested,
20169
+ reason: restartReason,
20170
+ agentStatus: agent.status
20171
+ });
20172
+ const deferAck = reloadStep !== "teardown-and-ack";
20173
+ if (reloadStep === "await-render") {
20174
+ log(`[restart] config-change reload for '${agent.code_name}' still waiting on a fresh integrations render (ENG-11912)`);
20175
+ continue;
20176
+ }
19944
20177
  const framework = agent.framework ?? agentFrameworkCache.get(agent.code_name) ?? DEFAULT_FRAMEWORK;
19945
20178
  if (restartTargetsOpencodeServe(framework)) {
19946
20179
  stopOpencodeSession(agent.code_name, log);
19947
20180
  } else {
19948
20181
  const killed = killAgentPane(agent.code_name);
19949
20182
  if (killAbortsRestart(killed, restartReason)) {
20183
+ if (reloadStep === "teardown-await-render") configReloads.forget(agent.agent_id);
19950
20184
  log(`[restart] tmux kill for '${agent.code_name}' ${killed} (timeout ${TMUX_KILL_TIMEOUT_MS}ms) - not acking, the next poll retries [ENG-11963]`);
19951
20185
  continue;
19952
20186
  }
@@ -19968,6 +20202,7 @@ async function pollCycleInner() {
19968
20202
  });
19969
20203
  }
19970
20204
  }
20205
+ if (deferAck) continue;
19971
20206
  restartAcks.set(agent.agent_id, requested);
19972
20207
  if (prev) prev.lastRestartProcessedAt = requested;
19973
20208
  }
@@ -20283,6 +20518,16 @@ async function pollCycleInner() {
20283
20518
  void maybeReportActivityCache({ api, log });
20284
20519
  const crossAgentPrune = managedPruneLedger.summarize();
20285
20520
  if (crossAgentPrune) log(crossAgentPrune);
20521
+ for (const ack of configReloads.takeConfirmed(agents.map((a) => a.agent_id))) {
20522
+ const already = restartAcks.get(ack.agentId) ?? state9.agents.find((a) => a.agentId === ack.agentId)?.lastRestartProcessedAt ?? null;
20523
+ if (already && !stampIsOlder(already, ack.requestedAt)) continue;
20524
+ restartAcks.set(ack.agentId, ack.requestedAt);
20525
+ void api.post("/host/restart-ack", {
20526
+ host_id: hostId,
20527
+ agent_id: ack.agentId,
20528
+ restart_requested_at: ack.requestedAt
20529
+ }).catch((err) => log(`[restart] clear failed for agent_id=${ack.agentId}: ${err.message}`));
20530
+ }
20286
20531
  const restartAckStateChanged = applyRestartAcks({
20287
20532
  agentStates,
20288
20533
  priorAgents: state9.agents,
@@ -22011,17 +22256,22 @@ async function processAgent(agent, agentStates, managedToolkits) {
22011
22256
  encodeIntegrationEgressDomains(egressDomains)
22012
22257
  );
22013
22258
  }
22014
- return (integrationsData.integrations ?? []).map(withResolvedRemoteMcp);
22259
+ if (!Array.isArray(integrationsData.integrations)) {
22260
+ throw new Error("/host/agent-integrations body had no integrations array");
22261
+ }
22262
+ return integrationsData.integrations.map(withResolvedRemoteMcp);
22015
22263
  };
22016
22264
  const integrationsToken = integrationsFetchGate.beginFetch(agent.agent_id);
22017
22265
  const cachedIntegrations = lastIntegrationsPayload.get(agent.agent_id);
22018
22266
  let integrations;
22267
+ let integrationsFresh = false;
22019
22268
  if (cachedIntegrations !== void 0 && !integrationsFetchGate.shouldFetch(agent.agent_id)) {
22020
22269
  integrations = cachedIntegrations;
22021
22270
  pollCycleIntegrationsSkips += 1;
22022
22271
  } else {
22023
22272
  integrations = await fetchIntegrations();
22024
22273
  lastIntegrationsPayload.set(agent.agent_id, integrations);
22274
+ integrationsFresh = true;
22025
22275
  integrationsFetchGate.markFetched(agent.agent_id, integrationsToken);
22026
22276
  pollCycleIntegrationsFetches += 1;
22027
22277
  }
@@ -22157,18 +22407,43 @@ async function processAgent(agent, agentStates, managedToolkits) {
22157
22407
  else promptBindProbeAttempts.delete(agent.code_name);
22158
22408
  }
22159
22409
  }
22410
+ let orphanPruneFailed = false;
22160
22411
  if (frameworkAdapter.removeMcpServer && frameworkAdapter.readMcpServers) {
22412
+ let orphanKeys = [];
22413
+ frameworkAdapter.consumeMcpWriteFailures?.(agent.code_name);
22161
22414
  try {
22162
- const declaredServers = frameworkAdapter.readMcpServers(agent.code_name);
22163
- const expectedRemoteKeys = expectedRemoteMcpKeys(
22164
- integrations
22165
- );
22166
- for (const key of orphanedRemoteMcpKeys(declaredServers, expectedRemoteKeys)) {
22167
- frameworkAdapter.removeMcpServer(agent.code_name, key);
22168
- log(`[hot-reload] Removed orphaned remote MCP server '${key}' for '${agent.code_name}' (integration removed)`);
22415
+ const declaredServers = readDeclaredServersForPrune(frameworkAdapter, agent.code_name);
22416
+ if (declaredServers === null) {
22417
+ orphanPruneFailed = true;
22418
+ log(orphanPruneFailedLine(agent.code_name, [], "the MCP config could not be read"));
22419
+ } else {
22420
+ const expectedRemoteKeys = expectedRemoteMcpKeys(
22421
+ integrations
22422
+ );
22423
+ orphanKeys = orphanedRemoteMcpKeys(declaredServers, expectedRemoteKeys);
22424
+ for (const key of orphanKeys) {
22425
+ frameworkAdapter.removeMcpServer(agent.code_name, key);
22426
+ }
22427
+ const outcome = orphanPruneOutcome(
22428
+ orphanKeys,
22429
+ orphanKeys.length > 0 ? readDeclaredServersForPrune(frameworkAdapter, agent.code_name) : {}
22430
+ );
22431
+ if (outcome.failed) {
22432
+ orphanPruneFailed = true;
22433
+ log(orphanPruneFailedLine(agent.code_name, outcome.stuck, outcome.reason));
22434
+ } else if ((frameworkAdapter.consumeMcpWriteFailures?.(agent.code_name) ?? 0) > 0) {
22435
+ orphanPruneFailed = true;
22436
+ log(orphanPruneFailedLine(agent.code_name, orphanKeys, "removed from provision/.mcp.json but the project mirror the session loads was not written"));
22437
+ }
22438
+ for (const key of orphanKeys) {
22439
+ if (!(outcome.failed && outcome.stuck.includes(key))) {
22440
+ log(`[hot-reload] Removed orphaned remote MCP server '${key}' for '${agent.code_name}' (integration removed)`);
22441
+ }
22442
+ }
22169
22443
  }
22170
22444
  } catch (err) {
22171
- log(`[hot-reload] Failed to prune orphaned remote MCP servers for '${agent.code_name}': ${err.message}`);
22445
+ orphanPruneFailed = true;
22446
+ log(orphanPruneFailedLine(agent.code_name, orphanKeys, `prune threw: ${err.message}`));
22172
22447
  }
22173
22448
  }
22174
22449
  const currentIntIds = integrations.map((i) => i.definition_id);
@@ -22203,17 +22478,39 @@ async function processAgent(agent, agentStates, managedToolkits) {
22203
22478
  }
22204
22479
  let reapNote = "";
22205
22480
  let rotationHandled = true;
22481
+ let mcpWriteFailed = false;
22482
+ if (agentState.knownIntegrationHashes.get(agent.agent_id) === MCP_REPAIR_PENDING_HASH && frameworkAdapter.syncMcpMirror) {
22483
+ frameworkAdapter.consumeMcpWriteFailures?.(agent.code_name);
22484
+ frameworkAdapter.syncMcpMirror(agent.code_name);
22485
+ if ((frameworkAdapter.consumeMcpWriteFailures?.(agent.code_name) ?? 0) > 0) {
22486
+ mcpWriteFailed = true;
22487
+ log(`[hot-reload] MCP_MIRROR_REPAIR_FAILED agent='${agent.code_name}': the project MCP mirror still could not be written; the reload stays pending (ENG-11912)`);
22488
+ }
22489
+ }
22206
22490
  const EMPTY_INTEGRATIONS_HASH = "\0empty\0";
22207
22491
  if (integrations.length === 0 && frameworkAdapter.writeIntegrations) {
22208
22492
  const prevIntHash = agentState.knownIntegrationHashes.get(agent.agent_id);
22209
22493
  if (prevIntHash !== EMPTY_INTEGRATIONS_HASH) {
22210
22494
  try {
22495
+ frameworkAdapter.consumeMcpWriteFailures?.(agent.code_name);
22211
22496
  frameworkAdapter.writeIntegrations(agent.code_name, [], agent.agent_id, {
22212
22497
  renderClaudeMdSection: renderIntegrationsSection,
22213
22498
  log
22214
22499
  });
22500
+ if ((frameworkAdapter.consumeMcpWriteFailures?.(agent.code_name) ?? 0) > 0) {
22501
+ mcpWriteFailed = true;
22502
+ throw new Error("MCP config write did not land (MCP_WRITE_REFUSED)");
22503
+ }
22215
22504
  agentState.knownIntegrationHashes.set(agent.agent_id, EMPTY_INTEGRATIONS_HASH);
22216
22505
  log(`[ENG-8035] Pruned integration-derived MCP entries for '${agent.code_name}' (integrations.length=0)`);
22506
+ if (emptyPruneRestartsOpencode({
22507
+ hadIntegrations: prevIntHash !== void 0,
22508
+ framework: agentFrameworkCache.get(agent.code_name) ?? DEFAULT_FRAMEWORK,
22509
+ serveHealthy: isOpencodeSessionHealthy(agent.code_name)
22510
+ })) {
22511
+ log(`[hot-reload] opencode lost its last integration for '${agent.code_name}' - restarting serve to drop its MCP servers`);
22512
+ stopOpencodeSession(agent.code_name, log);
22513
+ }
22217
22514
  } catch (err) {
22218
22515
  rotationHandled = false;
22219
22516
  log(`[ENG-8035] Empty integration prune failed for '${agent.code_name}': ${err.message}`);
@@ -22233,10 +22530,18 @@ async function processAgent(agent, agentStates, managedToolkits) {
22233
22530
  preWriteEnv = void 0;
22234
22531
  }
22235
22532
  if (frameworkAdapter.writeIntegrations) {
22533
+ frameworkAdapter.consumeMcpWriteFailures?.(agent.code_name);
22236
22534
  frameworkAdapter.writeIntegrations(agent.code_name, integrations, agent.agent_id, {
22237
22535
  renderClaudeMdSection: renderIntegrationsSection,
22238
22536
  log
22239
22537
  });
22538
+ const refusedWrites = frameworkAdapter.consumeMcpWriteFailures?.(agent.code_name) ?? 0;
22539
+ if (refusedWrites > 0) {
22540
+ mcpWriteFailed = true;
22541
+ log(
22542
+ `[hot-reload] MCP_WRITE_REFUSED agent='${agent.code_name}' writes=${refusedWrites}: the rendered MCP config did not fully land, so a pending integration-change reload stays pending and the integrations hash is not recorded (retried next poll) (ENG-11912)`
22543
+ );
22544
+ }
22240
22545
  }
22241
22546
  log(`Integrations provisioned for '${agent.code_name}' (${integrations.length} integration(s))`);
22242
22547
  const fw = agentFrameworkCache.get(agent.code_name) ?? DEFAULT_FRAMEWORK;
@@ -22307,7 +22612,7 @@ async function processAgent(agent, agentStates, managedToolkits) {
22307
22612
  log(`[hot-reload] Failed to compute / reap affected MCP servers for '${agent.code_name}': ${err.message} \u2014 will retry next tick`);
22308
22613
  }
22309
22614
  }
22310
- const hashDecision = integrationHashDecision(rotationHandled, integrations, intHash);
22615
+ const hashDecision = integrationHashDecision(rotationHandled && !mcpWriteFailed, integrations, intHash);
22311
22616
  if (hashDecision.kind === "record") {
22312
22617
  agentState.knownIntegrationHashes.set(agent.agent_id, hashDecision.hash);
22313
22618
  } else if (hashDecision.kind === "forget") {
@@ -22316,6 +22621,38 @@ async function processAgent(agent, agentStates, managedToolkits) {
22316
22621
  }
22317
22622
  }
22318
22623
  }
22624
+ if (markMcpRepairPending(agentState.knownIntegrationHashes, agent.agent_id, orphanPruneFailed || mcpWriteFailed || !rotationHandled)) {
22625
+ log(`[hot-reload] '${agent.code_name}': MCP config writes did not all land this poll; the next poll re-renders to repair them (ENG-11912)`);
22626
+ }
22627
+ if (configReloadConfirmed({
22628
+ pending: configReloads.isPending(agent.agent_id),
22629
+ freshFetch: integrationsFresh,
22630
+ rendered: rotationHandled && !orphanPruneFailed && !mcpWriteFailed
22631
+ })) {
22632
+ const fwForReload = agentFrameworkCache.get(agent.code_name) ?? DEFAULT_FRAMEWORK;
22633
+ const staleTmuxSession = fwForReload === "opencode" ? opencodeTmuxSession(agent.code_name) : `agt-${agent.code_name}`;
22634
+ if (probeTmuxSession(staleTmuxSession) === "alive") {
22635
+ if (fwForReload === "opencode") {
22636
+ stopOpencodeSession(agent.code_name, log);
22637
+ } else {
22638
+ log(`[restart] '${agent.code_name}' is running config from before the reload's fresh render - restarting it (ENG-11912)`);
22639
+ try {
22640
+ syncExecFile("tmux", ["kill-session", "-t", `agt-${agent.code_name}`], { stdio: "ignore" });
22641
+ } catch {
22642
+ }
22643
+ stopPersistentSessionAndForgetMcpBaseline(agent.code_name, "integration-change");
22644
+ }
22645
+ }
22646
+ const staleSessionState = probeTmuxSession(staleTmuxSession);
22647
+ if (staleSessionStopConfirmed(staleSessionState)) {
22648
+ configReloads.confirm(agent.agent_id);
22649
+ log(`[restart] config-change reload for '${agent.code_name}' rendered from fresh integrations - acking (ENG-11912)`);
22650
+ } else {
22651
+ log(
22652
+ `[restart] STALE_SESSION_STOP_FAILED agent='${agent.code_name}' session_state=${staleSessionState}: the session spawned from pre-reload config is still running or could not be probed, so the config-change reload stays pending and the stop is retried next poll (ENG-11912)`
22653
+ );
22654
+ }
22655
+ }
22319
22656
  if (capSurfaceHash !== prevCapSurfaceHash && rotationHandled) {
22320
22657
  if (intFlap.flapping) {
22321
22658
  log(`[mcp-flap-dampener] suppressed integration-update notice for '${agent.code_name}' (set flapping, ENG-6123): ${capSurfaceNames}`);
@@ -24544,9 +24881,6 @@ function ensureRealtimeDriftStarted(agentStates) {
24544
24881
  });
24545
24882
  }
24546
24883
  var restartInFlight = /* @__PURE__ */ new Set();
24547
- function restartReasonNeedsRender(reason) {
24548
- return reason != null && reason !== "manual" && reason !== MANAGER_RESTART_REASON;
24549
- }
24550
24884
  async function managerRestartMayKill(agentId, codeName, requestedAt, lane, framework) {
24551
24885
  let verdict;
24552
24886
  if (framework !== "claude-code") {
@@ -24606,6 +24940,10 @@ async function handleRestartDoorbell(agentId, requestedAt, restartReason) {
24606
24940
  triggerEarlyPoll(`config-change reload for '${codeName}' (reason=${restartReason})`, agentId);
24607
24941
  return;
24608
24942
  }
24943
+ if (configReloads.isPending(agentId)) {
24944
+ triggerEarlyPoll(`restart for '${codeName}' while a config-change reload is pending`, agentId);
24945
+ return;
24946
+ }
24609
24947
  if (!hostFlagStore().getBoolean("restart-doorbell")) {
24610
24948
  if (restartReason === MANAGER_RESTART_REASON) {
24611
24949
  triggerEarlyPoll(`manager restart for '${codeName}' (fast lane off)`, agentId);
@@ -24619,7 +24957,7 @@ async function handleRestartDoorbell(agentId, requestedAt, restartReason) {
24619
24957
  if (!refreshData) return;
24620
24958
  const framework = refreshData.agent?.framework ?? agentFrameworkCache.get(codeName) ?? DEFAULT_FRAMEWORK;
24621
24959
  const hostId = await getHostId();
24622
- const parkForRestart = await import("../responsiveness-probe-SVSMKLYS.js").then(
24960
+ const parkForRestart = await import("../responsiveness-probe-J7DA3AB4.js").then(
24623
24961
  (m) => m.parkPendingInbound,
24624
24962
  (err) => err
24625
24963
  );
@@ -24692,7 +25030,7 @@ async function handleRestartDoorbell(agentId, requestedAt, restartReason) {
24692
25030
  void api.post("/host/restart-ack", { host_id: hostId, agent_id: agentId, restart_requested_at: requestedAt }).catch((err) => log(`[restart-lane] ack failed for '${codeName}': ${err.message}`));
24693
25031
  void (async () => {
24694
25032
  try {
24695
- const { collectDiagnostics } = await import("../persistent-session-ZTDFRERR.js");
25033
+ const { collectDiagnostics } = await import("../persistent-session-TBE4KP4K.js");
24696
25034
  await api.post("/host/heartbeat", {
24697
25035
  host_id: hostId,
24698
25036
  agent_diagnostics: collectDiagnostics([codeName], quarantineEntriesFor, claudeMdSizeFor, spawnOutcomeForDiagnostics, pidPressureFor, forwardedToolsFor, runtimeVersionFor, sessionActivityFor)
@@ -24743,7 +25081,7 @@ async function respawnAgentAfterMcpStop(codeName, reason) {
24743
25081
  }
24744
25082
  try {
24745
25083
  const hostId = await getHostId();
24746
- const { collectDiagnostics } = await import("../persistent-session-ZTDFRERR.js");
25084
+ const { collectDiagnostics } = await import("../persistent-session-TBE4KP4K.js");
24747
25085
  await api.post("/host/heartbeat", {
24748
25086
  host_id: hostId,
24749
25087
  agent_diagnostics: collectDiagnostics([codeName], quarantineEntriesFor, claudeMdSizeFor, spawnOutcomeForDiagnostics, pidPressureFor, forwardedToolsFor, runtimeVersionFor, sessionActivityFor)
@@ -25445,7 +25783,7 @@ async function processClaudePairSessions(agents) {
25445
25783
  snapshotPairConfig,
25446
25784
  // ENG-11659: result -> report body + the manager.log line that records it.
25447
25785
  planPairStartReport
25448
- } = await import("../claude-pair-runtime-BJLV7HMD.js");
25786
+ } = await import("../claude-pair-runtime-CTJCJNK4.js");
25449
25787
  const { resetClaudeSignin, describeSigninResetForLog, describeSigninResetFailure } = await import("../claude-signin-reset-6IJMMVYG.js");
25450
25788
  for (const pairId of pendingResp.cancelled_pair_ids ?? []) {
25451
25789
  log(`[claude-pair] sweeping orphan tmux session for pair ${pairId.slice(0, 8)}`);