agent-relay-server 0.121.5 → 0.122.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (179) hide show
  1. package/docs/openapi.json +1 -1
  2. package/package.json +6 -6
  3. package/public/assets/{MessageBubble-CLqxCG9b.js → MessageBubble-DRdUD-kW.js} +2 -2
  4. package/public/assets/{MessageBubble-CLqxCG9b.js.map → MessageBubble-DRdUD-kW.js.map} +1 -1
  5. package/public/assets/{PlanGraphPanel-BkkToFEb.js → PlanGraphPanel-siKMPCln.js} +2 -2
  6. package/public/assets/{PlanGraphPanel-BkkToFEb.js.map → PlanGraphPanel-siKMPCln.js.map} +1 -1
  7. package/public/assets/{activity-D-ocGQGs.js → activity-D3MNcSaV.js} +2 -2
  8. package/public/assets/{activity-D-ocGQGs.js.map → activity-D3MNcSaV.js.map} +1 -1
  9. package/public/assets/{agent-profiles-CRPgYTyb.js → agent-profiles-CKzttq6G.js} +2 -2
  10. package/public/assets/{agent-profiles-CRPgYTyb.js.map → agent-profiles-CKzttq6G.js.map} +1 -1
  11. package/public/assets/{agent-type-icon-CeEoMouY.js → agent-type-icon-0ZJRP1Vy.js} +2 -2
  12. package/public/assets/{agent-type-icon-CeEoMouY.js.map → agent-type-icon-0ZJRP1Vy.js.map} +1 -1
  13. package/public/assets/{agents-Chw5E_2q.js → agents-CuVj_rfG.js} +2 -2
  14. package/public/assets/{agents-Chw5E_2q.js.map → agents-CuVj_rfG.js.map} +1 -1
  15. package/public/assets/{analytics-BmNDG0hR.js → analytics-iob6C27d.js} +2 -2
  16. package/public/assets/{analytics-BmNDG0hR.js.map → analytics-iob6C27d.js.map} +1 -1
  17. package/public/assets/{automation-D7g90kTv.js → automation-B2ixxs4q.js} +2 -2
  18. package/public/assets/{automation-D7g90kTv.js.map → automation-B2ixxs4q.js.map} +1 -1
  19. package/public/assets/{branch-state-badge-Bv7DhLBZ.js → branch-state-badge-CafBJWKo.js} +2 -2
  20. package/public/assets/{branch-state-badge-Bv7DhLBZ.js.map → branch-state-badge-CafBJWKo.js.map} +1 -1
  21. package/public/assets/{channels-CLwPeEPi.js → channels-C-WsbL2H.js} +2 -2
  22. package/public/assets/{channels-CLwPeEPi.js.map → channels-C-WsbL2H.js.map} +1 -1
  23. package/public/assets/{chat-Cgj7VKzc.js → chat-DeoVTVob.js} +2 -2
  24. package/public/assets/{chat-Cgj7VKzc.js.map → chat-DeoVTVob.js.map} +1 -1
  25. package/public/assets/{connectors-Br6fiTny.js → connectors-C2Ac03LJ.js} +2 -2
  26. package/public/assets/{connectors-Br6fiTny.js.map → connectors-C2Ac03LJ.js.map} +1 -1
  27. package/public/assets/display-CJzSoTMq.js +3 -0
  28. package/public/assets/display-CJzSoTMq.js.map +1 -0
  29. package/public/assets/{formatted-body-CmkuD23M.js → formatted-body-35XBOY5L.js} +3 -3
  30. package/public/assets/{formatted-body-CmkuD23M.js.map → formatted-body-35XBOY5L.js.map} +1 -1
  31. package/public/assets/{formatted-body-impl-DbdFmbwW.js → formatted-body-impl-RmDxI5Ux.js} +2 -2
  32. package/public/assets/{formatted-body-impl-DbdFmbwW.js.map → formatted-body-impl-RmDxI5Ux.js.map} +1 -1
  33. package/public/assets/index-D0xMQQb_.js +25 -0
  34. package/public/assets/{index-D9OogaB5.js.map → index-D0xMQQb_.js.map} +1 -1
  35. package/public/assets/{insights-qvaPqWCV.js → insights-B643SFvm.js} +2 -2
  36. package/public/assets/{insights-qvaPqWCV.js.map → insights-B643SFvm.js.map} +1 -1
  37. package/public/assets/{integrations-DYEGSqq_.js → integrations-hFIHeCF4.js} +2 -2
  38. package/public/assets/{integrations-DYEGSqq_.js.map → integrations-hFIHeCF4.js.map} +1 -1
  39. package/public/assets/{maintenance-C0HIEB-J.js → maintenance-CURvdp_Z.js} +2 -2
  40. package/public/assets/{maintenance-C0HIEB-J.js.map → maintenance-CURvdp_Z.js.map} +1 -1
  41. package/public/assets/{managed-agents-DdS7aI38.js → managed-agents-DrZtdlSn.js} +2 -2
  42. package/public/assets/{managed-agents-DdS7aI38.js.map → managed-agents-DrZtdlSn.js.map} +1 -1
  43. package/public/assets/{markdown-preview-impl-BnXMH1z1.js → markdown-preview-impl-CVDO--ek.js} +2 -2
  44. package/public/assets/{markdown-preview-impl-BnXMH1z1.js.map → markdown-preview-impl-CVDO--ek.js.map} +1 -1
  45. package/public/assets/{memory-CSwx7bz8.js → memory-Bm7dt_Qf.js} +2 -2
  46. package/public/assets/{memory-CSwx7bz8.js.map → memory-Bm7dt_Qf.js.map} +1 -1
  47. package/public/assets/{messages-Be9CmvDv.js → messages-DTq4i2KZ.js} +2 -2
  48. package/public/assets/{messages-Be9CmvDv.js.map → messages-DTq4i2KZ.js.map} +1 -1
  49. package/public/assets/{orchestrators-BgtvvHvo.js → orchestrators-Dra318Ap.js} +2 -2
  50. package/public/assets/{orchestrators-BgtvvHvo.js.map → orchestrators-Dra318Ap.js.map} +1 -1
  51. package/public/assets/{overview-BvhbPWtF.js → overview-yr1Vmk64.js} +2 -2
  52. package/public/assets/{overview-BvhbPWtF.js.map → overview-yr1Vmk64.js.map} +1 -1
  53. package/public/assets/{pairs-CpXSOMx0.js → pairs-mnlKDBGp.js} +2 -2
  54. package/public/assets/{pairs-CpXSOMx0.js.map → pairs-mnlKDBGp.js.map} +1 -1
  55. package/public/assets/projects-Dzdf-gkK.js +2 -0
  56. package/public/assets/{projects-DdPNPFJI.js.map → projects-Dzdf-gkK.js.map} +1 -1
  57. package/public/assets/prompt-settings-ByL8SNCi.js +2 -0
  58. package/public/assets/{prompt-settings-BpZse7-X.js.map → prompt-settings-ByL8SNCi.js.map} +1 -1
  59. package/public/assets/{registry-pb1gTZEg.js → registry-CXWyOtpr.js} +2 -2
  60. package/public/assets/{registry-pb1gTZEg.js.map → registry-CXWyOtpr.js.map} +1 -1
  61. package/public/assets/{security-BgcX1n9D.js → security-0SBsc_4W.js} +2 -2
  62. package/public/assets/{security-BgcX1n9D.js.map → security-0SBsc_4W.js.map} +1 -1
  63. package/public/assets/{select-DZPVpKPv.js → select-Bw5z2KJ_.js} +2 -2
  64. package/public/assets/{select-DZPVpKPv.js.map → select-Bw5z2KJ_.js.map} +1 -1
  65. package/public/assets/{settings-hd5kzdRB.js → settings-78Cyq_tA.js} +4 -4
  66. package/public/assets/{settings-hd5kzdRB.js.map → settings-78Cyq_tA.js.map} +1 -1
  67. package/public/assets/{store-DKTLubBT.js → store-BPrVuKiv.js} +4 -4
  68. package/public/assets/store-BPrVuKiv.js.map +1 -0
  69. package/public/assets/{tasks-C5d2LU5E.js → tasks-Cg2MMeri.js} +2 -2
  70. package/public/assets/{tasks-C5d2LU5E.js.map → tasks-Cg2MMeri.js.map} +1 -1
  71. package/public/assets/teams-DWv6UwFV.js +2 -0
  72. package/public/assets/{teams-B8f2pGJe.js.map → teams-DWv6UwFV.js.map} +1 -1
  73. package/public/assets/{terminal-viewer-impl-CxAscH0U.js → terminal-viewer-impl-DBLDjbIg.js} +2 -2
  74. package/public/assets/{terminal-viewer-impl-CxAscH0U.js.map → terminal-viewer-impl-DBLDjbIg.js.map} +1 -1
  75. package/public/assets/{types-uVOXgvMT.js → types-BeJUSfDj.js} +2 -2
  76. package/public/assets/types-BeJUSfDj.js.map +1 -0
  77. package/public/assets/{user-avatar-Dw6mzWhv.js → user-avatar-BsOLyVJj.js} +2 -2
  78. package/public/assets/{user-avatar-Dw6mzWhv.js.map → user-avatar-BsOLyVJj.js.map} +1 -1
  79. package/public/assets/{work-queue-9imc7aNK.js → work-queue-DmwvnF6F.js} +2 -2
  80. package/public/assets/{work-queue-9imc7aNK.js.map → work-queue-DmwvnF6F.js.map} +1 -1
  81. package/public/assets/{workspaces-CLYc3yF3.js → workspaces-dIBivJN8.js} +2 -2
  82. package/public/assets/{workspaces-CLYc3yF3.js.map → workspaces-dIBivJN8.js.map} +1 -1
  83. package/public/index.html +6 -6
  84. package/runner/plugins/claude/.claude-plugin/plugin.json +1 -1
  85. package/runner/plugins/claude/monitors/relay-monitor.provisioned.mjs +44 -938
  86. package/runner/src/adapter.ts +53 -18
  87. package/runner/src/adapters/claude-delivery.ts +127 -0
  88. package/runner/src/adapters/claude-quota-harvest.ts +92 -0
  89. package/runner/src/adapters/claude-session-probe.ts +225 -0
  90. package/runner/src/adapters/claude-status-detectors.ts +147 -0
  91. package/runner/src/adapters/claude-transcript-tail.ts +128 -0
  92. package/runner/src/adapters/claude-transcript.ts +414 -0
  93. package/runner/src/adapters/claude.ts +672 -0
  94. package/runner/src/adapters/codex-agent-message-capture.ts +139 -0
  95. package/runner/src/adapters/codex-client.ts +279 -0
  96. package/runner/src/adapters/codex.ts +1345 -0
  97. package/runner/src/attachment-cache.ts +189 -0
  98. package/runner/src/busy-reconciler.ts +102 -0
  99. package/runner/src/claim-tracker.ts +140 -0
  100. package/runner/src/claude-prompt-gates.ts +268 -0
  101. package/runner/src/config.ts +1 -4
  102. package/runner/src/context-probe-state.ts +6 -0
  103. package/runner/src/continuation-archive.ts +179 -0
  104. package/runner/src/control-server.ts +639 -0
  105. package/runner/src/index.ts +396 -0
  106. package/runner/src/launch-assembly.ts +508 -0
  107. package/runner/src/liveness.ts +50 -0
  108. package/runner/src/logger.ts +99 -0
  109. package/runner/src/mcp-outbox.ts +120 -0
  110. package/runner/src/message-body-config/config.ts +3 -0
  111. package/runner/src/message-body-config.ts +1 -0
  112. package/runner/src/native-self-resume.ts +202 -0
  113. package/runner/src/outbox.ts +342 -0
  114. package/runner/src/process-meta.ts +9 -0
  115. package/runner/src/profile-home.ts +260 -0
  116. package/runner/src/profile-projection.ts +305 -0
  117. package/runner/src/providers.ts +20 -0
  118. package/runner/src/provisioning.ts +314 -0
  119. package/runner/src/quota.ts +40 -0
  120. package/runner/src/rate-limit.ts +189 -0
  121. package/runner/src/relay-injection-events.ts +102 -0
  122. package/runner/src/relay-instructions.ts +60 -0
  123. package/runner/src/relay-mcp-proxy.ts +383 -0
  124. package/runner/src/relay-mcp.ts +156 -0
  125. package/runner/src/reply-obligation-cache.ts +136 -0
  126. package/runner/src/response-capture-report.ts +63 -0
  127. package/runner/src/runner-core.ts +2409 -0
  128. package/runner/src/runner-helpers.ts +435 -0
  129. package/runner/src/runner-insights.ts +105 -0
  130. package/runner/src/runner.ts +14 -0
  131. package/runner/src/session-destroy.ts +22 -0
  132. package/runner/src/session-insights.ts +118 -0
  133. package/runner/src/session-scratch.ts +271 -0
  134. package/runner/src/template-resolver.ts +29 -0
  135. package/runner/src/version.ts +43 -0
  136. package/src/agent-card-projection.ts +5 -1
  137. package/src/agent-command-activity.ts +39 -0
  138. package/src/automations/reconcile.ts +2 -2
  139. package/src/cli/workspace.ts +3 -1
  140. package/src/config.ts +10 -1
  141. package/src/db/agents.ts +118 -37
  142. package/src/db/message-reads.ts +50 -0
  143. package/src/db/messages.ts +48 -9
  144. package/src/db/migrations.ts +54 -0
  145. package/src/db/provider-quota-burn.ts +96 -67
  146. package/src/db/provider-quotas.ts +29 -7
  147. package/src/db/scheduled-timers.ts +21 -0
  148. package/src/db/schema.ts +1 -0
  149. package/src/db/tasks.ts +33 -3
  150. package/src/db/work-evidence.ts +10 -7
  151. package/src/event-loop-lag.ts +15 -0
  152. package/src/gate-resolver.ts +19 -1
  153. package/src/maintenance/jobs.ts +23 -6
  154. package/src/managed-policy.ts +5 -12
  155. package/src/mcp-plan-tools.ts +13 -1
  156. package/src/project-instructions.ts +36 -2
  157. package/src/quota-advisory.ts +6 -4
  158. package/src/quota-band-transition.ts +23 -14
  159. package/src/routes/agent-sessions.ts +39 -7
  160. package/src/routes/agents.ts +3 -2
  161. package/src/routes/tasks.ts +16 -4
  162. package/src/routes/workspaces.ts +35 -10
  163. package/src/services/plan-graph.ts +27 -9
  164. package/src/services/register-agent.ts +12 -12
  165. package/src/services/send-message.ts +43 -15
  166. package/src/services/spawn-agent.ts +3 -0
  167. package/src/spawn-command.ts +8 -0
  168. package/src/spawn-targets.ts +19 -34
  169. package/src/sse.ts +25 -3
  170. package/src/workspace-merge.ts +25 -5
  171. package/src/workspace-orphans.ts +13 -6
  172. package/public/assets/display-exQDWum3.js +0 -3
  173. package/public/assets/display-exQDWum3.js.map +0 -1
  174. package/public/assets/index-D9OogaB5.js +0 -25
  175. package/public/assets/projects-DdPNPFJI.js +0 -2
  176. package/public/assets/prompt-settings-BpZse7-X.js +0 -2
  177. package/public/assets/store-DKTLubBT.js.map +0 -1
  178. package/public/assets/teams-B8f2pGJe.js +0 -2
  179. package/public/assets/types-uVOXgvMT.js.map +0 -1
@@ -1,8 +1,8 @@
1
1
  import type { AgentProfile, LivenessSignal, Message, ProviderState } from "agent-relay-sdk";
2
- import { isRecord } from "agent-relay-sdk";
2
+ import { isRecord } from "agent-relay-sdk/types/guards";
3
3
  import type { LivenessInputs } from "./liveness";
4
4
  import type { SessionEvent } from "./session-insights";
5
- import { messageBodyMaxCharsFromEnv } from "./config";
5
+ import { messageBodyMaxCharsFromEnv } from "./message-body-config";
6
6
  import { relayReplyReminderText } from "./relay-instructions";
7
7
  import { renderRunnerTemplate } from "./template-resolver";
8
8
 
@@ -250,6 +250,53 @@ export function providerMessageBodyMaxChars(): number {
250
250
  return DEFAULT_PROVIDER_MESSAGE_BODY_MAX_CHARS;
251
251
  }
252
252
 
253
+ export interface DeliveredBodyPreview {
254
+ body: string;
255
+ truncated: boolean;
256
+ /** Retrieval-guidance lines (empty when not truncated). Call sites may append provider extras. */
257
+ guidance: string[];
258
+ }
259
+
260
+ // #1058 — one home for the delivered-body cap. Head-only truncation silently ate the TAIL, which is
261
+ // exactly where a report-up final puts its verdict / SHIP recommendation. Preserve BOTH ends: keep a
262
+ // head slice for opening context and a tail slice for the conclusion, eliding the middle and pointing
263
+ // at the untrimmed body. The tail is favored (it holds the verdict). Slices snap to whitespace so we
264
+ // don't deliver a half-word at either seam. Grep before adding another truncation site — this is it.
265
+ export function previewDeliveredBody(
266
+ rawBody: string,
267
+ messageId: number,
268
+ maxChars: number = providerMessageBodyMaxChars(),
269
+ ): DeliveredBodyPreview {
270
+ if (rawBody.length <= maxChars) return { body: rawBody, truncated: false, guidance: [] };
271
+ const fetchLines = [
272
+ `Read full: agent-relay get-message ${messageId}`,
273
+ `Body only: agent-relay get-message ${messageId} --body`,
274
+ ];
275
+ const marker = (elided: number) => `[… ${elided} chars elided from the middle — full report: relay_get_message #${messageId} …]`;
276
+ // Reserve room for the marker and its two blank-line joins; upper-bound the marker length by using
277
+ // the (always-larger) full body length so the reserved budget can never underflow the real marker.
278
+ const budget = maxChars - marker(rawBody.length).length - 4;
279
+ if (budget < 200) {
280
+ // Cap too small to keep a useful head — front-truncate, preserving the tail/verdict whole.
281
+ const tail = rawBody.slice(rawBody.length - maxChars).replace(/^\S*\s+/, "").trimStart();
282
+ return {
283
+ body: tail,
284
+ truncated: true,
285
+ guidance: [`[truncated: showing last ${tail.length} of ${rawBody.length} chars — head trimmed, tail/verdict preserved]`, ...fetchLines],
286
+ };
287
+ }
288
+ const headChars = Math.floor(budget * 0.35);
289
+ const tailChars = budget - headChars;
290
+ const head = rawBody.slice(0, headChars).replace(/\s+\S*$/, "").trimEnd();
291
+ const tail = rawBody.slice(rawBody.length - tailChars).replace(/^\S*\s+/, "").trimStart();
292
+ const elided = rawBody.length - head.length - tail.length;
293
+ return {
294
+ body: `${head}\n\n${marker(elided)}\n\n${tail}`,
295
+ truncated: true,
296
+ guidance: [`[truncated: showing first ${head.length} + last ${tail.length} of ${rawBody.length} chars — tail/verdict preserved]`, ...fetchLines],
297
+ };
298
+ }
299
+
253
300
  function attachmentRefs(message: Message): Record<string, unknown>[] {
254
301
  const payloadRefs = message.payload?.attachments;
255
302
  const topLevelRefs = (message as Message & { attachments?: unknown }).attachments;
@@ -375,23 +422,11 @@ export function providerMessageText(messages: Message[]): string {
375
422
  const subject = message.subject ? `Subject: ${message.subject}\n` : "";
376
423
  const isMemoryContext = isMemoryInjection(message);
377
424
  const canReferenceMessage = isPersistedRelayMessage(message) && !isMemoryContext && !isReactionNotification(message);
378
- const shouldPreview = canReferenceMessage && message.body.length > maxChars;
379
- const preview = shouldPreview
380
- ? {
381
- body: message.body.slice(0, maxChars),
382
- truncated: true,
383
- }
384
- : {
385
- body: message.body,
386
- truncated: false,
387
- };
425
+ const preview = canReferenceMessage
426
+ ? previewDeliveredBody(message.body, message.id, maxChars)
427
+ : { body: message.body, truncated: false, guidance: [] };
388
428
  const truncationGuidance = preview.truncated
389
- ? [
390
- `[truncated: showing first ${maxChars} of ${message.body.length} chars]`,
391
- `Read full: agent-relay get-message ${message.id}`,
392
- `Body only: agent-relay get-message ${message.id} --body`,
393
- `Long reply CLI fallback: agent-relay /reply ${message.id} --body-file response.md`,
394
- ].join("\n")
429
+ ? [...preview.guidance, `Long reply CLI fallback: agent-relay /reply ${message.id} --body-file response.md`].join("\n")
395
430
  : undefined;
396
431
  if (isMemoryContext) {
397
432
  return [
@@ -0,0 +1,127 @@
1
+ import type { Message } from "agent-relay-sdk";
2
+ import { isRecord } from "agent-relay-sdk/types/guards";
3
+ import { dedupePersistedMessages, isNotificationMessage, NOTIFICATION_NUDGE, previewDeliveredBody, providerAttachmentText, providerMessageBodyMaxChars } from "../adapter";
4
+ import { relayReplyReminderText } from "../relay-instructions";
5
+
6
+ const REMINDER_EVERY_DELIVERIES = 5;
7
+
8
+ interface ClaudeDeliveryTextOptions {
9
+ deliveryCount: number;
10
+ readOnly?: boolean;
11
+ // false = isolated profile with no relay plugin/CLI surface. The agent cannot /reply or
12
+ // /claim, so strip the reply-reminder block and the server-baked claim-task instruction —
13
+ // it's just confusing noise in a clean-room run. Defaults to true (relay-aware agents).
14
+ relaySurface?: boolean;
15
+ }
16
+
17
+ // Server-baked trailing line from taskMessageBody() in src/db.ts. Meaningless to an isolated
18
+ // agent (sole claimant, no relay CLI), so drop it from delivered text when there's no surface.
19
+ const TASK_CLAIM_INSTRUCTION = "Claim this task before working it, then update task status when finished.";
20
+
21
+ function stripRelayScaffolding(body: string): string {
22
+ const lines = body.split("\n");
23
+ const popTrailingBlanks = () => {
24
+ while (lines.length && (lines.at(-1) ?? "").trim() === "") lines.pop();
25
+ };
26
+ popTrailingBlanks();
27
+ if (lines.at(-1) === TASK_CLAIM_INSTRUCTION) {
28
+ lines.pop();
29
+ popTrailingBlanks();
30
+ }
31
+ return lines.join("\n");
32
+ }
33
+
34
+ function isMemoryInjection(message: Message): boolean {
35
+ return isRecord(message.payload) && message.payload.memoryInjection === true;
36
+ }
37
+
38
+ function isReactionNotification(message: Message): boolean {
39
+ const event = isRecord(message.payload?.event) ? message.payload.event : undefined;
40
+ return message.payload?.reactionNotification === true || event?.type === "message.reaction";
41
+ }
42
+
43
+ function isSpawnObligationMessage(message: Message): boolean {
44
+ return isRecord(message.payload) && message.payload.source === "spawn-obligation";
45
+ }
46
+
47
+ function isPersistedRelayMessage(message: Message): boolean {
48
+ return Number.isSafeInteger(message.id) && message.id > 0;
49
+ }
50
+
51
+ function providerSenderLabel(message: Message): string {
52
+ if (message.from === "user") return "human user";
53
+ const source = isRecord(message.payload?.source) ? message.payload.source : undefined;
54
+ const isHumanChannel = Boolean(source && (
55
+ isRecord(source.telegram) ||
56
+ isRecord(source.slack) ||
57
+ isRecord(source.discord)
58
+ ));
59
+ return isHumanChannel ? `human user via ${message.from}` : message.from;
60
+ }
61
+
62
+ function shouldShowReplyReminder(deliveryCount: number): boolean {
63
+ return deliveryCount <= 1 || deliveryCount % REMINDER_EVERY_DELIVERIES === 0;
64
+ }
65
+
66
+ function latestReplyableMessage(messages: Message[]): Message | undefined {
67
+ return messages
68
+ .filter((message) => isPersistedRelayMessage(message) && !isMemoryInjection(message) && !isReactionNotification(message) && !isSpawnObligationMessage(message) && message.replyExpected !== false)
69
+ .at(-1);
70
+ }
71
+
72
+ function formatMessage(message: Message, relaySurface: boolean): string {
73
+ const subject = message.subject ? `Subject: ${message.subject}\n` : "";
74
+ const isMemoryContext = isMemoryInjection(message);
75
+ const canFetchMessage = isPersistedRelayMessage(message);
76
+ const rawBody = relaySurface ? message.body : stripRelayScaffolding(message.body);
77
+ const preview = canFetchMessage
78
+ ? previewDeliveredBody(rawBody, message.id, providerMessageBodyMaxChars())
79
+ : { body: rawBody, truncated: false, guidance: [] };
80
+ const truncationGuidance = preview.truncated ? preview.guidance.join("\n") : undefined;
81
+
82
+ if (isMemoryContext) {
83
+ return [
84
+ `[agent-relay context from ${message.from}]`,
85
+ providerAttachmentText(message),
86
+ `${subject}${preview.body}`,
87
+ truncationGuidance,
88
+ ].filter(Boolean).join("\n");
89
+ }
90
+
91
+ return [
92
+ `[relay message #${message.id} from ${providerSenderLabel(message)}]`,
93
+ providerAttachmentText(message),
94
+ `${subject}${preview.body}`,
95
+ truncationGuidance,
96
+ ].filter(Boolean).join("\n");
97
+ }
98
+
99
+ function replyReminder(message: Message, readOnly: boolean): string {
100
+ const command = readOnly
101
+ ? `agent-relay /reply ${message.id} "<your reply>"`
102
+ : relayReplyReminderText(message.id);
103
+ return [
104
+ "[agent-relay reply reminder]",
105
+ readOnly
106
+ ? `If this batch needs a response, send one useful reply to the latest relevant message: ${command}`
107
+ : command,
108
+ "If you already delivered the useful response through Relay, do not send a separate status-only confirmation.",
109
+ "If multiple messages arrived together, cover them in one reply instead of answering each line separately.",
110
+ ].join("\n");
111
+ }
112
+
113
+ export function claudeProviderMessageText(messages: Message[], options: ClaudeDeliveryTextOptions): string {
114
+ const relaySurface = options.relaySurface !== false;
115
+ const uniqueMessages = dedupePersistedMessages(messages);
116
+ const sections = uniqueMessages.map((message) => formatMessage(message, relaySurface));
117
+ const replyable = latestReplyableMessage(uniqueMessages);
118
+ // Isolated agents have no way to reply through Relay — never append the reminder/nudge.
119
+ if (relaySurface && replyable && shouldShowReplyReminder(options.deliveryCount)) {
120
+ sections.push(replyReminder(replyable, options.readOnly === true));
121
+ } else if (relaySurface && !replyable && uniqueMessages.some(isNotificationMessage)) {
122
+ // #283 — pure notification batch (no message wants a reply): drop the scaffold, append the
123
+ // one-line nudge so a long context can't make the agent forget the session-start no-reply rule.
124
+ sections.push(NOTIFICATION_NUDGE);
125
+ }
126
+ return sections.join("\n\n");
127
+ }
@@ -0,0 +1,92 @@
1
+ import type { QuotaState, RelayHttpClient } from "agent-relay-sdk";
2
+ import { quotaStateFromProbeMetrics } from "agent-relay-sdk/context-probe";
3
+ import { readRunnerContextProbeState } from "../context-probe-state";
4
+ import { DEFAULT_PROVIDER_QUOTA_CONFIG, normalizeProviderQuotaConfig, resolveClaudeStatuslineQuotaIdentity } from "../quota";
5
+
6
+ const PASSIVE_QUOTA_CONFIG_REFRESH_MS = 60_000;
7
+ const PASSIVE_QUOTA_SAMPLE_STALE_MS = 10 * 60_000;
8
+ const PASSIVE_QUOTA_LEASE_MAX_TTL_MS = 10 * 60_000;
9
+ const PASSIVE_QUOTA_LEASE_PADDING_MS = 60_000;
10
+
11
+ interface ClaudeQuotaHarvestOptions {
12
+ agentId: string;
13
+ provider: string;
14
+ http: () => Pick<RelayHttpClient, "acquireProviderQuotaPublisherLease" | "getProviderQuotaConfig" | "upsertProviderQuota">;
15
+ }
16
+
17
+ export class ClaudeQuotaHarvest {
18
+ private config = { ...DEFAULT_PROVIDER_QUOTA_CONFIG };
19
+ private configRefreshAt = 0;
20
+ private lastReportAt?: number;
21
+ private lease?: { accountKey: string; leaseToken: string; expiresAt: number };
22
+ private nextLeaseAttemptAt?: number;
23
+
24
+ constructor(private readonly options: ClaudeQuotaHarvestOptions) {}
25
+
26
+ async publish(): Promise<void> {
27
+ if (this.options.provider !== "claude") return;
28
+ const probeMetrics = readRunnerContextProbeState(this.options.agentId);
29
+ const now = Date.now();
30
+ const quota = probeMetrics ? freshQuotaFromProbeMetrics(probeMetrics, now) : undefined;
31
+ if (!quota) return;
32
+ const config = await this.refreshConfig();
33
+ if (!config.enabled) return;
34
+ if (this.lastReportAt !== undefined && now - this.lastReportAt < config.pollIntervalMs) return;
35
+ const identity = await resolveClaudeStatuslineQuotaIdentity({ env: process.env });
36
+ if (!identity) return;
37
+ if (!await this.ensurePublisherLease(identity.accountKey, config.pollIntervalMs, now)) return;
38
+ await this.options.http().upsertProviderQuota({
39
+ provider: "claude",
40
+ accountKey: identity.accountKey,
41
+ quota,
42
+ lastAttemptAt: quota.updatedAt,
43
+ sourceAgentId: this.options.agentId,
44
+ });
45
+ this.lastReportAt = now;
46
+ }
47
+
48
+ private async refreshConfig() {
49
+ const now = Date.now();
50
+ if (now < this.configRefreshAt) return this.config;
51
+ this.configRefreshAt = now + PASSIVE_QUOTA_CONFIG_REFRESH_MS;
52
+ try {
53
+ const map = await this.options.http().getProviderQuotaConfig();
54
+ this.config = map.claude
55
+ ? normalizeProviderQuotaConfig(map.claude)
56
+ : { ...DEFAULT_PROVIDER_QUOTA_CONFIG };
57
+ } catch {
58
+ // Keep the previous config; defaults preserve collection if the relay is older
59
+ // or temporarily unreachable during a liveness tick.
60
+ }
61
+ return this.config;
62
+ }
63
+
64
+ private async ensurePublisherLease(accountKey: string, pollIntervalMs: number, now: number): Promise<boolean> {
65
+ if (this.lease?.accountKey === accountKey && this.lease.expiresAt > now) return true;
66
+ if (this.nextLeaseAttemptAt !== undefined && now < this.nextLeaseAttemptAt) return false;
67
+ const leaseToken = this.lease?.accountKey === accountKey ? this.lease.leaseToken : undefined;
68
+ const result = await this.options.http().acquireProviderQuotaPublisherLease({
69
+ provider: "claude",
70
+ accountKey,
71
+ sourceAgentId: this.options.agentId,
72
+ ...(leaseToken ? { leaseToken } : {}),
73
+ ttlMs: Math.min(PASSIVE_QUOTA_LEASE_MAX_TTL_MS, pollIntervalMs + PASSIVE_QUOTA_LEASE_PADDING_MS),
74
+ });
75
+ if (!result.acquired || !result.lease) {
76
+ this.lease = undefined;
77
+ this.nextLeaseAttemptAt = now + Math.min(result.retryAfterMs ?? pollIntervalMs, pollIntervalMs);
78
+ return false;
79
+ }
80
+ this.lease = { accountKey, leaseToken: result.lease.leaseToken, expiresAt: result.lease.expiresAt };
81
+ this.nextLeaseAttemptAt = undefined;
82
+ return true;
83
+ }
84
+ }
85
+
86
+ function freshQuotaFromProbeMetrics(metrics: NonNullable<ReturnType<typeof readRunnerContextProbeState>>, now: number): QuotaState | undefined {
87
+ if (now - metrics.timestamp > PASSIVE_QUOTA_SAMPLE_STALE_MS) return undefined;
88
+ const quota = quotaStateFromProbeMetrics(metrics);
89
+ if (!quota) return undefined;
90
+ const windows = quota.windows.filter((window) => window.resetsAt === undefined || window.resetsAt > now);
91
+ return windows.length > 0 ? { ...quota, windows, updatedAt: now } : undefined;
92
+ }
@@ -0,0 +1,225 @@
1
+ // #766/#768 — Claude Code's intrinsic, machine-readable session probe.
2
+ //
3
+ // Claude Code ≥2.1.119 writes `$CLAUDE_CONFIG_DIR/sessions/<pid>.json` and rewrites
4
+ // it on every status transition. It carries an authoritative `status` field
5
+ // (busy|shell|idle|waiting, plus `waitingFor` when waiting) — the very
6
+ // "machine-readable ready/busy signal" the old pane-scrape comment claimed didn't
7
+ // exist. The runner manages the claude pid and its CLAUDE_CONFIG_DIR, so this is a
8
+ // direct keyed read — no enumeration, no cwd/solo-multi disambiguation.
9
+ //
10
+ // This is the single home (DRY) for reading + version-gating + mapping that probe.
11
+ // `probeActivity`, the BusyReconciler backstop, and the monitorless turn-watch all
12
+ // delegate here; the legacy pane-scrape stays only as the graceful fallback for
13
+ // pre-2.1.119 / probe-missing sessions (e.g. a claude-rig host whose real config
14
+ // home the runner can't resolve). Schema is reverse-engineered (pbauermeister/
15
+ // claude-busy-monitor), so we gate on `version`/presence and degrade gracefully if
16
+ // Anthropic ever drifts it.
17
+ import { readFileSync } from "node:fs";
18
+ import { homedir } from "node:os";
19
+ import { join } from "node:path";
20
+ import { isPidAlive } from "agent-relay-sdk/process-utils";
21
+ import { tmuxCommand } from "agent-relay-sdk/tmux-utils";
22
+
23
+ /** Raw probe status; "unknown" = absent / unparseable / version-gated out. */
24
+ export type ClaudeProbeStatus = "busy" | "shell" | "idle" | "waiting" | "unknown";
25
+
26
+ /** The 3-valued activity the reconciler + monitorless turn-watch consume. */
27
+ export type ClaudeProbeActivity = "busy" | "idle" | "unknown";
28
+
29
+ /** First Claude Code version that writes the session probe. Below this → fallback. */
30
+ export const CLAUDE_PROBE_MIN_VERSION = "2.1.119";
31
+
32
+ export interface ClaudeSessionReading {
33
+ /** Raw probe status, or "unknown" when the probe is absent/old/unparseable. */
34
+ status: ClaudeProbeStatus;
35
+ /** `waitingFor` reason when status==="waiting" (e.g. "approve Bash"), else null. */
36
+ waitingFor: string | null;
37
+ /** Probe `version`, or null when unavailable. */
38
+ version: string | null;
39
+ /** `procStart` (process start-time token, == `/proc/<pid>/stat` field 22), or null. */
40
+ procStart: string | null;
41
+ /** `updatedAt` epoch-ms of the last probe write, or null. */
42
+ updatedAt: number | null;
43
+ /** True iff a present, parseable, version-gated probe produced `status`. */
44
+ available: boolean;
45
+ }
46
+
47
+ const UNAVAILABLE: ClaudeSessionReading = { status: "unknown", waitingFor: null, version: null, procStart: null, updatedAt: null, available: false };
48
+
49
+ /**
50
+ * Process-liveness seam for the staleness guard (#769 P1-B), injectable in tests.
51
+ * procStartOf — the start-time token of a LIVE pid (to compare against the probe's
52
+ * `procStart`), or null when the pid is dead/unreadable. Catches both a frozen
53
+ * probe from a SIGKILLed claude AND a sub-second pid-reuse window (a reused pid
54
+ * has a different start time).
55
+ * pidAlive — liveness fallback for probes that predate `procStart`.
56
+ */
57
+ export interface ClaudeProbeLiveness {
58
+ procStartOf(pid: number): string | null;
59
+ pidAlive(pid: number): boolean;
60
+ }
61
+
62
+ // Default (Linux /proc) liveness. `procStart` in the probe is `/proc/<pid>/stat`
63
+ // field 22 (starttime, clock-ticks since boot) — verified equal live on CC 2.1.193.
64
+ // NB: we deliberately do NOT gate on `updatedAt` freshness — Claude only rewrites
65
+ // the probe on a status *transition*, so a legitimately busy turn keeps a frozen
66
+ // `updatedAt` for its whole duration (verified: a 90s+ busy turn never rewrote it).
67
+ // A staleness threshold would force a long busy turn back to the pane-scrape and
68
+ // reintroduce the #766 idle-while-working bug; pid-liveness + procStart cover the
69
+ // SIGKILL-frozen and pid-reuse cases without that hazard.
70
+ const DEFAULT_LIVENESS: ClaudeProbeLiveness = {
71
+ procStartOf: readProcStartTime,
72
+ pidAlive: isPidAlive,
73
+ };
74
+
75
+ function readProcStartTime(pid: number): string | null {
76
+ try {
77
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
78
+ // comm (field 2) is parenthesized and may contain spaces — slice past the last
79
+ // ')' so the remaining whitespace split starts cleanly at field 3 (state).
80
+ const after = stat.slice(stat.lastIndexOf(")") + 1).trim();
81
+ const fields = after.split(/\s+/);
82
+ return fields[19] ?? null; // field 22 (starttime) = index 19 after dropping pid+comm
83
+ } catch {
84
+ return null;
85
+ }
86
+ }
87
+
88
+ /** The per-session probe path the runner reads directly (keyed by claude's pid). */
89
+ export function claudeSessionProbePath(configHome: string, pid: number): string {
90
+ return join(configHome, "sessions", `${pid}.json`);
91
+ }
92
+
93
+ /** Dotted-version compare; true iff `version` >= `min`. Missing/non-numeric → gate closed. */
94
+ export function claudeVersionAtLeast(version: string | null | undefined, min: string): boolean {
95
+ if (!version) return false;
96
+ const actual = version.split(".");
97
+ const wanted = min.split(".");
98
+ for (let i = 0; i < wanted.length; i++) {
99
+ const x = Number.parseInt(actual[i] ?? "0", 10);
100
+ const y = Number.parseInt(wanted[i] ?? "0", 10);
101
+ if (Number.isNaN(x)) return false; // unparseable build → fall back, don't trust the probe
102
+ if (x !== y) return x > y;
103
+ }
104
+ return true;
105
+ }
106
+
107
+ function normalizeStatus(value: unknown): ClaudeProbeStatus {
108
+ switch (value) {
109
+ case "busy":
110
+ case "shell":
111
+ case "idle":
112
+ case "waiting":
113
+ return value;
114
+ default:
115
+ return "unknown";
116
+ }
117
+ }
118
+
119
+ /** Pure: parse a probe JSON body + version-gate it. Malformed / old / unknown status → unavailable. */
120
+ export function parseClaudeSessionProbe(raw: string, minVersion = CLAUDE_PROBE_MIN_VERSION): ClaudeSessionReading {
121
+ let parsed: unknown;
122
+ try {
123
+ parsed = JSON.parse(raw);
124
+ } catch {
125
+ return UNAVAILABLE;
126
+ }
127
+ if (!parsed || typeof parsed !== "object") return UNAVAILABLE;
128
+ const probe = parsed as Record<string, unknown>;
129
+ const version = typeof probe.version === "string" ? probe.version : null;
130
+ const procStart = typeof probe.procStart === "string" ? probe.procStart : null;
131
+ const updatedAt = typeof probe.updatedAt === "number" ? probe.updatedAt : null;
132
+ if (!claudeVersionAtLeast(version, minVersion)) return { ...UNAVAILABLE, version, procStart, updatedAt };
133
+ const status = normalizeStatus(probe.status);
134
+ if (status === "unknown") return { status: "unknown", waitingFor: null, version, procStart, updatedAt, available: false };
135
+ const waitingFor = typeof probe.waitingFor === "string" && probe.waitingFor.trim() ? probe.waitingFor : null;
136
+ return { status, waitingFor, version, procStart, updatedAt, available: true };
137
+ }
138
+
139
+ /**
140
+ * Read + parse the probe for `pid` under `configHome`. Missing file (older CC, a
141
+ * config home the runner can't resolve, or claude not yet started) → unavailable,
142
+ * so the caller falls back to the pane-scrape. Sync: the file is a few hundred
143
+ * bytes and both call sites (4s reconcile poll, 1.5s monitorless tick) are timers.
144
+ */
145
+ export function readClaudeSessionStatus(
146
+ configHome: string,
147
+ pid: number,
148
+ opts: { minVersion?: string; liveness?: ClaudeProbeLiveness } = {},
149
+ ): ClaudeSessionReading {
150
+ let raw: string;
151
+ try {
152
+ raw = readFileSync(claudeSessionProbePath(configHome, pid), "utf8");
153
+ } catch {
154
+ return UNAVAILABLE;
155
+ }
156
+ const reading = parseClaudeSessionProbe(raw, opts.minVersion ?? CLAUDE_PROBE_MIN_VERSION);
157
+ if (!reading.available) return reading;
158
+ // #769 P1-B: a frozen probe from a SIGKILLed claude (or a reused pid) would report
159
+ // a stale busy/shell forever. Verify the pid still belongs to the same process.
160
+ const live = opts.liveness ?? DEFAULT_LIVENESS;
161
+ if (reading.procStart) {
162
+ if (live.procStartOf(pid) !== reading.procStart) return { ...reading, status: "unknown", available: false };
163
+ } else if (!live.pidAlive(pid)) {
164
+ return { ...reading, status: "unknown", available: false };
165
+ }
166
+ return reading;
167
+ }
168
+
169
+ /**
170
+ * Resolve the claude pid for the session probe (#766/#768): a directly-spawned
171
+ * process exposes it; a tmux-managed (headless) claude is the pane's process —
172
+ * buildTmuxArgs runs `bash launcher.sh` whose launcher `exec`s claude, so the pane
173
+ * pid IS the claude pid (verified live: pane_pid → sessions/<pid>.json). undefined
174
+ * when neither is available, which routes the caller to the pane-scrape fallback.
175
+ */
176
+ export function resolveClaudePid(directPid: number | undefined, tmuxSession?: string, tmuxSocket?: string): number | undefined {
177
+ if (typeof directPid === "number" && directPid > 0) return directPid;
178
+ if (!tmuxSession) return undefined;
179
+ const result = Bun.spawnSync(tmuxCommand(tmuxSocket, "display-message", "-p", "-t", tmuxSession, "-F", "#{pane_pid}"), {
180
+ stdin: "ignore", stdout: "pipe", stderr: "ignore",
181
+ });
182
+ if (result.exitCode !== 0) return undefined;
183
+ const pid = Number.parseInt(result.stdout.toString().trim(), 10);
184
+ return Number.isFinite(pid) && pid > 0 ? pid : undefined;
185
+ }
186
+
187
+ /**
188
+ * Resolve the managed claude's config home + pid, then read the probe. The runner
189
+ * knows the config home (CLAUDE_CONFIG_DIR in the spawn env, or the host default)
190
+ * and the pid (direct or via the tmux pane). Returns the reading plus the resolved
191
+ * pid (for #650 liveness wiring), or undefined when the pid can't be resolved.
192
+ */
193
+ export function readManagedClaudeStatus(args: {
194
+ pid?: number;
195
+ tmuxSession?: string;
196
+ tmuxSocket?: string;
197
+ configHomeEnv?: string;
198
+ }): { reading: ClaudeSessionReading; pid: number } | undefined {
199
+ const pid = resolveClaudePid(args.pid, args.tmuxSession, args.tmuxSocket);
200
+ if (pid === undefined) return undefined;
201
+ const configHome = args.configHomeEnv || process.env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude");
202
+ return { reading: readClaudeSessionStatus(configHome, pid), pid };
203
+ }
204
+
205
+ /**
206
+ * Map the intrinsic probe status to the 3-valued activity. The whole point of #766:
207
+ * busy/shell → busy — shell is shelled-out/local-bash (a tool/gate is running);
208
+ * the old pane-scrape misread it as idle and force-cleared.
209
+ * idle → idle
210
+ * waiting → unknown — a permission/input dialog is a parked (not done) turn, so
211
+ * we neither assert compute-busy nor let the backstop clear
212
+ * the live turn. `waitingFor` is surfaced separately for
213
+ * permission/asking detection.
214
+ */
215
+ export function claudeProbeActivity(status: ClaudeProbeStatus): ClaudeProbeActivity {
216
+ switch (status) {
217
+ case "busy":
218
+ case "shell":
219
+ return "busy";
220
+ case "idle":
221
+ return "idle";
222
+ default:
223
+ return "unknown";
224
+ }
225
+ }