@cortexkit/opencode-magic-context 0.43.0 → 0.43.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 (68) hide show
  1. package/dist/{announcement-8mgn61fw.js → announcement-1a8bvswd.js} +2 -1
  2. package/dist/{conflict-warning-hook-t2vb0wnx.js → conflict-warning-hook-956fkedc.js} +6 -4
  3. package/dist/{derive-budgets-0sg5vp61.js → derive-budgets-b8ybssh9.js} +3 -2
  4. package/dist/features/magic-context/dreamer/hidden-single-shot.d.ts +7 -4
  5. package/dist/features/magic-context/dreamer/hidden-single-shot.d.ts.map +1 -1
  6. package/dist/features/magic-context/dreamer/map-memories.d.ts +3 -1
  7. package/dist/features/magic-context/dreamer/map-memories.d.ts.map +1 -1
  8. package/dist/features/magic-context/dreamer/refresh-primers.d.ts +3 -1
  9. package/dist/features/magic-context/dreamer/refresh-primers.d.ts.map +1 -1
  10. package/dist/features/magic-context/dreamer/task-executor.d.ts.map +1 -1
  11. package/dist/features/magic-context/dreamer/verify.d.ts +4 -1
  12. package/dist/features/magic-context/dreamer/verify.d.ts.map +1 -1
  13. package/dist/features/magic-context/memory/verification-paths.d.ts.map +1 -1
  14. package/dist/hooks/auto-update-checker/checker.d.ts +1 -0
  15. package/dist/hooks/auto-update-checker/checker.d.ts.map +1 -1
  16. package/dist/hooks/magic-context/compartment-trigger.d.ts +2 -1
  17. package/dist/hooks/magic-context/compartment-trigger.d.ts.map +1 -1
  18. package/dist/hooks/magic-context/hook.d.ts.map +1 -1
  19. package/dist/hooks/magic-context/lkg-slot.d.ts +1 -0
  20. package/dist/hooks/magic-context/lkg-slot.d.ts.map +1 -1
  21. package/dist/hooks/magic-context/rust-mode-transform.d.ts +2 -0
  22. package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
  23. package/dist/hooks/magic-context/send-session-notification.d.ts +1 -0
  24. package/dist/hooks/magic-context/send-session-notification.d.ts.map +1 -1
  25. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  26. package/dist/{index-8w1skpnm.js → index-0ccmyzbj.js} +6 -6
  27. package/dist/{index-w2ety11c.js → index-1gtwrdc4.js} +3 -3
  28. package/dist/{index-ntbmt6rq.js → index-4b30nf6z.js} +1 -1
  29. package/dist/{index-99sfbrrf.js → index-6w9p73jz.js} +1 -1
  30. package/dist/{index-4ftb5hcq.js → index-6z9g64js.js} +7 -1
  31. package/dist/{index-d0dh7v0f.js → index-7wpwr2e2.js} +115 -86
  32. package/dist/{index-9skq8m9y.js → index-9r1cbh9e.js} +1 -1
  33. package/dist/{safe-notification-target-fepvcbsj.js → index-febg06dy.js} +6 -7
  34. package/dist/{index-ygwdyntq.js → index-j7cnyvq1.js} +6 -4
  35. package/dist/{index-rpz2me0v.js → index-kpmmr8s0.js} +2 -2
  36. package/dist/{index-ykg9sdzz.js → index-v8qr6tt2.js} +1 -1
  37. package/dist/{index-qp20p2py.js → index-wgzyeyf5.js} +1 -1
  38. package/dist/{index-rvwvdq59.js → index-yc81txp4.js} +38 -4
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +577 -226
  41. package/dist/{message-time-backfill-gzjer78y.js → message-time-backfill-0ccvyk9n.js} +3 -2
  42. package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
  43. package/dist/{read-session-chunk-ec3jkvhg.js → read-session-chunk-z7fv0qjv.js} +4 -3
  44. package/dist/{recomp-orchestrator-6akjp11f.js → recomp-orchestrator-r00aa5t3.js} +9 -7
  45. package/dist/safe-notification-target-vrkjrbgb.js +10 -0
  46. package/dist/{send-session-notification-f6gwkesy.js → send-session-notification-3warjyjp.js} +7 -3
  47. package/dist/shared/data-path.d.ts.map +1 -1
  48. package/dist/shared/model-suggestion-retry.d.ts.map +1 -1
  49. package/dist/shared/test-temp-dir.d.ts +1 -1
  50. package/dist/shared/test-temp-dir.d.ts.map +1 -1
  51. package/dist/{task-config-ex4nt0q0.js → task-config-mgf5nsh3.js} +1 -1
  52. package/dist/v2/hidden-completion.d.ts.map +1 -1
  53. package/dist/v2/hooks/hidden-child.d.ts +6 -0
  54. package/dist/v2/hooks/hidden-child.d.ts.map +1 -1
  55. package/dist/v2/hooks/payload.d.ts.map +1 -1
  56. package/dist/v2/hooks/types.d.ts +1 -0
  57. package/dist/v2/hooks/types.d.ts.map +1 -1
  58. package/dist/v2/host-service.d.ts +1 -1
  59. package/dist/v2/host-service.d.ts.map +1 -1
  60. package/dist/v2/server.js +701 -305
  61. package/dist/wrapup-orchestrator-y0bs7t5a.js +18 -0
  62. package/package.json +2 -1
  63. package/src/features/magic-context/dreamer/task-registry.ts +1 -1
  64. package/src/shared/data-path.ts +6 -6
  65. package/src/shared/model-suggestion-retry.test.ts +43 -0
  66. package/src/shared/model-suggestion-retry.ts +17 -0
  67. package/src/shared/test-temp-dir.ts +3 -0
  68. package/dist/wrapup-orchestrator-5akc87gr.js +0 -16
package/dist/index.js CHANGED
@@ -1,3 +1,11 @@
1
+ import {
2
+ setHarness,
3
+ getHarness,
4
+ getDataDir,
5
+ getOpenCodeStorageDir,
6
+ getMagicContextStorageResolution,
7
+ getMagicContextStorageDir
8
+ } from "./index-6z9g64js.js";
1
9
  import {
2
10
  sanitizeDiagnosticText,
3
11
  hasShareabilitySensitiveText,
@@ -5,7 +13,7 @@ import {
5
13
  sessionLog,
6
14
  getLoggerDiagnostics,
7
15
  flushLogger
8
- } from "./index-qp20p2py.js";
16
+ } from "./index-wgzyeyf5.js";
9
17
  import {
10
18
  withContentLanguageDirective,
11
19
  buildPrimaryLanguageDirective,
@@ -224,6 +232,7 @@ import {
224
232
  registerLkgPersistence,
225
233
  beginLkgPass,
226
234
  visitMessageContentFields,
235
+ contentSnapshotValue,
227
236
  messageContentFields,
228
237
  signatureForFields,
229
238
  exactReusablePrefix,
@@ -289,6 +298,8 @@ import {
289
298
  detectThinkingBindingMismatch,
290
299
  isFable51ThinkingBindingModel,
291
300
  detectOverflow,
301
+ extractLatestAssistantText,
302
+ hasLengthCappedOutput,
292
303
  parseProviderModel,
293
304
  modelBodyField,
294
305
  toModelEntry,
@@ -299,8 +310,6 @@ import {
299
310
  promptSurfaceHashMaterial,
300
311
  createPromptSurfaceRuntime,
301
312
  createPromptSurfaceGuidanceEpochCache,
302
- extractLatestAssistantText,
303
- hasLengthCappedOutput,
304
313
  setKeepSubagents,
305
314
  teardownChildSession,
306
315
  renderUserFacingFailure,
@@ -465,7 +474,7 @@ import {
465
474
  setRecompStarting2,
466
475
  setRecompTerminal2,
467
476
  runManagedRecomp2
468
- } from "./index-d0dh7v0f.js";
477
+ } from "./index-7wpwr2e2.js";
469
478
  import {
470
479
  stripJsonComments,
471
480
  isPrototypePollutionKey,
@@ -496,7 +505,7 @@ import {
496
505
  deriveHistorianChunkTokens2,
497
506
  resolveKnownHistorianContextLimit2,
498
507
  resolveHistorianContextLimit2
499
- } from "./index-8w1skpnm.js";
508
+ } from "./index-0ccmyzbj.js";
500
509
  import {
501
510
  resolveOpenCodeDbPath,
502
511
  assertOpenCodeStoreGeneration,
@@ -519,7 +528,7 @@ import {
519
528
  latestPersistedMessageForRecovery,
520
529
  getMessageTimesFromOpenCodeDb,
521
530
  findLastAssistantModelFromOpenCodeDb
522
- } from "./index-ykg9sdzz.js";
531
+ } from "./index-v8qr6tt2.js";
523
532
  import {
524
533
  textMentionsRecentCommit,
525
534
  hasMeaningfulUserText2,
@@ -637,22 +646,23 @@ import {
637
646
  readRawSessionMessageById2,
638
647
  readSessionChunk2,
639
648
  readRawSessionSeedTail2
640
- } from "./index-ygwdyntq.js";
649
+ } from "./index-j7cnyvq1.js";
650
+ import"./index-febg06dy.js";
641
651
  import {
642
652
  getErrorMessage,
643
653
  describeError,
644
- sendIgnoredMessage2,
654
+ sendCommandResult2,
645
655
  flushIgnoredMessages2,
646
656
  clearIgnoredMessages2,
647
657
  observeIgnoredNotificationEvent2,
648
658
  sendStatusNotification2
649
- } from "./index-rvwvdq59.js";
659
+ } from "./index-yc81txp4.js";
650
660
  import {
651
661
  detectConflicts,
652
662
  resolveCompactionForBoot,
653
663
  sendConflictWarning2,
654
664
  cleanupConflictWarnings2
655
- } from "./index-rpz2me0v.js";
665
+ } from "./index-kpmmr8s0.js";
656
666
  import {
657
667
  resolveModelCalibration,
658
668
  calibrateBuckets
@@ -676,7 +686,7 @@ import {
676
686
  compareTaskOrder,
677
687
  buildDreamTaskRuntimeConfigs2,
678
688
  userMemoryCollectionEnabled2
679
- } from "./index-99sfbrrf.js";
689
+ } from "./index-6w9p73jz.js";
680
690
  import {
681
691
  registerNotificationSink2,
682
692
  pushNotification2,
@@ -692,24 +702,16 @@ import {
692
702
  ANNOUNCEMENT_FOOTER2,
693
703
  markAnnouncementSeen2,
694
704
  shouldShowAnnouncement2
695
- } from "./index-ntbmt6rq.js";
705
+ } from "./index-4b30nf6z.js";
696
706
  import {
697
707
  resolvePromptContext2
698
708
  } from "./index-fmsr7v69.js";
699
709
  import {
700
710
  runManagedWrapup2
701
- } from "./index-w2ety11c.js";
711
+ } from "./index-1gtwrdc4.js";
702
712
  import {
703
713
  logSlowWriteTransaction
704
- } from "./index-9skq8m9y.js";
705
- import {
706
- setHarness,
707
- getHarness,
708
- getDataDir,
709
- getOpenCodeStorageDir,
710
- getMagicContextStorageResolution,
711
- getMagicContextStorageDir
712
- } from "./index-4ftb5hcq.js";
714
+ } from "./index-9r1cbh9e.js";
713
715
  import {
714
716
  __toESM,
715
717
  __commonJS
@@ -12053,7 +12055,7 @@ async function getLatestVersion(channel = "latest", options = {}) {
12053
12055
  try {
12054
12056
  if (options.signal?.aborted)
12055
12057
  return null;
12056
- const response = await fetch(buildRegistryUrl(options.registryUrl ?? NPM_REGISTRY_URL), {
12058
+ const response = await (options.fetch ?? fetch)(buildRegistryUrl(options.registryUrl ?? NPM_REGISTRY_URL), {
12057
12059
  signal: controller.signal,
12058
12060
  headers: { Accept: "application/json" }
12059
12061
  });
@@ -14575,13 +14577,13 @@ async function runHiddenSingleShotPrompt(args) {
14575
14577
  throw new Error(`${args.callContext} returned length-capped output`);
14576
14578
  }
14577
14579
  const text = completion.text;
14578
- if (!text)
14580
+ if (!text && !args.allowEmpty)
14579
14581
  throw new Error(`${args.callContext} returned no output`);
14580
- return args.parse(text);
14582
+ return args.parse(text ?? "", completion);
14581
14583
  }
14582
14584
  });
14583
14585
  promptSettled = true;
14584
- return { validated: run.validated, completion: run.output };
14586
+ return { validated: run.validated, completion: run.output, childSessionId: handle.id };
14585
14587
  } finally {
14586
14588
  await args.executor.close(handle, {
14587
14589
  promptSettled,
@@ -18044,8 +18046,36 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
18044
18046
  let promptSettled = false;
18045
18047
  const startedAt = Date.now();
18046
18048
  try {
18049
+ const prompt = buildMapMemoriesPrompt(args.projectIdentity, batch);
18050
+ if (args.hiddenCompletionExecutor) {
18051
+ const run = await runHiddenSingleShotPrompt({
18052
+ executor: args.hiddenCompletionExecutor,
18053
+ parentSessionId: args.parentSessionId,
18054
+ sessionDirectory: args.sessionDirectory,
18055
+ agent: DREAMER_MEMORY_MAPPER_AGENT,
18056
+ system: MAP_MEMORIES_SYSTEM_PROMPT,
18057
+ prompt,
18058
+ title: "magic-context-dream-map-memories",
18059
+ callContext: "dreamer:map-memories",
18060
+ model: args.model,
18061
+ fallbackModels: args.fallbackModels,
18062
+ timeoutMs: sliceMs,
18063
+ signal,
18064
+ parse: (text) => validateMapMemoriesManifest(text, new Set(batch.map((memory) => memory.id)))
18065
+ });
18066
+ recordInvocation2(args, startedAt, {
18067
+ status: "completed",
18068
+ messages: run.completion.messages ?? []
18069
+ });
18070
+ const outcome = await applyParsedBatchMappings(args, batch, run.validated);
18071
+ const returnedIds = new Set(run.validated.map((entry) => entry.id));
18072
+ return { ...outcome, requeue: batch.filter((memory) => !returnedIds.has(memory.id)) };
18073
+ }
18074
+ const client = args.client;
18075
+ if (!client)
18076
+ throw new Error("map-memories requires a client or hidden completion executor");
18047
18077
  const createResponse = await createChildSessionWithFence({
18048
- client: args.client,
18078
+ client,
18049
18079
  db: args.db,
18050
18080
  parentSessionId: args.parentSessionId,
18051
18081
  title: "magic-context-dream-map-memories",
@@ -18057,8 +18087,7 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
18057
18087
  agentSessionId = typeof created?.id === "string" ? created.id : null;
18058
18088
  if (!agentSessionId)
18059
18089
  throw new Error("Could not create map-memories session.");
18060
- const prompt = buildMapMemoriesPrompt(args.projectIdentity, batch);
18061
- const run = await promptSyncWithValidatedOutputRetry(args.client, {
18090
+ const run = await promptSyncWithValidatedOutputRetry(client, {
18062
18091
  path: { id: agentSessionId },
18063
18092
  query: { directory: args.sessionDirectory },
18064
18093
  body: {
@@ -18073,7 +18102,7 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
18073
18102
  fallbackModels: args.fallbackModels,
18074
18103
  callContext: "dreamer:map-memories",
18075
18104
  fetchOutput: async () => {
18076
- const messagesResponse = await args.client.session.messages({
18105
+ const messagesResponse = await client.session.messages({
18077
18106
  path: { id: agentSessionId },
18078
18107
  query: { directory: args.sessionDirectory, limit: 100 }
18079
18108
  });
@@ -18116,15 +18145,16 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
18116
18145
  }
18117
18146
  };
18118
18147
  } finally {
18119
- await teardownChildSession({
18120
- client: args.client,
18121
- sessionId: agentSessionId,
18122
- sessionDirectory: args.sessionDirectory,
18123
- promptSettled,
18124
- privacySensitive: true,
18125
- context: "[dreamer] map-memories",
18126
- log
18127
- });
18148
+ if (agentSessionId && args.client)
18149
+ await teardownChildSession({
18150
+ client: args.client,
18151
+ sessionId: agentSessionId,
18152
+ sessionDirectory: args.sessionDirectory,
18153
+ promptSettled,
18154
+ privacySensitive: true,
18155
+ context: "[dreamer] map-memories",
18156
+ log
18157
+ });
18128
18158
  }
18129
18159
  }
18130
18160
  async function applyParsedBatchMappings(args, batch, parsed) {
@@ -18717,8 +18747,41 @@ async function refreshOnePrimer(args, primer, sliceMs, signal) {
18717
18747
  let promptSettled = false;
18718
18748
  const startedAt = Date.now();
18719
18749
  try {
18750
+ const prompt = buildInvestigationPrompt(primer, seed.kind, seed.orientation, seed.prePost);
18751
+ if (args.hiddenCompletionExecutor) {
18752
+ const run = await runHiddenSingleShotPrompt({
18753
+ executor: args.hiddenCompletionExecutor,
18754
+ parentSessionId: args.parentSessionId,
18755
+ sessionDirectory: args.sessionDirectory,
18756
+ agent: DREAMER_PRIMER_INVESTIGATOR_AGENT,
18757
+ system: PRIMER_INVESTIGATOR_SYSTEM_PROMPT,
18758
+ prompt,
18759
+ title: "magic-context-dream-refresh-primers",
18760
+ callContext: "dreamer:refresh-primers",
18761
+ model: args.model,
18762
+ fallbackModels: args.fallbackModels,
18763
+ language: args.language,
18764
+ timeoutMs: sliceMs,
18765
+ signal,
18766
+ parse: (text) => parseAnswer([{ info: { role: "assistant" }, parts: [{ type: "text", text }] }], primer.answer)
18767
+ });
18768
+ recordInvocation3(args, startedAt, {
18769
+ status: "completed",
18770
+ messages: run.completion.messages ?? []
18771
+ });
18772
+ const answer = run.validated.trim();
18773
+ if (!answer || investigationToolCallCount(run.completion.messages ?? []) === 0)
18774
+ return false;
18775
+ runLeaseGuardedWrite(args.db, args.holderId, args.leaseKey, () => {
18776
+ updatePrimerAnswer(args.db, primer.id, answer);
18777
+ });
18778
+ return true;
18779
+ }
18780
+ const client = args.client;
18781
+ if (!client)
18782
+ throw new Error("refresh-primers requires a client or hidden completion executor");
18720
18783
  const createResponse = await createChildSessionWithFence({
18721
- client: args.client,
18784
+ client,
18722
18785
  db: args.db,
18723
18786
  parentSessionId: args.parentSessionId,
18724
18787
  title: "magic-context-dream-refresh-primers",
@@ -18730,8 +18793,7 @@ async function refreshOnePrimer(args, primer, sliceMs, signal) {
18730
18793
  agentSessionId = typeof created?.id === "string" ? created.id : null;
18731
18794
  if (!agentSessionId)
18732
18795
  throw new Error("Could not create primer refresh session.");
18733
- const prompt = buildInvestigationPrompt(primer, seed.kind, seed.orientation, seed.prePost);
18734
- const run = await promptSyncWithValidatedOutputRetry(args.client, {
18796
+ const run = await promptSyncWithValidatedOutputRetry(client, {
18735
18797
  path: { id: agentSessionId },
18736
18798
  query: { directory: args.sessionDirectory },
18737
18799
  body: {
@@ -18746,7 +18808,7 @@ async function refreshOnePrimer(args, primer, sliceMs, signal) {
18746
18808
  fallbackModels: args.fallbackModels,
18747
18809
  callContext: "dreamer:refresh-primers",
18748
18810
  fetchOutput: async () => {
18749
- const messagesResponse = await args.client.session.messages({
18811
+ const messagesResponse = await client.session.messages({
18750
18812
  path: { id: agentSessionId },
18751
18813
  query: { directory: args.sessionDirectory, limit: 100 }
18752
18814
  });
@@ -18775,15 +18837,16 @@ async function refreshOnePrimer(args, primer, sliceMs, signal) {
18775
18837
  recordInvocation3(args, startedAt, { status: failedInvocationStatus(error), error });
18776
18838
  throw error;
18777
18839
  } finally {
18778
- await teardownChildSession({
18779
- client: args.client,
18780
- sessionId: agentSessionId,
18781
- sessionDirectory: args.sessionDirectory,
18782
- promptSettled,
18783
- privacySensitive: true,
18784
- context: "[dreamer] refresh-primers",
18785
- log
18786
- });
18840
+ if (agentSessionId && args.client)
18841
+ await teardownChildSession({
18842
+ client: args.client,
18843
+ sessionId: agentSessionId,
18844
+ sessionDirectory: args.sessionDirectory,
18845
+ promptSettled,
18846
+ privacySensitive: true,
18847
+ context: "[dreamer] refresh-primers",
18848
+ log
18849
+ });
18787
18850
  }
18788
18851
  }
18789
18852
  function originSessionIdForPrimer(args, primer) {
@@ -19518,8 +19581,40 @@ async function verifyOneBatch(args, batch, sliceMs, signal) {
19518
19581
  let promptSettled = false;
19519
19582
  const startedAt = Date.now();
19520
19583
  try {
19584
+ const prompt = buildVerifyPrompt(args.projectIdentity, batch);
19585
+ if (args.hiddenCompletionExecutor) {
19586
+ const run = await runHiddenSingleShotPrompt({
19587
+ executor: args.hiddenCompletionExecutor,
19588
+ parentSessionId: args.parentSessionId,
19589
+ sessionDirectory: args.sessionDirectory,
19590
+ agent: DREAMER_MEMORY_MAPPER_AGENT,
19591
+ system: VERIFY_SYSTEM_PROMPT,
19592
+ prompt,
19593
+ title: "magic-context-dream-verify",
19594
+ callContext: "dreamer:verify",
19595
+ model: args.model,
19596
+ fallbackModels: args.fallbackModels,
19597
+ language: args.language,
19598
+ timeoutMs: sliceMs,
19599
+ signal,
19600
+ parse: (text) => {
19601
+ const providerFailure = providerOutputFailureFromInvalidManifest([], text);
19602
+ if (providerFailure)
19603
+ throw providerFailure;
19604
+ return validateVerifyManifest(text, new Set(batch.map((memory) => memory.id)));
19605
+ }
19606
+ });
19607
+ recordInvocation4(args, startedAt, {
19608
+ status: "completed",
19609
+ messages: run.completion.messages ?? []
19610
+ });
19611
+ return applyParsedVerifyManifest(args, batch, run.validated);
19612
+ }
19613
+ const client = args.client;
19614
+ if (!client)
19615
+ throw new Error("verify requires a client or hidden completion executor");
19521
19616
  const createResponse = await createChildSessionWithFence({
19522
- client: args.client,
19617
+ client,
19523
19618
  db: args.db,
19524
19619
  parentSessionId: args.parentSessionId,
19525
19620
  title: "magic-context-dream-verify",
@@ -19531,8 +19626,7 @@ async function verifyOneBatch(args, batch, sliceMs, signal) {
19531
19626
  agentSessionId = typeof created?.id === "string" ? created.id : null;
19532
19627
  if (!agentSessionId)
19533
19628
  throw new Error("Could not create verify session.");
19534
- const prompt = buildVerifyPrompt(args.projectIdentity, batch);
19535
- const run = await promptSyncWithValidatedOutputRetry(args.client, {
19629
+ const run = await promptSyncWithValidatedOutputRetry(client, {
19536
19630
  path: { id: agentSessionId },
19537
19631
  query: { directory: args.sessionDirectory },
19538
19632
  body: {
@@ -19547,7 +19641,7 @@ async function verifyOneBatch(args, batch, sliceMs, signal) {
19547
19641
  fallbackModels: args.fallbackModels,
19548
19642
  callContext: "dreamer:verify",
19549
19643
  fetchOutput: async () => {
19550
- const messagesResponse = await args.client.session.messages({
19644
+ const messagesResponse = await client.session.messages({
19551
19645
  path: { id: agentSessionId },
19552
19646
  query: { directory: args.sessionDirectory, limit: 100 }
19553
19647
  });
@@ -19588,15 +19682,16 @@ async function verifyOneBatch(args, batch, sliceMs, signal) {
19588
19682
  providerFailure
19589
19683
  };
19590
19684
  } finally {
19591
- await teardownChildSession({
19592
- client: args.client,
19593
- sessionId: agentSessionId,
19594
- sessionDirectory: args.sessionDirectory,
19595
- promptSettled,
19596
- privacySensitive: true,
19597
- context: "[dreamer] verify",
19598
- log
19599
- });
19685
+ if (agentSessionId && args.client)
19686
+ await teardownChildSession({
19687
+ client: args.client,
19688
+ sessionId: agentSessionId,
19689
+ sessionDirectory: args.sessionDirectory,
19690
+ promptSettled,
19691
+ privacySensitive: true,
19692
+ context: "[dreamer] verify",
19693
+ log
19694
+ });
19600
19695
  }
19601
19696
  }
19602
19697
  async function applyParsedVerifyManifest(args, batch, parsed) {
@@ -19764,6 +19859,8 @@ async function applyParsedVerifyManifest(args, batch, parsed) {
19764
19859
  async function normalizeFiles(args, rawFiles) {
19765
19860
  if (rawFiles.length === 0)
19766
19861
  return [];
19862
+ if (args.normalizeFiles)
19863
+ return args.normalizeFiles(rawFiles);
19767
19864
  const normalized = await normalizeVerificationFiles({
19768
19865
  cwd: args.sessionDirectory,
19769
19866
  files: rawFiles
@@ -20097,7 +20194,8 @@ function createDreamTaskExecutor(deps) {
20097
20194
  if (config.task === "map-memories") {
20098
20195
  const result = await mapMemories({
20099
20196
  db,
20100
- client: requireDreamClient(deps.client),
20197
+ client: deps.client,
20198
+ hiddenCompletionExecutor: deps.hiddenCompletionExecutor,
20101
20199
  projectIdentity,
20102
20200
  parentSessionId: parent,
20103
20201
  sessionDirectory: deps.sessionDirectory,
@@ -20134,7 +20232,8 @@ function createDreamTaskExecutor(deps) {
20134
20232
  const memoryBefore = getMemoryCountsByStatus(db, projectIdentity);
20135
20233
  const result = await runVerify({
20136
20234
  db,
20137
- client: requireDreamClient(deps.client),
20235
+ client: deps.client,
20236
+ hiddenCompletionExecutor: deps.hiddenCompletionExecutor,
20138
20237
  projectIdentity,
20139
20238
  parentSessionId: parent,
20140
20239
  sessionDirectory: deps.sessionDirectory,
@@ -20235,7 +20334,8 @@ function createDreamTaskExecutor(deps) {
20235
20334
  if (config.task === "refresh-primers") {
20236
20335
  const result = await refreshPrimers({
20237
20336
  db,
20238
- client: requireDreamClient(deps.client),
20337
+ client: deps.client,
20338
+ hiddenCompletionExecutor: deps.hiddenCompletionExecutor,
20239
20339
  projectIdentity,
20240
20340
  parentSessionId: parent,
20241
20341
  sessionDirectory: deps.sessionDirectory,
@@ -20503,24 +20603,45 @@ async function runRetrospectiveTask(config, ctx, helpers) {
20503
20603
  abortController.abort();
20504
20604
  }, ctx.leaseAcquisition);
20505
20605
  let childSessionId = null;
20606
+ let hiddenHandle = null;
20506
20607
  let promptSettled = false;
20507
20608
  try {
20508
- const createResponse = await createChildSessionWithFence({
20509
- client: requireDreamClient(deps.client),
20510
- db,
20511
- parentSessionId: parent ?? undefined,
20512
- title: "magic-context-dream-retrospective",
20513
- directory: deps.sessionDirectory
20514
- });
20515
- const created = normalizeSDKResponse(createResponse, null, { preferResponseOnMissingData: true });
20516
- childSessionId = typeof created?.id === "string" ? created.id : null;
20517
- if (!childSessionId)
20518
- throw new Error("Retrospective could not create its child session.");
20609
+ if (deps.hiddenCompletionExecutor) {
20610
+ hiddenHandle = await deps.hiddenCompletionExecutor.open({
20611
+ parentSessionId: parent ?? undefined,
20612
+ agent: DREAMER_RETROSPECTIVE_AGENT,
20613
+ kind: "dreamer-task",
20614
+ system: FRICTION_GATE_SYSTEM_PROMPT,
20615
+ model: config.model,
20616
+ configuredModels: [
20617
+ ...config.model ? [config.model] : [],
20618
+ ...config.fallbackModels ?? []
20619
+ ],
20620
+ timeoutMs: Math.max(1, deadline - Date.now()),
20621
+ title: "magic-context-dream-retrospective",
20622
+ directory: deps.sessionDirectory
20623
+ });
20624
+ childSessionId = hiddenHandle.id;
20625
+ } else {
20626
+ const createResponse = await createChildSessionWithFence({
20627
+ client: requireDreamClient(deps.client),
20628
+ db,
20629
+ parentSessionId: parent ?? undefined,
20630
+ title: "magic-context-dream-retrospective",
20631
+ directory: deps.sessionDirectory
20632
+ });
20633
+ const created = normalizeSDKResponse(createResponse, null, { preferResponseOnMissingData: true });
20634
+ childSessionId = typeof created?.id === "string" ? created.id : null;
20635
+ if (!childSessionId)
20636
+ throw new Error("Retrospective could not create its child session.");
20637
+ }
20519
20638
  const sessionId = childSessionId;
20639
+ if (!sessionId)
20640
+ throw new Error("Retrospective could not create its child session.");
20520
20641
  const runChildTurn = async (system, userText) => {
20521
20642
  const remainingMs = Math.max(0, deadline - Date.now());
20522
20643
  promptSettled = false;
20523
- const run = await promptSyncWithValidatedOutputRetry(requireDreamClient(deps.client), {
20644
+ const run = await promptSyncWithValidatedOutputRetry(deps.hiddenCompletionExecutor ? undefined : requireDreamClient(deps.client), {
20524
20645
  path: { id: sessionId },
20525
20646
  query: { directory: deps.sessionDirectory },
20526
20647
  body: {
@@ -20534,7 +20655,13 @@ async function runRetrospectiveTask(config, ctx, helpers) {
20534
20655
  signal: abortController.signal,
20535
20656
  fallbackModels: config.fallbackModels,
20536
20657
  callContext: "dreamer:retrospective",
20658
+ ...hiddenHandle && deps.hiddenCompletionExecutor ? {
20659
+ transport: Object.assign((request) => deps.hiddenCompletionExecutor?.attempt(hiddenHandle, request) ?? Promise.reject(new Error("Hidden transport unavailable")), { childSessionId: hiddenHandle.childSessionId })
20660
+ } : {},
20537
20661
  fetchOutput: async () => {
20662
+ if (hiddenHandle && deps.hiddenCompletionExecutor) {
20663
+ return deps.hiddenCompletionExecutor.collect(hiddenHandle, 50);
20664
+ }
20538
20665
  const messagesResponse = await requireDreamClient(deps.client).session.messages({
20539
20666
  path: { id: sessionId },
20540
20667
  query: { directory: deps.sessionDirectory, limit: 50 }
@@ -20544,14 +20671,15 @@ async function runRetrospectiveTask(config, ctx, helpers) {
20544
20671
  });
20545
20672
  },
20546
20673
  validateOutput: (outputMessages) => {
20547
- const text = extractLatestAssistantText(outputMessages);
20674
+ const text = hiddenHandle ? outputMessages.text : extractLatestAssistantText(outputMessages);
20548
20675
  if (!text)
20549
20676
  throw new Error("Retrospective child returned no output.");
20550
20677
  return text;
20551
20678
  }
20552
20679
  });
20553
20680
  promptSettled = true;
20554
- return run;
20681
+ const output = hiddenHandle ? run.output.messages ?? [] : run.output;
20682
+ return { ...run, output };
20555
20683
  };
20556
20684
  const finish = (run, watermark) => {
20557
20685
  if (parent && run) {
@@ -20681,15 +20809,23 @@ async function runRetrospectiveTask(config, ctx, helpers) {
20681
20809
  });
20682
20810
  } finally {
20683
20811
  heartbeat.stop();
20684
- await teardownChildSession({
20685
- client: requireDreamClient(deps.client),
20686
- sessionId: childSessionId,
20687
- sessionDirectory: deps.sessionDirectory,
20688
- promptSettled,
20689
- privacySensitive: true,
20690
- context: "[dreamer] retrospective",
20691
- log
20692
- });
20812
+ if (hiddenHandle && deps.hiddenCompletionExecutor) {
20813
+ await deps.hiddenCompletionExecutor.close(hiddenHandle, {
20814
+ promptSettled,
20815
+ privacySensitive: true,
20816
+ context: "[dreamer] retrospective",
20817
+ log
20818
+ });
20819
+ } else
20820
+ await teardownChildSession({
20821
+ client: requireDreamClient(deps.client),
20822
+ sessionId: childSessionId,
20823
+ sessionDirectory: deps.sessionDirectory,
20824
+ promptSettled,
20825
+ privacySensitive: true,
20826
+ context: "[dreamer] retrospective",
20827
+ log
20828
+ });
20693
20829
  }
20694
20830
  }
20695
20831
  async function runAgenticTask(config, ctx, helpers) {
@@ -20763,72 +20899,107 @@ async function runAgenticTask(config, ctx, helpers) {
20763
20899
  docsCurrentTokens: maintainDocsSnapshot ? Math.ceil([...maintainDocsSnapshot.values()].join("").length / 3.5) : 0,
20764
20900
  curate: curateMemories && curateCategory ? { category: curateCategory, memories: curateMemories } : undefined
20765
20901
  });
20766
- const createResponse = await createChildSessionWithFence({
20767
- client: requireDreamClient(deps.client),
20768
- db,
20769
- parentSessionId: parent ?? undefined,
20770
- title: `magic-context-dream-${task}`,
20771
- directory: docsDir
20772
- });
20773
- const created = normalizeSDKResponse(createResponse, null, {
20774
- preferResponseOnMissingData: true
20775
- });
20776
- childSessionId = typeof created?.id === "string" ? created.id : null;
20777
- if (!childSessionId)
20778
- throw new Error("Dreamer could not create its child session.");
20779
- const sessionId = childSessionId;
20780
- const remainingMs = Math.max(0, deadline - Date.now());
20781
- const run = await promptSyncWithValidatedOutputRetry(requireDreamClient(deps.client), {
20782
- path: { id: sessionId },
20783
- query: { directory: docsDir },
20784
- body: {
20902
+ let run;
20903
+ if (deps.hiddenCompletionExecutor) {
20904
+ const hidden = await runHiddenSingleShotPrompt({
20905
+ executor: deps.hiddenCompletionExecutor,
20906
+ parentSessionId: parent ?? undefined,
20907
+ sessionDirectory: docsDir,
20785
20908
  agent: task === "maintain-docs" ? DREAMER_DOCS_AGENT : DREAMER_AGENT,
20786
- system: task === "maintain-docs" ? MAINTAIN_DOCS_SYSTEM_PROMPT : withContentLanguageDirective(CURATE_SYSTEM_PROMPT, config.language ?? deps.language),
20787
- ...modelBodyField(config.model),
20788
- parts: [{ type: "text", text: taskPrompt, synthetic: true }]
20789
- }
20790
- }, {
20791
- timeoutMs: Math.min(remainingMs, config.timeoutMinutes * 60 * 1000),
20792
- signal: abortController.signal,
20793
- fallbackModels: config.fallbackModels,
20794
- callContext: `dreamer:${task}`,
20795
- fetchOutput: async () => {
20796
- const messagesResponse = await requireDreamClient(deps.client).session.messages({
20797
- path: { id: sessionId },
20798
- query: {
20799
- directory: docsDir,
20800
- ...task === "curate" ? {} : { limit: 50 }
20909
+ system: task === "maintain-docs" ? MAINTAIN_DOCS_SYSTEM_PROMPT : CURATE_SYSTEM_PROMPT,
20910
+ prompt: taskPrompt,
20911
+ title: `magic-context-dream-${task}`,
20912
+ callContext: `dreamer:${task}`,
20913
+ allowEmpty: task === "curate",
20914
+ model: config.model,
20915
+ fallbackModels: config.fallbackModels,
20916
+ language: task === "curate" ? config.language ?? deps.language : undefined,
20917
+ timeoutMs: Math.min(Math.max(0, deadline - Date.now()), config.timeoutMinutes * 60 * 1000),
20918
+ signal: abortController.signal,
20919
+ parse: (text, completion) => {
20920
+ if (task !== "curate")
20921
+ return text;
20922
+ const memoryOperations = inspectCurateMemoryOperations(completion.messages);
20923
+ if (text)
20924
+ validateCurateAssistantText(text);
20925
+ if (memoryOperations.totalCalls > 0 && memoryOperations.completedActions.length === 0)
20926
+ throw new Error("Curate returned no completed ctx_memory tool result.");
20927
+ if (!text && memoryOperations.completedActions.length === 0)
20928
+ throw new Error("Dreamer returned no assistant output.");
20929
+ return { text: text || null, memoryOperations };
20930
+ }
20931
+ });
20932
+ childSessionId = hidden.childSessionId;
20933
+ run = { output: hidden.completion.messages ?? [], validated: hidden.validated };
20934
+ promptSettled = true;
20935
+ } else {
20936
+ const createResponse = await createChildSessionWithFence({
20937
+ client: requireDreamClient(deps.client),
20938
+ db,
20939
+ parentSessionId: parent ?? undefined,
20940
+ title: `magic-context-dream-${task}`,
20941
+ directory: docsDir
20942
+ });
20943
+ const created = normalizeSDKResponse(createResponse, null, {
20944
+ preferResponseOnMissingData: true
20945
+ });
20946
+ childSessionId = typeof created?.id === "string" ? created.id : null;
20947
+ if (!childSessionId)
20948
+ throw new Error("Dreamer could not create its child session.");
20949
+ const sessionId = childSessionId;
20950
+ const remainingMs = Math.max(0, deadline - Date.now());
20951
+ run = await promptSyncWithValidatedOutputRetry(requireDreamClient(deps.client), {
20952
+ path: { id: sessionId },
20953
+ query: { directory: docsDir },
20954
+ body: {
20955
+ agent: task === "maintain-docs" ? DREAMER_DOCS_AGENT : DREAMER_AGENT,
20956
+ system: task === "maintain-docs" ? MAINTAIN_DOCS_SYSTEM_PROMPT : withContentLanguageDirective(CURATE_SYSTEM_PROMPT, config.language ?? deps.language),
20957
+ ...modelBodyField(config.model),
20958
+ parts: [{ type: "text", text: taskPrompt, synthetic: true }]
20959
+ }
20960
+ }, {
20961
+ timeoutMs: Math.min(remainingMs, config.timeoutMinutes * 60 * 1000),
20962
+ signal: abortController.signal,
20963
+ fallbackModels: config.fallbackModels,
20964
+ callContext: `dreamer:${task}`,
20965
+ fetchOutput: async () => {
20966
+ const messagesResponse = await requireDreamClient(deps.client).session.messages({
20967
+ path: { id: sessionId },
20968
+ query: {
20969
+ directory: docsDir,
20970
+ ...task === "curate" ? {} : { limit: 50 }
20971
+ }
20972
+ });
20973
+ return normalizeSDKResponse(messagesResponse, [], {
20974
+ preferResponseOnMissingData: true
20975
+ });
20976
+ },
20977
+ validateOutput: (messages) => {
20978
+ const text = extractLatestAssistantText(messages);
20979
+ if (task !== "curate") {
20980
+ if (!text)
20981
+ throw new Error("Dreamer returned no assistant output.");
20982
+ return text;
20983
+ }
20984
+ const memoryOperations = inspectCurateMemoryOperations(messages);
20985
+ if (text)
20986
+ validateCurateAssistantText(text);
20987
+ if (memoryOperations.completedActions.length > 0) {
20988
+ return { text, memoryOperations };
20801
20989
  }
20802
- });
20803
- return normalizeSDKResponse(messagesResponse, [], {
20804
- preferResponseOnMissingData: true
20805
- });
20806
- },
20807
- validateOutput: (messages) => {
20808
- const text = extractLatestAssistantText(messages);
20809
- if (task !== "curate") {
20810
20990
  if (!text)
20811
20991
  throw new Error("Dreamer returned no assistant output.");
20812
- return text;
20813
- }
20814
- const memoryOperations = inspectCurateMemoryOperations(messages);
20815
- if (text)
20816
- validateCurateAssistantText(text);
20817
- if (memoryOperations.completedActions.length > 0) {
20992
+ if (memoryOperations.totalCalls > 0) {
20993
+ throw new Error("Curate returned no completed ctx_memory tool result.");
20994
+ }
20818
20995
  return { text, memoryOperations };
20819
20996
  }
20820
- if (!text)
20821
- throw new Error("Dreamer returned no assistant output.");
20822
- if (memoryOperations.totalCalls > 0) {
20823
- throw new Error("Curate returned no completed ctx_memory tool result.");
20824
- }
20825
- return { text, memoryOperations };
20826
- }
20827
- });
20828
- promptSettled = true;
20997
+ });
20998
+ promptSettled = true;
20999
+ }
20829
21000
  if (leaseLost)
20830
21001
  throw new Error("Dream lease lost during task");
20831
- const curateRefused = task === "curate" ? takeCurateSafetyRefusalCount(sessionId) : 0;
21002
+ const curateRefused = task === "curate" ? takeCurateSafetyRefusalCount(childSessionId ?? "") : 0;
20832
21003
  if (curateRefused > 0) {
20833
21004
  helpers.reportProgress(curateRefused, curateRefused);
20834
21005
  log(`[dreamer] curate safety summary: refused=${curateRefused}`);
@@ -20898,15 +21069,16 @@ async function runAgenticTask(config, ctx, helpers) {
20898
21069
  heartbeat.stop();
20899
21070
  if (childSessionId)
20900
21071
  takeCurateSafetyRefusalCount(childSessionId);
20901
- await teardownChildSession({
20902
- client: requireDreamClient(deps.client),
20903
- sessionId: childSessionId,
20904
- sessionDirectory: docsDir,
20905
- promptSettled,
20906
- privacySensitive: true,
20907
- context: `[dreamer] ${task}`,
20908
- log
20909
- });
21072
+ if (!deps.hiddenCompletionExecutor)
21073
+ await teardownChildSession({
21074
+ client: requireDreamClient(deps.client),
21075
+ sessionId: childSessionId,
21076
+ sessionDirectory: docsDir,
21077
+ promptSettled,
21078
+ privacySensitive: true,
21079
+ context: `[dreamer] ${task}`,
21080
+ log
21081
+ });
20910
21082
  }
20911
21083
  }
20912
21084
 
@@ -26603,6 +26775,21 @@ function formatThresholdClampNote(opts) {
26603
26775
  // src/shared/rust-mode-status.ts
26604
26776
  var RUST_MODE_HOST_PATHS_LINE = "Host backends → MODULE: ctx_memory, ctx_note; historian: module-side";
26605
26777
 
26778
+ // src/hooks/magic-context/cache-busting-signals.ts
26779
+ function canConsumeDeferredOnThisPass(args) {
26780
+ if (args.justAwaitedPublication)
26781
+ return true;
26782
+ return args.schedulerDecision === "execute" || args.contextPercentage >= (args.forceMaterializationPercentage ?? escalationBands(65).forceMaterializationPercentage);
26783
+ }
26784
+ function hasReclaimRide(signals) {
26785
+ return signals.hardFold || signals.force || signals.explicitFlush || signals.publishedHistory;
26786
+ }
26787
+ var RECLAIM_RIDE_NAMES = ["hardFold", "force", "explicitFlush", "publishedHistory"];
26788
+ function reclaimRideLabel(signals) {
26789
+ const active = RECLAIM_RIDE_NAMES.filter((name) => signals[name]);
26790
+ return `ride=${active.length > 0 ? active.join("+") : "none"}`;
26791
+ }
26792
+
26606
26793
  // src/hooks/magic-context/compartment-trigger.ts
26607
26794
  var PROACTIVE_TRIGGER_OFFSET_PERCENTAGE = 2;
26608
26795
  var POST_DROP_TARGET_RATIO = 0.75;
@@ -26780,7 +26967,7 @@ function getUnsummarizedTailInfo(db, sessionId, triggerBudget, usage, executeThr
26780
26967
  function formatProjectedPostDropPercentage(value) {
26781
26968
  return value === null ? "none" : `${value.toFixed(1)}%`;
26782
26969
  }
26783
- function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPercentage, executeThresholdPercentage, triggerBudget, clearReasoningAge, commitClusterTrigger, preloadedActiveTags, contextLimit, inMemoryTail, taggerFloorOverride, reasoningProjection) {
26970
+ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPercentage, executeThresholdPercentage, triggerBudget, clearReasoningAge, commitClusterTrigger, preloadedActiveTags, contextLimit, inMemoryTail, taggerFloorOverride, reasoningProjection, reclaimRide) {
26784
26971
  if (sessionMeta.compartmentInProgress) {
26785
26972
  sessionLog(sessionId, `compartment trigger: skipped — historian already in progress (usage=${usage.percentage.toFixed(1)}%)`);
26786
26973
  return { shouldFire: false };
@@ -26838,10 +27025,12 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
26838
27025
  const canClearReasoning = reasoningProjection?.canClearReasoning ?? modelAcceptsEmptyContent(reasoningProjection?.providerID);
26839
27026
  const projectedPostDropPercentage = estimateProjectedPostDropPercentage(db, sessionId, usage, preloadedActiveTags ?? getActiveTagsBySession(db, sessionId), clearReasoningAge, sessionMeta.clearedReasoningThroughTag, canClearReasoning);
26840
27027
  const relativePostDropTarget = executeThresholdPercentage * POST_DROP_TARGET_RATIO;
27028
+ const rideLabel = reclaimRide ? reclaimRideLabel(reclaimRide) : "ride=none";
27029
+ const dropsCanLand = reclaimRide !== undefined && hasReclaimRide(reclaimRide);
26841
27030
  const forceMaterializationPercentage = escalationBands(executeThresholdPercentage).forceMaterializationPercentage;
26842
27031
  if (usage.percentage >= forceMaterializationPercentage) {
26843
- if (projectedPostDropPercentage !== null && projectedPostDropPercentage <= relativePostDropTarget) {
26844
- sessionLog(sessionId, `historian redundancy skip: summarizer not needed this pass — force band is ${forceMaterializationPercentage}%; queued/automatic drops are projected to reclaim to ${projectedPostDropPercentage.toFixed(1)}% (target ${relativePostDropTarget.toFixed(1)}%) on the next eligible execute pass`);
27032
+ if (dropsCanLand && projectedPostDropPercentage !== null && projectedPostDropPercentage <= relativePostDropTarget) {
27033
+ sessionLog(sessionId, `historian redundancy skip: summarizer not needed this pass — force band is ${forceMaterializationPercentage}%; queued/automatic drops are projected to reclaim to ${projectedPostDropPercentage.toFixed(1)}% (target ${relativePostDropTarget.toFixed(1)}%) on this pass (${rideLabel})`);
26845
27034
  return { shouldFire: false };
26846
27035
  }
26847
27036
  sessionLog(sessionId, `compartment trigger: force-firing at ${usage.percentage.toFixed(1)}% (projected post-drop ${formatProjectedPostDropPercentage(projectedPostDropPercentage)})`);
@@ -26901,8 +27090,8 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
26901
27090
  sessionLog(sessionId, `compartment trigger: not firing at ${usage.percentage.toFixed(1)}% — below proactive floor (${proactiveTriggerPercentage}%)`);
26902
27091
  return { shouldFire: false };
26903
27092
  }
26904
- if (projectedPostDropPercentage !== null && projectedPostDropPercentage <= relativePostDropTarget) {
26905
- sessionLog(sessionId, `historian redundancy skip: summarizer not needed this pass — usage is ${usage.percentage.toFixed(1)}%; queued/automatic drops are projected to reclaim to ${projectedPostDropPercentage.toFixed(1)}% (target ${relativePostDropTarget.toFixed(1)}%) on the next eligible execute pass`);
27093
+ if (dropsCanLand && projectedPostDropPercentage !== null && projectedPostDropPercentage <= relativePostDropTarget) {
27094
+ sessionLog(sessionId, `historian redundancy skip: summarizer not needed this pass — usage is ${usage.percentage.toFixed(1)}%; queued/automatic drops are projected to reclaim to ${projectedPostDropPercentage.toFixed(1)}% (target ${relativePostDropTarget.toFixed(1)}%) on this pass (${rideLabel})`);
26906
27095
  return { shouldFire: false };
26907
27096
  }
26908
27097
  if (!tailInfo.hasProtectedEligibleHead || !tailInfo.isMeaningful) {
@@ -30888,9 +31077,9 @@ function registerRpcHandlers(rpcServer, args) {
30888
31077
  return { count: buildCompartmentCount(db, sessionId, moduleStatus) };
30889
31078
  });
30890
31079
  const buildManagedCtx = async (db) => {
30891
- const { deriveHistorianChunkTokens, resolveHistorianContextLimit } = await import("./derive-budgets-0sg5vp61.js");
31080
+ const { deriveHistorianChunkTokens, resolveHistorianContextLimit } = await import("./derive-budgets-b8ybssh9.js");
30892
31081
  const { resolveHistorianModel } = await import("./model-resolution-dxatzjde.js");
30893
- const { userMemoryCollectionEnabled } = await import("./task-config-ex4nt0q0.js");
31082
+ const { userMemoryCollectionEnabled } = await import("./task-config-mgf5nsh3.js");
30894
31083
  const DEFAULT_HISTORIAN_TIMEOUT_MS = 600000;
30895
31084
  const runConfig = historianRunConfig(config, currentPluginConfigReader(directory)?.poll().effective ?? config);
30896
31085
  const historianModel = resolveHistorianModel(runConfig, "opencode");
@@ -30922,8 +31111,8 @@ function registerRpcHandlers(rpcServer, args) {
30922
31111
  const db = getDb();
30923
31112
  if (!db)
30924
31113
  return { ok: false, error: "db unavailable" };
30925
- const { runManagedRecomp } = await import("./recomp-orchestrator-6akjp11f.js");
30926
- const { sendIgnoredMessage } = await import("./send-session-notification-f6gwkesy.js");
31114
+ const { runManagedRecomp } = await import("./recomp-orchestrator-r00aa5t3.js");
31115
+ const { sendIgnoredMessage } = await import("./send-session-notification-3warjyjp.js");
30927
31116
  log(`[rpc] recomp requested for session ${sessionId}`);
30928
31117
  const ctx = await buildManagedCtx(db);
30929
31118
  runManagedRecomp(ctx, sessionId).then((message) => {
@@ -30981,7 +31170,7 @@ function registerRpcHandlers(rpcServer, args) {
30981
31170
  const db = getDb();
30982
31171
  if (!db)
30983
31172
  return { ok: false, error: "db unavailable" };
30984
- const { runManagedWrapup } = await import("./wrapup-orchestrator-5akc87gr.js");
31173
+ const { runManagedWrapup } = await import("./wrapup-orchestrator-y0bs7t5a.js");
30985
31174
  const model = liveSessionState.liveModelBySession.get(sessionId);
30986
31175
  const contextLimit = model ? resolveContextLimit(model.providerID, model.modelID, { db, sessionID: sessionId }) : 128000;
30987
31176
  const ctx = {
@@ -31838,21 +32027,6 @@ async function maybeDeliverChannel2(sessionId, deps) {
31838
32027
  }
31839
32028
  }
31840
32029
 
31841
- // src/hooks/magic-context/cache-busting-signals.ts
31842
- function canConsumeDeferredOnThisPass(args) {
31843
- if (args.justAwaitedPublication)
31844
- return true;
31845
- return args.schedulerDecision === "execute" || args.contextPercentage >= (args.forceMaterializationPercentage ?? escalationBands(65).forceMaterializationPercentage);
31846
- }
31847
- function hasReclaimRide(signals) {
31848
- return signals.hardFold || signals.force || signals.explicitFlush || signals.publishedHistory;
31849
- }
31850
- var RECLAIM_RIDE_NAMES = ["hardFold", "force", "explicitFlush", "publishedHistory"];
31851
- function reclaimRideLabel(signals) {
31852
- const active = RECLAIM_RIDE_NAMES.filter((name) => signals[name]);
31853
- return `ride=${active.length > 0 ? active.join("+") : "none"}`;
31854
- }
31855
-
31856
32030
  // src/hooks/magic-context/caveman-cleanup.ts
31857
32031
  var DEPTH_UNTOUCHED = 0;
31858
32032
  var DEPTH_LITE = 1;
@@ -36620,7 +36794,7 @@ function rustCaptureDigests(inputs, prior, acceptedInputs) {
36620
36794
  }
36621
36795
  function messageMatchesContentSnapshot(message, snapshot) {
36622
36796
  let fieldIndex = 0;
36623
- const matched = visitMessageContentFields(message, {
36797
+ const matched = visitMessageContentFields(contentSnapshotValue(message), {
36624
36798
  field(value) {
36625
36799
  if (!Object.is(value, snapshot.fields[fieldIndex]))
36626
36800
  return false;
@@ -36875,6 +37049,7 @@ function ensureState(states, sessionId) {
36875
37049
  if (!state) {
36876
37050
  state = {
36877
37051
  initialized: false,
37052
+ baselineSystemHashOmitted: false,
36878
37053
  consecutiveFailures: 0,
36879
37054
  passCount: 0,
36880
37055
  parked: false,
@@ -37836,6 +38011,7 @@ function createRustModeTransform(deps, options) {
37836
38011
  }
37837
38012
  }
37838
38013
  timings.preflight = performance.now() - passStartedAt;
38014
+ resolveCtxReduceAvailabilityFromMessages(sessionId, messages);
37839
38015
  const reduceAvailability = resolveCtxReduceAvailability(sessionId);
37840
38016
  resolveTodowriteAvailabilityFromMessages(sessionId, messages);
37841
38017
  const todoAvailability = resolveTodowriteAvailability(sessionId);
@@ -37907,6 +38083,8 @@ function createRustModeTransform(deps, options) {
37907
38083
  }
37908
38084
  const effectiveFloor = protectionFloorResolution.floor;
37909
38085
  const historianRun = deps.resolveHistorianRun?.();
38086
+ const observedSystemHash = sessionMeta.systemPromptHash ?? "";
38087
+ const rustSystemHash = state.baselineSystemHashOmitted && sessionMeta.cachedM0SystemHash === observedSystemHash ? "" : observedSystemHash;
37910
38088
  const passInputs = {
37911
38089
  now_ms: requestObservedAtMs,
37912
38090
  model_key: modelKey,
@@ -37928,7 +38106,7 @@ function createRustModeTransform(deps, options) {
37928
38106
  caveman_min_chars: deps.cavemanTextCompression?.minChars ?? 500,
37929
38107
  cache_ttl: sessionMeta.cacheTtl,
37930
38108
  is_subagent: sessionMeta.isSubagent,
37931
- system_prompt_hash: sessionMeta.systemPromptHash ?? "",
38109
+ system_prompt_hash: rustSystemHash,
37932
38110
  upgrade_state: readUpgradeState(deps.db, sessionId),
37933
38111
  tool_present: toolPresent,
37934
38112
  todo_tool_present: false,
@@ -38203,7 +38381,7 @@ function createRustModeTransform(deps, options) {
38203
38381
  modelKey: modelKey ?? null,
38204
38382
  providerId: model?.providerID ?? null,
38205
38383
  variant: deps.variantBySession?.get(sessionId),
38206
- systemPromptHash: sessionMeta.systemPromptHash ?? "",
38384
+ systemPromptHash: rustSystemHash,
38207
38385
  upgradeState: String(passInputs.upgrade_state ?? "")
38208
38386
  };
38209
38387
  let body = buildTransformBody({
@@ -38637,6 +38815,9 @@ function createRustModeTransform(deps, options) {
38637
38815
  state.ordinalContinuationBase = ordinalContinuationBase;
38638
38816
  }
38639
38817
  if (!stateSyncRetryBusy) {
38818
+ if (!state.initialized && !observedSystemHash) {
38819
+ state.baselineSystemHashOmitted = true;
38820
+ }
38640
38821
  state.initialized = true;
38641
38822
  state.seedPassPending = false;
38642
38823
  }
@@ -39757,7 +39938,12 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
39757
39938
  const tTrigger = performance.now();
39758
39939
  try {
39759
39940
  const inMemoryTail = buildTriggerInMemoryTail(db, sessionId, extractInMemoryMessageViews(messages));
39760
- const triggerResult = checkCompartmentTrigger(db, sessionId, sessionMeta, boundaryUsageForProtectedTail, sessionMeta.lastContextPercentage, boundaryExecuteThreshold, deriveTriggerBudget2(boundaryContextLimit, boundaryExecuteThreshold), deps.clearReasoningAge, historianRun?.commitClusterTrigger ?? deps.commitClusterTrigger, undefined, boundaryContextLimit, inMemoryTail, taggerFloor, { providerID: resolvedProviderID });
39941
+ const triggerResult = checkCompartmentTrigger(db, sessionId, sessionMeta, boundaryUsageForProtectedTail, sessionMeta.lastContextPercentage, boundaryExecuteThreshold, deriveTriggerBudget2(boundaryContextLimit, boundaryExecuteThreshold), deps.clearReasoningAge, historianRun?.commitClusterTrigger ?? deps.commitClusterTrigger, undefined, boundaryContextLimit, inMemoryTail, taggerFloor, { providerID: resolvedProviderID }, {
39942
+ hardFold: false,
39943
+ force: contextUsageEarly.percentage >= forceMaterializationPercentage && (contextUsageEarly.percentage >= 95 || getEmergencyInputSample(db, sessionId) === 0),
39944
+ explicitFlush: deps.pendingMaterializationSessions.has(sessionId),
39945
+ publishedHistory: isCacheBusting
39946
+ });
39761
39947
  if (triggerResult.shouldFire) {
39762
39948
  sessionLog(sessionId, `compartment trigger: firing (reason=${triggerResult.reason})`);
39763
39949
  updateSessionMeta(db, sessionId, { compartmentInProgress: true });
@@ -41990,7 +42176,7 @@ function createMagicContextHook(deps) {
41990
42176
  pauseEmbedDrain,
41991
42177
  getEmbedStatusText,
41992
42178
  sendNotification: async (sessionId, text, params) => {
41993
- await sendIgnoredMessage2(deps.client, sessionId, text, {
42179
+ await sendCommandResult2(deps.client, sessionId, text, {
41994
42180
  ...getLiveNotificationParams(sessionId, liveModelBySession, variantBySession, agentBySession, (deps.sampleDreamConfig?.() ?? deps.config).toast_duration_ms),
41995
42181
  ...params
41996
42182
  });
@@ -45728,9 +45914,33 @@ ${data.output?.output ?? ""}`
45728
45914
  var HIDDEN_HISTORIAN_AGENT = "historian";
45729
45915
  var HIDDEN_DREAMER_AGENT = "dreamer-classifier";
45730
45916
  var HIDDEN_CURATE_AGENT = DREAMER_AGENT;
45917
+ var READ_TOOLS = ["read", "grep", "glob"];
45918
+ var AGENT_TOOLS = {
45919
+ [HIDDEN_HISTORIAN_AGENT]: [],
45920
+ [HIDDEN_DREAMER_AGENT]: [],
45921
+ [HIDDEN_CURATE_AGENT]: ["ctx_memory", "ctx_memory_list"],
45922
+ [DREAMER_MEMORY_MAPPER_AGENT]: READ_TOOLS,
45923
+ [DREAMER_PRIMER_INVESTIGATOR_AGENT]: [...READ_TOOLS, "ctx_search"],
45924
+ [DREAMER_RETROSPECTIVE_AGENT]: ["ctx_search"]
45925
+ };
45926
+ var AGENT_STEPS = {
45927
+ [HIDDEN_CURATE_AGENT]: 150,
45928
+ [DREAMER_MEMORY_MAPPER_AGENT]: 60,
45929
+ [DREAMER_DOCS_AGENT]: 60,
45930
+ [DREAMER_PRIMER_INVESTIGATOR_AGENT]: 40,
45931
+ [DREAMER_RETROSPECTIVE_AGENT]: 40
45932
+ };
45933
+ function hiddenAgentFor(identity) {
45934
+ if (identity.kind === "dreamer-task" && identity.agent === DREAMER_DOCS_AGENT)
45935
+ return DREAMER_MEMORY_MAPPER_AGENT;
45936
+ return identity.kind === "dreamer-task" && AGENT_TOOLS[identity.agent] ? identity.agent : identity.kind === "dreamer-task" ? HIDDEN_DREAMER_AGENT : HIDDEN_HISTORIAN_AGENT;
45937
+ }
45938
+ function hiddenToolLoop(identity) {
45939
+ return identity.kind === "dreamer-task" && AGENT_STEPS[identity.agent] !== undefined;
45940
+ }
45731
45941
  async function registerHiddenChildAgents(agent) {
45732
45942
  await agent.transform((editor) => {
45733
- for (const id of [HIDDEN_HISTORIAN_AGENT, HIDDEN_DREAMER_AGENT, HIDDEN_CURATE_AGENT]) {
45943
+ for (const id of Object.keys(AGENT_TOOLS)) {
45734
45944
  editor.update(id, (config) => {
45735
45945
  config.system = "Magic Context hidden completion carrier.";
45736
45946
  config.description = "Internal Magic Context hidden completion carrier.";
@@ -45739,16 +45949,14 @@ async function registerHiddenChildAgents(agent) {
45739
45949
  config.request.settings = {};
45740
45950
  config.request.headers = {};
45741
45951
  config.request.body = {};
45952
+ config.steps = AGENT_STEPS[id];
45742
45953
  config.permissions = [
45743
45954
  { action: "*", resource: "*", effect: "deny" },
45744
- ...id === HIDDEN_CURATE_AGENT ? [
45745
- { action: "tool", resource: "ctx_memory", effect: "allow" },
45746
- {
45747
- action: "tool",
45748
- resource: "ctx_memory_list",
45749
- effect: "allow"
45750
- }
45751
- ] : []
45955
+ ...(AGENT_TOOLS[id] ?? []).map((tool) => ({
45956
+ action: tool,
45957
+ resource: "*",
45958
+ effect: "allow"
45959
+ }))
45752
45960
  ];
45753
45961
  });
45754
45962
  }
@@ -45793,15 +46001,21 @@ function calibratedParts(attempt) {
45793
46001
  class HiddenChildHook {
45794
46002
  childIDs = new Set;
45795
46003
  attempts = new Map;
46004
+ active = new Map;
45796
46005
  registerChild(sessionID) {
45797
46006
  this.childIDs.add(sessionID);
45798
46007
  }
45799
46008
  registerAttempt(marker, attempt) {
45800
46009
  this.registerChild(attempt.childSessionId);
46010
+ attempt.marker = marker;
45801
46011
  this.attempts.set(marker, attempt);
45802
46012
  }
45803
46013
  releaseAttempt(marker) {
46014
+ const attempt = this.attempts.get(marker);
45804
46015
  this.attempts.delete(marker);
46016
+ if (attempt && this.active.get(attempt.childSessionId) === attempt) {
46017
+ this.active.delete(attempt.childSessionId);
46018
+ }
45805
46019
  }
45806
46020
  owns(sessionID) {
45807
46021
  return this.childIDs.has(sessionID);
@@ -45812,19 +46026,43 @@ class HiddenChildHook {
45812
46026
  const raw = newestUserText(draft);
45813
46027
  const stripped = raw === undefined ? undefined : stripWellFormedLeadingTagPrefix(raw);
45814
46028
  const attempt = (raw !== undefined ? this.attempts.get(raw) : undefined) ?? (stripped && stripped !== raw ? this.attempts.get(stripped) : undefined);
45815
- if (!attempt || attempt.childSessionId !== draft.sessionID) {
46029
+ const current = this.active.get(draft.sessionID);
46030
+ const selected = attempt ?? current;
46031
+ if (!selected || selected.childSessionId !== draft.sessionID || attempt && current && current !== attempt) {
45816
46032
  throw new HiddenCompletionRefusal("hidden_prompt_unrecognized", "Refusing an unregistered prompt on a Magic Context hidden-run session", true);
45817
46033
  }
45818
- if (attempt.request.signal?.aborted) {
46034
+ if (selected.request.signal?.aborted) {
45819
46035
  throw new Error("Hidden completion prompt aborted");
45820
46036
  }
45821
- const system = typeof attempt.request.body.system === "string" ? attempt.request.body.system : attempt.identity.system;
46037
+ if (!selected.shaped) {
46038
+ if (!attempt)
46039
+ throw new HiddenCompletionRefusal("hidden_prompt_unrecognized", "Hidden child first step requires a registered marker", true);
46040
+ this.active.set(draft.sessionID, selected);
46041
+ }
46042
+ const steps = (selected.steps ?? 0) + 1;
46043
+ const cap = AGENT_STEPS[selected.identity.agent];
46044
+ if (cap !== undefined && steps > cap) {
46045
+ throw new Error(`Hidden agent exceeded its ${cap}-step limit`);
46046
+ }
46047
+ selected.steps = steps;
46048
+ const system = typeof selected.request.body.system === "string" ? selected.request.body.system : selected.identity.system;
45822
46049
  draft.system = [{ type: "text", text: system }];
45823
- draft.messages = [{ role: "user", content: calibratedParts(attempt) }];
45824
- draft.options = authoredOptions(attempt);
45825
- const dreamerTools = attempt.identity.agent === DREAMER_AGENT ? Object.fromEntries(["ctx_memory", "ctx_memory_list"].flatMap((id) => draft.tools[id] ? [[id, draft.tools[id]]] : [])) : {};
45826
- draft.tools = dreamerTools;
45827
- attempt.shaped = true;
46050
+ if (!selected.shaped) {
46051
+ draft.messages = [{ role: "user", content: calibratedParts(selected) }];
46052
+ } else {
46053
+ const first = draft.messages[0];
46054
+ const firstText = first && newestUserText({ ...draft, messages: [first] });
46055
+ const normalized = firstText === undefined ? undefined : stripWellFormedLeadingTagPrefix(firstText);
46056
+ if (normalized !== selected.marker) {
46057
+ throw new HiddenCompletionRefusal("hidden_prompt_unrecognized", "Hidden child history does not begin with this run's registered marker", true);
46058
+ }
46059
+ draft.messages[0] = { ...first, content: calibratedParts(selected) };
46060
+ }
46061
+ draft.options = authoredOptions(selected);
46062
+ const allowed = AGENT_TOOLS[hiddenAgentFor(selected.identity)] ?? [];
46063
+ draft.tools = Object.fromEntries(allowed.flatMap((id) => draft.tools[id] ? [[id, draft.tools[id]]] : []));
46064
+ selected.observedMessages = draft.messages;
46065
+ selected.shaped = true;
45828
46066
  return true;
45829
46067
  }
45830
46068
  }
@@ -45906,9 +46144,9 @@ function resolveOwnerHostService(owner, env = process.env, pid = process.pid) {
45906
46144
  }
45907
46145
  return own;
45908
46146
  }
45909
- async function removeHostSession(sessionID, owner, env = process.env) {
46147
+ async function removeHostSession(sessionID, owner, env = process.env, fetchSession = fetch) {
45910
46148
  const service = resolveOwnerHostService(owner, env);
45911
- const response = await fetch(`${service.url}/api/session/${encodeURIComponent(sessionID)}`, {
46149
+ const response = await fetchSession(`${service.url}/api/session/${encodeURIComponent(sessionID)}`, {
45912
46150
  method: "DELETE",
45913
46151
  headers: service.headers,
45914
46152
  signal: AbortSignal.timeout(60000)
@@ -46110,6 +46348,37 @@ function settledProviderError(row) {
46110
46348
  function successfulReusableAssistant(row) {
46111
46349
  return row !== undefined && (typeof row.data.finish === "string" || assistantOutcome(row) === "succeeded") && row.data.error === undefined && row.data.tokens !== undefined;
46112
46350
  }
46351
+ function toolLoopMessages(attempt) {
46352
+ const messages = attempt.observedMessages ?? [];
46353
+ const results = new Map;
46354
+ for (const message of messages) {
46355
+ if (message.role !== "tool")
46356
+ continue;
46357
+ for (const part of message.content) {
46358
+ if (part.type !== "tool-result" || typeof part.id !== "string")
46359
+ continue;
46360
+ const result = part.result;
46361
+ results.set(part.id, { status: result?.type === "error" ? "error" : "completed" });
46362
+ }
46363
+ }
46364
+ return messages.flatMap((message) => {
46365
+ if (message.role !== "assistant")
46366
+ return [];
46367
+ const parts = message.content.flatMap((part) => {
46368
+ if (part.type !== "tool-call" || typeof part.id !== "string" || typeof part.name !== "string")
46369
+ return [];
46370
+ const result = results.get(part.id);
46371
+ return [
46372
+ {
46373
+ type: "tool",
46374
+ tool: part.name,
46375
+ state: { status: result?.status ?? "pending", input: part.input }
46376
+ }
46377
+ ];
46378
+ });
46379
+ return parts.length ? [{ info: { role: "assistant" }, parts }] : [];
46380
+ });
46381
+ }
46113
46382
  function assistantText(row) {
46114
46383
  const text = (row.data.content ?? []).flatMap((part) => part.type === "text" && typeof part.text === "string" ? [part.text] : []).join("");
46115
46384
  return text.length > 0 ? text : null;
@@ -46361,7 +46630,7 @@ async function createV2HiddenCompletionExecutor(host, options) {
46361
46630
  }
46362
46631
  };
46363
46632
  return {
46364
- capabilities: { tools: false, harness: "opencode2" },
46633
+ capabilities: { tools: true, harness: "opencode2" },
46365
46634
  async open(identity) {
46366
46635
  const role = roleFor(identity);
46367
46636
  const releaseRole = await acquireRole(role);
@@ -46370,6 +46639,10 @@ async function createV2HiddenCompletionExecutor(host, options) {
46370
46639
  await options.ensureAgent?.();
46371
46640
  const head = await resolveHead(identity);
46372
46641
  let active = store.read().active[role];
46642
+ if (active && hiddenToolLoop(identity)) {
46643
+ retireChild(active, "fresh-tool-loop-run");
46644
+ active = undefined;
46645
+ }
46373
46646
  if (active && active.generation !== generation) {
46374
46647
  retireChild(active, "host-generation-changed");
46375
46648
  active = undefined;
@@ -46392,7 +46665,7 @@ async function createV2HiddenCompletionExecutor(host, options) {
46392
46665
  const title = roleTitle(role);
46393
46666
  const created = await host.create({
46394
46667
  title,
46395
- agent: roleAgent(role),
46668
+ agent: hiddenToolLoop(identity) ? hiddenAgentFor(identity) : roleAgent(role),
46396
46669
  model: {
46397
46670
  providerID: head.providerID,
46398
46671
  id: head.modelID,
@@ -46450,6 +46723,7 @@ async function createV2HiddenCompletionExecutor(host, options) {
46450
46723
  await switchChildModel(run, requested);
46451
46724
  const baseline = withReader(options.openReader, (reader) => reader.latestSequence(run.child.id));
46452
46725
  const marker = `mc:hidden:${crypto.randomUUID()}:${crypto.randomUUID()}`;
46726
+ run.completion = undefined;
46453
46727
  const attempt = {
46454
46728
  childSessionId: run.child.id,
46455
46729
  identity: run.identity,
@@ -46509,6 +46783,7 @@ async function createV2HiddenCompletionExecutor(host, options) {
46509
46783
  }
46510
46784
  run.completion = {
46511
46785
  text,
46786
+ ...hiddenToolLoop(run.identity) ? { messages: toolLoopMessages(attempt) } : {},
46512
46787
  reasoning: null,
46513
46788
  usage: reportedInput !== undefined || reportedOutput !== undefined ? {
46514
46789
  input: reportedInput ?? 0,
@@ -46553,7 +46828,9 @@ async function createV2HiddenCompletionExecutor(host, options) {
46553
46828
  return;
46554
46829
  try {
46555
46830
  const reusable = run.failed && !run.unsettledFailure;
46556
- if (!run.completion && (run.failed || !settlement.promptSettled) && !reusable) {
46831
+ if (hiddenToolLoop(run.identity)) {
46832
+ retire(run, settlement.promptSettled ? "tool-loop-settled" : "tool-loop-failed");
46833
+ } else if (!run.completion && (run.failed || !settlement.promptSettled) && !reusable) {
46557
46834
  retire(run, "hidden-run-failed");
46558
46835
  }
46559
46836
  } finally {
@@ -47279,6 +47556,23 @@ async function warmModelLimitCacheFromCatalog(context, options = {}) {
47279
47556
 
47280
47557
  // src/v2/hooks/payload.ts
47281
47558
  var HEAD_IDS = ["__magic_context_v2_m0__", "__magic_context_v2_m1__"];
47559
+ var HOST_CONTENT_TYPES = new Set([
47560
+ "text",
47561
+ "media",
47562
+ "tool-call",
47563
+ "tool-result",
47564
+ "reasoning",
47565
+ "compaction",
47566
+ "effort"
47567
+ ]);
47568
+ function rejectContentPart(message, part, reason) {
47569
+ const type = typeof part.type === "string" ? part.type : "<missing>";
47570
+ const text = `v2 context omitted a content part the host would reject: type=${type} message=${String(message.info.id ?? "<head>")} reason=${reason}`;
47571
+ if (typeof message.info.sessionID === "string")
47572
+ sessionLog(message.info.sessionID, text);
47573
+ else
47574
+ log(text);
47575
+ }
47282
47576
  function isHostInstance(value) {
47283
47577
  if (!value || typeof value !== "object" || Array.isArray(value))
47284
47578
  return false;
@@ -47469,6 +47763,56 @@ function adaptPayload(draft, admittedIDs = new Set) {
47469
47763
  const part = candidate;
47470
47764
  const bridge = bridges.get(part) ?? (part.type === "tool" && typeof part.callID === "string" ? bridgesFor(message)?.get(part.callID) : undefined);
47471
47765
  if (!bridge) {
47766
+ if (part.type === "tool") {
47767
+ const state = part.state;
47768
+ if (typeof part.callID !== "string" || typeof part.tool !== "string" || !state || typeof state !== "object") {
47769
+ rejectContentPart(message, part, "tool has no call ID, name, or state");
47770
+ continue;
47771
+ }
47772
+ content.push({
47773
+ type: "tool-call",
47774
+ id: part.callID,
47775
+ name: part.tool,
47776
+ input: state.input
47777
+ });
47778
+ if (state.status === "completed" || state.status === "error") {
47779
+ following.push({
47780
+ role: "tool",
47781
+ content: [
47782
+ {
47783
+ type: "tool-result",
47784
+ id: part.callID,
47785
+ name: part.tool,
47786
+ result: {
47787
+ type: state.status === "error" ? "error" : "text",
47788
+ value: toolStateContent(state)
47789
+ }
47790
+ }
47791
+ ]
47792
+ });
47793
+ }
47794
+ continue;
47795
+ }
47796
+ if (part.type === "file") {
47797
+ const mime = part.mime;
47798
+ const url = part.url;
47799
+ const prefix = `data:${mime};base64,`;
47800
+ if (typeof mime !== "string" || !/^image\/(png|jpeg|gif|webp)$/.test(mime) || typeof url !== "string" || !url.startsWith(prefix)) {
47801
+ rejectContentPart(message, part, "file is not an inline supported image");
47802
+ continue;
47803
+ }
47804
+ const asset = hostMediaAsset(url.slice(prefix.length), mime);
47805
+ if (typeof asset === "string") {
47806
+ rejectContentPart(message, part, `host media unavailable: ${asset}`);
47807
+ continue;
47808
+ }
47809
+ content.push({ type: "media", media: asset });
47810
+ continue;
47811
+ }
47812
+ if (!HOST_CONTENT_TYPES.has(String(part.type))) {
47813
+ rejectContentPart(message, part, "unknown host content type");
47814
+ continue;
47815
+ }
47472
47816
  const { synthetic: _synthetic, ...clean } = part;
47473
47817
  const original = hostPartTypes.has(clean.type) && !containsHostInstance(clean) ? hostParts.get(contentKey(clean)) : undefined;
47474
47818
  content.push(original ?? clean);
@@ -47476,14 +47820,23 @@ function adaptPayload(draft, admittedIDs = new Set) {
47476
47820
  }
47477
47821
  const state = part.state;
47478
47822
  if (bridge.native) {
47479
- const sourceState = bridge.native.state && typeof bridge.native.state === "object" ? bridge.native.state : {};
47480
- const nextState = { ...sourceState, input: state.input };
47481
- if (sourceState.content !== undefined) {
47482
- nextState.content = state.output === bridge.output ? sourceState.content : [{ type: "text", text: state.output }];
47483
- } else {
47484
- nextState.output = state.output;
47823
+ const native = bridge.native;
47824
+ const callID = String(native.id ?? native.callID ?? part.callID);
47825
+ const name = String(native.name ?? native.tool ?? part.tool);
47826
+ content.push({ type: "tool-call", id: callID, name, input: state.input });
47827
+ if (state.status === "completed" || state.status === "error") {
47828
+ following.push({
47829
+ role: "tool",
47830
+ content: [
47831
+ {
47832
+ type: "tool-result",
47833
+ id: callID,
47834
+ name,
47835
+ result: { type: "text", value: state.output }
47836
+ }
47837
+ ]
47838
+ });
47485
47839
  }
47486
- content.push({ ...bridge.native, state: nextState });
47487
47840
  continue;
47488
47841
  }
47489
47842
  if (bridge.call)
@@ -48753,7 +49106,7 @@ var server = async (ctx) => {
48753
49106
  if (hasBannerEntries)
48754
49107
  setTimeout(async () => {
48755
49108
  try {
48756
- const { sendStatusNotification } = await import("./send-session-notification-f6gwkesy.js");
49109
+ const { sendStatusNotification } = await import("./send-session-notification-3warjyjp.js");
48757
49110
  const clientWithSessions = ctx.client;
48758
49111
  const sessions = await Promise.resolve(clientWithSessions.session?.list?.()).catch(() => null);
48759
49112
  const sessionList = Array.isArray(sessions) ? sessions : sessions?.data;
@@ -48770,7 +49123,7 @@ var server = async (ctx) => {
48770
49123
  log(`[magic-context] opencode_db_missing path=${openCodeDbResolution.path} source=${openCodeDbResolution.source}`);
48771
49124
  setTimeout(async () => {
48772
49125
  try {
48773
- const { sendStatusNotification } = await import("./send-session-notification-f6gwkesy.js");
49126
+ const { sendStatusNotification } = await import("./send-session-notification-3warjyjp.js");
48774
49127
  const clientWithSessions = ctx.client;
48775
49128
  const sessions = await Promise.resolve(clientWithSessions.session?.list?.()).catch(() => null);
48776
49129
  const sessionList = Array.isArray(sessions) ? sessions : sessions?.data;
@@ -49037,12 +49390,12 @@ var server = async (ctx) => {
49037
49390
  {
49038
49391
  const fence = getSchemaFenceRejection();
49039
49392
  if (fence) {
49040
- import("./conflict-warning-hook-t2vb0wnx.js").then(({ sendSchemaFenceWarning }) => sendSchemaFenceWarning(ctx.client, ctx.directory, fence));
49393
+ import("./conflict-warning-hook-956fkedc.js").then(({ sendSchemaFenceWarning }) => sendSchemaFenceWarning(ctx.client, ctx.directory, fence));
49041
49394
  }
49042
49395
  }
49043
49396
  const serverUrl = ctx.serverUrl;
49044
49397
  const serverUrlStr = serverUrl instanceof URL ? serverUrl.toString().replace(/\/$/, "") : typeof serverUrl === "string" ? serverUrl.replace(/\/$/, "") : undefined;
49045
- import("./send-session-notification-f6gwkesy.js").then(({ setNotificationServerUrl }) => {
49398
+ import("./send-session-notification-3warjyjp.js").then(({ setNotificationServerUrl }) => {
49046
49399
  setNotificationServerUrl(serverUrlStr);
49047
49400
  });
49048
49401
  if (conflictResult?.hasConflict) {
@@ -49056,7 +49409,7 @@ var server = async (ctx) => {
49056
49409
  }
49057
49410
  if (pluginConfig.enabled && !conflictResult?.hasConflict) {
49058
49411
  setTimeout(() => {
49059
- import("./announcement-8mgn61fw.js").then(({
49412
+ import("./announcement-1a8bvswd.js").then(({
49060
49413
  shouldShowAnnouncement,
49061
49414
  ANNOUNCEMENT_VERSION,
49062
49415
  ANNOUNCEMENT_FEATURES,
@@ -49065,7 +49418,7 @@ var server = async (ctx) => {
49065
49418
  }) => {
49066
49419
  if (!shouldShowAnnouncement())
49067
49420
  return;
49068
- return import("./conflict-warning-hook-t2vb0wnx.js").then(({ sendStartupAnnouncement }) => sendStartupAnnouncement(ctx.client, ctx.directory, ANNOUNCEMENT_VERSION, ANNOUNCEMENT_FEATURES, ANNOUNCEMENT_FOOTER, markAnnouncementSeen));
49421
+ return import("./conflict-warning-hook-956fkedc.js").then(({ sendStartupAnnouncement }) => sendStartupAnnouncement(ctx.client, ctx.directory, ANNOUNCEMENT_VERSION, ANNOUNCEMENT_FEATURES, ANNOUNCEMENT_FOOTER, markAnnouncementSeen));
49069
49422
  }).catch(() => {});
49070
49423
  }, 8000);
49071
49424
  }
@@ -49138,9 +49491,7 @@ var server = async (ctx) => {
49138
49491
  const provId = typed.model?.providerID;
49139
49492
  const modId = typed.model?.modelID;
49140
49493
  const agent = typed.agent;
49141
- if (provId && modId && agent) {
49142
- lastChatContext = { providerID: provId, modelID: modId, agentName: agent };
49143
- }
49494
+ lastChatContext = provId && modId ? { providerID: provId, modelID: modId, agentName: agent || "default" } : null;
49144
49495
  await magicContextRuntime.magicContext?.["chat.message"]?.(input, output);
49145
49496
  },
49146
49497
  "tool.definition": async (input, output) => {