@desplega.ai/agent-swarm 1.145.0 → 1.147.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (221) hide show
  1. package/README.md +2 -1
  2. package/dist/{acp-adapter-580t41c0.js → acp-adapter-9n319wqc.js} +61 -6
  3. package/dist/{actions-m662tjng.js → actions-2vxqvpr9.js} +9 -8
  4. package/dist/{app-zb3rndm8.js → app-w066xfy0.js} +6 -5
  5. package/dist/assistant-kt31dj2h.js +236 -0
  6. package/dist/{boot-reembed-072x00vn.js → boot-reembed-az5rassp.js} +7 -6
  7. package/dist/{boot-reembed-65zz2smt.js → boot-reembed-j3mm3rfz.js} +8 -7
  8. package/dist/{boot-scrub-logs-yz0ams04.js → boot-scrub-logs-b6h54817.js} +4 -4
  9. package/dist/{claude-adapter-paj270y2.js → claude-adapter-w1z04ann.js} +8 -6
  10. package/dist/{claude-managed-setup-w619jncn.js → claude-managed-setup-f5pmsyrp.js} +24 -3
  11. package/dist/{claude-sdk-session-swt80j9z.js → claude-sdk-session-f0cc1kec.js} +8 -6
  12. package/dist/{cli-dt553ktb.js → cli-0b6y7kxm.js} +1 -1
  13. package/dist/{cli-bxdhw615.js → cli-12fz972k.js} +4 -4
  14. package/dist/{cli-s2f20r5w.js → cli-1th1728g.js} +2 -2
  15. package/dist/{cli-rs6ec3b9.js → cli-3tgwnf43.js} +3 -3
  16. package/dist/{cli-gxnzc6wh.js → cli-4nr988h6.js} +1 -1
  17. package/dist/{cli-axs8e6d4.js → cli-53s590z8.js} +1 -1
  18. package/dist/{cli-ygbjp3z8.js → cli-54wwve05.js} +5 -4
  19. package/dist/{cli-v0asr5yv.js → cli-719k9j2c.js} +2 -2
  20. package/dist/{cli-anktweqr.js → cli-89xfd7f9.js} +21 -47
  21. package/dist/{cli-q34a0e10.js → cli-8v0g1yc8.js} +1 -1
  22. package/dist/cli-9d8ntetj.js +42 -0
  23. package/dist/{cli-z9fprcrf.js → cli-atcve9y8.js} +881 -738
  24. package/dist/{cli-jmb7g47h.js → cli-b5bq9crk.js} +14 -31
  25. package/dist/cli-d8brzxjb.js +190 -0
  26. package/dist/{cli-gzky0gkr.js → cli-de14znh8.js} +2 -2
  27. package/dist/{cli-xytwff7f.js → cli-dttph1bw.js} +2 -2
  28. package/dist/cli-ep19k3mb.js +19 -0
  29. package/dist/{cli-m1xa8be7.js → cli-f146mn5s.js} +7 -50
  30. package/dist/{cli-1fj0chdk.js → cli-f7dsy61y.js} +5 -3
  31. package/dist/{cli-f567d5c1.js → cli-ftht3zzj.js} +2782 -2589
  32. package/dist/{cli-a0g1gbt5.js → cli-hbv0kq6w.js} +2 -2
  33. package/dist/{cli-fhsz3twr.js → cli-jsp14b6c.js} +171 -1
  34. package/dist/{cli-7fnkj1hj.js → cli-kpv03zhj.js} +21 -17
  35. package/dist/{cli-m4j6trn4.js → cli-m8yrsg97.js} +2 -2
  36. package/dist/cli-m9sxbkhm.js +779 -0
  37. package/dist/cli-mmemxxdc.js +823 -0
  38. package/dist/{cli-tqtvj5pt.js → cli-n8508nre.js} +1 -1
  39. package/dist/{cli-z96t0thj.js → cli-p1d5b073.js} +37 -2
  40. package/dist/{cli-gh8y8f36.js → cli-rw51bq3j.js} +13 -10
  41. package/dist/{cli-59ej1c07.js → cli-smby5m17.js} +7 -6
  42. package/dist/{cli-65vqzz3v.js → cli-tzvk9haz.js} +94 -372
  43. package/dist/{cli-dc9k2ba9.js → cli-w9kb3bk1.js} +1 -1
  44. package/dist/{cli-kpev657q.js → cli-y6b6fb76.js} +25 -3
  45. package/dist/{cli-123q2get.js → cli-yz3djrm0.js} +9 -9
  46. package/dist/{cli-wvp6bvy4.js → cli-zhjmqxzh.js} +1 -1
  47. package/dist/cli.js +13 -13
  48. package/dist/{codex-adapter-k98vaw2r.js → codex-adapter-zw4dwsx7.js} +2 -2
  49. package/dist/{codex-hook-9pf19cks.js → codex-hook-bw8p5nh4.js} +2 -2
  50. package/dist/{codex-session-runner-tngtphx7.js → codex-session-runner-k981s65v.js} +2 -2
  51. package/dist/{commands-y8nbr3fv.js → commands-sykrxx7e.js} +4 -4
  52. package/dist/{db-30p4h2t1.js → db-sfbsc8wt.js} +6 -4
  53. package/dist/handlers-0aspcejm.js +603 -0
  54. package/dist/{hook-dcw4jfbj.js → hook-4nvqj2sb.js} +7 -5
  55. package/dist/{hook-21jexvfx.js → hook-hxccs7m5.js} +24 -49
  56. package/dist/{http-r4kq5g8d.js → http-y06z517d.js} +230 -94
  57. package/dist/{index-q3qja6ta.js → index-hssww7kj.js} +15 -14
  58. package/dist/{index-gay66b9w.js → index-k8znfx0z.js} +13 -12
  59. package/dist/{index-53zyht4z.js → index-tce1rss4.js} +371 -110
  60. package/dist/{index-nqvf26za.js → index-x5j894zf.js} +14 -13
  61. package/dist/{keepalive-xs8fa55y.js → keepalive-w733ax66.js} +6 -6
  62. package/dist/{lead-d9m2t4s0.js → lead-75bjqa9d.js} +29 -27
  63. package/dist/{maintenance-3zh82g6z.js → maintenance-w4f1zjck.js} +8 -7
  64. package/dist/{oauth-refresh-sweep-03snsye5.js → oauth-refresh-sweep-wdetky26.js} +5 -5
  65. package/dist/{onboard-0cg1925x.js → onboard-bb5net8s.js} +2 -2
  66. package/dist/{otel-impl-0ab95z27.js → otel-impl-0w7c14ap.js} +1 -1
  67. package/dist/{pi-mono-adapter-dtkz4e7j.js → pi-mono-adapter-2has4gnp.js} +12 -2
  68. package/dist/{pricing-refresh-e5jhzz4j.js → pricing-refresh-9nzsrgcq.js} +6 -6
  69. package/dist/{rbac-roles-p1mf40z3.js → rbac-roles-r3hqjp09.js} +5 -5
  70. package/dist/{rbac-roles-2w3cmrkc.js → rbac-roles-z1jrffbt.js} +4 -4
  71. package/dist/{registry-9kdck5ye.js → registry-v5wytg0s.js} +1 -2
  72. package/dist/{render-v2-xhawry3k.js → render-v2-vbr89fnb.js} +6 -5
  73. package/dist/{seed-pricing-t223sw91.js → seed-pricing-g62hy1pk.js} +7 -5
  74. package/dist/{setup-zcs0rce7.js → setup-gnfqnptp.js} +2 -2
  75. package/dist/{worker-qnp2ka62.js → worker-kznxp4qm.js} +29 -27
  76. package/openapi.json +263 -12
  77. package/package.json +1 -1
  78. package/plugin/commands/start-worker.md +4 -9
  79. package/plugin/pi-skills/start-worker/SKILL.md +4 -9
  80. package/src/be/db/agents.ts +556 -0
  81. package/src/be/db/context-versions.ts +117 -0
  82. package/src/be/db/runtime.ts +406 -0
  83. package/src/be/db/tasks/read.ts +1167 -0
  84. package/src/be/db/tasks/write.ts +953 -0
  85. package/src/be/db.ts +584 -3429
  86. package/src/be/migrations/147_scheduled_tasks_parent_task.sql +7 -0
  87. package/src/be/migrations/148_pages_svg.sql +123 -0
  88. package/src/be/migrations/149_session_tokens.sql +24 -0
  89. package/src/be/scripts/typecheck.ts +1 -0
  90. package/src/be/seed-pricing.ts +13 -8
  91. package/src/be/seed-scripts/catalog/ops-catalog-audit.inline.ts +1 -1
  92. package/src/be/seed-scripts/catalog/ops-catalog-audit.ts +1 -1
  93. package/src/be/seed-scripts/catalog/star-history-refresh.ts +101 -0
  94. package/src/be/seed-scripts/catalog/star-history-renderer.ts +119 -0
  95. package/src/be/seed-scripts/index.ts +17 -0
  96. package/src/be/seed-skills/index.ts +14 -0
  97. package/src/be/swarm-config-guard.ts +5 -2
  98. package/src/be/task-attachment-store.ts +70 -0
  99. package/src/be/users.ts +77 -0
  100. package/src/commands/attachments-section.ts +37 -0
  101. package/src/commands/claude-managed-setup.ts +45 -3
  102. package/src/commands/claude-md-session.ts +408 -0
  103. package/src/commands/context-preamble.ts +15 -3
  104. package/src/commands/profile-sync.ts +205 -5
  105. package/src/commands/provider-credentials.ts +60 -27
  106. package/src/commands/runner.ts +63 -58
  107. package/src/commands/templates.ts +25 -2
  108. package/src/hooks/hook.ts +26 -67
  109. package/src/http/agents.ts +40 -1
  110. package/src/http/auth.ts +13 -1
  111. package/src/http/fs.ts +21 -51
  112. package/src/http/index.ts +2 -0
  113. package/src/http/mcp.ts +32 -0
  114. package/src/http/pages-public.ts +20 -4
  115. package/src/http/pages.ts +11 -3
  116. package/src/http/poll.ts +4 -0
  117. package/src/http/repos.ts +3 -3
  118. package/src/http/sessions.ts +82 -0
  119. package/src/http/tasks.ts +10 -2
  120. package/src/http/utils.ts +79 -1
  121. package/src/prompts/session-templates.ts +12 -8
  122. package/src/providers/acp-adapter.ts +62 -8
  123. package/src/providers/pi-mono-adapter.ts +23 -6
  124. package/src/providers/pricing-sources.md +11 -0
  125. package/src/scheduler/scheduler.test.ts +49 -2
  126. package/src/scheduler/scheduler.ts +4 -0
  127. package/src/scripts-runtime/sdk-allowlist.ts +1 -0
  128. package/src/scripts-runtime/types/stdlib.d.ts +8 -0
  129. package/src/scripts-runtime/types/swarm-sdk.d.ts +8 -0
  130. package/src/server.ts +2 -0
  131. package/src/slack/assistant.ts +87 -46
  132. package/src/slack/handlers.test.ts +1 -3
  133. package/src/slack/handlers.ts +102 -87
  134. package/src/slack/inbound-files.ts +466 -0
  135. package/src/slack/templates.ts +14 -0
  136. package/src/tasks/task-terminal-effects.ts +158 -0
  137. package/src/tests/acp-adapter.test.ts +369 -117
  138. package/src/tests/budget-claim-gate.test.ts +1 -0
  139. package/src/tests/build-pi-skills.test.ts +5 -7
  140. package/src/tests/claude-managed-setup.test.ts +52 -4
  141. package/src/tests/claude-md-session.test.ts +603 -0
  142. package/src/tests/codex-skill-resolver.test.ts +19 -0
  143. package/src/tests/context-versioning.test.ts +107 -0
  144. package/src/tests/cors-allowlist.test.ts +309 -0
  145. package/src/tests/credential-check.test.ts +157 -14
  146. package/src/tests/db-agents.test.ts +91 -0
  147. package/src/tests/db-context-versions.test.ts +37 -0
  148. package/src/tests/db-extraction-contract.test.ts +45 -0
  149. package/src/tests/db-runtime.test.ts +70 -0
  150. package/src/tests/db-task-read-contract.test.ts +624 -0
  151. package/src/tests/db-task-write-contract.test.ts +653 -0
  152. package/src/tests/db-tasks-read.test.ts +183 -0
  153. package/src/tests/db-tasks-write.test.ts +230 -0
  154. package/src/tests/defer-task.test.ts +389 -0
  155. package/src/tests/docs-index-footprint.test.js +2 -2
  156. package/src/tests/e2e-visuals-stage.test.ts +151 -0
  157. package/src/tests/file-lock.test.ts +144 -0
  158. package/src/tests/fixtures/file-lock-holder.ts +13 -0
  159. package/src/tests/fixtures/hold-file-lock.ts +25 -0
  160. package/src/tests/heartbeat-expiry.test.ts +188 -0
  161. package/src/tests/http-api-integration.test.ts +78 -1
  162. package/src/tests/pages-public-html.test.ts +43 -0
  163. package/src/tests/pages-svg-migration.test.ts +42 -0
  164. package/src/tests/preload.ts +4 -1
  165. package/src/tests/profile-sync-warning.test.ts +16 -0
  166. package/src/tests/profile-sync.test.ts +126 -0
  167. package/src/tests/prompt-template-session.test.ts +20 -4
  168. package/src/tests/provider-registration.test.ts +93 -0
  169. package/src/tests/rbac-e2e-helpers.test.ts +53 -0
  170. package/src/tests/rbac-e2e-helpers.ts +19 -2
  171. package/src/tests/reload-config.test.ts +26 -0
  172. package/src/tests/routing-affinity-inventory.test.ts +1 -1
  173. package/src/tests/runner-attachments-section.test.ts +22 -2
  174. package/src/tests/runner-context-preamble.test.ts +30 -0
  175. package/src/tests/runner-deployment-resume.test.ts +107 -0
  176. package/src/tests/runner-repo-autostash.test.ts +12 -0
  177. package/src/tests/script-connections.test.ts +4 -0
  178. package/src/tests/seed-scripts.test.ts +2 -2
  179. package/src/tests/session-tokens.test.ts +279 -0
  180. package/src/tests/slack-file-tools-attachments.test.ts +408 -0
  181. package/src/tests/slack-inbound-files.test.ts +847 -0
  182. package/src/tests/star-history-refresh.test.ts +102 -0
  183. package/src/tests/swarm-config-reserved-keys.test.ts +21 -0
  184. package/src/tests/swarm-repos.test.ts +20 -0
  185. package/src/tests/tool-annotations.test.ts +4 -3
  186. package/src/tests/ui-logs-parser.test.ts +176 -0
  187. package/src/tools/create-page.ts +4 -2
  188. package/src/tools/defer-task.ts +239 -0
  189. package/src/tools/repos/update-repo.ts +2 -2
  190. package/src/tools/schedules/create-schedule.ts +1 -0
  191. package/src/tools/schedules/list-schedules.ts +1 -0
  192. package/src/tools/schedules/patch-schedule.ts +1 -0
  193. package/src/tools/schedules/update-schedule.ts +1 -0
  194. package/src/tools/slack-download-file.ts +60 -29
  195. package/src/tools/slack-read.ts +73 -32
  196. package/src/tools/store-progress.ts +16 -146
  197. package/src/tools/tool-config.ts +1 -0
  198. package/src/tools/utils.ts +21 -0
  199. package/src/types.ts +37 -4
  200. package/src/utils/acp-session-token.ts +56 -0
  201. package/src/utils/file-lock.ts +111 -0
  202. package/src/utils/heartbeat-expiry.ts +78 -0
  203. package/src/utils/request-auth-context.ts +2 -0
  204. package/src/utils/task-attachment-links.ts +22 -0
  205. package/templates/skills/code-quality/content.md +8 -5
  206. package/templates/skills/download-task-attachment/content.md +2 -1
  207. package/{plugin/pi-skills → templates/skills}/review-offered-task/SKILL.md +5 -5
  208. package/templates/skills/review-offered-task/config.json +14 -0
  209. package/{plugin/commands/review-offered-task.md → templates/skills/review-offered-task/content.md} +3 -8
  210. package/templates/skills/scheduling/content.md +4 -0
  211. package/templates/skills/slack-interaction/content.md +2 -2
  212. package/templates/skills/work-on-task/SKILL.md +16 -0
  213. package/templates/skills/work-on-task/config.json +14 -0
  214. package/templates/skills/work-on-task/content.md +11 -0
  215. package/dist/assistant-0qt42nzg.js +0 -212
  216. package/dist/cli-fs1kkqgr.js +0 -317
  217. package/dist/cli-jnf5zghe.js +0 -269
  218. package/dist/cli-n1q8q14d.js +0 -177
  219. package/dist/handlers-yfp1qn81.js +0 -592
  220. package/plugin/commands/work-on-task.md +0 -39
  221. package/plugin/pi-skills/work-on-task/SKILL.md +0 -39
@@ -28,13 +28,15 @@
28
28
  */
29
29
 
30
30
  import { resolveTemplateAsync } from "../prompts/resolver.ts";
31
- import type { Agent, SwarmEvent } from "../types.ts";
31
+ import type { Agent, ProfileExpectedHashes, SwarmEvent } from "../types.ts";
32
32
  import { MAX_PROFILE_FILE_LENGTH } from "../utils/constants.ts";
33
+ import { withFileLock } from "../utils/file-lock.ts";
33
34
  import {
34
35
  type BudgetedIdentityField,
35
36
  IDENTITY_FIELD_BUDGETS,
36
37
  } from "../utils/identity-field-budget.ts";
37
38
  import { scrubSecrets } from "../utils/secret-scrubber.ts";
39
+ import { prependContextPreamble } from "./context-preamble.ts";
38
40
  import "./templates.ts";
39
41
 
40
42
  export const SOUL_MD_PATH = "/workspace/SOUL.md";
@@ -277,7 +279,9 @@ export async function prependProfileSyncRejectionBanner(
277
279
  readFile: FileReader = readFileIfExists,
278
280
  ): Promise<{ prompt: string; injected: boolean }> {
279
281
  const banner = await fetchProfileSyncRejectionBanner(config, fetchImpl, readFile);
280
- return banner ? { prompt: banner + prompt, injected: true } : { prompt, injected: false };
282
+ return banner
283
+ ? { prompt: prependContextPreamble(prompt, banner), injected: true }
284
+ : { prompt, injected: false };
281
285
  }
282
286
 
283
287
  export async function writeIdentityBaselines(baselines: IdentityBaselines): Promise<void> {
@@ -295,12 +299,159 @@ export async function readIdentityBaselines(
295
299
  return null;
296
300
  }
297
301
  }
302
+
298
303
  /**
299
304
  * Claude Code's personal-file CLAUDE.md path. This is what the Claude plugin
300
305
  * Stop hook reads and owns — the runner only uses it as a backstop for an
301
306
  * all-Claude batch (never overwriting it with the workspace materialization).
302
307
  */
303
308
  export const CLAUDE_MD_PATH = `${process.env.HOME}/.claude/CLAUDE.md`;
309
+ /**
310
+ * Lineage record of the LAST content the Claude hook wrote to CLAUDE_MD_PATH (a
311
+ * SessionStart materialization or a Stop `.bak` restore). Maintained by
312
+ * `claude-md-session.ts`; also read by the runner's backstop below. It lives next
313
+ * to the file it describes: same owner, same scope (one per `~/.claude`), and not
314
+ * in a world-writable directory where another user could plant a symlink.
315
+ */
316
+ export const CLAUDE_MD_LINEAGE_PATH = `${CLAUDE_MD_PATH}.lineage.json`;
317
+ /**
318
+ * Lock serializing every multi-file transition of CLAUDE_MD_PATH + its lineage
319
+ * record across processes (hook SessionStart/Stop and the runner backstop).
320
+ */
321
+ export const CLAUDE_MD_LOCK_PATH = `${CLAUDE_MD_PATH}.lock`;
322
+ /**
323
+ * Every holder of CLAUDE_MD_LOCK_PATH bounds its network call by this, so other
324
+ * processes waiting for the lock (within the 60 s Claude Code hook timeout) are
325
+ * not held up by a hung request.
326
+ */
327
+ export const CLAUDE_MD_SYNC_TIMEOUT_MS = 10_000;
328
+ /** The runner backstop is best effort: it waits briefly, then skips this round. */
329
+ const RUNNER_LOCK_WAIT_MS = 15_000;
330
+
331
+ /** `fetch` bounded by CLAUDE_MD_SYNC_TIMEOUT_MS, for calls made while holding the lock. */
332
+ export function fetchWithSyncTimeout(fetchImpl: typeof fetch = fetch): typeof fetch {
333
+ return ((input, init) =>
334
+ fetchImpl(input, {
335
+ ...init,
336
+ signal: AbortSignal.timeout(CLAUDE_MD_SYNC_TIMEOUT_MS),
337
+ })) as typeof fetch;
338
+ }
339
+
340
+ /**
341
+ * Whether a CLAUDE.md sync reads the Claude hook's personal file (and so must
342
+ * follow its lineage, under its lock) rather than an unconditional source.
343
+ */
344
+ export function syncsHookOwnedClaudeMd(
345
+ claudeMdPath: string,
346
+ changeSource: ProfileChangeSource,
347
+ ): boolean {
348
+ return claudeMdPath === CLAUDE_MD_PATH && changeSource === "session_sync";
349
+ }
350
+
351
+ /** Where the content of CLAUDE_MD_PATH came from; see `claude-md-session.ts`. */
352
+ export interface ClaudeMdLineage {
353
+ /** Hash of the content a hook wrote, or null if it restored an agent's edit. */
354
+ written: string | null;
355
+ /** Hash of the DB value that content derives from, or null if unknown. */
356
+ base: string | null;
357
+ }
358
+
359
+ const SHA256_HEX = /^[0-9a-f]{64}$/;
360
+
361
+ /**
362
+ * Parse a lineage record; null for anything that is not exactly that shape —
363
+ * both keys present, each a lowercase sha256 hex or null.
364
+ */
365
+ export function parseClaudeMdLineage(raw: string | undefined): ClaudeMdLineage | null {
366
+ if (!raw) return null;
367
+ let value: unknown;
368
+ try {
369
+ value = JSON.parse(raw);
370
+ } catch {
371
+ return null;
372
+ }
373
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
374
+ const { written, base } = value as Record<string, unknown>;
375
+ const hashOrNull = (v: unknown) => v === null || (typeof v === "string" && SHA256_HEX.test(v));
376
+ if (!("written" in value) || !("base" in value) || !hashOrNull(written) || !hashOrNull(base)) {
377
+ return null;
378
+ }
379
+ return { written: written as string | null, base: base as string | null };
380
+ }
381
+
382
+ /**
383
+ * What the record holds while a hook write is in flight: marked before the file
384
+ * is touched, replaced by the real lineage after. It names the content being
385
+ * written but is no lineage (it has no base), so whatever the file holds counts
386
+ * as hook-written and is never pushed (see `effectiveClaudeMdLineage`) — also
387
+ * when the real lineage never lands.
388
+ */
389
+ export function claudeMdPendingRecord(written: string): string {
390
+ return JSON.stringify({ pending: true, written });
391
+ }
392
+
393
+ /** The hash a pending record says a hook was writing; null for any other record. */
394
+ export function parseClaudeMdPendingRecord(raw: string | undefined): string | null {
395
+ if (!raw) return null;
396
+ try {
397
+ const value = JSON.parse(raw) as { pending?: unknown; written?: unknown } | null;
398
+ const written = value?.pending === true ? value.written : undefined;
399
+ return typeof written === "string" && SHA256_HEX.test(written) ? written : null;
400
+ } catch {
401
+ return null;
402
+ }
403
+ }
404
+
405
+ /** Lineage of content whose origin is unknown: counts as hook-written, never pushed. */
406
+ export function hookWrittenLineage(content: string): ClaudeMdLineage {
407
+ return { written: contentSha256(content), base: null };
408
+ }
409
+
410
+ /**
411
+ * The lineage to decide on, from the raw record file: absent → null (no lineage
412
+ * yet, the previous behaviour); present but unreadable or malformed → the content
413
+ * counts as hook-written, so a bad record never turns into an unconditional push.
414
+ */
415
+ export function effectiveClaudeMdLineage(
416
+ raw: string | undefined,
417
+ content: string,
418
+ ): ClaudeMdLineage | null {
419
+ if (raw === undefined) return null;
420
+ return parseClaudeMdLineage(raw) ?? hookWrittenLineage(content);
421
+ }
422
+
423
+ /**
424
+ * Lineage of content found on disk, given the last record: the hook's own write
425
+ * inherits the record; anything else is an edit on top of the record's base.
426
+ */
427
+ export function claudeMdLineageOf(
428
+ content: string,
429
+ record: ClaudeMdLineage | null,
430
+ ): ClaudeMdLineage {
431
+ if (record && record.written === contentSha256(content)) return record;
432
+ return { written: null, base: record?.base ?? null };
433
+ }
434
+
435
+ /**
436
+ * The CLAUDE.md `session_sync` body, or null to skip:
437
+ * - no record at all → the previous unconditional sync;
438
+ * - content a hook wrote, or equal to its own base → skip: not an edit;
439
+ * - otherwise an edit → sent with its base as `expectedHashes.claudeMd`
440
+ * (unconditional only if that base is unknown).
441
+ */
442
+ export function planClaudeMdSync(state: {
443
+ content: string;
444
+ record: ClaudeMdLineage | null;
445
+ }): ProfilePayload["body"] | null {
446
+ const { content, record } = state;
447
+ if (!content.trim()) return null;
448
+ if (record === null) return { claudeMd: content, changeSource: "session_sync" };
449
+
450
+ const { written, base } = claudeMdLineageOf(content, record);
451
+ if (written !== null || contentSha256(content) === base) return null;
452
+ if (base === null) return { claudeMd: content, changeSource: "session_sync" };
453
+ return { claudeMd: content, changeSource: "session_sync", expectedHashes: { claudeMd: base } };
454
+ }
304
455
  /**
305
456
  * Workspace CLAUDE.md — the agent-level instructions file the runner
306
457
  * materializes from the `claudeMd` DB field at boot (`runner.ts`) and that the
@@ -371,6 +522,8 @@ export interface ProfileSyncOptions {
371
522
  * `resolveClaudeMdPath`.
372
523
  */
373
524
  claudeMdPath?: string;
525
+ /** Lock for the personal-file CLAUDE.md sync (tests); defaults to CLAUDE_MD_LOCK_PATH. */
526
+ claudeMdLock?: { path?: string; waitMs?: number };
374
527
  /** Injectable fetch for tests. Defaults to the global `fetch`. */
375
528
  fetchImpl?: typeof fetch;
376
529
  }
@@ -394,7 +547,8 @@ export function resolveClaudeMdPath(completedProviders: readonly string[]): stri
394
547
  /** A single profile-update POST body, tagged with a label for logging. */
395
548
  export interface ProfilePayload {
396
549
  label: string;
397
- body: Record<string, string>;
550
+ /** Field values are strings; `expectedHashes` (compare-and-set) is an object. */
551
+ body: Record<string, string | ProfileExpectedHashes>;
398
552
  }
399
553
 
400
554
  /**
@@ -615,6 +769,15 @@ export async function collectProfilePayloads(
615
769
  if (raw?.trim()) {
616
770
  if (baselines?.claudeMd && contentSha256(raw) === baselines.claudeMd) {
617
771
  // CLAUDE.md unchanged during session — skip to preserve Lead's DB edits
772
+ } else if (syncsHookOwnedClaudeMd(claudeMdPath, changeSource)) {
773
+ // The personal file is owned by the Claude hook, which keeps its lineage:
774
+ // skip what a hook wrote, send an edit against the base it derives from.
775
+ // Without a record the only base the runner knows is its boot baseline.
776
+ const record =
777
+ effectiveClaudeMdLineage(await readFile(CLAUDE_MD_LINEAGE_PATH), raw) ??
778
+ (baselines?.claudeMd ? { written: null, base: baselines.claudeMd } : null);
779
+ const body = planClaudeMdSync({ content: raw, record });
780
+ if (body) payloads.push({ label: "claude", body });
618
781
  } else {
619
782
  payloads.push({ label: "claude", body: { claudeMd: raw, changeSource } });
620
783
  }
@@ -686,14 +849,51 @@ export async function syncProfileFilesToServer(opts: ProfileSyncOptions): Promis
686
849
  const changeSource = opts.changeSource ?? "session_sync";
687
850
  const fields = opts.fields ?? ["identity", "claude", "setup"];
688
851
 
852
+ const claudeMdPath = opts.claudeMdPath ?? CLAUDE_MD_PATH;
853
+ // The personal file is rewritten together with its lineage record by the
854
+ // Claude hook; reading the pair mid-transition can misjudge a restored copy as
855
+ // an edit. So that group is read and posted under the same lock the hook holds.
856
+ const claudeUnderLock =
857
+ fields.includes("claude") && syncsHookOwnedClaudeMd(claudeMdPath, changeSource);
858
+ const unlockedFields = claudeUnderLock ? fields.filter((f) => f !== "claude") : fields;
859
+
689
860
  const payloads = await collectProfilePayloads(
690
- fields,
861
+ unlockedFields,
691
862
  changeSource,
692
863
  readFileIfExists,
693
- opts.claudeMdPath ?? CLAUDE_MD_PATH,
864
+ claudeMdPath,
694
865
  opts.agentId,
695
866
  );
696
867
  for (const payload of payloads) {
697
868
  await postProfileUpdate(opts, payload);
698
869
  }
870
+
871
+ if (claudeUnderLock) {
872
+ const { path: lockPath = CLAUDE_MD_LOCK_PATH, waitMs = RUNNER_LOCK_WAIT_MS } =
873
+ opts.claudeMdLock ?? {};
874
+ const bounded = { ...opts, fetchImpl: fetchWithSyncTimeout(opts.fetchImpl) };
875
+ const locked = await withFileLock(
876
+ lockPath,
877
+ async () => {
878
+ const claude = await collectProfilePayloads(
879
+ ["claude"],
880
+ changeSource,
881
+ readFileIfExists,
882
+ claudeMdPath,
883
+ opts.agentId,
884
+ );
885
+ for (const payload of claude) await postProfileUpdate(bounded, payload);
886
+ },
887
+ { waitMs },
888
+ );
889
+ // Never read or push the hook-owned file without the lock.
890
+ if (!locked.acquired) {
891
+ const detail = locked.error === undefined ? "" : `: ${String(locked.error)}`;
892
+ console.warn(
893
+ scrubSecrets(
894
+ `[profile-sync] no CLAUDE.md lock (${locked.reason})${detail} — backstop sync skipped`,
895
+ ),
896
+ );
897
+ }
898
+ }
699
899
  }
@@ -44,20 +44,45 @@ export type SupportedProvider =
44
44
  | "acp";
45
45
 
46
46
  /**
47
- * True when the pi harness should use the AWS SDK Bedrock path: either an
48
- * explicit `BEDROCK_AUTH_MODE=sdk`, or — preserving prefix-inference semantics —
47
+ * True when the pi harness authenticates against Bedrock rather than a provider
48
+ * API key: an explicit `BEDROCK_AUTH_MODE=sdk` (AWS credential chain), an
49
+ * explicit `BEDROCK_AUTH_MODE=bearer` (Bedrock API key in
50
+ * `AWS_BEARER_TOKEN_BEDROCK`), or — preserving prefix-inference semantics —
49
51
  * `BEDROCK_AUTH_MODE` absent with a `MODEL_OVERRIDE=amazon-bedrock/*` selection.
50
52
  * Single source of truth for the gate so the live-test arm and the worker
51
- * reconcile loop agree with `checkPiMonoCredentials`.
53
+ * reconcile loop agree with `checkPiMonoCredentials`, which owns the per-mode
54
+ * readiness rules (what must be present, how readiness is reported).
52
55
  */
53
- export function isBedrockSdkMode(env: Record<string, string | undefined>): boolean {
56
+ export function isBedrockMode(env: Record<string, string | undefined>): boolean {
54
57
  const mode = env.BEDROCK_AUTH_MODE?.toLowerCase();
55
58
  return (
56
59
  mode === "sdk" ||
60
+ mode === "bearer" ||
57
61
  (mode === undefined && Boolean(env.MODEL_OVERRIDE?.toLowerCase().startsWith("amazon-bedrock/")))
58
62
  );
59
63
  }
60
64
 
65
+ /**
66
+ * Scheduling decision for the runner's post-task Bedrock enumeration refresh
67
+ * (see the throttled branch in `runner.ts`). Kept pure so the gate can be
68
+ * exercised without spinning the runner: it fires for the pi harness in any
69
+ * Bedrock mode (`sdk`, `bearer`, or the `MODEL_OVERRIDE=amazon-bedrock/*`
70
+ * inference) once `intervalMs` has elapsed since the last refresh.
71
+ */
72
+ export function shouldRefreshBedrockStatus(opts: {
73
+ harnessProvider: string | null | undefined;
74
+ env: Record<string, string | undefined>;
75
+ lastRefreshAt: number;
76
+ now: number;
77
+ intervalMs: number;
78
+ }): boolean {
79
+ return (
80
+ opts.harnessProvider === "pi" &&
81
+ isBedrockMode(opts.env) &&
82
+ opts.now - opts.lastRefreshAt > opts.intervalMs
83
+ );
84
+ }
85
+
61
86
  /**
62
87
  * Static documentation of which env vars each provider considers when running
63
88
  * `checkCredentials`. Used by the dashboard to render hints before any worker
@@ -82,6 +107,25 @@ export const REQUIRED_CRED_VARS_BY_PROVIDER: Record<SupportedProvider, readonly
82
107
  acp: [],
83
108
  };
84
109
 
110
+ type CredentialChecker = (
111
+ env: Record<string, string | undefined>,
112
+ opts?: CredCheckOptions,
113
+ ) => CredStatus | Promise<CredStatus>;
114
+
115
+ /** The handlers used by the credential-readiness dispatcher. */
116
+ export const CREDENTIAL_PROVIDER_CHECKERS: Record<SupportedProvider, CredentialChecker> = {
117
+ claude: (env) => checkClaudeCredentials(env),
118
+ "claude-managed": (env) => checkClaudeManagedCredentials(env),
119
+ codex: (env, opts) => checkCodexCredentials(env, opts),
120
+ devin: (env) => checkDevinCredentials(env),
121
+ opencode: (env, opts) => checkOpencodeCredentials(env, opts),
122
+ pi: async (env, opts) => {
123
+ const { checkPiMonoCredentials } = await import("../providers/pi-mono-adapter");
124
+ return checkPiMonoCredentials(env, opts);
125
+ },
126
+ acp: () => ({ ready: true, missing: [], satisfiedBy: "sdk-delegated" }),
127
+ };
128
+
85
129
  /**
86
130
  * Run the predicate for `provider`. Unknown providers throw — call sites
87
131
  * should treat that as a configuration bug, not a user-correctable state.
@@ -95,28 +139,17 @@ export async function checkProviderCredentials(
95
139
  env: Record<string, string | undefined>,
96
140
  opts?: CredCheckOptions,
97
141
  ): Promise<CredStatus> {
98
- switch (provider) {
99
- case "claude":
100
- return checkClaudeCredentials(env);
101
- case "claude-managed":
102
- return checkClaudeManagedCredentials(env);
103
- case "codex":
104
- return checkCodexCredentials(env, opts);
105
- case "devin":
106
- return checkDevinCredentials(env);
107
- case "opencode":
108
- return checkOpencodeCredentials(env, opts);
109
- case "pi": {
110
- const { checkPiMonoCredentials } = await import("../providers/pi-mono-adapter");
111
- return checkPiMonoCredentials(env, opts);
112
- }
113
- case "acp":
114
- return { ready: true, missing: [], satisfiedBy: "sdk-delegated" };
115
- default:
116
- throw new Error(
117
- `checkProviderCredentials: unknown provider "${provider}". Supported: claude, claude-managed, codex, devin, opencode, pi, acp.`,
118
- );
142
+ const checker = (CREDENTIAL_PROVIDER_CHECKERS as Record<string, CredentialChecker | undefined>)[
143
+ provider
144
+ ];
145
+ if (!checker) {
146
+ throw new Error(
147
+ `checkProviderCredentials: unknown provider "${provider}". Supported: ${Object.keys(
148
+ CREDENTIAL_PROVIDER_CHECKERS,
149
+ ).join(", ")}.`,
150
+ );
119
151
  }
152
+ return checker(env, opts);
120
153
  }
121
154
 
122
155
  // ─── Live "Test connection" dispatcher ───────────────────────────────────────
@@ -336,14 +369,14 @@ export async function validateProviderCredentials(provider: string): Promise<Liv
336
369
  }
337
370
  case "pi":
338
371
  case "opencode": {
339
- // For the pi Bedrock path, the real credential check is the AWS SDK
372
+ // For the pi Bedrock path (sdk or bearer), the real credential check is the AWS SDK
340
373
  // enumeration (`ListFoundationModels` + `ListInferenceProfiles`) that
341
374
  // `checkProviderCredentials` (the `pi` dynamic-import arm) already ran.
342
375
  // That result is already in `buildCredStatusReport` — the live-test is a
343
376
  // pass-through / no-op so we never issue a second AWS SDK call here
344
377
  // (which would drag the SDK into the wrong binary or make slow IMDS
345
378
  // calls on non-EC2 hosts).
346
- if (provider === "pi" && isBedrockSdkMode(env)) {
379
+ if (provider === "pi" && isBedrockMode(env)) {
347
380
  return presenceCheckOk();
348
381
  }
349
382
  // Both pi-mono and opencode resolve credentials in the same order:
@@ -65,7 +65,12 @@ import { isSteeringEnabled } from "../utils/steering-enabled.ts";
65
65
  import { interpolate } from "../utils/template.ts";
66
66
  import { detectVcsProvider } from "../vcs/index.ts";
67
67
  import { validateJsonSchema } from "../workflows/json-schema-validator.ts";
68
- import { buildContextPreamble, buildResumeContextPreamble } from "./context-preamble.ts";
68
+ import { buildAttachmentsSection } from "./attachments-section.ts";
69
+ import {
70
+ buildContextPreamble,
71
+ buildResumeContextPreamble,
72
+ prependContextPreamble,
73
+ } from "./context-preamble.ts";
69
74
  import {
70
75
  awaitCredentials,
71
76
  BootMaxWaitExceededError,
@@ -84,12 +89,12 @@ import {
84
89
  import {
85
90
  buildCredStatusReport,
86
91
  buildLatestModelReport,
87
- isBedrockSdkMode,
88
92
  isCredCheckDisabled,
89
93
  reportAcpStatus,
90
94
  reportCredStatus,
91
95
  reportLatestModel,
92
96
  sendCredStatusReport,
97
+ shouldRefreshBedrockStatus,
93
98
  } from "./provider-credentials.ts";
94
99
  import {
95
100
  type ResumeSessionCandidate,
@@ -99,6 +104,8 @@ import {
99
104
  // Side-effect import: registers runner trigger/resumption templates
100
105
  import "./templates.ts";
101
106
 
107
+ export { buildAttachmentsSection } from "./attachments-section.ts";
108
+
102
109
  /** Throttle interval for progress updates (3 seconds). */
103
110
  const PROGRESS_THROTTLE_MS = 3000;
104
111
 
@@ -249,6 +256,9 @@ async function listSwarmAutostashes(clonePath: string, role: string): Promise<Sw
249
256
  * src/tasks/worker-follow-up.ts after a task completes/fails or needs
250
257
  * re-delegation; they inherit the parent's vcsRepo/branch context via
251
258
  * createTaskExtended's parentTaskId inheritance (src/be/db.ts).
259
+ * - "deferred": the wake-up task a `defer-task` schedule creates
260
+ * (src/tools/defer-task.ts) — it carries the deferred task as its
261
+ * `parentTaskId` and resumes that work on the same clone.
252
262
  * - "agentmail-reply": AgentMail follow-up on an EXISTING thread
253
263
  * (src/agentmail/handlers.ts) — always carries `parentTaskId` pointing at
254
264
  * the task it's continuing (as opposed to "agentmail-message", which fires
@@ -260,6 +270,10 @@ async function listSwarmAutostashes(clonePath: string, role: string): Promise<Sw
260
270
  */
261
271
  const CONTINUATION_TASK_TYPES = new Set([
262
272
  "resume",
273
+ // "deferred": a `defer-task` wake-up continues the parent's work on the same
274
+ // clone. The parent is already `completed`, so the parent-status check alone
275
+ // would read this as a first kickoff and hard-reset the clone.
276
+ "deferred",
263
277
  "follow-up",
264
278
  "reroute-decision",
265
279
  "agentmail-reply",
@@ -2004,11 +2018,13 @@ async function pauseTaskViaAPI(config: ApiConfig, role: string, taskId: string):
2004
2018
  }
2005
2019
 
2006
2020
  /** Fetch paused tasks from API for this agent */
2007
- async function getPausedTasksFromAPI(config: ApiConfig): Promise<
2021
+ export async function getPausedTasksFromAPI(config: ApiConfig): Promise<
2008
2022
  Array<{
2009
2023
  id: string;
2010
2024
  task: string;
2011
2025
  progress?: string;
2026
+ attachments?: unknown[];
2027
+ outputSchema?: Record<string, unknown>;
2012
2028
  claudeSessionId?: string;
2013
2029
  provider?: ProviderName;
2014
2030
  providerMeta?: Record<string, unknown>;
@@ -2044,6 +2060,8 @@ async function getPausedTasksFromAPI(config: ApiConfig): Promise<
2044
2060
  id: string;
2045
2061
  task: string;
2046
2062
  progress?: string;
2063
+ attachments?: unknown[];
2064
+ outputSchema?: Record<string, unknown>;
2047
2065
  claudeSessionId?: string;
2048
2066
  provider?: ProviderName;
2049
2067
  providerMeta?: Record<string, unknown>;
@@ -2085,20 +2103,26 @@ async function resumeTaskViaAPI(config: ApiConfig, taskId: string): Promise<bool
2085
2103
  }
2086
2104
 
2087
2105
  /** Build prompt for a resumed task */
2088
- async function buildResumePrompt(
2089
- task: { id: string; task: string; progress?: string },
2106
+ export async function buildResumePrompt(
2107
+ task: {
2108
+ id: string;
2109
+ task: string;
2110
+ progress?: string;
2111
+ attachments?: unknown[];
2112
+ outputSchema?: Record<string, unknown>;
2113
+ },
2090
2114
  fmt: (cmd: string) => string = (cmd) => `/${cmd}`,
2091
2115
  options?: { hasMcp?: boolean },
2092
2116
  ): Promise<string> {
2093
2117
  const hasMcp = options?.hasMcp !== false;
2094
- const completionInstructions = hasMcp
2095
- ? '\n\nWhen done, use `store-progress` with status: "completed" and include your output.'
2096
- : "";
2118
+ const completionInstructions = await buildTaskOutputInstructions(task.outputSchema, hasMcp);
2119
+ const attachmentsSection = buildAttachmentsSection(task.id, task.attachments);
2097
2120
  if (task.progress) {
2098
2121
  const result = await resolveTemplateAsync("task.resumption.with_progress", {
2099
2122
  work_on_task_cmd: hasMcp ? fmt("work-on-task") : "",
2100
2123
  task_id: hasMcp ? task.id : "",
2101
2124
  task_description: task.task,
2125
+ attachments_section: attachmentsSection,
2102
2126
  progress: task.progress,
2103
2127
  completion_instructions: completionInstructions,
2104
2128
  });
@@ -2109,6 +2133,7 @@ async function buildResumePrompt(
2109
2133
  work_on_task_cmd: hasMcp ? fmt("work-on-task") : "",
2110
2134
  task_id: hasMcp ? task.id : "",
2111
2135
  task_description: task.task,
2136
+ attachments_section: attachmentsSection,
2112
2137
  completion_instructions: completionInstructions,
2113
2138
  });
2114
2139
  return result.text;
@@ -2776,6 +2801,8 @@ interface Trigger {
2776
2801
  }>;
2777
2802
  cursorUpdates?: Array<{ channelId: string; ts: string }>; // Deferred cursor commits for channel_activity
2778
2803
  requestedBy?: {
2804
+ /** `users.id`; absent for the UNKNOWN-identity sentinel (Slack-only requester). */
2805
+ id?: string;
2779
2806
  name: string;
2780
2807
  email?: string;
2781
2808
  role?: string;
@@ -2975,41 +3002,19 @@ async function pollForTriggerOnce(opts: PollOptions): Promise<Trigger | null> {
2975
3002
  return null; // Timeout reached, no trigger found
2976
3003
  }
2977
3004
 
2978
- /**
2979
- * Build a ready-to-run fetch recipe for each task attachment, so the agent
2980
- * can download the bytes in one call via the provider-agnostic
2981
- * `/api/fs/tasks/{taskId}/files/{attachmentId}/raw` route — instead of having
2982
- * to discover the file's storage provider/org/drive itself (e.g. guessing at
2983
- * the `agent-fs` CLI with no org context). MCP_BASE_URL/API_KEY/AGENT_ID are
2984
- * already present in every worker container's env.
2985
- */
2986
- export function buildAttachmentsSection(
2987
- taskId: string | undefined,
2988
- attachmentsRaw: unknown,
2989
- ): string {
2990
- if (!taskId || !Array.isArray(attachmentsRaw) || attachmentsRaw.length === 0) return "";
2991
-
2992
- const lines = attachmentsRaw
2993
- .filter((a): a is Record<string, unknown> => !!a && typeof a === "object")
2994
- .map((a) => {
2995
- const id = typeof a.id === "string" ? a.id : undefined;
2996
- const name = typeof a.name === "string" ? a.name : id;
2997
- if (!id || !name) return null;
2998
- const details = [
2999
- typeof a.mimeType === "string" ? a.mimeType : null,
3000
- typeof a.sizeBytes === "number" ? `${a.sizeBytes} bytes` : null,
3001
- ]
3002
- .filter(Boolean)
3003
- .join(", ");
3004
- const url = `$MCP_BASE_URL/api/fs/tasks/${taskId}/files/${id}/raw`;
3005
- const cmd = `curl -s -H "Authorization: Bearer \${AGENT_SWARM_API_KEY:-$API_KEY}" -H "X-Agent-ID: $AGENT_ID" "${url}" -o /tmp/${name}`;
3006
- return `- ${name}${details ? ` (${details})` : ""}: \`${cmd}\``;
3007
- })
3008
- .filter((line): line is string => line !== null);
3009
-
3010
- if (lines.length === 0) return "";
3011
-
3012
- return `\n\n📎 Attachment(s) — fetch directly, no need to discover the storage path yourself:\n${lines.join("\n")}`;
3005
+ /** Share the output contract between initial dispatch and deployment resume. */
3006
+ async function buildTaskOutputInstructions(
3007
+ outputSchema: unknown,
3008
+ hasMcp: boolean,
3009
+ ): Promise<string> {
3010
+ if (!hasMcp) return "";
3011
+ const result =
3012
+ outputSchema && typeof outputSchema === "object"
3013
+ ? await resolveTemplateAsync("task.output.schema", {
3014
+ schema: JSON.stringify(outputSchema, null, 2),
3015
+ })
3016
+ : await resolveTemplateAsync("task.output.generic", {});
3017
+ return result.text;
3013
3018
  }
3014
3019
 
3015
3020
  /** Build prompt based on trigger type */
@@ -3032,20 +3037,16 @@ async function buildPromptForTrigger(
3032
3037
  // Build output instructions — use outputSchema if present, otherwise generic.
3033
3038
  // Skip store-progress references for providers without MCP (e.g. Devin).
3034
3039
  const taskObj = trigger.task as Record<string, unknown> | undefined;
3035
- let outputInstructions: string;
3036
- if (!hasMcp) {
3037
- outputInstructions = "";
3038
- } else if (taskObj?.outputSchema && typeof taskObj.outputSchema === "object") {
3039
- outputInstructions = `\n\n**Required Output Format**: When completing this task, you MUST call store-progress with output that is valid JSON conforming to this schema:\n\`\`\`json\n${JSON.stringify(taskObj.outputSchema, null, 2)}\n\`\`\`\nCall store-progress with status "completed" and your JSON output. If your output doesn't match the schema, the tool call will fail and you should fix and retry.`;
3040
- } else {
3041
- outputInstructions =
3042
- '\n\nWhen done, use `store-progress` with status: "completed" and include your output.';
3043
- }
3040
+ const outputInstructions = await buildTaskOutputInstructions(taskObj?.outputSchema, hasMcp);
3044
3041
 
3045
3042
  // Include requesting user info if available from the poll trigger
3046
3043
  const requestedBy = trigger.requestedBy;
3044
+ const requesterDetails = [
3045
+ requestedBy?.email,
3046
+ requestedBy?.id ? `user ${requestedBy.id}` : undefined,
3047
+ ].filter(Boolean);
3047
3048
  const requestedBySection = requestedBy
3048
- ? `\n\nRequested by: ${requestedBy.name}${requestedBy.email ? ` (${requestedBy.email})` : ""}`
3049
+ ? `\n\nRequested by: ${requestedBy.name}${requesterDetails.length > 0 ? ` (${requesterDetails.join(", ")})` : ""}`
3049
3050
  : "";
3050
3051
 
3051
3052
  const attachmentsSection = buildAttachmentsSection(trigger.taskId, taskObj?.attachments);
@@ -5671,7 +5672,7 @@ export async function runAgent(config: RunnerConfig, opts: RunnerOptions) {
5671
5672
  if (task.parentTaskId && apiUrl) {
5672
5673
  const contextPreamble = await buildContextPreamble(apiUrl, apiKey, task.parentTaskId);
5673
5674
  if (contextPreamble) {
5674
- resumePrompt = contextPreamble + resumePrompt;
5675
+ resumePrompt = prependContextPreamble(resumePrompt, contextPreamble);
5675
5676
  console.log(
5676
5677
  `[${role}] Injected context preamble into resumed follow-up task prompt (parent: ${task.parentTaskId.slice(0, 8)})`,
5677
5678
  );
@@ -5928,9 +5929,13 @@ export async function runAgent(config: RunnerConfig, opts: RunnerOptions) {
5928
5929
  console.warn(`[${role}] cred_status post_task report failed (non-fatal): ${err}`),
5929
5930
  );
5930
5931
  } else if (
5931
- currentHarness === "pi" &&
5932
- isBedrockSdkMode(process.env) &&
5933
- Date.now() - lastBedrockRefreshAt > BEDROCK_REFRESH_INTERVAL_MS
5932
+ shouldRefreshBedrockStatus({
5933
+ harnessProvider: currentHarness,
5934
+ env: process.env,
5935
+ lastRefreshAt: lastBedrockRefreshAt,
5936
+ now: Date.now(),
5937
+ intervalMs: BEDROCK_REFRESH_INTERVAL_MS,
5938
+ })
5934
5939
  ) {
5935
5940
  // Bedrock enumeration drifts independently of the harness_provider:
5936
5941
  // access granted (or revoked) in the AWS console after boot won't flip
@@ -6135,7 +6140,7 @@ export async function runAgent(config: RunnerConfig, opts: RunnerOptions) {
6135
6140
  ? await buildResumeContextPreamble(apiUrl, apiKey, taskObj.parentTaskId)
6136
6141
  : await buildContextPreamble(apiUrl, apiKey, taskObj.parentTaskId);
6137
6142
  if (contextPreamble) {
6138
- triggerPrompt = contextPreamble + triggerPrompt;
6143
+ triggerPrompt = prependContextPreamble(triggerPrompt, contextPreamble);
6139
6144
  console.log(
6140
6145
  `[${role}] Injected ${isResumeTask ? "resume" : "context"} preamble for ${
6141
6146
  isResumeTask ? "resume" : "follow-up"