@cortexkit/opencode-magic-context 0.49.77 → 0.49.79

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 (80) hide show
  1. package/dist/auto-search-worker.js +1 -1
  2. package/dist/chunk-embedding-write-worker.js +1 -1
  3. package/dist/{context-8zhjv9tj.js → context-gb3gjahp.js} +63 -143
  4. package/dist/features/magic-context/dreamer/curate-category-rotation.d.ts +1 -1
  5. package/dist/features/magic-context/dreamer/curate-category-rotation.d.ts.map +1 -1
  6. package/dist/features/magic-context/dreamer/curate-memory-safety.d.ts +5 -1
  7. package/dist/features/magic-context/dreamer/curate-memory-safety.d.ts.map +1 -1
  8. package/dist/features/magic-context/dreamer/task-executor.d.ts +2 -0
  9. package/dist/features/magic-context/dreamer/task-executor.d.ts.map +1 -1
  10. package/dist/hooks/magic-context/image-token-estimate.d.ts.map +1 -1
  11. package/dist/{index-5jtq51xv.js → index-2dadxknq.js} +110 -59
  12. package/dist/{index-8mt6vvwx.js → index-2q0t43fy.js} +1 -1
  13. package/dist/{index-1pfjvk89.js → index-8ykmp4jv.js} +6 -6
  14. package/dist/{index-kn23xzst.js → index-aawwdt26.js} +1 -1
  15. package/dist/{index-ng6gfs0y.js → index-enpatj5k.js} +120 -14
  16. package/dist/{index-xkn7vq89.js → index-f619wjj9.js} +3 -3
  17. package/dist/{index-swfwxev1.js → index-hgdkwp21.js} +2 -2
  18. package/dist/{index-72qk8fs8.js → index-m0tbtzqh.js} +3 -3
  19. package/dist/{index-r865s8hf.js → index-m6rkq3t4.js} +1 -1
  20. package/dist/{index-dcdk1thy.js → index-sy5wbbw6.js} +5 -5
  21. package/dist/{index-7jj5jk78.js → index-tvkzkk4s.js} +5 -5
  22. package/dist/{index-k6b1av2m.js → index-twmeey4h.js} +2 -2
  23. package/dist/{index-bw3pmrtk.js → index-v8x07j6c.js} +4 -4
  24. package/dist/{index-rjm4hjyb.js → index-xsdaz3mq.js} +1 -1
  25. package/dist/{index-bdnak4d0.js → index-y208s7zx.js} +5 -3
  26. package/dist/{index-vr6t0y4w.js → index-zzvd4a9z.js} +1 -1
  27. package/dist/index.js +18 -18
  28. package/dist/{message-index-bounded-s0bckzqz.js → message-index-bounded-cfkeyf72.js} +3 -3
  29. package/dist/migration-worker.js +1 -1
  30. package/dist/raw-ordinal-warmup-worker.js +4 -4
  31. package/dist/{read-session-chunk-kqyb1y8c.js → read-session-chunk-s3qac56g.js} +2 -2
  32. package/dist/{recomp-orchestrator-38ed4yhj.js → recomp-orchestrator-jf60eef6.js} +7 -7
  33. package/dist/{render-8s531gd5.js → render-bjxgkrk6.js} +6 -6
  34. package/dist/{search-archive-4vcfm0wv.js → search-archive-a60k0x2n.js} +4 -4
  35. package/dist/{search-m4r4v4aw.js → search-mpde08f1.js} +5 -5
  36. package/dist/shared/subagent-runner.d.ts +9 -0
  37. package/dist/shared/subagent-runner.d.ts.map +1 -1
  38. package/dist/{storage-tags-d3nqrva7.js → storage-tags-6e83pvff.js} +1 -1
  39. package/dist/{store-h2a1g3wh.js → store-j5rvve3v.js} +1 -1
  40. package/dist/{transform-postprocess-phase-ch5fsw7h.js → transform-postprocess-phase-m1be339w.js} +8 -8
  41. package/dist/v2/auto-search-worker.js +1 -1
  42. package/dist/v2/chunk-embedding-write-worker.js +1 -1
  43. package/dist/v2/{context-9nm9edea.js → context-fzp6ynz4.js} +156 -185
  44. package/dist/v2/fold/host-media.d.ts +16 -11
  45. package/dist/v2/fold/host-media.d.ts.map +1 -1
  46. package/dist/v2/fold/native-replay.d.ts.map +1 -1
  47. package/dist/v2/fold/restore.d.ts +7 -5
  48. package/dist/v2/fold/restore.d.ts.map +1 -1
  49. package/dist/v2/hooks/context.d.ts.map +1 -1
  50. package/dist/v2/hooks/payload.d.ts +8 -0
  51. package/dist/v2/hooks/payload.d.ts.map +1 -1
  52. package/dist/v2/hooks/store.d.ts.map +1 -1
  53. package/dist/v2/{message-index-bounded-vfx2zx9y.js → message-index-bounded-0xy4dn04.js} +3 -3
  54. package/dist/v2/migration-worker.js +1 -1
  55. package/dist/v2/raw-ordinal-warmup-worker.js +4 -4
  56. package/dist/v2/{read-session-chunk-bh402br0.js → read-session-chunk-6mt2t6dy.js} +2 -2
  57. package/dist/v2/{recomp-orchestrator-43grkr1k.js → recomp-orchestrator-4r63zen2.js} +6 -6
  58. package/dist/v2/{render-90pve6jf.js → render-7tr9d67f.js} +6 -6
  59. package/dist/v2/{search-archive-9sx7fn3t.js → search-archive-2ck9sbsc.js} +4 -4
  60. package/dist/v2/{search-xr5wb3a3.js → search-y01mww69.js} +4 -4
  61. package/dist/v2/{server-86vydsx9.js → server-0dmzr7f9.js} +2 -2
  62. package/dist/v2/{server-92fhew3p.js → server-1svqwm7m.js} +5 -5
  63. package/dist/v2/{server-6jxvkyrr.js → server-2gcfmd47.js} +1 -1
  64. package/dist/v2/{server-b0k0cfkd.js → server-d7dbk2h6.js} +2 -2
  65. package/dist/v2/{server-gsz7h1zr.js → server-dhdn8mwq.js} +1 -1
  66. package/dist/v2/{server-06ew2dbf.js → server-qpnjsg1v.js} +4 -4
  67. package/dist/v2/{server-fw2sjpkx.js → server-r00xyx66.js} +1 -1
  68. package/dist/v2/{server-b8qp1ark.js → server-r9xsgnez.js} +1 -1
  69. package/dist/v2/{server-65r7p1z4.js → server-tkznm2j9.js} +2 -2
  70. package/dist/v2/{server-474m6n9v.js → server-wc0bb04b.js} +120 -14
  71. package/dist/v2/{server-cxkb9725.js → server-xdh4r20h.js} +5 -3
  72. package/dist/v2/server.js +2 -2
  73. package/dist/v2/{storage-tags-j4he6hwe.js → storage-tags-z8j8wq34.js} +1 -1
  74. package/dist/v2/{store-4se2a0n0.js → store-1fax2zhj.js} +1 -1
  75. package/dist/v2/{v2-archive-reader-rm5qkv00.js → v2-archive-reader-jatkdt2s.js} +1 -1
  76. package/dist/v2/{wrapup-orchestrator-ghbsa00k.js → wrapup-orchestrator-z91sebhb.js} +6 -6
  77. package/dist/{v2-archive-reader-gwe0ry1a.js → v2-archive-reader-sw01917z.js} +1 -1
  78. package/dist/{wrapup-orchestrator-q12ejyw9.js → wrapup-orchestrator-1k48hzxg.js} +8 -8
  79. package/package.json +1 -1
  80. package/src/shared/subagent-runner.ts +10 -0
@@ -220,7 +220,7 @@ import {
220
220
  startCompartmentAgent,
221
221
  setRecompStarting2,
222
222
  setRecompTerminal2
223
- } from "./server-92fhew3p.js";
223
+ } from "./server-1svqwm7m.js";
224
224
  import {
225
225
  resolveHistorianModel2
226
226
  } from "./server-5kym00ag.js";
@@ -534,7 +534,7 @@ import {
534
534
  adoptNullOwnerToolTag2,
535
535
  getCandidateToolOwners2,
536
536
  pickNearestPriorOwner2
537
- } from "./server-cxkb9725.js";
537
+ } from "./server-xdh4r20h.js";
538
538
  import {
539
539
  textMentionsRecentCommit,
540
540
  hasMeaningfulUserText2,
@@ -616,12 +616,12 @@ import {
616
616
  readRawSessionMessageOrdinalById2,
617
617
  readSessionChunk2,
618
618
  readRawSessionSeedTail2
619
- } from "./server-6jxvkyrr.js";
619
+ } from "./server-2gcfmd47.js";
620
620
  import {
621
621
  cleanSearchText,
622
622
  matchedSearchSnippet,
623
623
  getLastIndexedOrdinal
624
- } from "./server-fw2sjpkx.js";
624
+ } from "./server-r00xyx66.js";
625
625
  import"./server-ds8vpfkr.js";
626
626
  import {
627
627
  getMessageIndexEpoch,
@@ -648,7 +648,7 @@ import {
648
648
  resolveMemoriesByIdsForSearch2,
649
649
  unifiedSearch2,
650
650
  formatSearchResults2
651
- } from "./server-65r7p1z4.js";
651
+ } from "./server-tkznm2j9.js";
652
652
  import {
653
653
  embedPauseBySession,
654
654
  embedRunStateBySession,
@@ -796,7 +796,7 @@ import {
796
796
  saveSourceContent,
797
797
  replaceSourceContent,
798
798
  getSourceContents
799
- } from "./server-gsz7h1zr.js";
799
+ } from "./server-dhdn8mwq.js";
800
800
  import {
801
801
  startBootDeadline,
802
802
  getUnconfirmedMigrationHolders,
@@ -812,7 +812,7 @@ import {
812
812
  openDatabaseAsync,
813
813
  isDatabasePersisted,
814
814
  getDatabasePersistenceError
815
- } from "./server-b8qp1ark.js";
815
+ } from "./server-r9xsgnez.js";
816
816
  import {
817
817
  V2_MEMORY_CATEGORIES,
818
818
  CATEGORY_PRIORITY
@@ -974,6 +974,9 @@ import {
974
974
  sendStatusNotification2
975
975
  } from "./server-qjff96a6.js";
976
976
  import {
977
+ rememberHostMedia,
978
+ hostMediaAsset,
979
+ hostMediaFromEncoded,
977
980
  isToolError,
978
981
  toolErrorText,
979
982
  toolStateContent,
@@ -982,6 +985,7 @@ import {
982
985
  formatStorageRecoveryNotice,
983
986
  hasStorageNoticeShape,
984
987
  dropStorageNotices,
988
+ HOST_RESTORE_MEDIA,
985
989
  restoreRow,
986
990
  servedBoundaryRow2,
987
991
  resolveV2BoundaryUserMessage2,
@@ -989,7 +993,7 @@ import {
989
993
  readV2RawMessagePagesForConversion2,
990
994
  createV2RawMessageReader2,
991
995
  createV2RawMessageProvider2
992
- } from "./server-474m6n9v.js";
996
+ } from "./server-wc0bb04b.js";
993
997
  import {
994
998
  resolvePromptContext2
995
999
  } from "./server-fmsr7v69.js";
@@ -997,14 +1001,14 @@ import {
997
1001
  renderMessageByOrdinal2,
998
1002
  renderVerboseRangeForTool2,
999
1003
  renderItemByTag2
1000
- } from "./server-86vydsx9.js";
1004
+ } from "./server-0dmzr7f9.js";
1001
1005
  import"./server-52x68mj4.js";
1002
1006
  import {
1003
1007
  readV2ArchiveOffThread2
1004
- } from "./server-06ew2dbf.js";
1008
+ } from "./server-qpnjsg1v.js";
1005
1009
  import {
1006
1010
  renderSearchArchiveOffThread2
1007
- } from "./server-b0k0cfkd.js";
1011
+ } from "./server-d7dbk2h6.js";
1008
1012
  import {
1009
1013
  markHostInstructionRow,
1010
1014
  hostInstructionRow,
@@ -5492,7 +5496,7 @@ function beginCurateCategoryRun(db, projectIdentity, memories) {
5492
5496
  }));
5493
5497
  return scope;
5494
5498
  }
5495
- function curateTaskStateAfterSuccess(db, projectIdentity, category) {
5499
+ function curateTaskStateAfterCategoryTurn(db, projectIdentity, category) {
5496
5500
  const state = readState(db, projectIdentity);
5497
5501
  return JSON.stringify({
5498
5502
  ...state,
@@ -26189,7 +26193,7 @@ function registerRpcHandlers(rpcServer, args) {
26189
26193
  const db = readDatabase();
26190
26194
  if (!db)
26191
26195
  return { ok: false, error: "db unavailable" };
26192
- const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-43grkr1k.js"));
26196
+ const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-4r63zen2.js"));
26193
26197
  const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-8g4r97bp.js"));
26194
26198
  log2(`[rpc] recomp requested for session ${sessionId}`);
26195
26199
  if (!args.client && !args.hiddenCompletionExecutor) {
@@ -26274,7 +26278,7 @@ function registerRpcHandlers(rpcServer, args) {
26274
26278
  const db = readDatabase();
26275
26279
  if (!db)
26276
26280
  return { ok: false, error: "db unavailable" };
26277
- const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-ghbsa00k.js"));
26281
+ const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-z91sebhb.js"));
26278
26282
  const model = await args.readSelectedSessionModel?.(sessionId) ?? liveSessionState.liveModelBySession.get(sessionId);
26279
26283
  const window = resolveOpenCodeWrapupWindow(db, sessionId, model);
26280
26284
  if (!window)
@@ -27228,128 +27232,6 @@ function trimToRecordedBoundary(db, sessionId, messages) {
27228
27232
  return safeStart;
27229
27233
  }
27230
27234
 
27231
- // src/v2/fold/host-media.ts
27232
- var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
27233
- function isClassInstance(value) {
27234
- if (!isRecord5(value))
27235
- return false;
27236
- const prototype = Object.getPrototypeOf(value);
27237
- return prototype !== Object.prototype && prototype !== null;
27238
- }
27239
- var rememberedAssetClass;
27240
- var rememberedMessageClass;
27241
- var schemaUsesAssets = new WeakMap;
27242
- function rememberHostMedia(messages) {
27243
- for (const message of messages) {
27244
- if (!isClassInstance(message))
27245
- continue;
27246
- rememberedMessageClass ??= Object.getPrototypeOf(message).constructor;
27247
- if (rememberedAssetClass)
27248
- return;
27249
- const content = message.content;
27250
- if (!Array.isArray(content))
27251
- continue;
27252
- for (const part of content) {
27253
- if (!isRecord5(part) || part.type !== "media")
27254
- continue;
27255
- const media = part.media;
27256
- if (isClassInstance(media) && isRecord5(media.source)) {
27257
- rememberedAssetClass = Object.getPrototypeOf(media).constructor;
27258
- return;
27259
- }
27260
- }
27261
- }
27262
- }
27263
- function hostUsesMediaAssets() {
27264
- const messageClass = rememberedMessageClass;
27265
- if (!messageClass)
27266
- return rememberedAssetClass !== undefined;
27267
- const cached = schemaUsesAssets.get(messageClass);
27268
- if (cached !== undefined)
27269
- return cached;
27270
- let uses = rememberedAssetClass !== undefined;
27271
- if (!uses) {
27272
- try {
27273
- uses = JSON.stringify(messageClass.ast).includes('"Media.Asset"');
27274
- } catch {
27275
- uses = false;
27276
- }
27277
- }
27278
- schemaUsesAssets.set(messageClass, uses);
27279
- return uses;
27280
- }
27281
- function decodeThroughHostSchema(encoded) {
27282
- const source = encoded.source;
27283
- const messageClass = rememberedMessageClass;
27284
- if (!messageClass)
27285
- return "no host message class seen";
27286
- const fields = messageClass.fields;
27287
- const union = fields?.content?.value;
27288
- const members = union?.members;
27289
- if (!Array.isArray(members))
27290
- return "host content schema has no union members";
27291
- const mediaPart = members.find((member) => {
27292
- const typeField = member?.fields;
27293
- const literal = typeField?.type?.ast?.literal;
27294
- return literal === "media";
27295
- });
27296
- const assetSchema = mediaPart?.fields?.media;
27297
- const encoding = assetSchema?.ast?.encoding;
27298
- const decode = Array.isArray(encoding) ? encoding[0]?.transformation?.decode : undefined;
27299
- const getter = decode;
27300
- let asset;
27301
- if (getter?._tag === "Transform") {
27302
- if (typeof getter.transform !== "function")
27303
- return "host media schema has no decode transformation";
27304
- asset = getter.transform(encoded);
27305
- } else {
27306
- if (getter?._tag !== undefined)
27307
- return `host media schema has unsupported decode transformation: ${String(getter._tag)}`;
27308
- const run = getter?.run;
27309
- if (typeof run !== "function")
27310
- return "host media schema has no decode transformation";
27311
- const result = run.call(decode, { _tag: "Some", value: encoded }, {});
27312
- const option = result?._tag === "Success" ? result.value : undefined;
27313
- asset = option?._tag === "Some" ? option.value : undefined;
27314
- }
27315
- if (!isClassInstance(asset) || asset.source !== source)
27316
- return "host media schema decode did not return an asset";
27317
- return asset;
27318
- }
27319
- function hostMediaAsset(data, mediaType) {
27320
- return hostMediaFromEncoded({ source: { type: "base64", data, mediaType } });
27321
- }
27322
- function hostMediaFromEncoded(value) {
27323
- if (!isRecord5(value.source))
27324
- return "missing Media.Asset source";
27325
- const encoded = structuredClone(value);
27326
- if (encoded.source.type === "bytes") {
27327
- if (typeof encoded.source.data !== "string")
27328
- return "bytes media has no JSON codec payload";
27329
- encoded.source.data = new Uint8Array(Buffer.from(encoded.source.data, "base64"));
27330
- }
27331
- if (!["bytes", "base64", "url", "ref"].includes(String(encoded.source.type)))
27332
- return "unknown Media.Asset source";
27333
- let first = "no Media.Asset seen in this process";
27334
- if (rememberedAssetClass) {
27335
- try {
27336
- return new rememberedAssetClass(encoded);
27337
- } catch (error) {
27338
- first = `remembered asset class threw: ${String(error)}`;
27339
- }
27340
- }
27341
- let second;
27342
- try {
27343
- const decoded = decodeThroughHostSchema(encoded);
27344
- if (typeof decoded !== "string")
27345
- return decoded;
27346
- second = decoded;
27347
- } catch (error) {
27348
- second = `host media schema decode threw: ${String(error)}`;
27349
- }
27350
- return `${first}; ${second}`;
27351
- }
27352
-
27353
27235
  // src/v2/fold/idle.ts
27354
27236
  class HostFoldIdle {
27355
27237
  fold;
@@ -28115,6 +27997,43 @@ function rejectContentPart(message, part, reason) {
28115
27997
  else
28116
27998
  log2(text);
28117
27999
  }
28000
+ var mediaRepairLogged = new Set;
28001
+ function unpassableAttachmentNote(name, mediaType) {
28002
+ return `[Attachment ${name ? `"${name}" ` : ""}(${mediaType}) could not be passed to the model]`;
28003
+ }
28004
+ function repairMediaPart(message, partIndex, part) {
28005
+ const media = isRecord(part.media) ? part.media : undefined;
28006
+ const source = isRecord(media?.source) ? media.source : undefined;
28007
+ const mediaType = [part.mediaType, media?.mediaType, source?.mediaType].find((value) => typeof value === "string");
28008
+ let asset = "the part has neither an encoded asset nor inline data";
28009
+ if (media && source)
28010
+ asset = hostMediaFromEncoded(media);
28011
+ else if (part.media === undefined && typeof part.data === "string" && mediaType)
28012
+ asset = hostMediaAsset(part.data, mediaType);
28013
+ const sessionID = typeof message.info.sessionID === "string" ? message.info.sessionID : "";
28014
+ const key = JSON.stringify([sessionID, message.info.id ?? null, partIndex]);
28015
+ if (!mediaRepairLogged.has(key)) {
28016
+ mediaRepairLogged.add(key);
28017
+ const where = `message=${String(message.info.id ?? "<head>")} part=${partIndex} mediaType=${mediaType ?? "unknown"} fields=${Object.keys(part).join(",")}`;
28018
+ const text = typeof asset === "string" ? `v2 context replaced a media part that has no host asset by a note: ${where} reason=${JSON.stringify(asset)}` : `v2 context rebuilt a media part that had no host asset instance: ${where}`;
28019
+ if (sessionID)
28020
+ sessionLog2(sessionID, text);
28021
+ else
28022
+ log2(text);
28023
+ }
28024
+ if (typeof asset !== "string") {
28025
+ if (media)
28026
+ return { ...part, media: asset };
28027
+ const { type: _type, mediaType: _mediaType, data: _data, ...rest } = part;
28028
+ return { type: "media", media: asset, ...rest };
28029
+ }
28030
+ const name = typeof part.filename === "string" ? part.filename : undefined;
28031
+ return {
28032
+ type: "text",
28033
+ text: unpassableAttachmentNote(name, mediaType ?? "unknown media type"),
28034
+ ...part.cache === undefined ? {} : { cache: part.cache }
28035
+ };
28036
+ }
28118
28037
  var emptyTextOmissionLogged = new Set;
28119
28038
  function placeCacheHint(content, hint) {
28120
28039
  if (content.length === 0 || content.some((part) => part.cache !== undefined))
@@ -28481,6 +28400,10 @@ function adaptPayload(draft, syntheticIDs = new Set, messageTimes = new Map, hid
28481
28400
  const { synthetic: _synthetic, ...clean } = part;
28482
28401
  const original = hostPartTypes.has(clean.type) && !containsHostInstance(clean) ? hostParts.get(contentKey(clean)) : undefined;
28483
28402
  const projected = original ?? clean;
28403
+ if (projected.type === "media" && !isHostInstance(projected.media)) {
28404
+ content.push(repairMediaPart(message, partIndex, projected));
28405
+ continue;
28406
+ }
28484
28407
  if (imageOmissions.get(message.info.id ?? "")?.has(partIndex))
28485
28408
  emptyImages.add(projected);
28486
28409
  content.push(projected);
@@ -29438,10 +29361,7 @@ ${cached}
29438
29361
  return this.replayInput(args, replay);
29439
29362
  }
29440
29363
  rendered(row, model) {
29441
- return restoreRow(row, model, hostUsesMediaAssets() ? {
29442
- asset: hostMediaAsset,
29443
- unavailable: () => {}
29444
- } : undefined);
29364
+ return restoreRow(row, model, HOST_RESTORE_MEDIA);
29445
29365
  }
29446
29366
  record(row, messages) {
29447
29367
  const data = JSON.stringify(encodeNative(messages));
@@ -33865,6 +33785,22 @@ function isDirectiveShapedProjectRule(category, content) {
33865
33785
  // src/features/magic-context/dreamer/curate-memory-safety.ts
33866
33786
  var PROJECT_SCOPED_CATEGORIES = new Set(V2_MEMORY_CATEGORIES);
33867
33787
  var USER_PROFILE_REFERENCE = /\buser(?:[\s_-]+)(?:profile|preferences?)\b|\bU\d+\b/i;
33788
+ var CURATE_SAFETY_REFUSAL_REASONS = [
33789
+ "missing-active-same-category-successor",
33790
+ "user-profile-is-not-project-memory",
33791
+ "directive-shaped-project-rule",
33792
+ "content-loss"
33793
+ ];
33794
+ var refusalReasons = new Set(CURATE_SAFETY_REFUSAL_REASONS);
33795
+ function parseCurateSafetyRefusal(action, output) {
33796
+ if (action !== "archive" && action !== "update")
33797
+ return null;
33798
+ const refusal = /^Skipped (archive|update) for memory \[ID: -?\d+(?:, -?\d+)*\]: curate safety refusal \(([a-z,-]+)\); refused=[1-9]\d*\.$/.exec(output);
33799
+ if (refusal?.[1] !== action || !refusal[2])
33800
+ return null;
33801
+ const reasons = [...new Set(refusal[2].split(","))];
33802
+ return reasons.every((reason) => refusalReasons.has(reason)) ? reasons : null;
33803
+ }
33868
33804
  var refusalCountsBySession = new Map;
33869
33805
  function isSurvivingConsolidationTarget(memory, successor, projectIdentity) {
33870
33806
  return successor !== null && successor.id !== memory.id && successor.status === "active" && successor.supersededByMemoryId === null && (successor.expiresAt === null || successor.expiresAt > Date.now()) && projectIdentity(successor) === projectIdentity(memory) && successor.category === memory.category;
@@ -38862,8 +38798,11 @@ function validateCurateAssistantText(text) {
38862
38798
  }
38863
38799
  return text;
38864
38800
  }
38801
+ function emptyCurateMemoryOperations() {
38802
+ return { totalCalls: 0, completedActions: [], refusals: [] };
38803
+ }
38865
38804
  function inspectCurateMemoryOperations(messages) {
38866
- const summary = { totalCalls: 0, completedActions: [] };
38805
+ const summary = emptyCurateMemoryOperations();
38867
38806
  if (!Array.isArray(messages))
38868
38807
  return summary;
38869
38808
  for (const message of messages) {
@@ -38878,28 +38817,69 @@ function inspectCurateMemoryOperations(messages) {
38878
38817
  const toolName = part.tool ?? part.name;
38879
38818
  if (toolName !== "ctx_memory")
38880
38819
  continue;
38820
+ const state = isRecord(part.state) ? part.state : null;
38821
+ const input = isRecord(state?.input) ? state.input : null;
38822
+ const action = input?.action;
38823
+ const output = state?.status === "completed" && typeof state.output === "string" ? state.output : null;
38824
+ if (output && (action === "get" || action === "list") && /^(?:Found \d+ (?:active )?memor(?:y|ies):|No active memories found\.$|id -?\d+: not found or not visible from this project)/.test(output))
38825
+ continue;
38881
38826
  summary.totalCalls += 1;
38882
- if (!isRecord(part.state) || part.state.status !== "completed")
38827
+ if (!output)
38883
38828
  continue;
38884
- const input = isRecord(part.state.input) ? part.state.input : null;
38885
- const action = input?.action;
38886
- const output = typeof part.state.output === "string" ? part.state.output : "";
38887
- if (output === "completed" && (action === "merge" || action === "archive" || action === "update") || action === "merge" && output.startsWith("Merged memories") || action === "archive" && output.startsWith("Archived memor") || action === "update" && output.startsWith("Updated memory"))
38829
+ if (action === "merge" && output.startsWith("Merged memories") || action === "archive" && output.startsWith("Archived memor") || action === "update" && output.startsWith("Updated memory")) {
38888
38830
  summary.completedActions.push(action);
38831
+ } else {
38832
+ const reasons = parseCurateSafetyRefusal(action, output);
38833
+ if (reasons)
38834
+ summary.refusals.push(reasons);
38835
+ }
38889
38836
  }
38890
38837
  }
38891
38838
  return summary;
38892
38839
  }
38840
+ function unrecognisedCurateOperations(operations) {
38841
+ return operations.totalCalls - operations.completedActions.length - operations.refusals.length;
38842
+ }
38843
+ function validateCurateOutput(messages, text, transport) {
38844
+ const operations = inspectCurateMemoryOperations(messages);
38845
+ if (text)
38846
+ validateCurateAssistantText(text);
38847
+ if (operations.completedActions.length || operations.refusals.length && !unrecognisedCurateOperations(operations))
38848
+ return operations;
38849
+ if (!text && transport === "child")
38850
+ throw new Error("Dreamer returned no assistant output.");
38851
+ if (operations.totalCalls > 0)
38852
+ throw new Error("Curate returned no completed ctx_memory tool result.");
38853
+ if (!text)
38854
+ throw new Error("Dreamer returned no assistant output.");
38855
+ return operations;
38856
+ }
38893
38857
  function formatExpiredArchiveProgress(count) {
38894
38858
  return `curate: archived ${count} expired ${count === 1 ? "memory" : "memories"}`;
38895
38859
  }
38896
- function formatCurateMemoryOperations(actions) {
38860
+ function formatCurateMemoryOperations(operations) {
38861
+ const { completedActions: actions, refusals } = operations;
38862
+ if (!actions.length && !refusals.length)
38863
+ return null;
38897
38864
  const actionCounts = new Map;
38898
38865
  for (const action of actions)
38899
38866
  actionCounts.set(action, (actionCounts.get(action) ?? 0) + 1);
38900
38867
  const actionDetail = [...actionCounts].map(([action, count]) => count === 1 ? action : `${action} ×${count}`).join(", ");
38901
- const noun = actions.length === 1 ? "operation" : "operations";
38902
- return `curate: ${actions.length} memory ${noun} applied${actionDetail ? ` (${actionDetail})` : ""}`;
38868
+ const applied = actions.length ? `${actions.length} memory ${actions.length === 1 ? "operation" : "operations"} applied (${actionDetail})` : "no changes";
38869
+ const detail = [`curate: ${applied}`];
38870
+ if (refusals.length) {
38871
+ const reasonCounts = new Map;
38872
+ for (const reasons of refusals) {
38873
+ for (const reason of reasons)
38874
+ reasonCounts.set(reason, (reasonCounts.get(reason) ?? 0) + 1);
38875
+ }
38876
+ const countedReasons = [...reasonCounts].sort(([a], [b]) => a.localeCompare(b)).map(([reason, count]) => `${reason} ×${count}`).join(", ");
38877
+ detail.push(`${refusals.length} ${refusals.length === 1 ? "operation" : "operations"} refused (${countedReasons})`);
38878
+ }
38879
+ const unrecognised = unrecognisedCurateOperations(operations);
38880
+ if (unrecognised)
38881
+ detail.push(`${unrecognised} with an unrecognised result`);
38882
+ return detail.join("; ");
38903
38883
  }
38904
38884
  function requireDreamClient(client) {
38905
38885
  if (!client)
@@ -39107,6 +39087,7 @@ function createDreamTaskExecutor(deps) {
39107
39087
  };
39108
39088
  return writtenIds.length || deletedIds.length || archivedIds.length || mergedIds.length ? changes : null;
39109
39089
  }
39090
+ let curateCategory;
39110
39091
  try {
39111
39092
  const skip = (reason) => {
39112
39093
  log2(`[dreamer] ${config.task}: skipped (${reason})`);
@@ -39418,7 +39399,10 @@ function createDreamTaskExecutor(deps) {
39418
39399
  computeMemoryDelta,
39419
39400
  reportProgress,
39420
39401
  leaseAcquisition,
39421
- moduleRoute
39402
+ moduleRoute,
39403
+ onCurateCategory: (category) => {
39404
+ curateCategory = category;
39405
+ }
39422
39406
  });
39423
39407
  } catch (error) {
39424
39408
  if (error instanceof DreamTokenBudgetExceeded) {
@@ -39436,7 +39420,11 @@ function createDreamTaskExecutor(deps) {
39436
39420
  transient,
39437
39421
  error: brief,
39438
39422
  failureDetail: formatDreamRunFailure(failure),
39439
- ...retrospectiveOverflow ? { schedulePatch: retrospectiveOverflow.schedulePatch } : {}
39423
+ ...retrospectiveOverflow ? { schedulePatch: retrospectiveOverflow.schedulePatch } : curateCategory && !transient ? {
39424
+ schedulePatch: {
39425
+ taskStateJson: curateTaskStateAfterCategoryTurn(db, projectIdentity, curateCategory)
39426
+ }
39427
+ } : {}
39440
39428
  };
39441
39429
  } finally {
39442
39430
  deps.onProgress?.(null, config.task);
@@ -39943,6 +39931,8 @@ async function runAgenticTask(config, ctx, helpers) {
39943
39931
  const scope = beginCurateCategoryRun(db, projectIdentity, loadActiveMemoryPromptMemories(db, projectIdentity));
39944
39932
  curateMemories = scope?.memories ?? [];
39945
39933
  curateCategory = scope?.category;
39934
+ if (curateCategory)
39935
+ helpers.onCurateCategory(curateCategory);
39946
39936
  log2(`[dreamer] curate pool: category=${curateCategory ?? "none"} in_scope=${curateMemories.length} expired_archived=${expiredArchived}`);
39947
39937
  if (curateMemories.length === 0) {
39948
39938
  const progress = expiredArchived > 0 ? formatExpiredArchiveProgress(expiredArchived) : "curate: no populated project-memory category";
@@ -39978,7 +39968,7 @@ async function runAgenticTask(config, ctx, helpers) {
39978
39968
  }
39979
39969
  const curateChunks = curateMemories ? chunkCurateMemories(curateMemories, Math.max(4000, Math.floor(resolveRetrospectiveUsableInputTokens(config, deps) * 2))) : [];
39980
39970
  const batches = task === "curate" ? curateChunks : [{ memories: [], crossChunkCandidates: [] }];
39981
- const completedActions = [];
39971
+ const curateOperations = emptyCurateMemoryOperations();
39982
39972
  let curateRefused = 0;
39983
39973
  let run = {
39984
39974
  output: [],
@@ -40027,14 +40017,7 @@ async function runAgenticTask(config, ctx, helpers) {
40027
40017
  parseDocsProposalOutput(text);
40028
40018
  if (task !== "curate")
40029
40019
  return text;
40030
- const memoryOperations = inspectCurateMemoryOperations(completion.messages);
40031
- if (text)
40032
- validateCurateAssistantText(text);
40033
- if (memoryOperations.totalCalls > 0 && memoryOperations.completedActions.length === 0)
40034
- throw new Error("Curate returned no completed ctx_memory tool result.");
40035
- if (!text && memoryOperations.completedActions.length === 0)
40036
- throw new Error("Dreamer returned no assistant output.");
40037
- return { text: text || null, memoryOperations };
40020
+ return validateCurateOutput(completion.messages, text, "hidden");
40038
40021
  }
40039
40022
  });
40040
40023
  childSessionId = hidden.childSessionId;
@@ -40093,24 +40076,15 @@ async function runAgenticTask(config, ctx, helpers) {
40093
40076
  parseDocsProposalOutput(text);
40094
40077
  return text;
40095
40078
  }
40096
- const memoryOperations = inspectCurateMemoryOperations(messages);
40097
- if (text)
40098
- validateCurateAssistantText(text);
40099
- if (memoryOperations.completedActions.length > 0) {
40100
- return { text, memoryOperations };
40101
- }
40102
- if (!text)
40103
- throw new Error("Dreamer returned no assistant output.");
40104
- if (memoryOperations.totalCalls > 0) {
40105
- throw new Error("Curate returned no completed ctx_memory tool result.");
40106
- }
40107
- return { text, memoryOperations };
40079
+ return validateCurateOutput(messages, text, "child");
40108
40080
  }
40109
40081
  });
40110
40082
  promptSettled = true;
40111
40083
  }
40112
- if (task === "curate") {
40113
- completedActions.push(...run.validated.memoryOperations.completedActions);
40084
+ if (typeof run.validated !== "string") {
40085
+ curateOperations.totalCalls += run.validated.totalCalls;
40086
+ curateOperations.completedActions.push(...run.validated.completedActions);
40087
+ curateOperations.refusals.push(...run.validated.refusals);
40114
40088
  curateRefused += takeCurateSafetyRefusalCount(childSessionId ?? "");
40115
40089
  }
40116
40090
  if (childSessionId && !deps.hiddenCompletionExecutor) {
@@ -40126,17 +40100,15 @@ async function runAgenticTask(config, ctx, helpers) {
40126
40100
  childSessionId = null;
40127
40101
  }
40128
40102
  }
40129
- if (task === "curate")
40130
- run.validated = {
40131
- text: null,
40132
- memoryOperations: { totalCalls: completedActions.length, completedActions }
40133
- };
40134
40103
  if (leaseLost)
40135
40104
  throw new Error("Dream lease lost during task");
40136
40105
  if (curateRefused > 0) {
40137
40106
  helpers.reportProgress(curateRefused, curateRefused);
40138
40107
  log2(`[dreamer] curate safety summary: refused=${curateRefused}`);
40139
40108
  }
40109
+ const unrecognised = unrecognisedCurateOperations(curateOperations);
40110
+ if (unrecognised > 0)
40111
+ log2(`[dreamer] curate result summary: unrecognised=${unrecognised}`);
40140
40112
  recordInvocation("completed", run.output);
40141
40113
  if (task === "maintain-docs" && docsHashes && changes) {
40142
40114
  try {
@@ -40156,13 +40128,12 @@ async function runAgenticTask(config, ctx, helpers) {
40156
40128
  return { status: "failed", error: reason };
40157
40129
  }
40158
40130
  }
40159
- const curateOutput = task === "curate" ? run.validated : undefined;
40160
40131
  const curateScopeProgress = task === "curate" && curateCategory && curateMemories ? `curate: ${curateCategory} (${curateMemories.length})` : null;
40161
40132
  const progress = [
40162
40133
  curateScopeProgress,
40163
40134
  expiredArchived > 0 ? formatExpiredArchiveProgress(expiredArchived) : null,
40164
- curateOutput && curateOutput.memoryOperations.completedActions.length > 0 ? formatCurateMemoryOperations(curateOutput.memoryOperations.completedActions) : null,
40165
- curateRefused > 0 ? `curate: refused ${curateRefused} unsafe mutation(s)` : null
40135
+ formatCurateMemoryOperations(curateOperations),
40136
+ curateRefused > 0 && !curateOperations.refusals.length ? `curate: refused ${curateRefused} unsafe mutation(s)` : null
40166
40137
  ].filter((value) => Boolean(value)).join("; ");
40167
40138
  const curateCount = task === "curate" && curateCategory ? loadActiveMemoryPromptMemories(db, projectIdentity).filter((memory) => curateCategoryForMemoryCategory(memory.category) === curateCategory).length : undefined;
40168
40139
  const curateBacklog = curateCount !== undefined && curateCategory ? {
@@ -40181,7 +40152,7 @@ async function runAgenticTask(config, ctx, helpers) {
40181
40152
  ...curateBacklog ? { backlog: curateBacklog } : {},
40182
40153
  ...curateCategory ? {
40183
40154
  schedulePatch: {
40184
- taskStateJson: curateTaskStateAfterSuccess(db, projectIdentity, curateCategory)
40155
+ taskStateJson: curateTaskStateAfterCategoryTurn(db, projectIdentity, curateCategory)
40185
40156
  }
40186
40157
  } : {}
40187
40158
  };
@@ -57944,10 +57915,10 @@ async function registerContext(context) {
57944
57915
  if (moduleBoundarySeq !== undefined)
57945
57916
  sessionLog2(draft.sessionID, `v2 restore: from the module boundary ${moduleBoundaryID} to the host checkpoint`);
57946
57917
  const present = new Set(args.messages.map((message) => message.id));
57947
- const restored = restoredRows.rows(reader, draft.sessionID, boundary, cut.seq).filter((row) => !retiredInstructions(row)).filter((row) => !present.has(row.id)).flatMap((row) => restoreRow(row, draft.model, hostUsesMediaAssets() ? {
57918
+ const restored = restoredRows.rows(reader, draft.sessionID, boundary, cut.seq).filter((row) => !retiredInstructions(row)).filter((row) => !present.has(row.id)).flatMap((row) => restoreRow(row, draft.model, {
57948
57919
  asset: hostMediaAsset,
57949
57920
  unavailable: (detail) => sessionLog2(draft.sessionID, `v2 restore: attachment replaced by a note row=${detail.rowID} name=${JSON.stringify(detail.name ?? null)} mediaType=${detail.mediaType} reason=${JSON.stringify(detail.reason)}`)
57950
- } : undefined));
57921
+ }));
57951
57922
  return [
57952
57923
  ...rustModeModuleClient ? [] : coveredInstructionRows(reader, draft.sessionID, Math.min(boundary, cut.seq), draft.model, retiredInstructions),
57953
57924
  ...restored,
@@ -3,8 +3,12 @@
3
3
  *
4
4
  * From OpenCode 2.0.15 a media content part carries its bytes in a `Media.Asset` class
5
5
  * instance, and after the context hook the host rebuilds every message with
6
- * `Message.make`, whose schema checks `value instanceof Asset`. Rows restored from the
7
- * store after a host checkpoint are built by Magic Context, not by the host, so their
6
+ * `Message.make`. Every OpenCode 2 host the plugin supports is at least that new (the
7
+ * oldest one the e2e lane pins is 2.0.22), so a media part handed to the host must hold
8
+ * a real host instance: on 2.0.x the schema's `instanceof Asset` check rejects anything
9
+ * else, and on 2.3.x `Message.make` turns a part without one into an asset that has no
10
+ * bytes, which fails the request before any provider call. Rows restored from the store
11
+ * after a host checkpoint are built by Magic Context, not by the host, so their
8
12
  * attachments need a real host instance. The plugin cannot import that class: a second
9
13
  * copy of `@opencode/ai` has a different `Asset`, which fails the host's instanceof check.
10
14
  *
@@ -12,9 +16,9 @@
12
16
  * 1. The constructor of any `Media.Asset` the host itself put into a draft during this
13
17
  * process. `new Asset({ source: { type: "base64", data, mediaType } })` is exactly what
14
18
  * the host's own `Media.base64(data, mediaType)` does when it renders a stored row.
15
- * 2. The host's own schema, reached from the draft message's class:
16
- * `Message.fields.content.value` (the content-part union) → the member whose `type` is
17
- * the literal "media" → `fields.media` (`Media.AssetSchema`) → `ast.encoding[0]
19
+ * 2. The host's own schema, reached from a draft message's class:
20
+ * `fields.content.value` (the content-part union) → the member whose `type` is the
21
+ * literal "media" → `fields.media` (`Media.AssetSchema`) → `ast.encoding[0]
18
22
  * .transformation.decode`. OpenCode 2.0.22 (Effect 4.0.0-rc.112) exposes a getter whose
19
23
  * `run(some(encoded), {})` returns `Success(some(asset))`. OpenCode 2.2.3 (Effect 4.0.6)
20
24
  * uses a plain `{ _tag: "Transform", transform }` getter whose `transform(encoded)`
@@ -22,17 +26,18 @@
22
26
  * tags are unavailable: they need optional/effectful evaluation rather than a direct
23
27
  * synchronous transform. This depends on Effect Schema internals, so every step is
24
28
  * checked and any mismatch counts as unavailable.
29
+ *
30
+ * OpenCode 2.0 and 2.1 have one message class for every role. From 2.3 each role has its
31
+ * own class, and the system and tool classes have no media member at all; a draft can
32
+ * start with a system message (a reasoning-effort change, for one). So the schema is
33
+ * taken from the first message class whose content union has a media member, never from
34
+ * whichever message happens to come first.
25
35
  */
26
36
  type Part = Record<string, unknown>;
27
37
  /** Test hook: forget what earlier drafts taught this process. */
28
38
  export declare function resetHostMediaForTests(): void;
29
- /** Learn the host's message class and, when present, its `Media.Asset` class from a draft. */
39
+ /** Learn the host's media schema and, when present, its `Media.Asset` class from a draft. */
30
40
  export declare function rememberHostMedia(messages: ReadonlyArray<unknown>): void;
31
- /**
32
- * True when the remembered host message schema declares attachments as `Media.Asset`
33
- * (OpenCode 2.0.15 and later). Earlier hosts take the plain `{ mediaType, data }` shape.
34
- */
35
- export declare function hostUsesMediaAssets(): boolean;
36
41
  /**
37
42
  * The host's own `Media.Asset` for a base64 payload, or the reason neither zero-loss way
38
43
  * produced one.
@@ -1 +1 @@
1
- {"version":3,"file":"host-media.d.ts","sourceRoot":"","sources":["../../../src/v2/fold/host-media.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,KAAK,IAAI,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAgBpC,iEAAiE;AACjE,wBAAgB,sBAAsB,IAAI,IAAI,CAG7C;AAED,8FAA8F;AAC9F,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,aAAa,CAAC,OAAO,CAAC,GAAG,IAAI,CAgBxE;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,IAAI,OAAO,CAe7C;AAwCD;;;GAGG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAE/E;AAED,mFAAmF;AACnF,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,IAAI,GAAG,MAAM,GAAG,MAAM,CA0BjE"}
1
+ {"version":3,"file":"host-media.d.ts","sourceRoot":"","sources":["../../../src/v2/fold/host-media.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AAEH,KAAK,IAAI,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAkBpC,iEAAiE;AACjE,wBAAgB,sBAAsB,IAAI,IAAI,CAG7C;AA8BD,6FAA6F;AAC7F,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,aAAa,CAAC,OAAO,CAAC,GAAG,IAAI,CAiBxE;AA8BD;;;GAGG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAE/E;AAED,mFAAmF;AACnF,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,IAAI,GAAG,MAAM,GAAG,MAAM,CA0BjE"}