pi-mcp-extension 1.14.5 → 1.14.6

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.
package/README.md CHANGED
@@ -25,6 +25,7 @@
25
25
  - **Health checks** — Opt-in periodic pings to detect stale connections
26
26
  - **Safe process lifecycle** — Child PID tracking with tree-aware cleanup: descendants of wrapper commands (`npx`, `npm exec`, `uvx`, `sh -c`) are terminated too, and inherited pipes are released so teardown never stalls
27
27
  - **Stable tool names** — Sanitized, collision-avoiding names (`<prefix>_<server>_<tool>`, max 64 chars) that stay constant across reconnects, including when one server exposes two tools that sanitize to the same identifier: the name that needs no substitution keeps the unhashed form (`my_tool` wins over `my-tool`), remaining ties break by raw-name order, and the names that server's tools get never depend on `tools/list` order
28
+ - **Stable tool order** — Active MCP tools keep one deterministic order across session starts, `/tree` navigation, and idle or mid-turn `setActiveTools` updates (including `tool_search`): each active owned tool is sorted by Pi name among the slots it occupies, inactive tools stay off, and other extensions' tools never move. The same order is applied to outgoing provider tool declarations (top-level `tools`, AWS Bedrock Converse `toolConfig.tools`, Google/Vertex `config.tools[].functionDeclarations`, and `pi-messages` `context.messages[].toolsAdded`), which Pi otherwise rebuilds from the transcript's first-appearance order, so the system prompt's tool section and the tools this extension declares stay identical across session starts whatever order the eager servers connected in or the servers list their tools in — keeping a server-side prefix cache warm. A server that connects after an earlier turn is announced on that later turn through the provider's mid-conversation tool-addition channel, which cannot move back into earlier turns
28
29
  - **No tool churn** — Activate/deactivate pattern ensures tools don't flicker during reconnection
29
30
  - **Layered config & trust boundary** — Global `<agent dir>/mcp.json`, project `.pi/mcp.json` (loaded only in trusted projects, including Pi 1.3.0 partial overrides), and Pi 1.x extension-registered servers (`pi.registerMcpServer()`)
30
31
  - **Rich tool results & annotations** — MCP `text`, `image` (`ImageContent`), `structuredContent`, embedded `resource` text/images/binary blobs, `resource_link` hints, and `audio` fallback descriptions, plus `readOnlyHint`, `destructiveHint`, `idempotentHint`, and `openWorldHint` surfaced in tool descriptions and passed to Pi as structured tool `annotations` (boolean hints only), so permission extensions can inspect them
@@ -376,7 +377,7 @@ flowchart TD
376
377
  3. **Tools are discovered** via paginated `tools/list` calls (cursor-based, up to 100 pages) before a server enters `ready`
377
378
  4. **JSON Schema → TypeBox** conversion registers tools with Pi-compatible parameter schemas (preserving nullable union ordering, resolving `$ref`s cycle-safely, and inferring/flattening `allOf` object schemas)
378
379
  5. **Pi tools are registered** as `<prefix>_<server>_<tool>` (sanitized `[a-zA-Z0-9_]`, max 64 chars with an 8-char SHA-256 suffix on truncation or collision) and convert MCP `text`, `image` (`ImageContent`), `structuredContent`, `resource`, `resource_link`, and `audio` results. When one server exposes two tools that sanitize to the same identifier, the name that needed no substitution keeps the unhashed form (`my_tool` over `my-tool`), remaining ties break by the raw name's code-point order, and the assignment does not depend on `tools/list` order — so a reconnect cannot swap which MCP tool a Pi name executes. Embedded image resources become image blocks, binary resources include MIME type and byte count, and resource links include a `mcp_read_resource` hint.
379
- 6. **Tools activate/deactivate** automatically as servers connect/disconnect
380
+ 6. **Tools activate/deactivate** automatically as servers connect/disconnect, always in one deterministic order — the bridge's tools are sorted by Pi name among the slots they occupy, and other extensions' tools keep their positions — so connect timing and `tools/list` order cannot change the prompt head
380
381
  7. **AbortSignal** is wired through to `notifications/cancelled` for clean cancellation
381
382
  8. **Reconnection & recovery** uses a fixed delay schedule with configurable max retries on initial failure, health check failure, or unexpected transport close/error (`client.onclose` / `client.onerror`), while mid-session HTTP `401` / `403 insufficient_scope` invalidates stale tokens and surfaces a re-authorization hint
382
383
  9. **`list_changed` notifications** trigger re-discovery, deactivating stale tools automatically and invalidating the cached resource catalog
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mcp-extension",
3
- "version": "1.14.5",
3
+ "version": "1.14.6",
4
4
  "description": "Full-featured, lightweight MCP extension for the Pi coding agent: stdio, SSE & Streamable HTTP transports, OAuth 2.1 (PKCE + DCR), lazy/eager lifecycles — minimal dependencies, zero bloat.",
5
5
  "type": "module",
6
6
  "keywords": [
package/src/index.ts CHANGED
@@ -403,6 +403,19 @@ export default async function (pi: ExtensionAPI, paths: { bootstrapCwd?: string;
403
403
  return enqueueServerReconcile(ctx);
404
404
  });
405
405
 
406
+ // Keep active and outgoing tool order independent of connect timing, `/tree` transcript
407
+ // restoration, idle/mid-turn external `setActiveTools` reorderings (e.g. `tool_search` before
408
+ // continuation `sections.tools`, or idle shortcuts before `before_agent_start` snapshots
409
+ // `systemPromptOptions`), and first-appearance transcript replay (#278).
410
+ const normalizeActiveTools = (): void => {
411
+ bridge.orderActiveTools();
412
+ };
413
+ pi.on("session_tree", normalizeActiveTools);
414
+ pi.on("input", normalizeActiveTools);
415
+ pi.on("before_agent_start", normalizeActiveTools);
416
+ pi.on("tool_execution_end", normalizeActiveTools);
417
+ pi.on("before_provider_request", (event) => bridge.orderPayloadTools(event.payload));
418
+
406
419
  pi.on("session_shutdown", async (_event, ctx: ExtensionContext) => {
407
420
  // WHY: invalidate before tearing down so an in-flight startup or queued reconcile
408
421
  // observes a dead session and bails, then drain both after teardown so shutdown never
@@ -22,6 +22,12 @@ import { isCancellationError, isOAuthUnauthorizedError, isSdkTimeoutError } from
22
22
  import { convertJsonSchemaToTypebox } from "./schema-convert.js";
23
23
  import { listAllTools, type McpToolDefinition } from "./tool-discovery.js";
24
24
  import { convertResourceContent } from "./resource-bridge.js";
25
+ import {
26
+ compareCodePoints,
27
+ orderOwnedEntries,
28
+ orderPayloadToolEntries,
29
+ sameToolList,
30
+ } from "./tool-order.js";
25
31
 
26
32
  // ─── Types ────────────────────────────────────────────────────────────────────
27
33
 
@@ -70,18 +76,6 @@ function isLosslessToolName(rawToolName: string): boolean {
70
76
  return /^[a-zA-Z0-9_]+$/.test(rawToolName);
71
77
  }
72
78
 
73
- /** Compare strings by Unicode code point, not by UTF-16 code unit. */
74
- function compareCodePoints(a: string, b: string): number {
75
- const left = Array.from(a, (ch) => ch.codePointAt(0) ?? 0);
76
- const right = Array.from(b, (ch) => ch.codePointAt(0) ?? 0);
77
- const shared = Math.min(left.length, right.length);
78
- for (let i = 0; i < shared; i++) {
79
- const diff = (left[i] ?? 0) - (right[i] ?? 0);
80
- if (diff !== 0) return diff;
81
- }
82
- return left.length - right.length;
83
- }
84
-
85
79
  /**
86
80
  * Order a server's tools so Pi-name assignment depends only on the tool set and never on
87
81
  * the order `tools/list` happened to return (#213): a lossless raw name wins the unhashed
@@ -99,10 +93,10 @@ function compareToolsForNameAssignment(a: McpToolDefinition, b: McpToolDefinitio
99
93
 
100
94
  /**
101
95
  * Order a server's tools for Pi-name assignment. The server's own `tools/list` order is kept —
102
- * so registration order, and the tool order Pi shows the model, only move where they must —
103
- * except that tools competing for the same unhashed identifier are emitted as one deterministic
104
- * group in the position of the group's first member. Which tool the server listed first is not
105
- * part of the MCP contract, so it must not decide who wins that identifier (#213).
96
+ * so registration order only moves where it must — except that tools competing for the same
97
+ * unhashed identifier are emitted as one deterministic group in the position of the group's
98
+ * first member. Which tool the server listed first is not part of the MCP contract, so it must
99
+ * not decide who wins that identifier (#213).
106
100
  */
107
101
  function orderToolsForNameAssignment(
108
102
  prefix: string,
@@ -324,12 +318,6 @@ function normalizeRefreshArgs(
324
318
  return { isCurrent, options };
325
319
  }
326
320
 
327
- /** True when two tool-name lists have the same length and the same entries in order. */
328
- function sameToolList(left: readonly string[], right: readonly string[]): boolean {
329
- if (left.length !== right.length) return false;
330
- return left.every((name, index) => name === right[index]);
331
- }
332
-
333
321
  // ─── Tool Listing ─────────────────────────────────────────────────────────────
334
322
 
335
323
  export { listAllTools, type McpToolDefinition } from "./tool-discovery.js";
@@ -430,6 +418,47 @@ export class ToolBridge {
430
418
  return { discovered: names.size, active: [...names].filter((name) => active.has(name)).length };
431
419
  }
432
420
 
421
+ /**
422
+ * Re-apply this bridge's deterministic tool order to Pi's active list when owned tools have
423
+ * been reordered externally, and do nothing when already ordered.
424
+ *
425
+ * WHY: `/tree` navigation (`session_tree`) restores active tools from the transcript's
426
+ * first-appearance order without re-running `refreshTools`, and another extension or tool
427
+ * (e.g. `tool_search`) may call `pi.setActiveTools` idle or mid-turn; re-normalizing on
428
+ * `session_tree`, `input`, `before_agent_start`, and `tool_execution_end` keeps `sections.tools`
429
+ * in the system prompt aligned with `orderPayloadTools` without re-activating inactive tools (#278).
430
+ */
431
+ orderActiveTools(): void {
432
+ const current = this.pi.getActiveTools();
433
+ const ordered = orderOwnedEntries(
434
+ current,
435
+ (name) => name,
436
+ (name) => this.toolOwners.has(name),
437
+ );
438
+ if (ordered === undefined) return;
439
+ this.pi.setActiveTools(ordered);
440
+ }
441
+
442
+ /**
443
+ * Order this bridge's tools in an outgoing provider payload the same way they are ordered in
444
+ * Pi's active list — across top-level `tools` (Anthropic, OpenAI Chat Completions & Responses,
445
+ * Mistral), AWS Bedrock Converse `toolConfig.tools`, Google/Vertex
446
+ * `config.tools[].functionDeclarations`, and `pi-messages` `context.messages[].toolsAdded` —
447
+ * and return the payload untouched when they already are. Only entries this bridge owns move,
448
+ * and only among the slots they already occupy: another extension's tool and Pi's reserved
449
+ * trailing declarations (`__pi_deferred_placeholder__`, `cachePoint`, non-function Gemini tool
450
+ * groups, non-system messages) keep their positions.
451
+ *
452
+ * WHY: request tool arrays are not built from the active list — Pi replays the transcript's
453
+ * tool declarations in first-appearance order and emits no delta for a pure reorder, so a
454
+ * server that connects after the first turn leaves its tools at the end, in connect order.
455
+ * Sorting the payload makes the declared tools a function of the tool set, so the prompt head
456
+ * stays stable across sessions and a server-side prefix cache keeps its KV entries (#278).
457
+ */
458
+ orderPayloadTools(payload: unknown): unknown {
459
+ return orderPayloadToolEntries(payload, (name) => this.toolOwners.has(name));
460
+ }
461
+
433
462
  /** Deactivate all Pi tools belonging to a server (called on disconnect). */
434
463
  deactivateServer(serverName: string): void {
435
464
  this._bumpRefreshGeneration(serverName);
@@ -799,7 +828,8 @@ export class ToolBridge {
799
828
  /**
800
829
  * Reconcile a server's active tools in Pi in one write: drop any previously owned Pi tool
801
830
  * names that are not in `desiredActive`, append any `desiredActive` names not yet active,
802
- * and skip `pi.setActiveTools` altogether when the active set is unchanged.
831
+ * order the result, and skip `pi.setActiveTools` altogether when the active list already
832
+ * holds exactly that set in that order.
803
833
  */
804
834
  private _reconcileActiveTools(
805
835
  ownedPreviousNames: ReadonlySet<string>,
@@ -811,14 +841,30 @@ export class ToolBridge {
811
841
  (name) => !ownedPreviousNames.has(name) || desiredActive.has(name),
812
842
  );
813
843
  const newlyActive = [...desiredActive].filter((name) => !activeSet.has(name));
814
- const unchangedBeforeLoop =
815
- remaining.length === activeBefore.length && newlyActive.length === 0;
816
- // WHY: Even when `desiredActive` leaves `activeBefore` unchanged, `pi.registerTool()`
817
- // inside the loop may have auto-activated a newly registered hashed Pi name or a
818
- // `--tools` allowlist entry; re-read `getActiveTools()` before skipping the write.
819
- if (unchangedBeforeLoop && sameToolList(this.pi.getActiveTools(), activeBefore)) return;
820
-
821
- this.pi.setActiveTools(Array.from(new Set([...remaining, ...newlyActive])));
844
+ const nextActive = this._orderActiveTools(new Set([...remaining, ...newlyActive]));
845
+ // WHY: `pi.registerTool()` inside the loop may have auto-activated a newly registered hashed
846
+ // Pi name or a `--tools` allowlist entry, and a resumed session restores the order it ended
847
+ // with — so compare against a fresh read and write whenever the set *or* the order differs.
848
+ if (sameToolList(this.pi.getActiveTools(), nextActive)) return;
849
+
850
+ this.pi.setActiveTools(nextActive);
851
+ }
852
+
853
+ /**
854
+ * Order the active set so this bridge's tools are a pure function of the tool set: they are
855
+ * sorted by Pi name among the positions they already occupy, while every entry another
856
+ * extension owns keeps its position.
857
+ *
858
+ * WHY: a server's tools are registered as its connection completes, and `desiredActive`
859
+ * follows `tools/list` order, which the MCP spec does not define. Without a fixed order the
860
+ * active list — and with it the system prompt's tool section and the tools declared to the
861
+ * provider — depends on eager-connect timing, so a server-side prefix cache keyed on the
862
+ * prompt head misses on every session start or resume (#278).
863
+ */
864
+ private _orderActiveTools(active: ReadonlySet<string>): string[] {
865
+ const names = [...active];
866
+ const ordered = orderOwnedEntries(names, (name) => name, (name) => this.toolOwners.has(name));
867
+ return ordered ?? names;
822
868
  }
823
869
 
824
870
  private _deactivateServerTools(serverName: string): void {
@@ -0,0 +1,208 @@
1
+ /**
2
+ * Pure deterministic tool-ordering policy and provider-payload transforms (#278).
3
+ *
4
+ * Keeps MCP tool positions in Pi's active list and in outgoing provider requests a pure
5
+ * function of the tool set — independent of eager-connect timing, `tools/list` order,
6
+ * `/tree` transcript restoration, mid-turn `setActiveTools` calls, and first-appearance
7
+ * transcript replay — while leaving non-owned tools and provider-specific markers in place.
8
+ */
9
+
10
+ function isRecord(value: unknown): value is Record<string, unknown> {
11
+ return typeof value === "object" && value !== null && !Array.isArray(value);
12
+ }
13
+
14
+ /** True when two tool-name lists have the same length and the same entries in order. */
15
+ export function sameToolList(left: readonly string[], right: readonly string[]): boolean {
16
+ if (left.length !== right.length) return false;
17
+ return left.every((name, index) => name === right[index]);
18
+ }
19
+
20
+ /** Compare strings by Unicode code point, not by UTF-16 code unit. */
21
+ export function compareCodePoints(a: string, b: string): number {
22
+ const left = Array.from(a, (ch) => ch.codePointAt(0) ?? 0);
23
+ const right = Array.from(b, (ch) => ch.codePointAt(0) ?? 0);
24
+ const shared = Math.min(left.length, right.length);
25
+ for (let i = 0; i < shared; i++) {
26
+ const diff = (left[i] ?? 0) - (right[i] ?? 0);
27
+ if (diff !== 0) return diff;
28
+ }
29
+ return left.length - right.length;
30
+ }
31
+
32
+ /**
33
+ * Sort the entries `isOwned` selects into name order inside the slots they already occupy, and
34
+ * return `undefined` when the result is identical to `entries`.
35
+ *
36
+ * WHY: this bridge cannot move what it does not own — another extension's tools keep the position
37
+ * they were given, and so does Pi's trailing Anthropic `__pi_deferred_placeholder__`, which Pi
38
+ * requires last — while the bridge's own tools, whose insertion order depends on which server
39
+ * connected first and on `tools/list` order, end up in one deterministic order (#278).
40
+ */
41
+ export function orderOwnedEntries<T>(
42
+ entries: readonly T[],
43
+ nameOf: (entry: T) => string | undefined,
44
+ isOwned: (name: string) => boolean,
45
+ ): T[] | undefined {
46
+ const owned: Array<{ slot: number; name: string; entry: T }> = [];
47
+ entries.forEach((entry, slot) => {
48
+ const name = nameOf(entry);
49
+ if (name !== undefined && isOwned(name)) owned.push({ slot, name, entry });
50
+ });
51
+ if (owned.length < 2) return undefined;
52
+
53
+ const slots = owned.map((candidate) => candidate.slot);
54
+ owned.sort((left, right) => compareCodePoints(left.name, right.name));
55
+ const ordered = [...entries];
56
+ owned.forEach((candidate, index) => {
57
+ const slot = slots[index];
58
+ if (slot === undefined) return;
59
+ ordered[slot] = candidate.entry;
60
+ });
61
+ const unchanged = ordered.every((entry, index) => entry === entries[index]);
62
+ return unchanged ? undefined : ordered;
63
+ }
64
+
65
+ function nestedStringField(
66
+ record: Record<string, unknown>,
67
+ key: string,
68
+ field: string,
69
+ ): string | undefined {
70
+ const nested = record[key];
71
+ if (!isRecord(nested)) return undefined;
72
+ const value = nested[field];
73
+ return typeof value === "string" ? value : undefined;
74
+ }
75
+
76
+ /**
77
+ * Name of a provider tool definition: `{ name }` (Anthropic, OpenAI/Azure/Codex Responses,
78
+ * Gemini `functionDeclarations`, `pi-messages` `toolsAdded`), `{ function: { name } }`
79
+ * (OpenAI Chat Completions, Mistral), or `{ toolSpec: { name } }` (AWS Bedrock Converse).
80
+ */
81
+ function payloadToolName(definition: unknown): string | undefined {
82
+ if (!isRecord(definition)) return undefined;
83
+ const name = definition["name"];
84
+ if (typeof name === "string") return name;
85
+ return (
86
+ nestedStringField(definition, "function", "name") ??
87
+ nestedStringField(definition, "toolSpec", "name")
88
+ );
89
+ }
90
+
91
+ /**
92
+ * Keep a slot's `cache_control` breakpoint on that slot when another tool definition moves into
93
+ * it: Pi's Anthropic and OpenAI-completions adapters attach `cache_control` to the last tool
94
+ * slot before `before_provider_request` runs, so moving that object earlier would strand later
95
+ * tools outside the cached prefix and diverge from a session that started in sorted order.
96
+ */
97
+ function withSlotCacheControl(entry: unknown, slotEntry: unknown): unknown {
98
+ const entryRecord = entry as Record<string, unknown>;
99
+ const slotCache = (slotEntry as { cache_control?: unknown }).cache_control;
100
+ if (entryRecord["cache_control"] === slotCache) return entry;
101
+ if (slotCache === undefined) {
102
+ const { cache_control: _dropped, ...rest } = entryRecord;
103
+ return rest;
104
+ }
105
+ return { ...entryRecord, cache_control: slotCache };
106
+ }
107
+
108
+ /** Order one tool-definition array in place of its owned slots, keeping slot `cache_control`. */
109
+ function orderDefinitionList(
110
+ definitions: unknown,
111
+ isOwned: (name: string) => boolean,
112
+ ): unknown[] | undefined {
113
+ if (!Array.isArray(definitions) || definitions.length === 0) return undefined;
114
+ const ordered = orderOwnedEntries(definitions, payloadToolName, isOwned);
115
+ if (ordered === undefined) return undefined;
116
+ return ordered.map((entry, index) =>
117
+ entry === definitions[index] ? entry : withSlotCacheControl(entry, definitions[index]),
118
+ );
119
+ }
120
+
121
+ /** Order one Gemini `Tool` entry's `functionDeclarations` array when present. */
122
+ function orderGoogleToolGroup(
123
+ group: unknown,
124
+ isOwned: (name: string) => boolean,
125
+ ): unknown {
126
+ if (!isRecord(group)) return group;
127
+ const ordered = orderDefinitionList(group["functionDeclarations"], isOwned);
128
+ return ordered === undefined ? group : { ...group, functionDeclarations: ordered };
129
+ }
130
+
131
+ /** Order Gemini / Vertex `config.tools[].functionDeclarations` without mutating untouched groups. */
132
+ function orderGoogleConfigTools(
133
+ config: unknown,
134
+ isOwned: (name: string) => boolean,
135
+ ): Record<string, unknown> | undefined {
136
+ if (!isRecord(config) || !Array.isArray(config["tools"])) return undefined;
137
+ const tools = config["tools"];
138
+ const nextTools = tools.map((group) => orderGoogleToolGroup(group, isOwned));
139
+ const changed = nextTools.some((group, index) => group !== tools[index]);
140
+ return changed ? { ...config, tools: nextTools } : undefined;
141
+ }
142
+
143
+ /** Order Bedrock Converse `toolConfig.tools` (`{ toolSpec: { name } }`) when present. */
144
+ function orderBedrockToolConfig(
145
+ toolConfig: unknown,
146
+ isOwned: (name: string) => boolean,
147
+ ): Record<string, unknown> | undefined {
148
+ if (!isRecord(toolConfig)) return undefined;
149
+ const ordered = orderDefinitionList(toolConfig["tools"], isOwned);
150
+ return ordered === undefined ? undefined : { ...toolConfig, tools: ordered };
151
+ }
152
+
153
+ /** Order `toolsAdded` on one `pi-messages` `system` message while leaving other messages as is. */
154
+ function orderSystemMessageTools(
155
+ message: unknown,
156
+ isOwned: (name: string) => boolean,
157
+ ): unknown {
158
+ if (!isRecord(message) || message["role"] !== "system") return message;
159
+ const ordered = orderDefinitionList(message["toolsAdded"], isOwned);
160
+ return ordered === undefined ? message : { ...message, toolsAdded: ordered };
161
+ }
162
+
163
+ /**
164
+ * Order `pi-messages` `context.messages[].toolsAdded` within each `system` message without
165
+ * moving declarations across turns or mutating untouched messages.
166
+ */
167
+ function orderPiMessagesContext(
168
+ context: unknown,
169
+ isOwned: (name: string) => boolean,
170
+ ): Record<string, unknown> | undefined {
171
+ if (!isRecord(context) || !Array.isArray(context["messages"])) return undefined;
172
+ const messages = context["messages"];
173
+ const nextMessages = messages.map((message) => orderSystemMessageTools(message, isOwned));
174
+ const changed = nextMessages.some((message, index) => message !== messages[index]);
175
+ return changed ? { ...context, messages: nextMessages } : undefined;
176
+ }
177
+
178
+ /**
179
+ * Order nested provider tool containers: Bedrock `toolConfig.tools`, Google `config.tools`,
180
+ * or `pi-messages` `context.messages[].toolsAdded`.
181
+ */
182
+ function orderNestedPayloadTools(
183
+ payload: Record<string, unknown>,
184
+ isOwned: (name: string) => boolean,
185
+ ): Record<string, unknown> | undefined {
186
+ const orderedToolConfig = orderBedrockToolConfig(payload["toolConfig"], isOwned);
187
+ if (orderedToolConfig !== undefined) return { ...payload, toolConfig: orderedToolConfig };
188
+
189
+ const orderedGoogleConfig = orderGoogleConfigTools(payload["config"], isOwned);
190
+ if (orderedGoogleConfig !== undefined) return { ...payload, config: orderedGoogleConfig };
191
+
192
+ const orderedContext = orderPiMessagesContext(payload["context"], isOwned);
193
+ return orderedContext === undefined ? undefined : { ...payload, context: orderedContext };
194
+ }
195
+
196
+ /**
197
+ * Order owned tool definitions in an outgoing provider payload across all 10 built-in Pi API
198
+ * payload shapes, returning `payload` untouched when no owned slots move.
199
+ */
200
+ export function orderPayloadToolEntries(
201
+ payload: unknown,
202
+ isOwned: (name: string) => boolean,
203
+ ): unknown {
204
+ if (!isRecord(payload)) return payload;
205
+ const orderedTopLevel = orderDefinitionList(payload["tools"], isOwned);
206
+ if (orderedTopLevel !== undefined) return { ...payload, tools: orderedTopLevel };
207
+ return orderNestedPayloadTools(payload, isOwned) ?? payload;
208
+ }