@cortexkit/pi-magic-context 0.49.42 → 0.49.43

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 (2) hide show
  1. package/dist/index.js +332 -136
  2. package/package.json +3 -1
package/dist/index.js CHANGED
@@ -3584,7 +3584,7 @@ function startHostStallProfilerSwitch() {
3584
3584
  // package.json
3585
3585
  var package_default = {
3586
3586
  name: "@cortexkit/pi-magic-context",
3587
- version: "0.49.42",
3587
+ version: "0.49.43",
3588
3588
  type: "module",
3589
3589
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
3590
3590
  main: "dist/index.js",
@@ -3658,6 +3658,8 @@ var package_default = {
3658
3658
  "omp-pi-ai-18126": "npm:@oh-my-pi/pi-ai@18.12.6",
3659
3659
  "omp-pi-ai-1813": "npm:@oh-my-pi/pi-ai@18.13.0",
3660
3660
  "omp-pi-ai-18132": "npm:@oh-my-pi/pi-ai@18.13.2",
3661
+ "omp-pi-ai-18180": "npm:@oh-my-pi/pi-ai@18.18.0",
3662
+ "omp-pi-ai-18181": "npm:@oh-my-pi/pi-ai@18.18.1",
3661
3663
  "pi-agent-core-087": "npm:@earendil-works/pi-agent-core@0.87.1",
3662
3664
  "pi-ai-086": "npm:@earendil-works/pi-ai@0.86.0",
3663
3665
  "pi-ai-087": "npm:@earendil-works/pi-ai@0.87.1",
@@ -36734,6 +36736,151 @@ function piExpandChainedRequest(payload, chained, anchor, prepared, pass) {
36734
36736
  return { payload: { ...rest, input }, input };
36735
36737
  }
36736
36738
 
36739
+ // src/pi-dispatch-cursor.ts
36740
+ import { createHash as createHash14 } from "node:crypto";
36741
+ var MAX_BYTES = 32 * 1024 * 1024;
36742
+ var MAX_ENTRIES = 1e5;
36743
+ function object5(value) {
36744
+ return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
36745
+ }
36746
+ function piCursorConversation(payload) {
36747
+ const body = object5(payload);
36748
+ if (body?.messages !== undefined || body?.input !== undefined || body?.contents !== undefined || body?.request !== undefined)
36749
+ return;
36750
+ const state = object5(body?.conversationState);
36751
+ if (!state || !Array.isArray(state.rootPromptMessagesJson) || !Array.isArray(state.turns))
36752
+ return;
36753
+ let bytes = 0;
36754
+ let nodes = 0;
36755
+ const messages = [];
36756
+ const rootIds = [];
36757
+ const decode = (value, depth = 0) => {
36758
+ if (++nodes > MAX_ENTRIES || depth > 128)
36759
+ throw new Error("Cursor structure limit");
36760
+ if (value instanceof Uint8Array) {
36761
+ bytes += value.byteLength;
36762
+ if (bytes > MAX_BYTES)
36763
+ throw new Error("Cursor bytes limit");
36764
+ if (value.byteLength === 32)
36765
+ return { blobId: Buffer.from(value).toString("hex") };
36766
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(value));
36767
+ }
36768
+ if (Array.isArray(value))
36769
+ return value.map((entry) => decode(entry, depth + 1));
36770
+ const record = object5(value);
36771
+ if (record)
36772
+ return Object.fromEntries(Object.entries(record).map(([key, child]) => [
36773
+ key,
36774
+ decode(child, depth + 1)
36775
+ ]));
36776
+ return value;
36777
+ };
36778
+ try {
36779
+ const decoded = decode(state);
36780
+ for (const root of decoded.rootPromptMessagesJson) {
36781
+ const record = object5(root);
36782
+ if (typeof record?.blobId === "string")
36783
+ rootIds.push(record.blobId);
36784
+ else if (record && typeof record.role === "string")
36785
+ messages.push(record);
36786
+ else
36787
+ return;
36788
+ }
36789
+ for (const value of decoded.turns.slice(0, 8)) {
36790
+ const turn = object5(value);
36791
+ const agent = object5(object5(turn?.turn)?.value) ?? turn;
36792
+ const user = object5(agent?.userMessage);
36793
+ if (typeof user?.text === "string")
36794
+ messages.push({ role: "user", content: user.text });
36795
+ }
36796
+ const action = object5(object5(body?.action)?.action);
36797
+ if (!action || !["userMessageAction", "resumeAction"].includes(String(action.case)))
36798
+ return;
36799
+ let active = decode(body?.action);
36800
+ let activeText;
36801
+ if (action.case === "userMessageAction") {
36802
+ const user = object5(object5(action.value)?.userMessage);
36803
+ if (!user || typeof user.text !== "string")
36804
+ return;
36805
+ messages.push({ role: "user", content: user.text });
36806
+ activeText = user.text;
36807
+ const { messageId: _messageId, ...content } = user;
36808
+ active = decode({
36809
+ action: {
36810
+ case: action.case,
36811
+ value: { ...object5(action.value), userMessage: content }
36812
+ }
36813
+ });
36814
+ }
36815
+ return {
36816
+ conversation: {
36817
+ conversationState: decoded,
36818
+ action: active,
36819
+ customSystemPrompt: body?.customSystemPrompt
36820
+ },
36821
+ messages,
36822
+ rootIds,
36823
+ activeText
36824
+ };
36825
+ } catch {
36826
+ return;
36827
+ }
36828
+ }
36829
+ function piCursorManagedRoots(messages, signature, cwd) {
36830
+ if (!signature)
36831
+ return [];
36832
+ const roots = new Set;
36833
+ const date = new Date;
36834
+ const day = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
36835
+ const reminder = cwd && `<system-reminder>
36836
+ Today: ${day}; current working directory: '${cwd.replace(/\\/gu, "/")}'. Do not repeat this information in your reply.
36837
+ </system-reminder>`;
36838
+ for (const value of messages.slice(0, 8)) {
36839
+ const source = object5(value);
36840
+ if (!source || !["user", "developer"].includes(String(source.role)))
36841
+ continue;
36842
+ const message = piOmpUserHistory(source);
36843
+ const raw = typeof message.content === "string" ? [{ type: "text", text: message.content }] : message.content;
36844
+ if (!Array.isArray(raw))
36845
+ continue;
36846
+ const parts = [];
36847
+ let managed = false;
36848
+ for (const part of raw) {
36849
+ if (part?.type === "text" && typeof part.text === "string") {
36850
+ const text = part.text.trim();
36851
+ managed ||= text.slice(0, 4096).includes(signature);
36852
+ if (text)
36853
+ parts.push({ type: "text", text });
36854
+ } else if (part?.type === "image" && typeof part.data === "string") {
36855
+ parts.push({
36856
+ type: "image",
36857
+ image: `data:${part.mimeType};base64,${part.data}`,
36858
+ mediaType: part.mimeType
36859
+ });
36860
+ }
36861
+ }
36862
+ if (!managed)
36863
+ continue;
36864
+ const hash = (content) => {
36865
+ const json = JSON.stringify({ role: "user", content });
36866
+ if (json.length <= MAX_BYTES)
36867
+ roots.add(createHash14("sha256").update(json).digest("hex"));
36868
+ };
36869
+ hash(parts);
36870
+ if (reminder) {
36871
+ if (typeof message.content === "string")
36872
+ hash([
36873
+ { type: "text", text: `${reminder}
36874
+
36875
+ ${message.content}`.trim() }
36876
+ ]);
36877
+ else
36878
+ hash([{ type: "text", text: reminder }, ...parts]);
36879
+ }
36880
+ }
36881
+ return [...roots];
36882
+ }
36883
+
36737
36884
  // src/pi-dispatch-google.ts
36738
36885
  function piGoogleConversation(payload) {
36739
36886
  if (!payload || typeof payload !== "object")
@@ -36774,12 +36921,13 @@ function piConversationFields(payload) {
36774
36921
  };
36775
36922
  } else {
36776
36923
  const google = piGoogleConversation(payload);
36777
- if (!google)
36924
+ const cursor = google ? undefined : piCursorConversation(payload);
36925
+ if (!google && !cursor)
36778
36926
  return;
36779
- conversation = {
36780
- contents: google.contents,
36781
- systemInstruction: google.systemInstruction,
36782
- configSystemInstruction: google.config?.systemInstruction
36927
+ conversation = cursor?.conversation ?? {
36928
+ contents: google?.contents,
36929
+ systemInstruction: google?.systemInstruction,
36930
+ configSystemInstruction: google?.config?.systemInstruction
36783
36931
  };
36784
36932
  }
36785
36933
  const fields = [];
@@ -36853,15 +37001,20 @@ function piManagedSignature(messages) {
36853
37001
  }
36854
37002
  return;
36855
37003
  }
36856
- function piHasManagedSignature(payload, signature) {
37004
+ function piHasManagedSignature(payload, signature, cursorRoots) {
36857
37005
  if (!signature || !payload || typeof payload !== "object")
36858
37006
  return false;
36859
37007
  const body = payload;
36860
37008
  const google = piGoogleConversation(payload);
37009
+ const cursor = body.messages === undefined && body.input === undefined && !google ? piCursorConversation(payload) : undefined;
37010
+ if (cursor?.activeText?.slice(0, 4096).includes(signature))
37011
+ return true;
37012
+ if (cursorRoots?.length && cursor?.rootIds.some((id) => cursorRoots.includes(id)))
37013
+ return true;
36861
37014
  const nativeText = !!google || body.inferenceConfig !== undefined;
36862
37015
  if (typeof body.input === "string" && body.messages === undefined)
36863
37016
  return body.input.slice(0, 4096).includes(signature);
36864
- const messages = Array.isArray(body.messages) ? body.messages : Array.isArray(body.input) ? body.input : google?.contents;
37017
+ const messages = Array.isArray(body.messages) ? body.messages : Array.isArray(body.input) ? body.input : google?.contents ?? cursor?.messages;
36865
37018
  if (!messages)
36866
37019
  return false;
36867
37020
  for (const message of messages.slice(0, 8)) {
@@ -36879,12 +37032,36 @@ function piHasManagedSignature(payload, signature) {
36879
37032
  }
36880
37033
  return false;
36881
37034
  }
37035
+ function piDispatchShape(payload, api) {
37036
+ let keys;
37037
+ try {
37038
+ keys = payload && typeof payload === "object" ? Object.keys(payload).sort().slice(0, 12).join(",") : typeof payload;
37039
+ } catch {
37040
+ keys = "unreadable object";
37041
+ }
37042
+ return `provider API=${api ?? "unknown"} shape=${keys || "empty object"}`;
37043
+ }
37044
+
37045
+ // src/pi-dispatch-refused.ts
37046
+ function piRefusedPayload(message) {
37047
+ const fail = () => {
37048
+ throw new Error(message);
37049
+ };
37050
+ return new Proxy(Object.create(null), {
37051
+ get: (_target, key) => key === "then" ? undefined : fail(),
37052
+ ownKeys: fail,
37053
+ getOwnPropertyDescriptor: fail,
37054
+ set: fail,
37055
+ has: fail,
37056
+ getPrototypeOf: fail
37057
+ });
37058
+ }
36882
37059
 
36883
37060
  // src/pi-dispatch-assistant-history.ts
36884
37061
  function piOmitsTruncatedAssistant(message) {
36885
37062
  return (message.stopReason === "length" || message.stopReason === "error" || message.stopReason === "aborted") && Array.isArray(message.content) && !message.content.some((block) => block?.type === "text" || block?.type === "toolCall");
36886
37063
  }
36887
- function object5(value) {
37064
+ function object6(value) {
36888
37065
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
36889
37066
  }
36890
37067
  function nonblank(value) {
@@ -36900,7 +37077,7 @@ function piAnthropicAssistantReplay(message, model, host) {
36900
37077
  let thinking = false;
36901
37078
  let fallback = false;
36902
37079
  for (const value of message.content) {
36903
- const block = object5(value);
37080
+ const block = object6(value);
36904
37081
  if (!block)
36905
37082
  return "kept";
36906
37083
  if (block.type === "toolCall")
@@ -36967,7 +37144,7 @@ function piAnthropicOptionalThinking(message) {
36967
37144
  const texts = [];
36968
37145
  let fallback = false;
36969
37146
  for (const value of Array.isArray(message.content) ? message.content : []) {
36970
- const block = object5(value);
37147
+ const block = object6(value);
36971
37148
  if (block?.type === "thinking") {
36972
37149
  if (nonblank(block.thinkingSignature))
36973
37150
  signatures.push(block.thinkingSignature);
@@ -36984,7 +37161,7 @@ var THINKING_PRESENCE_PLACEHOLDER = "(no reasoning was returned for this turn)";
36984
37161
  function piExplainsOptionalAssistant(thinking, content) {
36985
37162
  const fromThinking = (text) => typeof text === "string" && thinking.texts.some((prepared) => text.includes(prepared));
36986
37163
  return Array.isArray(content) && content.length > 0 && content.every((value) => {
36987
- const block = object5(value);
37164
+ const block = object6(value);
36988
37165
  if (block?.type === "thinking") {
36989
37166
  if (nonblank(block.signature))
36990
37167
  return thinking.signatures.includes(block.signature);
@@ -37006,7 +37183,7 @@ var RESPONSES_APIS = new Set([
37006
37183
  "openai-codex-responses",
37007
37184
  "azure-openai-responses"
37008
37185
  ]);
37009
- function object6(value) {
37186
+ function object7(value) {
37010
37187
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
37011
37188
  }
37012
37189
  function piResponsesCallComponent(id) {
@@ -37017,12 +37194,12 @@ function piToolCallPairing(messages) {
37017
37194
  const responsesComponents = new Set;
37018
37195
  const opaqueCompositeIds = new Set;
37019
37196
  for (const value of messages) {
37020
- const message = object6(value);
37197
+ const message = object7(value);
37021
37198
  if (message?.role !== "assistant" || !Array.isArray(message.content))
37022
37199
  continue;
37023
37200
  const responses = RESPONSES_APIS.has(String(message.api));
37024
37201
  for (const part of message.content) {
37025
- const block = object6(part);
37202
+ const block = object7(part);
37026
37203
  if (block?.type !== "toolCall" || typeof block.id !== "string")
37027
37204
  continue;
37028
37205
  if (responses)
@@ -37043,7 +37220,7 @@ function piToolCallPairing(messages) {
37043
37220
  // src/pi-dispatch-chat-history.ts
37044
37221
  var MAX_EXACT_UNITS = 32 * 1024 * 1024;
37045
37222
  var IMAGE_CAPTION = "Attached image(s) from tool result:";
37046
- function object7(value) {
37223
+ function object8(value) {
37047
37224
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
37048
37225
  }
37049
37226
  function omitsAssistant(message, model, compat) {
@@ -37053,7 +37230,7 @@ function omitsAssistant(message, model, compat) {
37053
37230
  return true;
37054
37231
  let thinking = false;
37055
37232
  for (const value of message.content) {
37056
- const block = object7(value);
37233
+ const block = object8(value);
37057
37234
  if (!block)
37058
37235
  return false;
37059
37236
  if (block.type === "text") {
@@ -37075,15 +37252,15 @@ function omitsAssistant(message, model, compat) {
37075
37252
  function piChatHistoryPlan(messages, model) {
37076
37253
  if (model?.api !== "openai-completions")
37077
37254
  return;
37078
- const compat = object7(model.compat) ?? {};
37255
+ const compat = object8(model.compat) ?? {};
37079
37256
  const pairingId = piToolCallPairing(messages);
37080
37257
  const calls = new Set;
37081
37258
  for (const value of messages) {
37082
- const message = object7(value);
37259
+ const message = object8(value);
37083
37260
  if (message?.role !== "assistant" || !Array.isArray(message.content))
37084
37261
  continue;
37085
37262
  for (const value of message.content) {
37086
- const block = object7(value);
37263
+ const block = object8(value);
37087
37264
  if (block?.type === "toolCall" && typeof block.id === "string")
37088
37265
  calls.add(pairingId(block.id));
37089
37266
  }
@@ -37092,7 +37269,7 @@ function piChatHistoryPlan(messages, model) {
37092
37269
  let pending = new Set;
37093
37270
  let exactUnits = 0;
37094
37271
  for (let index = 0;index < messages.length; index++) {
37095
- const message = object7(messages[index]);
37272
+ const message = object8(messages[index]);
37096
37273
  if (!message)
37097
37274
  return;
37098
37275
  if ((message.role === "bashExecution" || message.role === "pythonExecution") && message.excludeFromContext === true)
@@ -37104,7 +37281,7 @@ function piChatHistoryPlan(messages, model) {
37104
37281
  continue;
37105
37282
  if (Array.isArray(message.content))
37106
37283
  for (const value of message.content) {
37107
- const block = object7(value);
37284
+ const block = object8(value);
37108
37285
  if (block?.type === "toolCall" && typeof block.id === "string")
37109
37286
  pending.add(pairingId(block.id));
37110
37287
  }
@@ -37116,7 +37293,7 @@ function piChatHistoryPlan(messages, model) {
37116
37293
  return;
37117
37294
  const parts = [];
37118
37295
  for (const value of message.content) {
37119
- const part = object7(value);
37296
+ const part = object8(value);
37120
37297
  if (part?.type === "text" && typeof part.text === "string" && part.text.trim())
37121
37298
  parts.push(part.text);
37122
37299
  }
@@ -37149,14 +37326,14 @@ ${parts.join(`
37149
37326
  };
37150
37327
  const vision = model.input?.includes("image") === true && compat.stripImageInput !== true;
37151
37328
  for (const step of transformed) {
37152
- const message = step.kind === "source" ? object7(messages[step.index]) : undefined;
37329
+ const message = step.kind === "source" ? object8(messages[step.index]) : undefined;
37153
37330
  if (message?.role !== "toolResult")
37154
37331
  flushImages();
37155
37332
  steps.push(step);
37156
37333
  if (message?.role !== "toolResult" || !vision || !Array.isArray(message.content))
37157
37334
  continue;
37158
37335
  for (const value of message.content) {
37159
- const block = object7(value);
37336
+ const block = object8(value);
37160
37337
  if (block?.type !== "image")
37161
37338
  continue;
37162
37339
  if (compat.requiresAssistantAfterToolResult === true)
@@ -37180,12 +37357,12 @@ ${parts.join(`
37180
37357
  function piMatchesChatImages(content, urls) {
37181
37358
  if (!Array.isArray(content) || content.length !== urls.length + 1)
37182
37359
  return false;
37183
- const caption = object7(content[0]);
37360
+ const caption = object8(content[0]);
37184
37361
  if (caption?.type !== "text" || caption.text !== IMAGE_CAPTION || Object.keys(caption).length !== 2)
37185
37362
  return false;
37186
37363
  for (let i = 0;i < urls.length; i++) {
37187
- const block = object7(content[i + 1]);
37188
- const image = object7(block?.image_url);
37364
+ const block = object8(content[i + 1]);
37365
+ const image = object8(block?.image_url);
37189
37366
  if (block?.type !== "image_url" || Object.keys(block).length !== 2 || !image || Object.keys(image).length !== 1 || image.url !== urls[i])
37190
37367
  return false;
37191
37368
  }
@@ -37193,7 +37370,7 @@ function piMatchesChatImages(content, urls) {
37193
37370
  }
37194
37371
 
37195
37372
  // src/pi-dispatch-date-reminder.ts
37196
- function object8(value) {
37373
+ function object9(value) {
37197
37374
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
37198
37375
  }
37199
37376
  function piDateReminderText(value, cwd) {
@@ -37217,8 +37394,8 @@ function piDateReminderWireText(content, cwd) {
37217
37394
  return piDateReminderText(content, cwd) ? content : undefined;
37218
37395
  if (!Array.isArray(content) || content.length !== 1)
37219
37396
  return;
37220
- const block = object8(content[0]);
37221
- const cache = object8(block?.cache_control);
37397
+ const block = object9(content[0]);
37398
+ const cache = object9(block?.cache_control);
37222
37399
  if (block?.type !== "text" || !cache || cache.type !== "ephemeral" || Object.keys(block).some((key) => !["type", "text", "cache_control"].includes(key)) || Object.keys(cache).some((key) => !["type", "ttl", "scope"].includes(key)) || cache.ttl !== undefined && cache.ttl !== "5m" && cache.ttl !== "1h" || cache.scope !== undefined && cache.scope !== "global")
37223
37400
  return;
37224
37401
  return piDateReminderText(block.text, cwd) ? block.text : undefined;
@@ -37238,15 +37415,15 @@ var PI_DATE_REMINDER_APIS = new Set([
37238
37415
  function singleText(value, type) {
37239
37416
  if (!Array.isArray(value) || value.length !== 1)
37240
37417
  return;
37241
- const part = object8(value[0]);
37418
+ const part = object9(value[0]);
37242
37419
  return part && (type === undefined ? Object.keys(part).length === 1 : part.type === type && Object.keys(part).length === 2) ? part.text : undefined;
37243
37420
  }
37244
37421
  function piWithoutDateReminders(payload, api, cwd, developerRole, includesPreparedFirstUser) {
37245
- const body = object8(payload);
37422
+ const body = object9(payload);
37246
37423
  if (!body)
37247
37424
  return;
37248
37425
  const google = api.startsWith("google-");
37249
- const envelope = google ? object8(body.request) ?? body : body;
37426
+ const envelope = google ? object9(body.request) ?? body : body;
37250
37427
  const field = google ? "contents" : api.endsWith("responses") ? "input" : "messages";
37251
37428
  const messages = envelope[field];
37252
37429
  if (!Array.isArray(messages))
@@ -37255,7 +37432,7 @@ function piWithoutDateReminders(payload, api, cwd, developerRole, includesPrepar
37255
37432
  let removed = false;
37256
37433
  const kept = [];
37257
37434
  for (const value of messages) {
37258
- const row = object8(value);
37435
+ const row = object9(value);
37259
37436
  if (!row)
37260
37437
  return;
37261
37438
  const text = google ? singleText(row.parts) : api === "bedrock-converse-stream" ? singleText(row.content) : api.endsWith("responses") ? singleText(row.content, "input_text") ?? (api === "openai-codex-responses" ? row.content : undefined) : row.content;
@@ -37272,7 +37449,7 @@ function piWithoutDateReminders(payload, api, cwd, developerRole, includesPrepar
37272
37449
  removed = true;
37273
37450
  continue;
37274
37451
  }
37275
- if (row.role === "user" && (typeof row.content === "string" || Array.isArray(row.content) && row.content.some((part) => object8(part)?.type === "input_text" || object8(part)?.type === "text" || typeof object8(part)?.text === "string") || Array.isArray(row.parts) && row.parts.some((part) => typeof object8(part)?.text === "string")))
37452
+ if (row.role === "user" && (typeof row.content === "string" || Array.isArray(row.content) && row.content.some((part) => object9(part)?.type === "input_text" || object9(part)?.type === "text" || typeof object9(part)?.text === "string") || Array.isArray(row.parts) && row.parts.some((part) => typeof object9(part)?.text === "string")))
37276
37453
  firstUser = true;
37277
37454
  kept.push(value);
37278
37455
  }
@@ -37283,22 +37460,22 @@ function piWithoutDateReminders(payload, api, cwd, developerRole, includesPrepar
37283
37460
  }
37284
37461
 
37285
37462
  // src/pi-dispatch-image-budget.ts
37286
- function object9(value) {
37463
+ function object10(value) {
37287
37464
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
37288
37465
  }
37289
37466
  function piImageBudgetPlan(model) {
37290
- if (!model?.input?.includes("image") || object9(model.compat)?.stripImageInput === true)
37467
+ if (!model?.input?.includes("image") || object10(model.compat)?.stripImageInput === true)
37291
37468
  return;
37292
37469
  return {
37293
37470
  count: 0,
37294
37471
  api: model.api,
37295
37472
  rows: new Map,
37296
- hoistToolImages: model.api?.startsWith("google-") === true && object9(model.compat)?.multimodalFunctionResponse !== true || model.api === "bedrock-converse-stream" && model.requiresToolResultImageHoisting === true,
37473
+ hoistToolImages: model.api?.startsWith("google-") === true && object10(model.compat)?.multimodalFunctionResponse !== true || model.api === "bedrock-converse-stream" && model.requiresToolResultImageHoisting === true,
37297
37474
  hoistErrorImages: model.api === "anthropic-messages" || model.api === "bedrock-converse-stream"
37298
37475
  };
37299
37476
  }
37300
37477
  function inputImage(block, api) {
37301
- const file = object9(block.providerFile);
37478
+ const file = object10(block.providerFile);
37302
37479
  if (api === "ollama-chat")
37303
37480
  return { kind: "bytes", value: String(block.data ?? "") };
37304
37481
  if ((api?.endsWith("responses") && file?.provider === "openai" || api === "anthropic-messages" && file?.provider === "anthropic") && typeof file?.id === "string")
@@ -37318,7 +37495,7 @@ function piRecordImages(plan, row, source) {
37318
37495
  return;
37319
37496
  const images = [];
37320
37497
  for (const value of source.content) {
37321
- const block = object9(value);
37498
+ const block = object10(value);
37322
37499
  if (block?.type === "image")
37323
37500
  images.push(inputImage(block, plan.api));
37324
37501
  }
@@ -37344,20 +37521,20 @@ function piWireImages(content, ollamaImages) {
37344
37521
  return [];
37345
37522
  const images = [];
37346
37523
  for (const value of content) {
37347
- const block = object9(value);
37524
+ const block = object10(value);
37348
37525
  if (!block)
37349
37526
  continue;
37350
- const source = object9(block.source);
37351
- const inline = object9(block.inlineData);
37352
- const file = object9(block.fileData);
37353
- const bedrock = object9(block.image);
37527
+ const source = object10(block.source);
37528
+ const inline = object10(block.inlineData);
37529
+ const file = object10(block.fileData);
37530
+ const bedrock = object10(block.image);
37354
37531
  if (block.type === "image_url" || block.type === "input_image") {
37355
37532
  if (typeof block.file_id === "string")
37356
37533
  images.push({ kind: "file", value: block.file_id });
37357
37534
  else
37358
37535
  images.push({
37359
37536
  kind: "url",
37360
- value: String(typeof block.image_url === "string" ? block.image_url : object9(block.image_url)?.url)
37537
+ value: String(typeof block.image_url === "string" ? block.image_url : object10(block.image_url)?.url)
37361
37538
  });
37362
37539
  } else if (block.type === "image") {
37363
37540
  if (source?.type === "file")
@@ -37381,7 +37558,7 @@ function piWireImages(content, ollamaImages) {
37381
37558
  else if (bedrock)
37382
37559
  images.push({
37383
37560
  kind: "data",
37384
- value: String(object9(bedrock.source)?.bytes),
37561
+ value: String(object10(bedrock.source)?.bytes),
37385
37562
  mime: `image/${bedrock.format}`
37386
37563
  });
37387
37564
  }
@@ -37403,11 +37580,11 @@ function piMatchesImages(actual, expected) {
37403
37580
  return true;
37404
37581
  }
37405
37582
  function piWireImageCount(payload) {
37406
- const body = object9(payload);
37583
+ const body = object10(payload);
37407
37584
  const visit = (value) => {
37408
37585
  if (Array.isArray(value))
37409
37586
  return value.reduce((n, item) => n + visit(item), 0);
37410
- const block = object9(value);
37587
+ const block = object10(value);
37411
37588
  if (!block)
37412
37589
  return 0;
37413
37590
  if (["image", "image_url", "input_image"].includes(String(block.type)) || block.inlineData || block.fileData || block.image)
@@ -37421,12 +37598,12 @@ function piWireImageCount(payload) {
37421
37598
  block.response
37422
37599
  ].reduce((n, item) => n + visit(item), Array.isArray(block.images) ? block.images.length : 0);
37423
37600
  };
37424
- return visit(body?.messages ?? body?.input ?? body?.contents ?? object9(body?.request)?.contents);
37601
+ return visit(body?.messages ?? body?.input ?? body?.contents ?? object10(body?.request)?.contents);
37425
37602
  }
37426
37603
 
37427
37604
  // src/pi-dispatch-responses-history.ts
37428
37605
  var MAX_TEXT_UNITS = 32 * 1024 * 1024;
37429
- function object10(value) {
37606
+ function object11(value) {
37430
37607
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
37431
37608
  }
37432
37609
  function wellFormed2(text) {
@@ -37441,7 +37618,7 @@ function textIdentity2(text, phase) {
37441
37618
  function signaturePhase(block) {
37442
37619
  try {
37443
37620
  if (typeof block.textSignature === "string") {
37444
- const signature = object10(JSON.parse(block.textSignature));
37621
+ const signature = object11(JSON.parse(block.textSignature));
37445
37622
  if (signature?.v === 1 && typeof signature.id === "string")
37446
37623
  return signature.phase;
37447
37624
  }
@@ -37463,19 +37640,19 @@ ${wellFormed2(text)}
37463
37640
  function coldReplayable(items) {
37464
37641
  let reasoning = false;
37465
37642
  for (const value of items) {
37466
- const item = object10(value);
37643
+ const item = object11(value);
37467
37644
  if (typeof item?.encrypted_content === "string")
37468
37645
  return false;
37469
37646
  if (item?.type !== "reasoning")
37470
37647
  continue;
37471
- if (!Array.isArray(item.content) || !item.content.some((part) => object10(part)?.type === "reasoning_text"))
37648
+ if (!Array.isArray(item.content) || !item.content.some((part) => object11(part)?.type === "reasoning_text"))
37472
37649
  return false;
37473
37650
  reasoning = true;
37474
37651
  }
37475
37652
  return reasoning;
37476
37653
  }
37477
37654
  function piResponsesAssistantTexts(value, model, host, alternatives, frozenTagStrips) {
37478
- const message = object10(value);
37655
+ const message = object11(value);
37479
37656
  if (!message || !Array.isArray(message.content))
37480
37657
  return;
37481
37658
  if (piOmitsTruncatedAssistant(message))
@@ -37485,7 +37662,7 @@ function piResponsesAssistantTexts(value, model, host, alternatives, frozenTagSt
37485
37662
  const sameModel = model !== undefined && typeof model.api === "string" && typeof model.id === "string" && typeof model.provider === "string" && message.api === model.api && message.model === model.id && message.provider === model.provider;
37486
37663
  let units = 0;
37487
37664
  for (const value of message.content) {
37488
- const block = object10(value);
37665
+ const block = object11(value);
37489
37666
  if (block?.type === "toolCall")
37490
37667
  continue;
37491
37668
  if (block?.type === "thinking") {
@@ -37495,7 +37672,7 @@ function piResponsesAssistantTexts(value, model, host, alternatives, frozenTagSt
37495
37672
  return;
37496
37673
  if (!block.thinking.trim())
37497
37674
  continue;
37498
- const compat = object10(model.compat);
37675
+ const compat = object11(model.compat);
37499
37676
  if (block.summary === false && (compat?.requiresReasoningContentForToolCalls === true || compat?.requiresReasoningContentForAllAssistantTurns === true))
37500
37677
  return;
37501
37678
  const text = demotedThinking(block.thinking, model);
@@ -37515,13 +37692,13 @@ function piResponsesAssistantTexts(value, model, host, alternatives, frozenTagSt
37515
37692
  texts.push(textIdentity2(wellFormed2(block.text), sameModel ? signaturePhase(block) : undefined));
37516
37693
  blocks.push(block);
37517
37694
  }
37518
- const payload = object10(message.providerPayload);
37695
+ const payload = object11(message.providerPayload);
37519
37696
  if (message.api !== model?.api || typeof model?.id !== "string" || typeof model?.provider !== "string" || message.model !== model?.id || (payload?.provider ?? message.provider) !== model?.provider || payload?.type !== "openaiResponsesHistory" || payload.dt !== true || !Array.isArray(payload.items))
37520
37697
  return texts;
37521
37698
  if (host === "omp" && model.api === "openai-codex-responses" && texts.every((text) => !/\S/u.test(JSON.parse(text)[0])) && payload.items.every((value) => {
37522
- const item = object10(value);
37699
+ const item = object11(value);
37523
37700
  return item?.type === "reasoning" || item?.type === "message" && item.role === "assistant" && Array.isArray(item.content) && item.content.every((value) => {
37524
- const part = object10(value);
37701
+ const part = object11(value);
37525
37702
  return part?.type === "output_text" && typeof part.text === "string" && !/\S/u.test(part.text);
37526
37703
  });
37527
37704
  }))
@@ -37538,7 +37715,7 @@ function piResponsesAssistantTexts(value, model, host, alternatives, frozenTagSt
37538
37715
  let rewrittenText = false;
37539
37716
  let allUnsignedFrozen = true;
37540
37717
  for (const value of payload.items) {
37541
- const item = object10(value);
37718
+ const item = object11(value);
37542
37719
  if (item?.type === "reasoning")
37543
37720
  continue;
37544
37721
  if (item?.type === "function_call" || item?.type === "custom_tool_call") {
@@ -37549,14 +37726,14 @@ function piResponsesAssistantTexts(value, model, host, alternatives, frozenTagSt
37549
37726
  return texts;
37550
37727
  const itemTexts = [];
37551
37728
  for (const value of item.content) {
37552
- const part = object10(value);
37729
+ const part = object11(value);
37553
37730
  const block = blocks[bound];
37554
37731
  if (!block || part?.type !== "output_text" || typeof part.text !== "string")
37555
37732
  return texts;
37556
37733
  let signature;
37557
37734
  try {
37558
37735
  if (typeof block.textSignature === "string")
37559
- signature = object10(JSON.parse(block.textSignature));
37736
+ signature = object11(JSON.parse(block.textSignature));
37560
37737
  } catch {
37561
37738
  return texts;
37562
37739
  }
@@ -37596,7 +37773,7 @@ function piResponsesWireTexts(value, phase) {
37596
37773
  const texts = [];
37597
37774
  let units = 0;
37598
37775
  for (const partValue of value) {
37599
- const part = object10(partValue);
37776
+ const part = object11(partValue);
37600
37777
  if (part?.type !== "output_text" || typeof part.text !== "string")
37601
37778
  return;
37602
37779
  units += part.text.length;
@@ -37635,11 +37812,11 @@ var TRANSFORM_MESSAGES_APIS = new Set([
37635
37812
  "devin-agent",
37636
37813
  "apple-foundation-models"
37637
37814
  ]);
37638
- function object11(value) {
37815
+ function object12(value) {
37639
37816
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
37640
37817
  }
37641
37818
  function messageStructure(value) {
37642
- const message = object11(value);
37819
+ const message = object12(value);
37643
37820
  if (!message)
37644
37821
  return;
37645
37822
  const role = [
@@ -37668,7 +37845,7 @@ function messageStructure(value) {
37668
37845
  }
37669
37846
  if (role === "assistant" && Array.isArray(message.content)) {
37670
37847
  for (const value of message.content) {
37671
- const block = object11(value);
37848
+ const block = object12(value);
37672
37849
  if (block?.type !== "toolCall" && block?.type !== "tool_use")
37673
37850
  continue;
37674
37851
  if (typeof block.id !== "string")
@@ -37684,7 +37861,7 @@ function windowCalls(message) {
37684
37861
  if (!Array.isArray(message.content))
37685
37862
  return [];
37686
37863
  return message.content.flatMap((value) => {
37687
- const block = object11(value);
37864
+ const block = object12(value);
37688
37865
  return block?.type === "toolCall" && typeof block.id === "string" ? [
37689
37866
  {
37690
37867
  id: block.id,
@@ -37694,7 +37871,7 @@ function windowCalls(message) {
37694
37871
  });
37695
37872
  }
37696
37873
  function duplicateSuffix(model) {
37697
- const compat = object11(model?.compat);
37874
+ const compat = object12(model?.compat);
37698
37875
  if (model?.api === "openai-completions") {
37699
37876
  if (compat?.requiresMistralToolIds === true)
37700
37877
  return { prefix: "dup", max: 9 };
@@ -37711,7 +37888,7 @@ function appendDuplicateSuffix(id, suffix, max) {
37711
37888
  }
37712
37889
  function projectMissingToolResults(messages, model, host = "omp") {
37713
37890
  const input = messages.filter((value) => {
37714
- const message = object11(value);
37891
+ const message = object12(value);
37715
37892
  return !((message?.role === "bashExecution" || message?.role === "pythonExecution") && message.excludeFromContext === true);
37716
37893
  });
37717
37894
  if (host === "pi")
@@ -37726,7 +37903,7 @@ function projectMissingToolResults(messages, model, host = "omp") {
37726
37903
  const realResults = new Map;
37727
37904
  const validToolUseIds = new Set;
37728
37905
  const deduplicated = input.map((value, index) => {
37729
- const message = object11(value);
37906
+ const message = object12(value);
37730
37907
  if (message?.role === "toolResult" && typeof message.toolCallId === "string") {
37731
37908
  let key = pairingId(message.toolCallId);
37732
37909
  let output = value;
@@ -37753,7 +37930,7 @@ function projectMissingToolResults(messages, model, host = "omp") {
37753
37930
  const touched = new Set;
37754
37931
  let changed = false;
37755
37932
  const content = message.content.map((part) => {
37756
- const block = object11(part);
37933
+ const block = object12(part);
37757
37934
  if (block?.type !== "toolCall" || typeof block.id !== "string")
37758
37935
  return part;
37759
37936
  const key = pairingId(block.id);
@@ -37832,7 +38009,7 @@ function projectMissingToolResults(messages, model, host = "omp") {
37832
38009
  };
37833
38010
  for (let index = 0;index < deduplicated.length; index++) {
37834
38011
  const value = deduplicated[index];
37835
- const message = object11(value);
38012
+ const message = object12(value);
37836
38013
  if (message?.role === "assistant") {
37837
38014
  flush(message.timestamp);
37838
38015
  if (piOmitsTruncatedAssistant(message))
@@ -37873,7 +38050,7 @@ function projectMissingToolResults(messages, model, host = "omp") {
37873
38050
  if (pending.some((call) => !answered.has(pairingId(call.id))) || aborted.size > 0)
37874
38051
  continue;
37875
38052
  const parts = message.content.flatMap((value) => {
37876
- const part = object11(value);
38053
+ const part = object12(value);
37877
38054
  return part?.type === "text" && typeof part.text === "string" && part.text.trim() ? [part.text] : [];
37878
38055
  });
37879
38056
  if (!parts.length)
@@ -37901,11 +38078,11 @@ function projectUnmodeledToolResults(messages) {
37901
38078
  return pipe > 0 ? id.slice(0, pipe) : id;
37902
38079
  };
37903
38080
  for (const value of messages) {
37904
- const message = object11(value);
38081
+ const message = object12(value);
37905
38082
  if (message?.role !== "assistant" || !Array.isArray(message.content))
37906
38083
  continue;
37907
38084
  for (const value of message.content) {
37908
- const block = object11(value);
38085
+ const block = object12(value);
37909
38086
  if (block?.type !== "toolCall" || typeof block.id !== "string")
37910
38087
  continue;
37911
38088
  if ([
@@ -37921,7 +38098,7 @@ function projectUnmodeledToolResults(messages) {
37921
38098
  const pairingId = (id) => !opaqueIds.has(id) && responsesComponents.has(component(id)) ? component(id) : id;
37922
38099
  const lastResult = new Map;
37923
38100
  messages.forEach((value, index) => {
37924
- const message = object11(value);
38101
+ const message = object12(value);
37925
38102
  if (message?.role === "toolResult" && typeof message.toolCallId === "string")
37926
38103
  lastResult.set(pairingId(message.toolCallId), index);
37927
38104
  });
@@ -37952,7 +38129,7 @@ function projectUnmodeledToolResults(messages) {
37952
38129
  };
37953
38130
  for (let index = 0;index < messages.length; index++) {
37954
38131
  const value = messages[index];
37955
- const message = object11(value);
38132
+ const message = object12(value);
37956
38133
  if ((message?.role === "bashExecution" || message?.role === "pythonExecution") && message.excludeFromContext === true)
37957
38134
  continue;
37958
38135
  if (message?.role !== "toolResult")
@@ -37994,7 +38171,7 @@ function projectPiToolResults(messages) {
37994
38171
  held.length = 0;
37995
38172
  };
37996
38173
  for (const value of messages) {
37997
- const message = object11(value);
38174
+ const message = object12(value);
37998
38175
  const role = message?.role;
37999
38176
  if (role === "assistant") {
38000
38177
  close(message?.timestamp);
@@ -38025,7 +38202,7 @@ function projectPiToolResults(messages) {
38025
38202
  function preparePiDispatch(messages, model, omp, cwd) {
38026
38203
  let output = messages;
38027
38204
  const structure = buildPiPreparedStructure(messages, model, omp ? (index, source) => {
38028
- if (object11(source.providerPayload)?.type !== "openaiResponsesHistory")
38205
+ if (object12(source.providerPayload)?.type !== "openaiResponsesHistory")
38029
38206
  return;
38030
38207
  if (output === messages)
38031
38208
  output = messages.slice();
@@ -38041,7 +38218,7 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38041
38218
  if (!messages.length || messages.length > MAX_MESSAGES)
38042
38219
  return;
38043
38220
  for (let index = 0;index < messages.length; index++) {
38044
- const source = object11(messages[index]);
38221
+ const source = object12(messages[index]);
38045
38222
  if (source?.role === "user" || source?.role === "compactionSummary")
38046
38223
  prepareUser?.(index, source);
38047
38224
  }
@@ -38058,7 +38235,7 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38058
38235
  let valid = true;
38059
38236
  for (let index = 0;index < projectedMessages.length; index++) {
38060
38237
  const message = projectedMessages[index];
38061
- const source = object11(message);
38238
+ const source = object12(message);
38062
38239
  if (rows.length === 0 && (source?.role === "system" || source?.role === "developer"))
38063
38240
  continue;
38064
38241
  if ((source?.role === "bashExecution" || source?.role === "pythonExecution") && source.excludeFromContext === true)
@@ -38082,7 +38259,7 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38082
38259
  "azure-openai-responses",
38083
38260
  "openai-codex-responses"
38084
38261
  ].includes(model?.api ?? "") && (source?.role === "user" || source?.role === "developer") && (typeof source.content === "string" ? !source.content.trim() : Array.isArray(source.content) && !source.content.some((value) => {
38085
- const block = object11(value);
38262
+ const block = object12(value);
38086
38263
  return block?.type === "image" || block?.type === "text" && typeof block.text === "string" && block.text.trim();
38087
38264
  })))
38088
38265
  continue;
@@ -38126,12 +38303,12 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38126
38303
  const positionedRows = [...byIndex];
38127
38304
  for (let position = positionedRows.length - 1;position >= 0; position--) {
38128
38305
  const [index, row] = positionedRows[position];
38129
- const source = object11(projectedMessages[index]);
38306
+ const source = object12(projectedMessages[index]);
38130
38307
  if (!source)
38131
38308
  return;
38132
38309
  const content = source.content;
38133
38310
  const parts = typeof content === "string" ? [{ type: "text", text: content }] : content;
38134
- const textOnly = Array.isArray(parts) && parts.every((part) => object11(part)?.type === "text" && typeof object11(part)?.text === "string");
38311
+ const textOnly = Array.isArray(parts) && parts.every((part) => object12(part)?.type === "text" && typeof object12(part)?.text === "string");
38135
38312
  const systemTexts = () => {
38136
38313
  const texts = parts.map((part) => part.text);
38137
38314
  return model?.api === "anthropic-messages" ? texts.filter((text) => text.trim()).map((text) => new TextDecoder().decode(new TextEncoder().encode(text))) : texts;
@@ -38139,7 +38316,7 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38139
38316
  if (piIsDeveloperHistory(source) && source.attribution !== "user") {
38140
38317
  const previous = rows[position - 1];
38141
38318
  const next = rows[position + 1];
38142
- const anthropicPromotable = model?.api === "anthropic-messages" && object11(model.compat)?.supportsMidConversationSystem === true && textOnly;
38319
+ const anthropicPromotable = model?.api === "anthropic-messages" && object12(model.compat)?.supportsMidConversationSystem === true && textOnly;
38143
38320
  if (anthropicPromotable)
38144
38321
  promotable.set(row, systemTexts());
38145
38322
  if (model?.api === "ollama-chat" || anthropicPromotable && (previous?.role === "user" || previous?.role === "toolResult") && (!next || next.role === "assistant"))
@@ -38193,7 +38370,7 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38193
38370
  continue;
38194
38371
  }
38195
38372
  const alternatives = {};
38196
- const texts = piResponsesAssistantTexts(projectedMessages[index], model, host, alternatives, object11(projectedMessages[index])?.[PI_NATIVE_TAG_STRIP_PROVENANCE]);
38373
+ const texts = piResponsesAssistantTexts(projectedMessages[index], model, host, alternatives, object12(projectedMessages[index])?.[PI_NATIVE_TAG_STRIP_PROVENANCE]);
38197
38374
  if (!texts) {
38198
38375
  responsesMessages = undefined;
38199
38376
  break;
@@ -38241,15 +38418,15 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
38241
38418
  ...modelsContinuePad ? { anthropicContinuePad: true } : {},
38242
38419
  ...modelsContinuePad && baseRows.some((row) => row.optionalThinking) ? { anthropicOptional: { rows: baseRows, promotable } } : {},
38243
38420
  ...model?.api?.startsWith("google-") ? {
38244
- googleFunctionIds: object11(model.compat)?.supportsFunctionPartId === true
38421
+ googleFunctionIds: object12(model.compat)?.supportsFunctionPartId === true
38245
38422
  } : {}
38246
38423
  };
38247
38424
  if (host === "omp" && PI_DATE_REMINDER_APIS.has(model?.api ?? ""))
38248
38425
  dateReminderPlans.set(prepared, {
38249
38426
  ...modelsContinuePad ? { plan: { rows: baseRows, promotable } } : {},
38250
38427
  firstUser: firstUserRow ? baseRows.indexOf(firstUserRow) : -1,
38251
- midConversationSystem: object11(model?.compat)?.supportsMidConversationSystem === true,
38252
- developerRole: object11(model?.compat)?.supportsDeveloperRole === true
38428
+ midConversationSystem: object12(model?.compat)?.supportsMidConversationSystem === true,
38429
+ developerRole: object12(model?.compat)?.supportsDeveloperRole === true
38253
38430
  });
38254
38431
  return prepared;
38255
38432
  }
@@ -38261,7 +38438,7 @@ function responsesLane(api) {
38261
38438
  ].includes(api ?? "");
38262
38439
  }
38263
38440
  function payloadStructure(payload, ollama = false, responsesItems = false, imageProjection = false) {
38264
- const body = object11(payload);
38441
+ const body = object12(payload);
38265
38442
  if (!body)
38266
38443
  return;
38267
38444
  const google = piGoogleConversation(payload);
@@ -38276,12 +38453,12 @@ function payloadStructure(payload, ollama = false, responsesItems = false, image
38276
38453
  return;
38277
38454
  const rows = [];
38278
38455
  for (const value of messages) {
38279
- const message = object11(value);
38456
+ const message = object12(value);
38280
38457
  if (!message)
38281
38458
  return;
38282
38459
  if (rows.length === 0 && (message.role === "system" || message.role === "developer"))
38283
38460
  continue;
38284
- if (message.role === "system" && Array.isArray(message.content) && message.content.every((block) => ["tool_addition", "tool_removal"].includes(String(object11(block)?.type))))
38461
+ if (message.role === "system" && Array.isArray(message.content) && message.content.every((block) => ["tool_addition", "tool_removal"].includes(String(object12(block)?.type))))
38285
38462
  continue;
38286
38463
  if (responses && message.type === "reasoning")
38287
38464
  continue;
@@ -38338,7 +38515,7 @@ function payloadStructure(payload, ollama = false, responsesItems = false, image
38338
38515
  continue;
38339
38516
  }
38340
38517
  if (message.role === "user" && Array.isArray(message.content)) {
38341
- const results = message.content.filter((block) => object11(block)?.type === "tool_result" || bedrock && object11(block)?.toolResult);
38518
+ const results = message.content.filter((block) => object12(block)?.type === "tool_result" || bedrock && object12(block)?.toolResult);
38342
38519
  if (results.length) {
38343
38520
  for (const block of results) {
38344
38521
  const id = bedrock ? block.toolResult?.toolUseId : block.tool_use_id;
@@ -38385,11 +38562,11 @@ function payloadStructure(payload, ollama = false, responsesItems = false, image
38385
38562
  }
38386
38563
  if (Array.isArray(message.tool_calls)) {
38387
38564
  for (const call of message.tool_calls) {
38388
- const source = object11(call);
38565
+ const source = object12(call);
38389
38566
  if (!source)
38390
38567
  return;
38391
38568
  if (source.id === undefined && ollama) {
38392
- const fn = object11(source.function);
38569
+ const fn = object12(source.function);
38393
38570
  if (typeof fn?.name !== "string")
38394
38571
  return;
38395
38572
  row.calls.push("");
@@ -38425,7 +38602,7 @@ function googleStructure(contents, imageProjection = false) {
38425
38602
  return;
38426
38603
  const rows = [];
38427
38604
  for (const value of contents) {
38428
- const message = object11(value);
38605
+ const message = object12(value);
38429
38606
  if (!message || !Array.isArray(message.parts))
38430
38607
  return;
38431
38608
  if (message.role !== "user" && message.role !== "model")
@@ -38440,11 +38617,11 @@ function googleStructure(contents, imageProjection = false) {
38440
38617
  };
38441
38618
  const results = [];
38442
38619
  for (const value of message.parts) {
38443
- const part = object11(value);
38620
+ const part = object12(value);
38444
38621
  if (!part)
38445
38622
  return;
38446
38623
  if (part.functionCall) {
38447
- const call = object11(part.functionCall);
38624
+ const call = object12(part.functionCall);
38448
38625
  if (row.role !== "assistant" || typeof call?.name !== "string" || call.id !== undefined && typeof call.id !== "string")
38449
38626
  return;
38450
38627
  row.calls.push(call.id ?? "");
@@ -38452,7 +38629,7 @@ function googleStructure(contents, imageProjection = false) {
38452
38629
  row.callNames.push(call.name);
38453
38630
  }
38454
38631
  if (part.functionResponse) {
38455
- const result = object11(part.functionResponse);
38632
+ const result = object12(part.functionResponse);
38456
38633
  if (row.role !== "user" || typeof result?.name !== "string" || result.id !== undefined && typeof result.id !== "string")
38457
38634
  return;
38458
38635
  results.push({
@@ -38486,11 +38663,11 @@ function matchesUserText(content, text, api, responses, googleOrBedrock) {
38486
38663
  if (responses || googleOrBedrock) {
38487
38664
  if (!Array.isArray(content) || content.length !== 1)
38488
38665
  return false;
38489
- const block = object11(content[0]);
38666
+ const block = object12(content[0]);
38490
38667
  return !!block && block.text === text && (responses ? block.type === "input_text" : Object.keys(block).length === 1);
38491
38668
  }
38492
38669
  if ((api === "anthropic-messages" || api === "factory-droid-agent") && Array.isArray(content)) {
38493
- const block = content.length === 1 ? object11(content[0]) : undefined;
38670
+ const block = content.length === 1 ? object12(content[0]) : undefined;
38494
38671
  return block?.type === "text" && block.text === text;
38495
38672
  }
38496
38673
  return content === text;
@@ -38624,15 +38801,15 @@ function countAnthropicOptionalAlignments(plan, base, wire, compare, reminders,
38624
38801
  function piPreparedStructureMismatch(payload, prepared, onImageTrim) {
38625
38802
  const plan = prepared && dateReminderPlans.get(prepared);
38626
38803
  try {
38627
- const body = plan ? object11(payload) : undefined;
38804
+ const body = plan ? object12(payload) : undefined;
38628
38805
  const messages = body?.messages ?? body?.input;
38629
38806
  if (Array.isArray(messages)) {
38630
38807
  for (const value of messages) {
38631
- const message = object11(value);
38808
+ const message = object12(value);
38632
38809
  if (message?.role !== "system" && message?.role !== "developer")
38633
38810
  break;
38634
38811
  const content = message.content;
38635
- const inputText = Array.isArray(content) && content.length === 1 && object11(content[0])?.type === "input_text" ? object11(content[0])?.text : undefined;
38812
+ const inputText = Array.isArray(content) && content.length === 1 && object12(content[0])?.type === "input_text" ? object12(content[0])?.text : undefined;
38636
38813
  if (piDateReminderWireText(content, plan?.cwd) !== undefined || piDateReminderText(inputText, plan?.cwd))
38637
38814
  return "comparison=role";
38638
38815
  }
@@ -38648,7 +38825,7 @@ function piPreparedStructureMismatch(payload, prepared, onImageTrim) {
38648
38825
  if (plan.firstUser < 0)
38649
38826
  return mismatch;
38650
38827
  const root = prepared.messages[plan.firstUser];
38651
- const body = object11(payload);
38828
+ const body = object12(payload);
38652
38829
  const routeRows = Array.isArray(body?.input) ? prepared.responsesMessages ?? prepared.messages : prepared.api === "openai-completions" ? prepared.chatMessages ?? prepared.messages : prepared.messages;
38653
38830
  const firstUser = routeRows.indexOf(root);
38654
38831
  if (firstUser < 0)
@@ -38659,11 +38836,11 @@ function piPreparedStructureMismatch(payload, prepared, onImageTrim) {
38659
38836
  });
38660
38837
  return filtered === undefined ? mismatch : preparedStructureMismatch(filtered, prepared, onImageTrim);
38661
38838
  }
38662
- const messages = object11(payload)?.messages;
38839
+ const messages = object12(payload)?.messages;
38663
38840
  if (!Array.isArray(messages))
38664
38841
  return mismatch;
38665
38842
  for (const value of messages) {
38666
- const message = object11(value);
38843
+ const message = object12(value);
38667
38844
  if (piDateReminderWireText(message?.content, plan.cwd) !== undefined && Object.keys(message ?? {}).some((key) => !["role", "content"].includes(key)))
38668
38845
  return mismatch;
38669
38846
  }
@@ -38703,7 +38880,7 @@ function preparedStructureMismatch(payload, prepared, onImageTrim, reminders, re
38703
38880
  return "comparison=image count";
38704
38881
  const imageProjection = trimmed > 0;
38705
38882
  stage = "wire rows";
38706
- const body = object11(payload);
38883
+ const body = object12(payload);
38707
38884
  const ollama = prepared?.api === "ollama-chat" && !!body && Array.isArray(body.messages) && body.input === undefined && body.system === undefined && body.inferenceConfig === undefined;
38708
38885
  const responses = body?.messages === undefined && Array.isArray(body?.input);
38709
38886
  rows = reminderWire ?? payloadStructure(payload, ollama, responses && !!prepared?.responsesMessages, imageProjection);
@@ -38730,7 +38907,7 @@ function preparedStructureMismatch(payload, prepared, onImageTrim, reminders, re
38730
38907
  if (expected.systemText !== undefined) {
38731
38908
  const texts = expected.systemText;
38732
38909
  const content = actual.wireContent;
38733
- const actualTexts = typeof content === "string" ? [content] : Array.isArray(content) && content.every((part) => object11(part)?.type === "text" && typeof object11(part)?.text === "string") ? content.map((part) => part.text) : undefined;
38910
+ const actualTexts = typeof content === "string" ? [content] : Array.isArray(content) && content.every((part) => object12(part)?.type === "text" && typeof object12(part)?.text === "string") ? content.map((part) => part.text) : undefined;
38734
38911
  if (!actualTexts || (typeof content === "string" ? content !== texts.join(`
38735
38912
  `) : JSON.stringify(actualTexts) !== JSON.stringify(texts)))
38736
38913
  return "content";
@@ -40137,6 +40314,7 @@ function releasePiOperationPayloads(operation) {
40137
40314
  operation.dispatchFields = undefined;
40138
40315
  operation.chainDispatchFields = undefined;
40139
40316
  operation.managedSignature = undefined;
40317
+ operation.cursorRoots = undefined;
40140
40318
  operation.preparedStructure = undefined;
40141
40319
  operation.preparedHistory = undefined;
40142
40320
  }
@@ -40277,10 +40455,10 @@ function registerPiGuardedContext(pi, handler, options = {}) {
40277
40455
  receiptMaps.add(imageTrimNotices);
40278
40456
  const chains = new Map;
40279
40457
  receiptMaps.add(chains);
40280
- const refuse = (ctx, budget, reason, isCurrent) => {
40458
+ const refuse = (ctx, budget, reason, isCurrent, abort = true) => {
40281
40459
  if (!isCurrent()) {
40282
40460
  log2(`[magic-context][pi] DISCARDED CONTEXT RESULT ${budget.diagnostic()}`, reason);
40283
- return;
40461
+ return RETRY_MESSAGE;
40284
40462
  }
40285
40463
  budget.abandoned = true;
40286
40464
  budget.recovery = budget.recovery === "not attempted" ? "no managed result; refused" : budget.recovery;
@@ -40297,7 +40475,7 @@ function registerPiGuardedContext(pi, handler, options = {}) {
40297
40475
  } catch (error) {
40298
40476
  log2("[magic-context][pi] refusal entry failed", error);
40299
40477
  } finally {
40300
- if (!budget.sideTurn)
40478
+ if (abort && !budget.sideTurn)
40301
40479
  ctx.abort();
40302
40480
  }
40303
40481
  try {
@@ -40305,6 +40483,7 @@ function registerPiGuardedContext(pi, handler, options = {}) {
40305
40483
  } catch (error) {
40306
40484
  log2("[magic-context][pi] refusal diagnostic failed", error);
40307
40485
  }
40486
+ return message;
40308
40487
  };
40309
40488
  if (fenceEnabled) {
40310
40489
  pi.on("agent_start", (_event, ctx) => {
@@ -40357,7 +40536,7 @@ function registerPiGuardedContext(pi, handler, options = {}) {
40357
40536
  cancelledOperation?.pass?.cancel();
40358
40537
  if (cancelledOperation)
40359
40538
  cancelledOperation.ready = false;
40360
- return;
40539
+ return piRefusedPayload("Magic Context request cancelled before provider dispatch.");
40361
40540
  }
40362
40541
  if (options.compactionOff?.(ctx)) {
40363
40542
  chains.delete(operationKey(ctx));
@@ -40369,12 +40548,19 @@ function registerPiGuardedContext(pi, handler, options = {}) {
40369
40548
  return;
40370
40549
  const nonces = unsendableNonces.get(key);
40371
40550
  if (nonces?.size) {
40372
- const serializedPayload = JSON.stringify(payload);
40551
+ let serializedPayload;
40552
+ try {
40553
+ serializedPayload = JSON.stringify(payload);
40554
+ } catch {
40555
+ const budget = new PiContextBudget;
40556
+ budget.stage = "provider dispatch";
40557
+ return piRefusedPayload(refuse(ctx, budget, `provider payload could not be inspected; ${piDispatchShape(payload, ctx.model?.api)}`, () => true, false));
40558
+ }
40373
40559
  if (serializedPayload && [...nonces].some((nonce) => serializedPayload.includes(nonce))) {
40374
40560
  const budget = new PiContextBudget;
40375
40561
  budget.stage = "provider dispatch";
40376
- refuse(ctx, budget, "superseded context fallback is not a managed request", () => true);
40377
- return;
40562
+ const message = refuse(ctx, budget, `superseded context fallback is not a managed request; ${piDispatchShape(payload, ctx.model?.api)}`, () => true, false);
40563
+ return piRefusedPayload(message);
40378
40564
  }
40379
40565
  }
40380
40566
  if (isOmpAdvisorRequest(payload))
@@ -40389,8 +40575,7 @@ function registerPiGuardedContext(pi, handler, options = {}) {
40389
40575
  const capture = isOmpUnmanagedCaptureRequest(payload);
40390
40576
  const budget = (capture ? undefined : active.pass) ?? new PiContextBudget;
40391
40577
  if (active.refused && active.pass === budget) {
40392
- ctx.abort();
40393
- return;
40578
+ return piRefusedPayload(active.refusalMessage ?? RETRY_MESSAGE);
40394
40579
  }
40395
40580
  let refusalOrigin;
40396
40581
  try {
@@ -40419,13 +40604,13 @@ function registerPiGuardedContext(pi, handler, options = {}) {
40419
40604
  checked = expanded.payload;
40420
40605
  chainInput = expanded.input;
40421
40606
  }
40422
- if (!piHasManagedSignature(checked, active.managedSignature))
40423
- throw new Error("provider request does not match this pass's managed dispatch (missing current receipt signature)");
40607
+ if (!piHasManagedSignature(checked, active.managedSignature, active.cursorRoots))
40608
+ throw new Error(ctx.model?.api === "cursor-agent" ? "provider request does not match this pass's managed dispatch (Cursor root hash did not match and active message has no current receipt signature)" : "provider request does not match this pass's managed dispatch (missing current receipt signature)");
40424
40609
  const fields = piConversationFields(payload);
40425
40610
  if (!fields)
40426
40611
  throw new Error("provider conversation identity could not be established");
40427
40612
  const body = checked;
40428
- const skipReason = active.preparedStructure ? active.preparedStructure.structuralSkipReason ?? (active.preparedStructure.api && body?.messages === undefined && Array.isArray(body?.input) && !active.preparedStructure.responsesMessages ? "provider selected Responses items without a matching history plan" : undefined) : "prepared history representation is not modeled";
40613
+ const skipReason = piCursorConversation(checked) ? "Cursor history blob IDs do not expose prepared turn structure" : active.preparedStructure ? active.preparedStructure.structuralSkipReason ?? (active.preparedStructure.api && body?.messages === undefined && Array.isArray(body?.input) && !active.preparedStructure.responsesMessages ? "provider selected Responses items without a matching history plan" : undefined) : "prepared history representation is not modeled";
40429
40614
  if (chained && skipReason)
40430
40615
  throw new Error("provider request does not match this pass's managed dispatch (chained continuation requires a modeled prepared history)");
40431
40616
  if (skipReason && !structureWarnings.has(key)) {
@@ -40469,14 +40654,22 @@ function registerPiGuardedContext(pi, handler, options = {}) {
40469
40654
  if (signal ? signal.aborted : budget.isCancelled(error)) {
40470
40655
  budget.cancel();
40471
40656
  active.ready = false;
40472
- return;
40657
+ return piRefusedPayload("Magic Context request cancelled before provider dispatch.");
40473
40658
  }
40474
40659
  active.refused = true;
40475
40660
  budget.stage = refusalOrigin ? `provider dispatch (origin=${refusalOrigin}; context stage=${budget.stage})` : "provider dispatch";
40476
- refuse(ctx, budget, error, isCurrent);
40661
+ const reason = new Error(`${error instanceof Error ? error.message : String(error)}; ${piDispatchShape(payload, ctx.model?.api)}`);
40662
+ active.refusalMessage = refuse(ctx, budget, reason, isCurrent, false);
40663
+ return piRefusedPayload(active.refusalMessage);
40477
40664
  }
40478
40665
  });
40479
40666
  }
40667
+ if (!fenceEnabled) {
40668
+ pi.on("before_provider_request", (_event, ctx) => {
40669
+ const operation = operations.get(operationKey(ctx));
40670
+ return operation?.refused ? piRefusedPayload(operation.refusalMessage ?? RETRY_MESSAGE) : undefined;
40671
+ });
40672
+ }
40480
40673
  pi.registerEntryRenderer?.(ENTRY_TYPE, (entry) => new Text2(entry.data?.message ?? RETRY_MESSAGE, 0, 0));
40481
40674
  pi.on("context", async (event, ctx) => {
40482
40675
  if (fenceEnabled && isOmpDumpContext())
@@ -40509,6 +40702,7 @@ function registerPiGuardedContext(pi, handler, options = {}) {
40509
40702
  active.dispatched = false;
40510
40703
  active.ready = false;
40511
40704
  active.refused = false;
40705
+ active.refusalMessage = undefined;
40512
40706
  const { isOwned, isCurrent, assertOwner } = createPiContextOwnershipGuards(operations, key, active, budget, owner);
40513
40707
  budget.assertOwner = assertOwner;
40514
40708
  try {
@@ -40525,6 +40719,8 @@ function registerPiGuardedContext(pi, handler, options = {}) {
40525
40719
  if (prepared.messages !== result.messages)
40526
40720
  result.messages = prepared.messages;
40527
40721
  active.managedSignature = piManagedSignature(result.messages);
40722
+ if (ctx.model?.api === "cursor-agent")
40723
+ active.cursorRoots = piCursorManagedRoots(result.messages, active.managedSignature, ctx.cwd);
40528
40724
  active.preparedStructure = prepared.structure;
40529
40725
  if (fenceEnabled && !budget.sideTurn && piChainCapableApi(ctx.model?.api))
40530
40726
  active.preparedHistory = piPreparedHistory(result.messages, ctx.model);
@@ -40576,7 +40772,7 @@ function registerPiGuardedContext(pi, handler, options = {}) {
40576
40772
  throw error;
40577
40773
  }
40578
40774
  active.refused = true;
40579
- refuse(ctx, budget, error, isOwned);
40775
+ active.refusalMessage = refuse(ctx, budget, error, isOwned);
40580
40776
  return { messages: event.messages };
40581
40777
  } finally {
40582
40778
  if (!fenceEnabled || budget.sideTurn)
@@ -40700,7 +40896,7 @@ function createPiFallbackIndex() {
40700
40896
  }
40701
40897
 
40702
40898
  // src/pi-fit-reclaim.ts
40703
- import { createHash as createHash14, randomUUID as randomUUID4 } from "node:crypto";
40899
+ import { createHash as createHash15, randomUUID as randomUUID4 } from "node:crypto";
40704
40900
  var pendingInput = new Set;
40705
40901
  var KEY3 = "piUpperEstimateReclaim";
40706
40902
  function piFitOverflowPossible(args) {
@@ -40736,7 +40932,7 @@ function piUpperReclaimCursor(args) {
40736
40932
  sessionId: args.sessionId,
40737
40933
  modelKey: args.modelKey,
40738
40934
  contextWindow: args.contextWindow ?? null,
40739
- head: head ? createHash14("sha256").update(JSON.stringify([
40935
+ head: head ? createHash15("sha256").update(JSON.stringify([
40740
40936
  Buffer.from(head.cachedM0Bytes ?? []).toString("base64"),
40741
40937
  Buffer.from(head.cachedM1Bytes ?? []).toString("base64"),
40742
40938
  head.cachedM0MuralDataUrl ?? null
@@ -40823,7 +41019,7 @@ async function waitForPiHistorianInTurn(sessionId, remainingMs, wait) {
40823
41019
  }
40824
41020
 
40825
41021
  // src/pi-lkg-fit-envelope.ts
40826
- import { createHash as createHash15 } from "node:crypto";
41022
+ import { createHash as createHash16 } from "node:crypto";
40827
41023
  function readPiLkgFitEnvelope(ctx, pi, modelKey, frozen, wireSchema) {
40828
41024
  try {
40829
41025
  if (!modelKey || typeof pi.getAllTools !== "function")
@@ -40885,7 +41081,7 @@ function readPiLkgFitEnvelope(ctx, pi, modelKey, frozen, wireSchema) {
40885
41081
  refusalToolDefinitionTokens,
40886
41082
  toolDefinitionsMeasured: refusalToolDefinitionTokens !== undefined,
40887
41083
  envelopeBytes: Buffer.byteLength(envelopeJson),
40888
- envelopeSignature: activeNames ? createHash15("sha256").update(envelopeJson).update(JSON.stringify(activeNames)).digest("hex") : undefined,
41084
+ envelopeSignature: activeNames ? createHash16("sha256").update(envelopeJson).update(JSON.stringify(activeNames)).digest("hex") : undefined,
40889
41085
  calibration
40890
41086
  };
40891
41087
  } catch {
@@ -40894,13 +41090,13 @@ function readPiLkgFitEnvelope(ctx, pi, modelKey, frozen, wireSchema) {
40894
41090
  }
40895
41091
 
40896
41092
  // src/pi-message-identity.ts
40897
- import { createHash as createHash18 } from "node:crypto";
41093
+ import { createHash as createHash19 } from "node:crypto";
40898
41094
 
40899
41095
  // src/pi-tool-identity.ts
40900
- import { createHash as createHash17 } from "node:crypto";
41096
+ import { createHash as createHash18 } from "node:crypto";
40901
41097
 
40902
41098
  // src/served-array-ledger.ts
40903
- import { createHash as createHash16 } from "node:crypto";
41099
+ import { createHash as createHash17 } from "node:crypto";
40904
41100
  import {
40905
41101
  closeSync as closeSync2,
40906
41102
  fstatSync,
@@ -41178,7 +41374,7 @@ function getPiLastServedArray(sessionId) {
41178
41374
  return previous ? `[${previous.serializedMessages.join(",")}]` : undefined;
41179
41375
  }
41180
41376
  function sha256(value) {
41181
- return createHash16("sha256").update(value).digest("hex");
41377
+ return createHash17("sha256").update(value).digest("hex");
41182
41378
  }
41183
41379
  function safeSessionFileStem(sessionId) {
41184
41380
  const readable = sessionId.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 96);
@@ -41463,7 +41659,7 @@ function readPiServedCachedArray(sessionId) {
41463
41659
  const memory = getPiLastServedArray(sessionId);
41464
41660
  const slot = memory === undefined ? getSlot(sessionId) : undefined;
41465
41661
  const jsonPrefix = memory ?? slot?.jsonPrefix;
41466
- if (jsonPrefix === undefined || createHash17("sha256").update(jsonPrefix).digest("hex") !== getPiLastServedDigest(sessionId))
41662
+ if (jsonPrefix === undefined || createHash18("sha256").update(jsonPrefix).digest("hex") !== getPiLastServedDigest(sessionId))
41467
41663
  return;
41468
41664
  let parsed;
41469
41665
  try {
@@ -41487,7 +41683,7 @@ function piMessageEntryFingerprint(message) {
41487
41683
  const m = message;
41488
41684
  if (typeof m.role !== "string")
41489
41685
  return null;
41490
- const contentHash = createHash18("sha256").update(stableStringify(m.content)).digest("hex");
41686
+ const contentHash = createHash19("sha256").update(stableStringify(m.content)).digest("hex");
41491
41687
  return JSON.stringify([
41492
41688
  typeof m.responseId === "string" ? m.responseId : null,
41493
41689
  typeof m.timestamp === "number" || typeof m.timestamp === "string" ? m.timestamp : null,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-magic-context",
3
- "version": "0.49.42",
3
+ "version": "0.49.43",
4
4
  "type": "module",
5
5
  "description": "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
6
6
  "main": "dist/index.js",
@@ -74,6 +74,8 @@
74
74
  "omp-pi-ai-18126": "npm:@oh-my-pi/pi-ai@18.12.6",
75
75
  "omp-pi-ai-1813": "npm:@oh-my-pi/pi-ai@18.13.0",
76
76
  "omp-pi-ai-18132": "npm:@oh-my-pi/pi-ai@18.13.2",
77
+ "omp-pi-ai-18180": "npm:@oh-my-pi/pi-ai@18.18.0",
78
+ "omp-pi-ai-18181": "npm:@oh-my-pi/pi-ai@18.18.1",
77
79
  "pi-agent-core-087": "npm:@earendil-works/pi-agent-core@0.87.1",
78
80
  "pi-ai-086": "npm:@earendil-works/pi-ai@0.86.0",
79
81
  "pi-ai-087": "npm:@earendil-works/pi-ai@0.87.1",