@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/v2/server.js CHANGED
@@ -1675,8 +1675,15 @@ function getHarness() {
1675
1675
  }
1676
1676
  var currentHarness = "opencode", harnessLocked = false;
1677
1677
 
1678
+ // src/shared/test-temp-dir.ts
1679
+ var STALE_TEMP_DIR_AGE_MS, registeredTempDirs;
1680
+ var init_test_temp_dir = __esm(() => {
1681
+ STALE_TEMP_DIR_AGE_MS = 60 * 60 * 1000;
1682
+ registeredTempDirs = new Set;
1683
+ });
1684
+
1678
1685
  // src/shared/data-path.ts
1679
- import { existsSync as existsSync2, mkdirSync, mkdtempSync, readFileSync as readFileSync2, writeFileSync } from "node:fs";
1686
+ import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync } from "node:fs";
1680
1687
  import * as os from "node:os";
1681
1688
  import * as path from "node:path";
1682
1689
  function getDataDir() {
@@ -1764,7 +1771,9 @@ function getLegacyOpenCodeMagicContextStorageDir() {
1764
1771
  return path.join(getOpenCodeStorageDir(), "plugin", "magic-context");
1765
1772
  }
1766
1773
  var GITIGNORE_GUARD_OPEN = "# >>> cortexkit:magic-context", GITIGNORE_GUARD_CLOSE = "# <<< cortexkit:magic-context";
1767
- var init_data_path = () => {};
1774
+ var init_data_path = __esm(() => {
1775
+ init_test_temp_dir();
1776
+ });
1768
1777
 
1769
1778
  // src/shared/harness-provider-map.ts
1770
1779
  function remapProviderPrefix(ref, map) {
@@ -8994,7 +9003,7 @@ var init_task_registry = __esm(() => {
8994
9003
  "maintain-docs": {
8995
9004
  requiresTools: true,
8996
9005
  transport: "tool-loop",
8997
- toolLoopPurpose: "needs file read and write tools to update project documentation"
9006
+ toolLoopPurpose: "needs read-only file tools to investigate documentation corrections"
8998
9007
  },
8999
9008
  "evaluate-smart-notes": { requiresTools: false, transport: "single-shot" },
9000
9009
  "review-user-memories": { requiresTools: false, transport: "single-shot" },
@@ -18005,6 +18014,8 @@ function hasCountableParts(message) {
18005
18014
  case "step-start":
18006
18015
  case "step-finish":
18007
18016
  return true;
18017
+ case "file":
18018
+ return typeof p.url === "string" && p.url.startsWith("data:image/");
18008
18019
  default:
18009
18020
  return false;
18010
18021
  }
@@ -25201,9 +25212,22 @@ function visitMessageContentFields(value, visitor) {
25201
25212
  }
25202
25213
  return visitor.field(LKG_SNAPSHOT_UNDEFINED);
25203
25214
  }
25215
+ function contentSnapshotValue(value) {
25216
+ if (!value || typeof value !== "object")
25217
+ return value;
25218
+ const message = value;
25219
+ const info = message.info;
25220
+ const summary = info?.summary;
25221
+ if (!Array.isArray(message.parts) || info?.role !== "user" || summary === null || typeof summary !== "object" || Array.isArray(summary) || Object.keys(summary).length !== 1 || !Array.isArray(summary.diffs) || summary.diffs.length !== 0)
25222
+ return value;
25223
+ return {
25224
+ ...message,
25225
+ info: Object.fromEntries(Object.entries(info).filter(([key]) => key !== "summary"))
25226
+ };
25227
+ }
25204
25228
  function messageContentFields(message) {
25205
25229
  const fields = [];
25206
- const complete = visitMessageContentFields(message, {
25230
+ const complete = visitMessageContentFields(contentSnapshotValue(message), {
25207
25231
  field(value) {
25208
25232
  fields.push(value);
25209
25233
  return true;
@@ -25269,7 +25293,7 @@ function lkgContentFields(value) {
25269
25293
  fields.push(LKG_SNAPSHOT_UNDEFINED);
25270
25294
  };
25271
25295
  try {
25272
- visit(value);
25296
+ visit(contentSnapshotValue(value));
25273
25297
  return fields;
25274
25298
  } catch {
25275
25299
  return null;
@@ -73985,7 +74009,12 @@ async function runGit(cwd, args) {
73985
74009
  encoding: "utf8"
73986
74010
  });
73987
74011
  return String(result.stdout);
73988
- } catch {
74012
+ } catch (error) {
74013
+ if (error.killed || error.code === "ETIMEDOUT") {
74014
+ throw new Error(`Git verification command timed out after ${GIT_TIMEOUT_MS2}ms`, {
74015
+ cause: error
74016
+ });
74017
+ }
73989
74018
  return null;
73990
74019
  }
73991
74020
  }
@@ -74408,6 +74437,45 @@ var init_note_nudger = __esm(() => {
74408
74437
  lastDeliveredAt = new Map;
74409
74438
  });
74410
74439
 
74440
+ // src/shared/safe-notification-target.ts
74441
+ function isDefaultSessionTitle(title) {
74442
+ return DEFAULT_TITLE_RE.test(title);
74443
+ }
74444
+ async function readSessionTitle(client, sessionId) {
74445
+ try {
74446
+ const c = client;
74447
+ if (typeof c.session?.get !== "function")
74448
+ return null;
74449
+ const raw = await Promise.resolve(c.session.get({ path: { id: sessionId } }));
74450
+ const obj = raw;
74451
+ const title = obj && typeof obj === "object" ? obj.data?.title ?? obj.title : undefined;
74452
+ return typeof title === "string" ? title : null;
74453
+ } catch {
74454
+ return null;
74455
+ }
74456
+ }
74457
+ async function waitForSafeNotificationTarget(client, sessionId, options) {
74458
+ const attempts = Math.max(1, options?.attempts ?? 4);
74459
+ const delayMs = options?.delayMs ?? 15000;
74460
+ for (let attempt = 0;attempt < attempts; attempt += 1) {
74461
+ const title = await readSessionTitle(client, sessionId);
74462
+ if (title === null)
74463
+ return "safe";
74464
+ if (!isDefaultSessionTitle(title))
74465
+ return "safe";
74466
+ if (attempt < attempts - 1) {
74467
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
74468
+ }
74469
+ }
74470
+ log(`[magic-context] notification skipped: session ${sessionId} still has its default title (would suppress title generation); will retry on a later startup`);
74471
+ return "skip";
74472
+ }
74473
+ var DEFAULT_TITLE_RE;
74474
+ var init_safe_notification_target = __esm(() => {
74475
+ init_logger();
74476
+ DEFAULT_TITLE_RE = /^(New session - |Child session - )\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
74477
+ });
74478
+
74411
74479
  // src/shared/rpc-notifications.ts
74412
74480
  function registerNotificationSink(sink) {
74413
74481
  sinks.add(sink);
@@ -74508,45 +74576,6 @@ var init_rpc_notifications = __esm(() => {
74508
74576
  sinks = new Set;
74509
74577
  });
74510
74578
 
74511
- // src/shared/safe-notification-target.ts
74512
- function isDefaultSessionTitle(title) {
74513
- return DEFAULT_TITLE_RE.test(title);
74514
- }
74515
- async function readSessionTitle(client, sessionId) {
74516
- try {
74517
- const c = client;
74518
- if (typeof c.session?.get !== "function")
74519
- return null;
74520
- const raw = await Promise.resolve(c.session.get({ path: { id: sessionId } }));
74521
- const obj = raw;
74522
- const title = obj && typeof obj === "object" ? obj.data?.title ?? obj.title : undefined;
74523
- return typeof title === "string" ? title : null;
74524
- } catch {
74525
- return null;
74526
- }
74527
- }
74528
- async function waitForSafeNotificationTarget(client, sessionId, options) {
74529
- const attempts = Math.max(1, options?.attempts ?? 4);
74530
- const delayMs = options?.delayMs ?? 15000;
74531
- for (let attempt = 0;attempt < attempts; attempt += 1) {
74532
- const title = await readSessionTitle(client, sessionId);
74533
- if (title === null)
74534
- return "safe";
74535
- if (!isDefaultSessionTitle(title))
74536
- return "safe";
74537
- if (attempt < attempts - 1) {
74538
- await new Promise((resolve) => setTimeout(resolve, delayMs));
74539
- }
74540
- }
74541
- log(`[magic-context] notification skipped: session ${sessionId} still has its default title (would suppress title generation); will retry on a later startup`);
74542
- return "skip";
74543
- }
74544
- var DEFAULT_TITLE_RE;
74545
- var init_safe_notification_target = __esm(() => {
74546
- init_logger();
74547
- DEFAULT_TITLE_RE = /^(New session - |Child session - )\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
74548
- });
74549
-
74550
74579
  // src/shared/prompt-context.ts
74551
74580
  function isRecord6(value) {
74552
74581
  return typeof value === "object" && value !== null;
@@ -74908,6 +74937,7 @@ async function sendStatusNotification(_client, sessionId, text, params) {
74908
74937
  var MAX_QUEUED_IGNORED_NOTIFICATIONS = 16, queuedIgnoredNotifications, flushingIgnoredNotifications, idleSessions, lastDeliveredText, activityEpoch, defaultHoldDetector = (sessionId) => !idleSessions.has(sessionId) || shouldHoldIgnoredNotification(sessionId), holdDetector, notificationServerUrl, noticeDeleter, notificationDiagnosticObserverForTests;
74909
74938
  var init_send_session_notification = __esm(async () => {
74910
74939
  init_logger();
74940
+ init_safe_notification_target();
74911
74941
  await init_read_session_db();
74912
74942
  queuedIgnoredNotifications = new Map;
74913
74943
  flushingIgnoredNotifications = new Set;
@@ -75052,6 +75082,74 @@ var init_storage_user_memory = __esm(() => {
75052
75082
  USER_MEMORY_CANDIDATE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
75053
75083
  });
75054
75084
 
75085
+ // src/shared/assistant-message-extractor.ts
75086
+ function asSessionMessage(value) {
75087
+ if (!isRecord3(value))
75088
+ return null;
75089
+ const info = value.info;
75090
+ const parts = value.parts;
75091
+ return {
75092
+ info: isRecord3(info) ? {
75093
+ role: typeof info.role === "string" ? info.role : undefined,
75094
+ time: isRecord3(info.time) ? {
75095
+ created: typeof info.time.created === "number" ? info.time.created : undefined
75096
+ } : undefined,
75097
+ error: info.error,
75098
+ finish: typeof info.finish === "string" ? info.finish : typeof info.finish_reason === "string" ? info.finish_reason : typeof info.finishReason === "string" ? info.finishReason : undefined
75099
+ } : undefined,
75100
+ parts
75101
+ };
75102
+ }
75103
+ function getCreatedTime(message) {
75104
+ return message.info?.time?.created ?? 0;
75105
+ }
75106
+ function getTextParts(message) {
75107
+ if (!Array.isArray(message.parts))
75108
+ return [];
75109
+ return message.parts.filter((part) => isRecord3(part)).map((part) => ({
75110
+ type: typeof part.type === "string" ? part.type : undefined,
75111
+ text: typeof part.text === "string" ? part.text : undefined
75112
+ })).filter((part) => part.type === "text" && Boolean(part.text));
75113
+ }
75114
+ function getLatestAssistantMessage(messages) {
75115
+ if (!Array.isArray(messages) || messages.length === 0)
75116
+ return null;
75117
+ return messages.map(asSessionMessage).filter((message) => message !== null).filter((message) => message.info?.role === "assistant").sort((a, b) => getCreatedTime(b) - getCreatedTime(a))[0] ?? null;
75118
+ }
75119
+ function extractLatestAssistantText(messages) {
75120
+ const latest = getLatestAssistantMessage(messages);
75121
+ if (!latest)
75122
+ return null;
75123
+ return getTextParts(latest).map((part) => part.text).join(`
75124
+ `) || null;
75125
+ }
75126
+ function extractLatestAssistantFailure(messages) {
75127
+ const latest = getLatestAssistantMessage(messages);
75128
+ if (!latest || latest.info?.error === undefined || latest.info.error === null)
75129
+ return null;
75130
+ return {
75131
+ error: latest.info.error,
75132
+ finish: latest.info.finish ?? null
75133
+ };
75134
+ }
75135
+ function hasLengthCappedOutput(value) {
75136
+ if (Array.isArray(value))
75137
+ return value.some((item) => hasLengthCappedOutput(item));
75138
+ if (!isRecord3(value))
75139
+ return false;
75140
+ if (value.length_capped === true || value.lengthCapped === true)
75141
+ return true;
75142
+ const finishReason = value.finish_reason ?? value.finishReason ?? value.finish ?? (value.type === "step-finish" ? value.reason : undefined) ?? value.stopReason;
75143
+ if (typeof finishReason === "string") {
75144
+ const normalized = finishReason.toLowerCase();
75145
+ if (normalized === "length" || normalized === "max_tokens" || normalized === "max_output_tokens") {
75146
+ return true;
75147
+ }
75148
+ }
75149
+ return Object.values(value).some((item) => hasLengthCappedOutput(item));
75150
+ }
75151
+ var init_assistant_message_extractor = () => {};
75152
+
75055
75153
  // src/shared/resolve-fallbacks.ts
75056
75154
  function parseProviderModel(spec) {
75057
75155
  const slash = spec.indexOf("/");
@@ -75343,6 +75441,17 @@ async function attemptAndValidate(client, args, timeoutMs, signal, callContext,
75343
75441
  };
75344
75442
  }
75345
75443
  try {
75444
+ if (!extractLatestAssistantText(output)) {
75445
+ const assistantFailure = extractLatestAssistantFailure(output);
75446
+ if (assistantFailure) {
75447
+ const error = new Error(`Host recorded assistant error: ${String(assistantFailure.error)}`);
75448
+ Object.assign(error, {
75449
+ name: "DreamerProviderOutputFailureError",
75450
+ transient: true
75451
+ });
75452
+ throw error;
75453
+ }
75454
+ }
75346
75455
  const validated = await options.validateOutput(output, attempt);
75347
75456
  return { output, validated, attempt };
75348
75457
  } catch (error) {
@@ -75429,6 +75538,7 @@ async function promptSyncWithValidatedOutputRetry(client, args, options) {
75429
75538
  var ABORT_CALL_TIMEOUT_MS = 3000, promptFailureDetails;
75430
75539
  var init_model_suggestion_retry = __esm(() => {
75431
75540
  init_overflow_detection();
75541
+ init_assistant_message_extractor();
75432
75542
  init_logger();
75433
75543
  init_redaction();
75434
75544
  promptFailureDetails = new WeakMap;
@@ -77636,74 +77746,6 @@ var init_subagent_token_capture = __esm(() => {
77636
77746
  init_logger();
77637
77747
  });
77638
77748
 
77639
- // src/shared/assistant-message-extractor.ts
77640
- function asSessionMessage(value) {
77641
- if (!isRecord3(value))
77642
- return null;
77643
- const info = value.info;
77644
- const parts = value.parts;
77645
- return {
77646
- info: isRecord3(info) ? {
77647
- role: typeof info.role === "string" ? info.role : undefined,
77648
- time: isRecord3(info.time) ? {
77649
- created: typeof info.time.created === "number" ? info.time.created : undefined
77650
- } : undefined,
77651
- error: info.error,
77652
- finish: typeof info.finish === "string" ? info.finish : typeof info.finish_reason === "string" ? info.finish_reason : typeof info.finishReason === "string" ? info.finishReason : undefined
77653
- } : undefined,
77654
- parts
77655
- };
77656
- }
77657
- function getCreatedTime(message) {
77658
- return message.info?.time?.created ?? 0;
77659
- }
77660
- function getTextParts(message) {
77661
- if (!Array.isArray(message.parts))
77662
- return [];
77663
- return message.parts.filter((part) => isRecord3(part)).map((part) => ({
77664
- type: typeof part.type === "string" ? part.type : undefined,
77665
- text: typeof part.text === "string" ? part.text : undefined
77666
- })).filter((part) => part.type === "text" && Boolean(part.text));
77667
- }
77668
- function getLatestAssistantMessage(messages) {
77669
- if (!Array.isArray(messages) || messages.length === 0)
77670
- return null;
77671
- return messages.map(asSessionMessage).filter((message) => message !== null).filter((message) => message.info?.role === "assistant").sort((a, b) => getCreatedTime(b) - getCreatedTime(a))[0] ?? null;
77672
- }
77673
- function extractLatestAssistantText(messages) {
77674
- const latest = getLatestAssistantMessage(messages);
77675
- if (!latest)
77676
- return null;
77677
- return getTextParts(latest).map((part) => part.text).join(`
77678
- `) || null;
77679
- }
77680
- function extractLatestAssistantFailure(messages) {
77681
- const latest = getLatestAssistantMessage(messages);
77682
- if (!latest || latest.info?.error === undefined || latest.info.error === null)
77683
- return null;
77684
- return {
77685
- error: latest.info.error,
77686
- finish: latest.info.finish ?? null
77687
- };
77688
- }
77689
- function hasLengthCappedOutput(value) {
77690
- if (Array.isArray(value))
77691
- return value.some((item) => hasLengthCappedOutput(item));
77692
- if (!isRecord3(value))
77693
- return false;
77694
- if (value.length_capped === true || value.lengthCapped === true)
77695
- return true;
77696
- const finishReason = value.finish_reason ?? value.finishReason ?? value.finish ?? (value.type === "step-finish" ? value.reason : undefined) ?? value.stopReason;
77697
- if (typeof finishReason === "string") {
77698
- const normalized = finishReason.toLowerCase();
77699
- if (normalized === "length" || normalized === "max_tokens" || normalized === "max_output_tokens") {
77700
- return true;
77701
- }
77702
- }
77703
- return Object.values(value).some((item) => hasLengthCappedOutput(item));
77704
- }
77705
- var init_assistant_message_extractor = () => {};
77706
-
77707
77749
  // src/shared/keep-subagents.ts
77708
77750
  function shouldKeepSubagents() {
77709
77751
  return keepSubagents;
@@ -108022,9 +108064,26 @@ init_window_geometry();
108022
108064
  init_compartment_storage();
108023
108065
  init_session_decision_calibration();
108024
108066
  init_logger();
108067
+ await init_storage();
108068
+
108069
+ // src/hooks/magic-context/cache-busting-signals.ts
108070
+ function canConsumeDeferredOnThisPass(args) {
108071
+ if (args.justAwaitedPublication)
108072
+ return true;
108073
+ return args.schedulerDecision === "execute" || args.contextPercentage >= (args.forceMaterializationPercentage ?? escalationBands(65).forceMaterializationPercentage);
108074
+ }
108075
+ function hasReclaimRide(signals) {
108076
+ return signals.hardFold || signals.force || signals.explicitFlush || signals.publishedHistory;
108077
+ }
108078
+ var RECLAIM_RIDE_NAMES = ["hardFold", "force", "explicitFlush", "publishedHistory"];
108079
+ function reclaimRideLabel(signals) {
108080
+ const active = RECLAIM_RIDE_NAMES.filter((name) => signals[name]);
108081
+ return `ride=${active.length > 0 ? active.join("+") : "none"}`;
108082
+ }
108083
+
108084
+ // src/hooks/magic-context/compartment-trigger.ts
108025
108085
  init_read_session_true_raw_tokens();
108026
108086
  await __promiseAll([
108027
- init_storage(),
108028
108087
  init_protected_tail_boundary(),
108029
108088
  init_read_session_chunk()
108030
108089
  ]);
@@ -108204,7 +108263,7 @@ function getUnsummarizedTailInfo(db, sessionId, triggerBudget, usage, executeThr
108204
108263
  function formatProjectedPostDropPercentage(value) {
108205
108264
  return value === null ? "none" : `${value.toFixed(1)}%`;
108206
108265
  }
108207
- function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPercentage, executeThresholdPercentage, triggerBudget, clearReasoningAge, commitClusterTrigger, preloadedActiveTags, contextLimit, inMemoryTail, taggerFloorOverride, reasoningProjection) {
108266
+ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPercentage, executeThresholdPercentage, triggerBudget, clearReasoningAge, commitClusterTrigger, preloadedActiveTags, contextLimit, inMemoryTail, taggerFloorOverride, reasoningProjection, reclaimRide) {
108208
108267
  if (sessionMeta.compartmentInProgress) {
108209
108268
  sessionLog(sessionId, `compartment trigger: skipped — historian already in progress (usage=${usage.percentage.toFixed(1)}%)`);
108210
108269
  return { shouldFire: false };
@@ -108262,10 +108321,12 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
108262
108321
  const canClearReasoning = reasoningProjection?.canClearReasoning ?? modelAcceptsEmptyContent(reasoningProjection?.providerID);
108263
108322
  const projectedPostDropPercentage = estimateProjectedPostDropPercentage(db, sessionId, usage, preloadedActiveTags ?? getActiveTagsBySession(db, sessionId), clearReasoningAge, sessionMeta.clearedReasoningThroughTag, canClearReasoning);
108264
108323
  const relativePostDropTarget = executeThresholdPercentage * POST_DROP_TARGET_RATIO;
108324
+ const rideLabel = reclaimRide ? reclaimRideLabel(reclaimRide) : "ride=none";
108325
+ const dropsCanLand = reclaimRide !== undefined && hasReclaimRide(reclaimRide);
108265
108326
  const forceMaterializationPercentage = escalationBands(executeThresholdPercentage).forceMaterializationPercentage;
108266
108327
  if (usage.percentage >= forceMaterializationPercentage) {
108267
- if (projectedPostDropPercentage !== null && projectedPostDropPercentage <= relativePostDropTarget) {
108268
- 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`);
108328
+ if (dropsCanLand && projectedPostDropPercentage !== null && projectedPostDropPercentage <= relativePostDropTarget) {
108329
+ 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})`);
108269
108330
  return { shouldFire: false };
108270
108331
  }
108271
108332
  sessionLog(sessionId, `compartment trigger: force-firing at ${usage.percentage.toFixed(1)}% (projected post-drop ${formatProjectedPostDropPercentage(projectedPostDropPercentage)})`);
@@ -108325,8 +108386,8 @@ function checkCompartmentTrigger(db, sessionId, sessionMeta, usage, _previousPer
108325
108386
  sessionLog(sessionId, `compartment trigger: not firing at ${usage.percentage.toFixed(1)}% — below proactive floor (${proactiveTriggerPercentage}%)`);
108326
108387
  return { shouldFire: false };
108327
108388
  }
108328
- if (projectedPostDropPercentage !== null && projectedPostDropPercentage <= relativePostDropTarget) {
108329
- 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`);
108389
+ if (dropsCanLand && projectedPostDropPercentage !== null && projectedPostDropPercentage <= relativePostDropTarget) {
108390
+ 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})`);
108330
108391
  return { shouldFire: false };
108331
108392
  }
108332
108393
  if (!tailInfo.hasProtectedEligibleHead || !tailInfo.isMeaningful) {
@@ -109081,21 +109142,6 @@ init_harness_provider_map();
109081
109142
  init_logger();
109082
109143
  init_models_dev_cache();
109083
109144
 
109084
- // src/hooks/magic-context/cache-busting-signals.ts
109085
- function canConsumeDeferredOnThisPass(args) {
109086
- if (args.justAwaitedPublication)
109087
- return true;
109088
- return args.schedulerDecision === "execute" || args.contextPercentage >= (args.forceMaterializationPercentage ?? escalationBands(65).forceMaterializationPercentage);
109089
- }
109090
- function hasReclaimRide(signals) {
109091
- return signals.hardFold || signals.force || signals.explicitFlush || signals.publishedHistory;
109092
- }
109093
- var RECLAIM_RIDE_NAMES = ["hardFold", "force", "explicitFlush", "publishedHistory"];
109094
- function reclaimRideLabel(signals) {
109095
- const active = RECLAIM_RIDE_NAMES.filter((name) => signals[name]);
109096
- return `ride=${active.length > 0 ? active.join("+") : "none"}`;
109097
- }
109098
-
109099
109145
  // src/hooks/magic-context/caveman-cleanup.ts
109100
109146
  init_shared();
109101
109147
  await init_storage();
@@ -115888,7 +115934,7 @@ function rustCaptureDigests(inputs, prior, acceptedInputs) {
115888
115934
  }
115889
115935
  function messageMatchesContentSnapshot(message, snapshot) {
115890
115936
  let fieldIndex = 0;
115891
- const matched = visitMessageContentFields(message, {
115937
+ const matched = visitMessageContentFields(contentSnapshotValue(message), {
115892
115938
  field(value) {
115893
115939
  if (!Object.is(value, snapshot.fields[fieldIndex]))
115894
115940
  return false;
@@ -116143,6 +116189,7 @@ function ensureState(states, sessionId) {
116143
116189
  if (!state) {
116144
116190
  state = {
116145
116191
  initialized: false,
116192
+ baselineSystemHashOmitted: false,
116146
116193
  consecutiveFailures: 0,
116147
116194
  passCount: 0,
116148
116195
  parked: false,
@@ -117104,6 +117151,7 @@ function createRustModeTransform(deps, options) {
117104
117151
  }
117105
117152
  }
117106
117153
  timings.preflight = performance.now() - passStartedAt;
117154
+ resolveCtxReduceAvailabilityFromMessages(sessionId, messages);
117107
117155
  const reduceAvailability = resolveCtxReduceAvailability(sessionId);
117108
117156
  resolveTodowriteAvailabilityFromMessages(sessionId, messages);
117109
117157
  const todoAvailability = resolveTodowriteAvailability(sessionId);
@@ -117175,6 +117223,8 @@ function createRustModeTransform(deps, options) {
117175
117223
  }
117176
117224
  const effectiveFloor = protectionFloorResolution.floor;
117177
117225
  const historianRun = deps.resolveHistorianRun?.();
117226
+ const observedSystemHash = sessionMeta.systemPromptHash ?? "";
117227
+ const rustSystemHash = state.baselineSystemHashOmitted && sessionMeta.cachedM0SystemHash === observedSystemHash ? "" : observedSystemHash;
117178
117228
  const passInputs = {
117179
117229
  now_ms: requestObservedAtMs,
117180
117230
  model_key: modelKey,
@@ -117196,7 +117246,7 @@ function createRustModeTransform(deps, options) {
117196
117246
  caveman_min_chars: deps.cavemanTextCompression?.minChars ?? 500,
117197
117247
  cache_ttl: sessionMeta.cacheTtl,
117198
117248
  is_subagent: sessionMeta.isSubagent,
117199
- system_prompt_hash: sessionMeta.systemPromptHash ?? "",
117249
+ system_prompt_hash: rustSystemHash,
117200
117250
  upgrade_state: readUpgradeState(deps.db, sessionId),
117201
117251
  tool_present: toolPresent,
117202
117252
  todo_tool_present: false,
@@ -117471,7 +117521,7 @@ function createRustModeTransform(deps, options) {
117471
117521
  modelKey: modelKey ?? null,
117472
117522
  providerId: model?.providerID ?? null,
117473
117523
  variant: deps.variantBySession?.get(sessionId),
117474
- systemPromptHash: sessionMeta.systemPromptHash ?? "",
117524
+ systemPromptHash: rustSystemHash,
117475
117525
  upgradeState: String(passInputs.upgrade_state ?? "")
117476
117526
  };
117477
117527
  let body = buildTransformBody({
@@ -117905,6 +117955,9 @@ function createRustModeTransform(deps, options) {
117905
117955
  state.ordinalContinuationBase = ordinalContinuationBase;
117906
117956
  }
117907
117957
  if (!stateSyncRetryBusy) {
117958
+ if (!state.initialized && !observedSystemHash) {
117959
+ state.baselineSystemHashOmitted = true;
117960
+ }
117908
117961
  state.initialized = true;
117909
117962
  state.seedPassPending = false;
117910
117963
  }
@@ -119033,7 +119086,12 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
119033
119086
  const tTrigger = performance.now();
119034
119087
  try {
119035
119088
  const inMemoryTail = buildTriggerInMemoryTail(db, sessionId, extractInMemoryMessageViews(messages));
119036
- const triggerResult = checkCompartmentTrigger(db, sessionId, sessionMeta, boundaryUsageForProtectedTail, sessionMeta.lastContextPercentage, boundaryExecuteThreshold, deriveTriggerBudget(boundaryContextLimit, boundaryExecuteThreshold), deps.clearReasoningAge, historianRun?.commitClusterTrigger ?? deps.commitClusterTrigger, undefined, boundaryContextLimit, inMemoryTail, taggerFloor, { providerID: resolvedProviderID });
119089
+ const triggerResult = checkCompartmentTrigger(db, sessionId, sessionMeta, boundaryUsageForProtectedTail, sessionMeta.lastContextPercentage, boundaryExecuteThreshold, deriveTriggerBudget(boundaryContextLimit, boundaryExecuteThreshold), deps.clearReasoningAge, historianRun?.commitClusterTrigger ?? deps.commitClusterTrigger, undefined, boundaryContextLimit, inMemoryTail, taggerFloor, { providerID: resolvedProviderID }, {
119090
+ hardFold: false,
119091
+ force: contextUsageEarly.percentage >= forceMaterializationPercentage && (contextUsageEarly.percentage >= 95 || getEmergencyInputSample(db, sessionId) === 0),
119092
+ explicitFlush: deps.pendingMaterializationSessions.has(sessionId),
119093
+ publishedHistory: isCacheBusting
119094
+ });
119037
119095
  if (triggerResult.shouldFire) {
119038
119096
  sessionLog(sessionId, `compartment trigger: firing (reason=${triggerResult.reason})`);
119039
119097
  updateSessionMeta(db, sessionId, { compartmentInProgress: true });
@@ -122771,9 +122829,33 @@ init_tag_content_primitives();
122771
122829
  var HIDDEN_HISTORIAN_AGENT = "historian";
122772
122830
  var HIDDEN_DREAMER_AGENT = "dreamer-classifier";
122773
122831
  var HIDDEN_CURATE_AGENT = DREAMER_AGENT;
122832
+ var READ_TOOLS = ["read", "grep", "glob"];
122833
+ var AGENT_TOOLS = {
122834
+ [HIDDEN_HISTORIAN_AGENT]: [],
122835
+ [HIDDEN_DREAMER_AGENT]: [],
122836
+ [HIDDEN_CURATE_AGENT]: ["ctx_memory", "ctx_memory_list"],
122837
+ [DREAMER_MEMORY_MAPPER_AGENT]: READ_TOOLS,
122838
+ [DREAMER_PRIMER_INVESTIGATOR_AGENT]: [...READ_TOOLS, "ctx_search"],
122839
+ [DREAMER_RETROSPECTIVE_AGENT]: ["ctx_search"]
122840
+ };
122841
+ var AGENT_STEPS = {
122842
+ [HIDDEN_CURATE_AGENT]: 150,
122843
+ [DREAMER_MEMORY_MAPPER_AGENT]: 60,
122844
+ [DREAMER_DOCS_AGENT]: 60,
122845
+ [DREAMER_PRIMER_INVESTIGATOR_AGENT]: 40,
122846
+ [DREAMER_RETROSPECTIVE_AGENT]: 40
122847
+ };
122848
+ function hiddenAgentFor(identity) {
122849
+ if (identity.kind === "dreamer-task" && identity.agent === DREAMER_DOCS_AGENT)
122850
+ return DREAMER_MEMORY_MAPPER_AGENT;
122851
+ return identity.kind === "dreamer-task" && AGENT_TOOLS[identity.agent] ? identity.agent : identity.kind === "dreamer-task" ? HIDDEN_DREAMER_AGENT : HIDDEN_HISTORIAN_AGENT;
122852
+ }
122853
+ function hiddenToolLoop(identity) {
122854
+ return identity.kind === "dreamer-task" && AGENT_STEPS[identity.agent] !== undefined;
122855
+ }
122774
122856
  async function registerHiddenChildAgents(agent) {
122775
122857
  await agent.transform((editor) => {
122776
- for (const id of [HIDDEN_HISTORIAN_AGENT, HIDDEN_DREAMER_AGENT, HIDDEN_CURATE_AGENT]) {
122858
+ for (const id of Object.keys(AGENT_TOOLS)) {
122777
122859
  editor.update(id, (config) => {
122778
122860
  config.system = "Magic Context hidden completion carrier.";
122779
122861
  config.description = "Internal Magic Context hidden completion carrier.";
@@ -122782,16 +122864,14 @@ async function registerHiddenChildAgents(agent) {
122782
122864
  config.request.settings = {};
122783
122865
  config.request.headers = {};
122784
122866
  config.request.body = {};
122867
+ config.steps = AGENT_STEPS[id];
122785
122868
  config.permissions = [
122786
122869
  { action: "*", resource: "*", effect: "deny" },
122787
- ...id === HIDDEN_CURATE_AGENT ? [
122788
- { action: "tool", resource: "ctx_memory", effect: "allow" },
122789
- {
122790
- action: "tool",
122791
- resource: "ctx_memory_list",
122792
- effect: "allow"
122793
- }
122794
- ] : []
122870
+ ...(AGENT_TOOLS[id] ?? []).map((tool) => ({
122871
+ action: tool,
122872
+ resource: "*",
122873
+ effect: "allow"
122874
+ }))
122795
122875
  ];
122796
122876
  });
122797
122877
  }
@@ -122836,15 +122916,21 @@ function calibratedParts(attempt) {
122836
122916
  class HiddenChildHook {
122837
122917
  childIDs = new Set;
122838
122918
  attempts = new Map;
122919
+ active = new Map;
122839
122920
  registerChild(sessionID) {
122840
122921
  this.childIDs.add(sessionID);
122841
122922
  }
122842
122923
  registerAttempt(marker, attempt) {
122843
122924
  this.registerChild(attempt.childSessionId);
122925
+ attempt.marker = marker;
122844
122926
  this.attempts.set(marker, attempt);
122845
122927
  }
122846
122928
  releaseAttempt(marker) {
122929
+ const attempt = this.attempts.get(marker);
122847
122930
  this.attempts.delete(marker);
122931
+ if (attempt && this.active.get(attempt.childSessionId) === attempt) {
122932
+ this.active.delete(attempt.childSessionId);
122933
+ }
122848
122934
  }
122849
122935
  owns(sessionID) {
122850
122936
  return this.childIDs.has(sessionID);
@@ -122855,19 +122941,43 @@ class HiddenChildHook {
122855
122941
  const raw = newestUserText(draft);
122856
122942
  const stripped = raw === undefined ? undefined : stripWellFormedLeadingTagPrefix(raw);
122857
122943
  const attempt = (raw !== undefined ? this.attempts.get(raw) : undefined) ?? (stripped && stripped !== raw ? this.attempts.get(stripped) : undefined);
122858
- if (!attempt || attempt.childSessionId !== draft.sessionID) {
122944
+ const current = this.active.get(draft.sessionID);
122945
+ const selected = attempt ?? current;
122946
+ if (!selected || selected.childSessionId !== draft.sessionID || attempt && current && current !== attempt) {
122859
122947
  throw new HiddenCompletionRefusal("hidden_prompt_unrecognized", "Refusing an unregistered prompt on a Magic Context hidden-run session", true);
122860
122948
  }
122861
- if (attempt.request.signal?.aborted) {
122949
+ if (selected.request.signal?.aborted) {
122862
122950
  throw new Error("Hidden completion prompt aborted");
122863
122951
  }
122864
- const system = typeof attempt.request.body.system === "string" ? attempt.request.body.system : attempt.identity.system;
122952
+ if (!selected.shaped) {
122953
+ if (!attempt)
122954
+ throw new HiddenCompletionRefusal("hidden_prompt_unrecognized", "Hidden child first step requires a registered marker", true);
122955
+ this.active.set(draft.sessionID, selected);
122956
+ }
122957
+ const steps = (selected.steps ?? 0) + 1;
122958
+ const cap = AGENT_STEPS[selected.identity.agent];
122959
+ if (cap !== undefined && steps > cap) {
122960
+ throw new Error(`Hidden agent exceeded its ${cap}-step limit`);
122961
+ }
122962
+ selected.steps = steps;
122963
+ const system = typeof selected.request.body.system === "string" ? selected.request.body.system : selected.identity.system;
122865
122964
  draft.system = [{ type: "text", text: system }];
122866
- draft.messages = [{ role: "user", content: calibratedParts(attempt) }];
122867
- draft.options = authoredOptions(attempt);
122868
- const dreamerTools = attempt.identity.agent === DREAMER_AGENT ? Object.fromEntries(["ctx_memory", "ctx_memory_list"].flatMap((id) => draft.tools[id] ? [[id, draft.tools[id]]] : [])) : {};
122869
- draft.tools = dreamerTools;
122870
- attempt.shaped = true;
122965
+ if (!selected.shaped) {
122966
+ draft.messages = [{ role: "user", content: calibratedParts(selected) }];
122967
+ } else {
122968
+ const first = draft.messages[0];
122969
+ const firstText = first && newestUserText({ ...draft, messages: [first] });
122970
+ const normalized = firstText === undefined ? undefined : stripWellFormedLeadingTagPrefix(firstText);
122971
+ if (normalized !== selected.marker) {
122972
+ throw new HiddenCompletionRefusal("hidden_prompt_unrecognized", "Hidden child history does not begin with this run's registered marker", true);
122973
+ }
122974
+ draft.messages[0] = { ...first, content: calibratedParts(selected) };
122975
+ }
122976
+ draft.options = authoredOptions(selected);
122977
+ const allowed = AGENT_TOOLS[hiddenAgentFor(selected.identity)] ?? [];
122978
+ draft.tools = Object.fromEntries(allowed.flatMap((id) => draft.tools[id] ? [[id, draft.tools[id]]] : []));
122979
+ selected.observedMessages = draft.messages;
122980
+ selected.shaped = true;
122871
122981
  return true;
122872
122982
  }
122873
122983
  }
@@ -122949,9 +123059,9 @@ function resolveOwnerHostService(owner, env = process.env, pid = process.pid) {
122949
123059
  }
122950
123060
  return own;
122951
123061
  }
122952
- async function removeHostSession(sessionID, owner, env = process.env) {
123062
+ async function removeHostSession(sessionID, owner, env = process.env, fetchSession = fetch) {
122953
123063
  const service = resolveOwnerHostService(owner, env);
122954
- const response = await fetch(`${service.url}/api/session/${encodeURIComponent(sessionID)}`, {
123064
+ const response = await fetchSession(`${service.url}/api/session/${encodeURIComponent(sessionID)}`, {
122955
123065
  method: "DELETE",
122956
123066
  headers: service.headers,
122957
123067
  signal: AbortSignal.timeout(60000)
@@ -123153,6 +123263,37 @@ function settledProviderError(row) {
123153
123263
  function successfulReusableAssistant(row) {
123154
123264
  return row !== undefined && (typeof row.data.finish === "string" || assistantOutcome(row) === "succeeded") && row.data.error === undefined && row.data.tokens !== undefined;
123155
123265
  }
123266
+ function toolLoopMessages(attempt) {
123267
+ const messages = attempt.observedMessages ?? [];
123268
+ const results = new Map;
123269
+ for (const message of messages) {
123270
+ if (message.role !== "tool")
123271
+ continue;
123272
+ for (const part of message.content) {
123273
+ if (part.type !== "tool-result" || typeof part.id !== "string")
123274
+ continue;
123275
+ const result = part.result;
123276
+ results.set(part.id, { status: result?.type === "error" ? "error" : "completed" });
123277
+ }
123278
+ }
123279
+ return messages.flatMap((message) => {
123280
+ if (message.role !== "assistant")
123281
+ return [];
123282
+ const parts = message.content.flatMap((part) => {
123283
+ if (part.type !== "tool-call" || typeof part.id !== "string" || typeof part.name !== "string")
123284
+ return [];
123285
+ const result = results.get(part.id);
123286
+ return [
123287
+ {
123288
+ type: "tool",
123289
+ tool: part.name,
123290
+ state: { status: result?.status ?? "pending", input: part.input }
123291
+ }
123292
+ ];
123293
+ });
123294
+ return parts.length ? [{ info: { role: "assistant" }, parts }] : [];
123295
+ });
123296
+ }
123156
123297
  function assistantText(row) {
123157
123298
  const text = (row.data.content ?? []).flatMap((part) => part.type === "text" && typeof part.text === "string" ? [part.text] : []).join("");
123158
123299
  return text.length > 0 ? text : null;
@@ -123404,7 +123545,7 @@ async function createV2HiddenCompletionExecutor(host, options) {
123404
123545
  }
123405
123546
  };
123406
123547
  return {
123407
- capabilities: { tools: false, harness: "opencode2" },
123548
+ capabilities: { tools: true, harness: "opencode2" },
123408
123549
  async open(identity) {
123409
123550
  const role = roleFor(identity);
123410
123551
  const releaseRole = await acquireRole(role);
@@ -123413,6 +123554,10 @@ async function createV2HiddenCompletionExecutor(host, options) {
123413
123554
  await options.ensureAgent?.();
123414
123555
  const head = await resolveHead(identity);
123415
123556
  let active = store.read().active[role];
123557
+ if (active && hiddenToolLoop(identity)) {
123558
+ retireChild(active, "fresh-tool-loop-run");
123559
+ active = undefined;
123560
+ }
123416
123561
  if (active && active.generation !== generation) {
123417
123562
  retireChild(active, "host-generation-changed");
123418
123563
  active = undefined;
@@ -123435,7 +123580,7 @@ async function createV2HiddenCompletionExecutor(host, options) {
123435
123580
  const title = roleTitle(role);
123436
123581
  const created = await host.create({
123437
123582
  title,
123438
- agent: roleAgent(role),
123583
+ agent: hiddenToolLoop(identity) ? hiddenAgentFor(identity) : roleAgent(role),
123439
123584
  model: {
123440
123585
  providerID: head.providerID,
123441
123586
  id: head.modelID,
@@ -123493,6 +123638,7 @@ async function createV2HiddenCompletionExecutor(host, options) {
123493
123638
  await switchChildModel(run, requested);
123494
123639
  const baseline = withReader(options.openReader, (reader) => reader.latestSequence(run.child.id));
123495
123640
  const marker = `mc:hidden:${crypto.randomUUID()}:${crypto.randomUUID()}`;
123641
+ run.completion = undefined;
123496
123642
  const attempt = {
123497
123643
  childSessionId: run.child.id,
123498
123644
  identity: run.identity,
@@ -123552,6 +123698,7 @@ async function createV2HiddenCompletionExecutor(host, options) {
123552
123698
  }
123553
123699
  run.completion = {
123554
123700
  text,
123701
+ ...hiddenToolLoop(run.identity) ? { messages: toolLoopMessages(attempt) } : {},
123555
123702
  reasoning: null,
123556
123703
  usage: reportedInput !== undefined || reportedOutput !== undefined ? {
123557
123704
  input: reportedInput ?? 0,
@@ -123596,7 +123743,9 @@ async function createV2HiddenCompletionExecutor(host, options) {
123596
123743
  return;
123597
123744
  try {
123598
123745
  const reusable = run.failed && !run.unsettledFailure;
123599
- if (!run.completion && (run.failed || !settlement.promptSettled) && !reusable) {
123746
+ if (hiddenToolLoop(run.identity)) {
123747
+ retire(run, settlement.promptSettled ? "tool-loop-settled" : "tool-loop-failed");
123748
+ } else if (!run.completion && (run.failed || !settlement.promptSettled) && !reusable) {
123600
123749
  retire(run, "hidden-run-failed");
123601
123750
  }
123602
123751
  } finally {
@@ -125137,13 +125286,13 @@ async function runHiddenSingleShotPrompt(args) {
125137
125286
  throw new Error(`${args.callContext} returned length-capped output`);
125138
125287
  }
125139
125288
  const text = completion.text;
125140
- if (!text)
125289
+ if (!text && !args.allowEmpty)
125141
125290
  throw new Error(`${args.callContext} returned no output`);
125142
- return args.parse(text);
125291
+ return args.parse(text ?? "", completion);
125143
125292
  }
125144
125293
  });
125145
125294
  promptSettled = true;
125146
- return { validated: run.validated, completion: run.output };
125295
+ return { validated: run.validated, completion: run.output, childSessionId: handle.id };
125147
125296
  } finally {
125148
125297
  await args.executor.close(handle, {
125149
125298
  promptSettled,
@@ -126226,7 +126375,7 @@ import { createHash as createHash30 } from "node:crypto";
126226
126375
  import {
126227
126376
  existsSync as existsSync16,
126228
126377
  mkdirSync as mkdirSync11,
126229
- mkdtempSync as mkdtempSync2,
126378
+ mkdtempSync,
126230
126379
  readdirSync as readdirSync6,
126231
126380
  readFileSync as readFileSync16,
126232
126381
  realpathSync as realpathSync4,
@@ -126333,7 +126482,7 @@ function protectedBytes(text) {
126333
126482
  ].map((match) => match[0]);
126334
126483
  }
126335
126484
  function diff(name, before, after) {
126336
- const dir = mkdtempSync2(join17(tmpdir2(), "mc-doc-diff-"));
126485
+ const dir = mkdtempSync(join17(tmpdir2(), "mc-doc-diff-"));
126337
126486
  try {
126338
126487
  writeFileSync8(join17(dir, "before"), before);
126339
126488
  writeFileSync8(join17(dir, "after"), after);
@@ -128305,8 +128454,36 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
128305
128454
  let promptSettled = false;
128306
128455
  const startedAt = Date.now();
128307
128456
  try {
128457
+ const prompt = buildMapMemoriesPrompt(args.projectIdentity, batch);
128458
+ if (args.hiddenCompletionExecutor) {
128459
+ const run = await runHiddenSingleShotPrompt({
128460
+ executor: args.hiddenCompletionExecutor,
128461
+ parentSessionId: args.parentSessionId,
128462
+ sessionDirectory: args.sessionDirectory,
128463
+ agent: DREAMER_MEMORY_MAPPER_AGENT,
128464
+ system: MAP_MEMORIES_SYSTEM_PROMPT,
128465
+ prompt,
128466
+ title: "magic-context-dream-map-memories",
128467
+ callContext: "dreamer:map-memories",
128468
+ model: args.model,
128469
+ fallbackModels: args.fallbackModels,
128470
+ timeoutMs: sliceMs,
128471
+ signal,
128472
+ parse: (text) => validateMapMemoriesManifest(text, new Set(batch.map((memory) => memory.id)))
128473
+ });
128474
+ recordInvocation2(args, startedAt, {
128475
+ status: "completed",
128476
+ messages: run.completion.messages ?? []
128477
+ });
128478
+ const outcome = await applyParsedBatchMappings(args, batch, run.validated);
128479
+ const returnedIds = new Set(run.validated.map((entry) => entry.id));
128480
+ return { ...outcome, requeue: batch.filter((memory) => !returnedIds.has(memory.id)) };
128481
+ }
128482
+ const client = args.client;
128483
+ if (!client)
128484
+ throw new Error("map-memories requires a client or hidden completion executor");
128308
128485
  const createResponse = await createChildSessionWithFence({
128309
- client: args.client,
128486
+ client,
128310
128487
  db: args.db,
128311
128488
  parentSessionId: args.parentSessionId,
128312
128489
  title: "magic-context-dream-map-memories",
@@ -128318,8 +128495,7 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
128318
128495
  agentSessionId = typeof created?.id === "string" ? created.id : null;
128319
128496
  if (!agentSessionId)
128320
128497
  throw new Error("Could not create map-memories session.");
128321
- const prompt = buildMapMemoriesPrompt(args.projectIdentity, batch);
128322
- const run = await promptSyncWithValidatedOutputRetry(args.client, {
128498
+ const run = await promptSyncWithValidatedOutputRetry(client, {
128323
128499
  path: { id: agentSessionId },
128324
128500
  query: { directory: args.sessionDirectory },
128325
128501
  body: {
@@ -128334,7 +128510,7 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
128334
128510
  fallbackModels: args.fallbackModels,
128335
128511
  callContext: "dreamer:map-memories",
128336
128512
  fetchOutput: async () => {
128337
- const messagesResponse = await args.client.session.messages({
128513
+ const messagesResponse = await client.session.messages({
128338
128514
  path: { id: agentSessionId },
128339
128515
  query: { directory: args.sessionDirectory, limit: 100 }
128340
128516
  });
@@ -128377,15 +128553,16 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
128377
128553
  }
128378
128554
  };
128379
128555
  } finally {
128380
- await teardownChildSession({
128381
- client: args.client,
128382
- sessionId: agentSessionId,
128383
- sessionDirectory: args.sessionDirectory,
128384
- promptSettled,
128385
- privacySensitive: true,
128386
- context: "[dreamer] map-memories",
128387
- log
128388
- });
128556
+ if (agentSessionId && args.client)
128557
+ await teardownChildSession({
128558
+ client: args.client,
128559
+ sessionId: agentSessionId,
128560
+ sessionDirectory: args.sessionDirectory,
128561
+ promptSettled,
128562
+ privacySensitive: true,
128563
+ context: "[dreamer] map-memories",
128564
+ log
128565
+ });
128389
128566
  }
128390
128567
  }
128391
128568
  async function applyParsedBatchMappings(args, batch, parsed) {
@@ -129001,8 +129178,41 @@ async function refreshOnePrimer(args, primer, sliceMs, signal) {
129001
129178
  let promptSettled = false;
129002
129179
  const startedAt = Date.now();
129003
129180
  try {
129181
+ const prompt = buildInvestigationPrompt(primer, seed.kind, seed.orientation, seed.prePost);
129182
+ if (args.hiddenCompletionExecutor) {
129183
+ const run = await runHiddenSingleShotPrompt({
129184
+ executor: args.hiddenCompletionExecutor,
129185
+ parentSessionId: args.parentSessionId,
129186
+ sessionDirectory: args.sessionDirectory,
129187
+ agent: DREAMER_PRIMER_INVESTIGATOR_AGENT,
129188
+ system: PRIMER_INVESTIGATOR_SYSTEM_PROMPT,
129189
+ prompt,
129190
+ title: "magic-context-dream-refresh-primers",
129191
+ callContext: "dreamer:refresh-primers",
129192
+ model: args.model,
129193
+ fallbackModels: args.fallbackModels,
129194
+ language: args.language,
129195
+ timeoutMs: sliceMs,
129196
+ signal,
129197
+ parse: (text) => parseAnswer([{ info: { role: "assistant" }, parts: [{ type: "text", text }] }], primer.answer)
129198
+ });
129199
+ recordInvocation3(args, startedAt, {
129200
+ status: "completed",
129201
+ messages: run.completion.messages ?? []
129202
+ });
129203
+ const answer = run.validated.trim();
129204
+ if (!answer || investigationToolCallCount(run.completion.messages ?? []) === 0)
129205
+ return false;
129206
+ runLeaseGuardedWrite(args.db, args.holderId, args.leaseKey, () => {
129207
+ updatePrimerAnswer(args.db, primer.id, answer);
129208
+ });
129209
+ return true;
129210
+ }
129211
+ const client = args.client;
129212
+ if (!client)
129213
+ throw new Error("refresh-primers requires a client or hidden completion executor");
129004
129214
  const createResponse = await createChildSessionWithFence({
129005
- client: args.client,
129215
+ client,
129006
129216
  db: args.db,
129007
129217
  parentSessionId: args.parentSessionId,
129008
129218
  title: "magic-context-dream-refresh-primers",
@@ -129014,8 +129224,7 @@ async function refreshOnePrimer(args, primer, sliceMs, signal) {
129014
129224
  agentSessionId = typeof created?.id === "string" ? created.id : null;
129015
129225
  if (!agentSessionId)
129016
129226
  throw new Error("Could not create primer refresh session.");
129017
- const prompt = buildInvestigationPrompt(primer, seed.kind, seed.orientation, seed.prePost);
129018
- const run = await promptSyncWithValidatedOutputRetry(args.client, {
129227
+ const run = await promptSyncWithValidatedOutputRetry(client, {
129019
129228
  path: { id: agentSessionId },
129020
129229
  query: { directory: args.sessionDirectory },
129021
129230
  body: {
@@ -129030,7 +129239,7 @@ async function refreshOnePrimer(args, primer, sliceMs, signal) {
129030
129239
  fallbackModels: args.fallbackModels,
129031
129240
  callContext: "dreamer:refresh-primers",
129032
129241
  fetchOutput: async () => {
129033
- const messagesResponse = await args.client.session.messages({
129242
+ const messagesResponse = await client.session.messages({
129034
129243
  path: { id: agentSessionId },
129035
129244
  query: { directory: args.sessionDirectory, limit: 100 }
129036
129245
  });
@@ -129059,15 +129268,16 @@ async function refreshOnePrimer(args, primer, sliceMs, signal) {
129059
129268
  recordInvocation3(args, startedAt, { status: failedInvocationStatus(error), error });
129060
129269
  throw error;
129061
129270
  } finally {
129062
- await teardownChildSession({
129063
- client: args.client,
129064
- sessionId: agentSessionId,
129065
- sessionDirectory: args.sessionDirectory,
129066
- promptSettled,
129067
- privacySensitive: true,
129068
- context: "[dreamer] refresh-primers",
129069
- log
129070
- });
129271
+ if (agentSessionId && args.client)
129272
+ await teardownChildSession({
129273
+ client: args.client,
129274
+ sessionId: agentSessionId,
129275
+ sessionDirectory: args.sessionDirectory,
129276
+ promptSettled,
129277
+ privacySensitive: true,
129278
+ context: "[dreamer] refresh-primers",
129279
+ log
129280
+ });
129071
129281
  }
129072
129282
  }
129073
129283
  function originSessionIdForPrimer(args, primer) {
@@ -129757,8 +129967,40 @@ async function verifyOneBatch(args, batch, sliceMs, signal) {
129757
129967
  let promptSettled = false;
129758
129968
  const startedAt = Date.now();
129759
129969
  try {
129970
+ const prompt = buildVerifyPrompt(args.projectIdentity, batch);
129971
+ if (args.hiddenCompletionExecutor) {
129972
+ const run = await runHiddenSingleShotPrompt({
129973
+ executor: args.hiddenCompletionExecutor,
129974
+ parentSessionId: args.parentSessionId,
129975
+ sessionDirectory: args.sessionDirectory,
129976
+ agent: DREAMER_MEMORY_MAPPER_AGENT,
129977
+ system: VERIFY_SYSTEM_PROMPT,
129978
+ prompt,
129979
+ title: "magic-context-dream-verify",
129980
+ callContext: "dreamer:verify",
129981
+ model: args.model,
129982
+ fallbackModels: args.fallbackModels,
129983
+ language: args.language,
129984
+ timeoutMs: sliceMs,
129985
+ signal,
129986
+ parse: (text) => {
129987
+ const providerFailure = providerOutputFailureFromInvalidManifest([], text);
129988
+ if (providerFailure)
129989
+ throw providerFailure;
129990
+ return validateVerifyManifest(text, new Set(batch.map((memory) => memory.id)));
129991
+ }
129992
+ });
129993
+ recordInvocation4(args, startedAt, {
129994
+ status: "completed",
129995
+ messages: run.completion.messages ?? []
129996
+ });
129997
+ return applyParsedVerifyManifest(args, batch, run.validated);
129998
+ }
129999
+ const client = args.client;
130000
+ if (!client)
130001
+ throw new Error("verify requires a client or hidden completion executor");
129760
130002
  const createResponse = await createChildSessionWithFence({
129761
- client: args.client,
130003
+ client,
129762
130004
  db: args.db,
129763
130005
  parentSessionId: args.parentSessionId,
129764
130006
  title: "magic-context-dream-verify",
@@ -129770,8 +130012,7 @@ async function verifyOneBatch(args, batch, sliceMs, signal) {
129770
130012
  agentSessionId = typeof created?.id === "string" ? created.id : null;
129771
130013
  if (!agentSessionId)
129772
130014
  throw new Error("Could not create verify session.");
129773
- const prompt = buildVerifyPrompt(args.projectIdentity, batch);
129774
- const run = await promptSyncWithValidatedOutputRetry(args.client, {
130015
+ const run = await promptSyncWithValidatedOutputRetry(client, {
129775
130016
  path: { id: agentSessionId },
129776
130017
  query: { directory: args.sessionDirectory },
129777
130018
  body: {
@@ -129786,7 +130027,7 @@ async function verifyOneBatch(args, batch, sliceMs, signal) {
129786
130027
  fallbackModels: args.fallbackModels,
129787
130028
  callContext: "dreamer:verify",
129788
130029
  fetchOutput: async () => {
129789
- const messagesResponse = await args.client.session.messages({
130030
+ const messagesResponse = await client.session.messages({
129790
130031
  path: { id: agentSessionId },
129791
130032
  query: { directory: args.sessionDirectory, limit: 100 }
129792
130033
  });
@@ -129827,15 +130068,16 @@ async function verifyOneBatch(args, batch, sliceMs, signal) {
129827
130068
  providerFailure
129828
130069
  };
129829
130070
  } finally {
129830
- await teardownChildSession({
129831
- client: args.client,
129832
- sessionId: agentSessionId,
129833
- sessionDirectory: args.sessionDirectory,
129834
- promptSettled,
129835
- privacySensitive: true,
129836
- context: "[dreamer] verify",
129837
- log
129838
- });
130071
+ if (agentSessionId && args.client)
130072
+ await teardownChildSession({
130073
+ client: args.client,
130074
+ sessionId: agentSessionId,
130075
+ sessionDirectory: args.sessionDirectory,
130076
+ promptSettled,
130077
+ privacySensitive: true,
130078
+ context: "[dreamer] verify",
130079
+ log
130080
+ });
129839
130081
  }
129840
130082
  }
129841
130083
  async function applyParsedVerifyManifest(args, batch, parsed) {
@@ -130003,6 +130245,8 @@ async function applyParsedVerifyManifest(args, batch, parsed) {
130003
130245
  async function normalizeFiles(args, rawFiles) {
130004
130246
  if (rawFiles.length === 0)
130005
130247
  return [];
130248
+ if (args.normalizeFiles)
130249
+ return args.normalizeFiles(rawFiles);
130006
130250
  const normalized = await normalizeVerificationFiles({
130007
130251
  cwd: args.sessionDirectory,
130008
130252
  files: rawFiles
@@ -130336,7 +130580,8 @@ function createDreamTaskExecutor(deps) {
130336
130580
  if (config.task === "map-memories") {
130337
130581
  const result = await mapMemories({
130338
130582
  db,
130339
- client: requireDreamClient(deps.client),
130583
+ client: deps.client,
130584
+ hiddenCompletionExecutor: deps.hiddenCompletionExecutor,
130340
130585
  projectIdentity,
130341
130586
  parentSessionId: parent,
130342
130587
  sessionDirectory: deps.sessionDirectory,
@@ -130373,7 +130618,8 @@ function createDreamTaskExecutor(deps) {
130373
130618
  const memoryBefore = getMemoryCountsByStatus(db, projectIdentity);
130374
130619
  const result = await runVerify({
130375
130620
  db,
130376
- client: requireDreamClient(deps.client),
130621
+ client: deps.client,
130622
+ hiddenCompletionExecutor: deps.hiddenCompletionExecutor,
130377
130623
  projectIdentity,
130378
130624
  parentSessionId: parent,
130379
130625
  sessionDirectory: deps.sessionDirectory,
@@ -130474,7 +130720,8 @@ function createDreamTaskExecutor(deps) {
130474
130720
  if (config.task === "refresh-primers") {
130475
130721
  const result = await refreshPrimers({
130476
130722
  db,
130477
- client: requireDreamClient(deps.client),
130723
+ client: deps.client,
130724
+ hiddenCompletionExecutor: deps.hiddenCompletionExecutor,
130478
130725
  projectIdentity,
130479
130726
  parentSessionId: parent,
130480
130727
  sessionDirectory: deps.sessionDirectory,
@@ -130742,24 +130989,45 @@ async function runRetrospectiveTask(config, ctx, helpers) {
130742
130989
  abortController.abort();
130743
130990
  }, ctx.leaseAcquisition);
130744
130991
  let childSessionId = null;
130992
+ let hiddenHandle = null;
130745
130993
  let promptSettled = false;
130746
130994
  try {
130747
- const createResponse = await createChildSessionWithFence({
130748
- client: requireDreamClient(deps.client),
130749
- db,
130750
- parentSessionId: parent ?? undefined,
130751
- title: "magic-context-dream-retrospective",
130752
- directory: deps.sessionDirectory
130753
- });
130754
- const created = normalizeSDKResponse(createResponse, null, { preferResponseOnMissingData: true });
130755
- childSessionId = typeof created?.id === "string" ? created.id : null;
130756
- if (!childSessionId)
130757
- throw new Error("Retrospective could not create its child session.");
130995
+ if (deps.hiddenCompletionExecutor) {
130996
+ hiddenHandle = await deps.hiddenCompletionExecutor.open({
130997
+ parentSessionId: parent ?? undefined,
130998
+ agent: DREAMER_RETROSPECTIVE_AGENT,
130999
+ kind: "dreamer-task",
131000
+ system: FRICTION_GATE_SYSTEM_PROMPT,
131001
+ model: config.model,
131002
+ configuredModels: [
131003
+ ...config.model ? [config.model] : [],
131004
+ ...config.fallbackModels ?? []
131005
+ ],
131006
+ timeoutMs: Math.max(1, deadline - Date.now()),
131007
+ title: "magic-context-dream-retrospective",
131008
+ directory: deps.sessionDirectory
131009
+ });
131010
+ childSessionId = hiddenHandle.id;
131011
+ } else {
131012
+ const createResponse = await createChildSessionWithFence({
131013
+ client: requireDreamClient(deps.client),
131014
+ db,
131015
+ parentSessionId: parent ?? undefined,
131016
+ title: "magic-context-dream-retrospective",
131017
+ directory: deps.sessionDirectory
131018
+ });
131019
+ const created = normalizeSDKResponse(createResponse, null, { preferResponseOnMissingData: true });
131020
+ childSessionId = typeof created?.id === "string" ? created.id : null;
131021
+ if (!childSessionId)
131022
+ throw new Error("Retrospective could not create its child session.");
131023
+ }
130758
131024
  const sessionId = childSessionId;
131025
+ if (!sessionId)
131026
+ throw new Error("Retrospective could not create its child session.");
130759
131027
  const runChildTurn = async (system, userText) => {
130760
131028
  const remainingMs = Math.max(0, deadline - Date.now());
130761
131029
  promptSettled = false;
130762
- const run = await promptSyncWithValidatedOutputRetry(requireDreamClient(deps.client), {
131030
+ const run = await promptSyncWithValidatedOutputRetry(deps.hiddenCompletionExecutor ? undefined : requireDreamClient(deps.client), {
130763
131031
  path: { id: sessionId },
130764
131032
  query: { directory: deps.sessionDirectory },
130765
131033
  body: {
@@ -130773,7 +131041,13 @@ async function runRetrospectiveTask(config, ctx, helpers) {
130773
131041
  signal: abortController.signal,
130774
131042
  fallbackModels: config.fallbackModels,
130775
131043
  callContext: "dreamer:retrospective",
131044
+ ...hiddenHandle && deps.hiddenCompletionExecutor ? {
131045
+ transport: Object.assign((request) => deps.hiddenCompletionExecutor?.attempt(hiddenHandle, request) ?? Promise.reject(new Error("Hidden transport unavailable")), { childSessionId: hiddenHandle.childSessionId })
131046
+ } : {},
130776
131047
  fetchOutput: async () => {
131048
+ if (hiddenHandle && deps.hiddenCompletionExecutor) {
131049
+ return deps.hiddenCompletionExecutor.collect(hiddenHandle, 50);
131050
+ }
130777
131051
  const messagesResponse = await requireDreamClient(deps.client).session.messages({
130778
131052
  path: { id: sessionId },
130779
131053
  query: { directory: deps.sessionDirectory, limit: 50 }
@@ -130783,14 +131057,15 @@ async function runRetrospectiveTask(config, ctx, helpers) {
130783
131057
  });
130784
131058
  },
130785
131059
  validateOutput: (outputMessages) => {
130786
- const text = extractLatestAssistantText(outputMessages);
131060
+ const text = hiddenHandle ? outputMessages.text : extractLatestAssistantText(outputMessages);
130787
131061
  if (!text)
130788
131062
  throw new Error("Retrospective child returned no output.");
130789
131063
  return text;
130790
131064
  }
130791
131065
  });
130792
131066
  promptSettled = true;
130793
- return run;
131067
+ const output = hiddenHandle ? run.output.messages ?? [] : run.output;
131068
+ return { ...run, output };
130794
131069
  };
130795
131070
  const finish = (run, watermark) => {
130796
131071
  if (parent && run) {
@@ -130920,15 +131195,23 @@ async function runRetrospectiveTask(config, ctx, helpers) {
130920
131195
  });
130921
131196
  } finally {
130922
131197
  heartbeat.stop();
130923
- await teardownChildSession({
130924
- client: requireDreamClient(deps.client),
130925
- sessionId: childSessionId,
130926
- sessionDirectory: deps.sessionDirectory,
130927
- promptSettled,
130928
- privacySensitive: true,
130929
- context: "[dreamer] retrospective",
130930
- log
130931
- });
131198
+ if (hiddenHandle && deps.hiddenCompletionExecutor) {
131199
+ await deps.hiddenCompletionExecutor.close(hiddenHandle, {
131200
+ promptSettled,
131201
+ privacySensitive: true,
131202
+ context: "[dreamer] retrospective",
131203
+ log
131204
+ });
131205
+ } else
131206
+ await teardownChildSession({
131207
+ client: requireDreamClient(deps.client),
131208
+ sessionId: childSessionId,
131209
+ sessionDirectory: deps.sessionDirectory,
131210
+ promptSettled,
131211
+ privacySensitive: true,
131212
+ context: "[dreamer] retrospective",
131213
+ log
131214
+ });
130932
131215
  }
130933
131216
  }
130934
131217
  async function runAgenticTask(config, ctx, helpers) {
@@ -131002,72 +131285,107 @@ async function runAgenticTask(config, ctx, helpers) {
131002
131285
  docsCurrentTokens: maintainDocsSnapshot ? Math.ceil([...maintainDocsSnapshot.values()].join("").length / 3.5) : 0,
131003
131286
  curate: curateMemories && curateCategory ? { category: curateCategory, memories: curateMemories } : undefined
131004
131287
  });
131005
- const createResponse = await createChildSessionWithFence({
131006
- client: requireDreamClient(deps.client),
131007
- db,
131008
- parentSessionId: parent ?? undefined,
131009
- title: `magic-context-dream-${task}`,
131010
- directory: docsDir
131011
- });
131012
- const created = normalizeSDKResponse(createResponse, null, {
131013
- preferResponseOnMissingData: true
131014
- });
131015
- childSessionId = typeof created?.id === "string" ? created.id : null;
131016
- if (!childSessionId)
131017
- throw new Error("Dreamer could not create its child session.");
131018
- const sessionId = childSessionId;
131019
- const remainingMs = Math.max(0, deadline - Date.now());
131020
- const run = await promptSyncWithValidatedOutputRetry(requireDreamClient(deps.client), {
131021
- path: { id: sessionId },
131022
- query: { directory: docsDir },
131023
- body: {
131288
+ let run;
131289
+ if (deps.hiddenCompletionExecutor) {
131290
+ const hidden = await runHiddenSingleShotPrompt({
131291
+ executor: deps.hiddenCompletionExecutor,
131292
+ parentSessionId: parent ?? undefined,
131293
+ sessionDirectory: docsDir,
131024
131294
  agent: task === "maintain-docs" ? DREAMER_DOCS_AGENT : DREAMER_AGENT,
131025
- system: task === "maintain-docs" ? MAINTAIN_DOCS_SYSTEM_PROMPT : withContentLanguageDirective(CURATE_SYSTEM_PROMPT, config.language ?? deps.language),
131026
- ...modelBodyField(config.model),
131027
- parts: [{ type: "text", text: taskPrompt, synthetic: true }]
131028
- }
131029
- }, {
131030
- timeoutMs: Math.min(remainingMs, config.timeoutMinutes * 60 * 1000),
131031
- signal: abortController.signal,
131032
- fallbackModels: config.fallbackModels,
131033
- callContext: `dreamer:${task}`,
131034
- fetchOutput: async () => {
131035
- const messagesResponse = await requireDreamClient(deps.client).session.messages({
131036
- path: { id: sessionId },
131037
- query: {
131038
- directory: docsDir,
131039
- ...task === "curate" ? {} : { limit: 50 }
131295
+ system: task === "maintain-docs" ? MAINTAIN_DOCS_SYSTEM_PROMPT : CURATE_SYSTEM_PROMPT,
131296
+ prompt: taskPrompt,
131297
+ title: `magic-context-dream-${task}`,
131298
+ callContext: `dreamer:${task}`,
131299
+ allowEmpty: task === "curate",
131300
+ model: config.model,
131301
+ fallbackModels: config.fallbackModels,
131302
+ language: task === "curate" ? config.language ?? deps.language : undefined,
131303
+ timeoutMs: Math.min(Math.max(0, deadline - Date.now()), config.timeoutMinutes * 60 * 1000),
131304
+ signal: abortController.signal,
131305
+ parse: (text, completion) => {
131306
+ if (task !== "curate")
131307
+ return text;
131308
+ const memoryOperations = inspectCurateMemoryOperations(completion.messages);
131309
+ if (text)
131310
+ validateCurateAssistantText(text);
131311
+ if (memoryOperations.totalCalls > 0 && memoryOperations.completedActions.length === 0)
131312
+ throw new Error("Curate returned no completed ctx_memory tool result.");
131313
+ if (!text && memoryOperations.completedActions.length === 0)
131314
+ throw new Error("Dreamer returned no assistant output.");
131315
+ return { text: text || null, memoryOperations };
131316
+ }
131317
+ });
131318
+ childSessionId = hidden.childSessionId;
131319
+ run = { output: hidden.completion.messages ?? [], validated: hidden.validated };
131320
+ promptSettled = true;
131321
+ } else {
131322
+ const createResponse = await createChildSessionWithFence({
131323
+ client: requireDreamClient(deps.client),
131324
+ db,
131325
+ parentSessionId: parent ?? undefined,
131326
+ title: `magic-context-dream-${task}`,
131327
+ directory: docsDir
131328
+ });
131329
+ const created = normalizeSDKResponse(createResponse, null, {
131330
+ preferResponseOnMissingData: true
131331
+ });
131332
+ childSessionId = typeof created?.id === "string" ? created.id : null;
131333
+ if (!childSessionId)
131334
+ throw new Error("Dreamer could not create its child session.");
131335
+ const sessionId = childSessionId;
131336
+ const remainingMs = Math.max(0, deadline - Date.now());
131337
+ run = await promptSyncWithValidatedOutputRetry(requireDreamClient(deps.client), {
131338
+ path: { id: sessionId },
131339
+ query: { directory: docsDir },
131340
+ body: {
131341
+ agent: task === "maintain-docs" ? DREAMER_DOCS_AGENT : DREAMER_AGENT,
131342
+ system: task === "maintain-docs" ? MAINTAIN_DOCS_SYSTEM_PROMPT : withContentLanguageDirective(CURATE_SYSTEM_PROMPT, config.language ?? deps.language),
131343
+ ...modelBodyField(config.model),
131344
+ parts: [{ type: "text", text: taskPrompt, synthetic: true }]
131345
+ }
131346
+ }, {
131347
+ timeoutMs: Math.min(remainingMs, config.timeoutMinutes * 60 * 1000),
131348
+ signal: abortController.signal,
131349
+ fallbackModels: config.fallbackModels,
131350
+ callContext: `dreamer:${task}`,
131351
+ fetchOutput: async () => {
131352
+ const messagesResponse = await requireDreamClient(deps.client).session.messages({
131353
+ path: { id: sessionId },
131354
+ query: {
131355
+ directory: docsDir,
131356
+ ...task === "curate" ? {} : { limit: 50 }
131357
+ }
131358
+ });
131359
+ return normalizeSDKResponse(messagesResponse, [], {
131360
+ preferResponseOnMissingData: true
131361
+ });
131362
+ },
131363
+ validateOutput: (messages) => {
131364
+ const text = extractLatestAssistantText(messages);
131365
+ if (task !== "curate") {
131366
+ if (!text)
131367
+ throw new Error("Dreamer returned no assistant output.");
131368
+ return text;
131369
+ }
131370
+ const memoryOperations = inspectCurateMemoryOperations(messages);
131371
+ if (text)
131372
+ validateCurateAssistantText(text);
131373
+ if (memoryOperations.completedActions.length > 0) {
131374
+ return { text, memoryOperations };
131040
131375
  }
131041
- });
131042
- return normalizeSDKResponse(messagesResponse, [], {
131043
- preferResponseOnMissingData: true
131044
- });
131045
- },
131046
- validateOutput: (messages) => {
131047
- const text = extractLatestAssistantText(messages);
131048
- if (task !== "curate") {
131049
131376
  if (!text)
131050
131377
  throw new Error("Dreamer returned no assistant output.");
131051
- return text;
131052
- }
131053
- const memoryOperations = inspectCurateMemoryOperations(messages);
131054
- if (text)
131055
- validateCurateAssistantText(text);
131056
- if (memoryOperations.completedActions.length > 0) {
131378
+ if (memoryOperations.totalCalls > 0) {
131379
+ throw new Error("Curate returned no completed ctx_memory tool result.");
131380
+ }
131057
131381
  return { text, memoryOperations };
131058
131382
  }
131059
- if (!text)
131060
- throw new Error("Dreamer returned no assistant output.");
131061
- if (memoryOperations.totalCalls > 0) {
131062
- throw new Error("Curate returned no completed ctx_memory tool result.");
131063
- }
131064
- return { text, memoryOperations };
131065
- }
131066
- });
131067
- promptSettled = true;
131383
+ });
131384
+ promptSettled = true;
131385
+ }
131068
131386
  if (leaseLost)
131069
131387
  throw new Error("Dream lease lost during task");
131070
- const curateRefused = task === "curate" ? takeCurateSafetyRefusalCount(sessionId) : 0;
131388
+ const curateRefused = task === "curate" ? takeCurateSafetyRefusalCount(childSessionId ?? "") : 0;
131071
131389
  if (curateRefused > 0) {
131072
131390
  helpers.reportProgress(curateRefused, curateRefused);
131073
131391
  log(`[dreamer] curate safety summary: refused=${curateRefused}`);
@@ -131137,15 +131455,16 @@ async function runAgenticTask(config, ctx, helpers) {
131137
131455
  heartbeat.stop();
131138
131456
  if (childSessionId)
131139
131457
  takeCurateSafetyRefusalCount(childSessionId);
131140
- await teardownChildSession({
131141
- client: requireDreamClient(deps.client),
131142
- sessionId: childSessionId,
131143
- sessionDirectory: docsDir,
131144
- promptSettled,
131145
- privacySensitive: true,
131146
- context: `[dreamer] ${task}`,
131147
- log
131148
- });
131458
+ if (!deps.hiddenCompletionExecutor)
131459
+ await teardownChildSession({
131460
+ client: requireDreamClient(deps.client),
131461
+ sessionId: childSessionId,
131462
+ sessionDirectory: docsDir,
131463
+ promptSettled,
131464
+ privacySensitive: true,
131465
+ context: `[dreamer] ${task}`,
131466
+ log
131467
+ });
131149
131468
  }
131150
131469
  }
131151
131470
 
@@ -131598,7 +131917,25 @@ async function warmModelLimitCacheFromCatalog(context, options = {}) {
131598
131917
  }
131599
131918
 
131600
131919
  // src/v2/hooks/payload.ts
131920
+ init_logger();
131601
131921
  var HEAD_IDS = ["__magic_context_v2_m0__", "__magic_context_v2_m1__"];
131922
+ var HOST_CONTENT_TYPES = new Set([
131923
+ "text",
131924
+ "media",
131925
+ "tool-call",
131926
+ "tool-result",
131927
+ "reasoning",
131928
+ "compaction",
131929
+ "effort"
131930
+ ]);
131931
+ function rejectContentPart(message, part, reason) {
131932
+ const type = typeof part.type === "string" ? part.type : "<missing>";
131933
+ const text = `v2 context omitted a content part the host would reject: type=${type} message=${String(message.info.id ?? "<head>")} reason=${reason}`;
131934
+ if (typeof message.info.sessionID === "string")
131935
+ sessionLog(message.info.sessionID, text);
131936
+ else
131937
+ log(text);
131938
+ }
131602
131939
  function isHostInstance(value) {
131603
131940
  if (!value || typeof value !== "object" || Array.isArray(value))
131604
131941
  return false;
@@ -131789,6 +132126,56 @@ function adaptPayload(draft, admittedIDs = new Set) {
131789
132126
  const part = candidate;
131790
132127
  const bridge = bridges.get(part) ?? (part.type === "tool" && typeof part.callID === "string" ? bridgesFor(message)?.get(part.callID) : undefined);
131791
132128
  if (!bridge) {
132129
+ if (part.type === "tool") {
132130
+ const state = part.state;
132131
+ if (typeof part.callID !== "string" || typeof part.tool !== "string" || !state || typeof state !== "object") {
132132
+ rejectContentPart(message, part, "tool has no call ID, name, or state");
132133
+ continue;
132134
+ }
132135
+ content.push({
132136
+ type: "tool-call",
132137
+ id: part.callID,
132138
+ name: part.tool,
132139
+ input: state.input
132140
+ });
132141
+ if (state.status === "completed" || state.status === "error") {
132142
+ following.push({
132143
+ role: "tool",
132144
+ content: [
132145
+ {
132146
+ type: "tool-result",
132147
+ id: part.callID,
132148
+ name: part.tool,
132149
+ result: {
132150
+ type: state.status === "error" ? "error" : "text",
132151
+ value: toolStateContent(state)
132152
+ }
132153
+ }
132154
+ ]
132155
+ });
132156
+ }
132157
+ continue;
132158
+ }
132159
+ if (part.type === "file") {
132160
+ const mime = part.mime;
132161
+ const url = part.url;
132162
+ const prefix = `data:${mime};base64,`;
132163
+ if (typeof mime !== "string" || !/^image\/(png|jpeg|gif|webp)$/.test(mime) || typeof url !== "string" || !url.startsWith(prefix)) {
132164
+ rejectContentPart(message, part, "file is not an inline supported image");
132165
+ continue;
132166
+ }
132167
+ const asset = hostMediaAsset(url.slice(prefix.length), mime);
132168
+ if (typeof asset === "string") {
132169
+ rejectContentPart(message, part, `host media unavailable: ${asset}`);
132170
+ continue;
132171
+ }
132172
+ content.push({ type: "media", media: asset });
132173
+ continue;
132174
+ }
132175
+ if (!HOST_CONTENT_TYPES.has(String(part.type))) {
132176
+ rejectContentPart(message, part, "unknown host content type");
132177
+ continue;
132178
+ }
131792
132179
  const { synthetic: _synthetic, ...clean } = part;
131793
132180
  const original = hostPartTypes.has(clean.type) && !containsHostInstance(clean) ? hostParts.get(contentKey(clean)) : undefined;
131794
132181
  content.push(original ?? clean);
@@ -131796,14 +132183,23 @@ function adaptPayload(draft, admittedIDs = new Set) {
131796
132183
  }
131797
132184
  const state = part.state;
131798
132185
  if (bridge.native) {
131799
- const sourceState = bridge.native.state && typeof bridge.native.state === "object" ? bridge.native.state : {};
131800
- const nextState = { ...sourceState, input: state.input };
131801
- if (sourceState.content !== undefined) {
131802
- nextState.content = state.output === bridge.output ? sourceState.content : [{ type: "text", text: state.output }];
131803
- } else {
131804
- nextState.output = state.output;
132186
+ const native = bridge.native;
132187
+ const callID = String(native.id ?? native.callID ?? part.callID);
132188
+ const name = String(native.name ?? native.tool ?? part.tool);
132189
+ content.push({ type: "tool-call", id: callID, name, input: state.input });
132190
+ if (state.status === "completed" || state.status === "error") {
132191
+ following.push({
132192
+ role: "tool",
132193
+ content: [
132194
+ {
132195
+ type: "tool-result",
132196
+ id: callID,
132197
+ name,
132198
+ result: { type: "text", value: state.output }
132199
+ }
132200
+ ]
132201
+ });
131805
132202
  }
131806
- content.push({ ...bridge.native, state: nextState });
131807
132203
  continue;
131808
132204
  }
131809
132205
  if (bridge.call)
@@ -147857,7 +148253,7 @@ async function getLatestVersion(channel = "latest", options = {}) {
147857
148253
  try {
147858
148254
  if (options.signal?.aborted)
147859
148255
  return null;
147860
- const response = await fetch(buildRegistryUrl(options.registryUrl ?? NPM_REGISTRY_URL), {
148256
+ const response = await (options.fetch ?? fetch)(buildRegistryUrl(options.registryUrl ?? NPM_REGISTRY_URL), {
147861
148257
  signal: controller.signal,
147862
148258
  headers: { Accept: "application/json" }
147863
148259
  });