@fabric-harness/sdk 6.4.0 → 6.5.0

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 (149) hide show
  1. package/connector-spec/voice-telephony.md +120 -104
  2. package/dist/agent-route.d.ts +20 -2
  3. package/dist/agent-route.d.ts.map +1 -1
  4. package/dist/agent-route.js +31 -1
  5. package/dist/agent-route.js.map +1 -1
  6. package/dist/agent-router.d.ts +42 -0
  7. package/dist/agent-router.d.ts.map +1 -1
  8. package/dist/agent-router.js +49 -1
  9. package/dist/agent-router.js.map +1 -1
  10. package/dist/agent.d.ts.map +1 -1
  11. package/dist/agent.js +3 -0
  12. package/dist/agent.js.map +1 -1
  13. package/dist/attachment-store.d.ts +69 -0
  14. package/dist/attachment-store.d.ts.map +1 -1
  15. package/dist/attachment-store.js +183 -14
  16. package/dist/attachment-store.js.map +1 -1
  17. package/dist/attachments.d.ts +136 -0
  18. package/dist/attachments.d.ts.map +1 -0
  19. package/dist/attachments.js +332 -0
  20. package/dist/attachments.js.map +1 -0
  21. package/dist/channel.d.ts.map +1 -1
  22. package/dist/channel.js +26 -3
  23. package/dist/channel.js.map +1 -1
  24. package/dist/conversation-history.d.ts +186 -0
  25. package/dist/conversation-history.d.ts.map +1 -0
  26. package/dist/conversation-history.js +481 -0
  27. package/dist/conversation-history.js.map +1 -0
  28. package/dist/conversation-ui.d.ts +43 -2
  29. package/dist/conversation-ui.d.ts.map +1 -1
  30. package/dist/conversation-ui.js +44 -14
  31. package/dist/conversation-ui.js.map +1 -1
  32. package/dist/cost-budget.d.ts +50 -0
  33. package/dist/cost-budget.d.ts.map +1 -1
  34. package/dist/cost-budget.js +74 -4
  35. package/dist/cost-budget.js.map +1 -1
  36. package/dist/cost-enforcement.d.ts +32 -0
  37. package/dist/cost-enforcement.d.ts.map +1 -0
  38. package/dist/cost-enforcement.js +116 -0
  39. package/dist/cost-enforcement.js.map +1 -0
  40. package/dist/delivered-message.d.ts +20 -6
  41. package/dist/delivered-message.d.ts.map +1 -1
  42. package/dist/delivered-message.js +37 -8
  43. package/dist/delivered-message.js.map +1 -1
  44. package/dist/events.d.ts +13 -1
  45. package/dist/events.d.ts.map +1 -1
  46. package/dist/events.js.map +1 -1
  47. package/dist/experimental.d.ts +2 -2
  48. package/dist/experimental.d.ts.map +1 -1
  49. package/dist/experimental.js +1 -1
  50. package/dist/experimental.js.map +1 -1
  51. package/dist/governed-voice.d.ts +6 -0
  52. package/dist/governed-voice.d.ts.map +1 -1
  53. package/dist/governed-voice.js +142 -35
  54. package/dist/governed-voice.js.map +1 -1
  55. package/dist/history.d.ts +3 -2
  56. package/dist/history.d.ts.map +1 -1
  57. package/dist/history.js +57 -23
  58. package/dist/history.js.map +1 -1
  59. package/dist/index.d.ts +21 -14
  60. package/dist/index.d.ts.map +1 -1
  61. package/dist/index.js +11 -7
  62. package/dist/index.js.map +1 -1
  63. package/dist/loop.d.ts +25 -2
  64. package/dist/loop.d.ts.map +1 -1
  65. package/dist/loop.js +409 -60
  66. package/dist/loop.js.map +1 -1
  67. package/dist/model-pricing.d.ts +77 -4
  68. package/dist/model-pricing.d.ts.map +1 -1
  69. package/dist/model-pricing.js +259 -18
  70. package/dist/model-pricing.js.map +1 -1
  71. package/dist/model.d.ts +115 -3
  72. package/dist/model.d.ts.map +1 -1
  73. package/dist/model.js +376 -57
  74. package/dist/model.js.map +1 -1
  75. package/dist/pi-document-attachments.d.ts +43 -0
  76. package/dist/pi-document-attachments.d.ts.map +1 -0
  77. package/dist/pi-document-attachments.js +155 -0
  78. package/dist/pi-document-attachments.js.map +1 -0
  79. package/dist/pi-loop-runtime.d.ts +103 -1
  80. package/dist/pi-loop-runtime.d.ts.map +1 -1
  81. package/dist/pi-loop-runtime.js +850 -109
  82. package/dist/pi-loop-runtime.js.map +1 -1
  83. package/dist/prompt-attachments.d.ts +98 -0
  84. package/dist/prompt-attachments.d.ts.map +1 -0
  85. package/dist/prompt-attachments.js +279 -0
  86. package/dist/prompt-attachments.js.map +1 -0
  87. package/dist/session.d.ts +52 -0
  88. package/dist/session.d.ts.map +1 -1
  89. package/dist/session.js +410 -33
  90. package/dist/session.js.map +1 -1
  91. package/dist/stream-chunks.d.ts +15 -1
  92. package/dist/stream-chunks.d.ts.map +1 -1
  93. package/dist/stream-chunks.js +39 -18
  94. package/dist/stream-chunks.js.map +1 -1
  95. package/dist/strict.d.ts +23 -16
  96. package/dist/strict.d.ts.map +1 -1
  97. package/dist/strict.js +12 -8
  98. package/dist/strict.js.map +1 -1
  99. package/dist/submission-context.d.ts +7 -0
  100. package/dist/submission-context.d.ts.map +1 -1
  101. package/dist/submission-context.js.map +1 -1
  102. package/dist/submission-runner.d.ts +5 -0
  103. package/dist/submission-runner.d.ts.map +1 -1
  104. package/dist/submission-runner.js +11 -2
  105. package/dist/submission-runner.js.map +1 -1
  106. package/dist/types.d.ts +26 -0
  107. package/dist/types.d.ts.map +1 -1
  108. package/dist/types.js.map +1 -1
  109. package/dist/usage-completeness.d.ts +39 -0
  110. package/dist/usage-completeness.d.ts.map +1 -0
  111. package/dist/usage-completeness.js +135 -0
  112. package/dist/usage-completeness.js.map +1 -0
  113. package/dist/voice-openai-realtime.d.ts +24 -2
  114. package/dist/voice-openai-realtime.d.ts.map +1 -1
  115. package/dist/voice-openai-realtime.js +266 -49
  116. package/dist/voice-openai-realtime.js.map +1 -1
  117. package/dist/voice-pipeline.d.ts +81 -3
  118. package/dist/voice-pipeline.d.ts.map +1 -1
  119. package/dist/voice-pipeline.js +429 -60
  120. package/dist/voice-pipeline.js.map +1 -1
  121. package/dist/voice-stt-cartesia.d.ts +8 -0
  122. package/dist/voice-stt-cartesia.d.ts.map +1 -1
  123. package/dist/voice-stt-cartesia.js +77 -17
  124. package/dist/voice-stt-cartesia.js.map +1 -1
  125. package/dist/voice-stt-deepgram.d.ts +10 -2
  126. package/dist/voice-stt-deepgram.d.ts.map +1 -1
  127. package/dist/voice-stt-deepgram.js +78 -18
  128. package/dist/voice-stt-deepgram.js.map +1 -1
  129. package/dist/voice-stt.d.ts +13 -3
  130. package/dist/voice-stt.d.ts.map +1 -1
  131. package/dist/voice-tts-cartesia.d.ts +8 -0
  132. package/dist/voice-tts-cartesia.d.ts.map +1 -1
  133. package/dist/voice-tts-cartesia.js +48 -105
  134. package/dist/voice-tts-cartesia.js.map +1 -1
  135. package/dist/voice-tts-elevenlabs.d.ts +10 -1
  136. package/dist/voice-tts-elevenlabs.d.ts.map +1 -1
  137. package/dist/voice-tts-elevenlabs.js +50 -113
  138. package/dist/voice-tts-elevenlabs.js.map +1 -1
  139. package/dist/voice-ws-client.js +16 -3
  140. package/dist/voice-ws-client.js.map +1 -1
  141. package/dist/voice-ws-shared.d.ts +205 -6
  142. package/dist/voice-ws-shared.d.ts.map +1 -1
  143. package/dist/voice-ws-shared.js +510 -15
  144. package/dist/voice-ws-shared.js.map +1 -1
  145. package/dist/voice.d.ts +98 -4
  146. package/dist/voice.d.ts.map +1 -1
  147. package/dist/voice.js +71 -1
  148. package/dist/voice.js.map +1 -1
  149. package/package.json +3 -3
@@ -1,8 +1,35 @@
1
1
  import { Agent } from "@earendil-works/pi-agent-core";
2
- import { createModels, Type } from "@earendil-works/pi-ai";
2
+ import { createAssistantMessageEventStream, createModels, toToolDeclaration, Type, } from "@earendil-works/pi-ai";
3
3
  import { builtinProviders } from "@earendil-works/pi-ai/providers/all";
4
- import { defaultLoopRuntime } from "./loop.js";
4
+ import { hasPriceableUsage, isValidCostUsd } from "./cost-budget.js";
5
+ import { enforceCallCost, enforcePendingScopeViolation, } from "./cost-enforcement.js";
6
+ import { isContextOverflowError } from "./context-budget.js";
7
+ import { FabricError } from "./error.js";
8
+ import { defaultLoopRuntime, mapModelError } from "./loop.js";
9
+ import { estimateModelCost, isModelPriceKnown, warnUnknownModelPrice, } from "./model-pricing.js";
5
10
  import { evaluateToolCallPolicy } from "./policy.js";
11
+ import { calculateRetryDelay, isRetryableModelError, MAX_TRANSIENT_MODEL_RETRIES, sleepWithAbort, TRANSIENT_MODEL_RETRY_BASE_DELAY_MS, } from "./model.js";
12
+ import { prepareDocumentRequest } from "./pi-document-attachments.js";
13
+ import { attachmentOmittedPlaceholder, collectAttachmentPayloads, isNativeImageMimeType, redactAttachmentPayloads, } from "./attachments.js";
14
+ /**
15
+ * Name of the Pi system-prompt section that carries Harness's system
16
+ * instruction. Pi 0.86+ keeps the prompt in transcript system messages; a
17
+ * later message that replaces this section is how a refreshed instruction
18
+ * takes effect mid-run.
19
+ */
20
+ const FABRIC_SYSTEM_SECTION = "fabric-harness";
21
+ const DEFAULT_MAX_CACHED_AGENTS = 256;
22
+ /** Native-loop default for `PromptRunInput.maxIterations`. */
23
+ const DEFAULT_MAX_ITERATIONS = 8;
24
+ const DYNAMIC_MODELS = new WeakSet();
25
+ /**
26
+ * Whether a Pi model object was synthesized by Harness with zero metadata
27
+ * instead of coming from the Pi catalog. Such models report `$0` cost
28
+ * because their price is unknown, not because they are free.
29
+ */
30
+ export function isDynamicModel(model) {
31
+ return DYNAMIC_MODELS.has(model);
32
+ }
6
33
  export class PiAgentLoopRuntime {
7
34
  name = "pi-agent-core";
8
35
  options;
@@ -16,6 +43,38 @@ export class PiAgentLoopRuntime {
16
43
  this.models.setProvider(provider);
17
44
  }
18
45
  }
46
+ /**
47
+ * Resolve a `provider/model` reference the same way `runPrompt` does and
48
+ * describe its catalog metadata, including whether its cost is known.
49
+ */
50
+ describeModel(modelRef) {
51
+ const model = this.resolvePiModel(modelRef);
52
+ const dynamic = isDynamicModel(model);
53
+ const tiers = model.cost.tiers?.map((tier) => ({
54
+ inputTokensAbove: tier.inputTokensAbove,
55
+ inputPerMTok: tier.input,
56
+ outputPerMTok: tier.output,
57
+ cacheReadPerMTok: tier.cacheRead,
58
+ cacheWritePerMTok: tier.cacheWrite,
59
+ }));
60
+ return {
61
+ provider: model.provider,
62
+ id: model.id,
63
+ api: model.api,
64
+ contextWindow: model.contextWindow,
65
+ maxTokens: model.maxTokens,
66
+ reasoning: model.reasoning,
67
+ cost: {
68
+ inputPerMTok: model.cost.input,
69
+ outputPerMTok: model.cost.output,
70
+ cacheReadPerMTok: model.cost.cacheRead,
71
+ cacheWritePerMTok: model.cost.cacheWrite,
72
+ ...(tiers?.length ? { tiers } : {}),
73
+ },
74
+ dynamic,
75
+ costKnown: !dynamic || isModelPriceKnown(`${model.provider}/${model.id}`),
76
+ };
77
+ }
19
78
  async runPrompt(input) {
20
79
  if (input.toolCalls?.length)
21
80
  return defaultLoopRuntime.runPrompt(input);
@@ -46,68 +105,140 @@ export class PiAgentLoopRuntime {
46
105
  await applyTurnRefresh();
47
106
  this.callPolicies.set(input.sessionId, input.policy);
48
107
  let selectedModel = this.resolvePiModel(input.model ?? this.options.model);
49
- const { systemPrompt, messages } = splitSystemMessages(historyBeforeCurrentPrompt(input.messages, input.text), selectedModel);
108
+ const { history, current } = historyBeforeCurrentPrompt(input.messages, input.text);
109
+ let declaredSystemPrompt = systemInstructionOf(history);
50
110
  const tools = [...input.tools.values()].map((tool) => this.toPiTool(tool, input));
111
+ const messages = [
112
+ ...leadingSystemMessage(declaredSystemPrompt, tools),
113
+ ...convertMessagesToPi(history.filter((message) => message.role !== "system"), selectedModel),
114
+ ];
51
115
  // pi-ai owns per-model capability detection and wire mapping for reasoning
52
116
  // (OpenAI `reasoning_effort`, Anthropic thinking budgets, Gemini
53
117
  // thinkingConfig). We pass the requested level through and let it clamp.
54
118
  const thinkingLevel = input.thinkingLevel ?? "off";
55
- // Try to reuse a cached Agent for this session
119
+ const costContext = {
120
+ ...(input.costBudget ? { costBudget: input.costBudget } : {}),
121
+ ...(input.requestCostLimitApproval
122
+ ? { requestCostLimitApproval: input.requestCostLimitApproval }
123
+ : {}),
124
+ emit: input.emit,
125
+ };
126
+ // Hooks and listeners must not reject inside Pi's loop unnoticed: Pi
127
+ // records a generic failed turn. Keep the first Harness error and rethrow
128
+ // it intact once the run settles.
129
+ let hookError;
130
+ const capture = async (run) => {
131
+ try {
132
+ return await run();
133
+ }
134
+ catch (error) {
135
+ hookError ??= error;
136
+ throw error;
137
+ }
138
+ };
139
+ let latestUsage;
140
+ // Captured from events: a concurrent dispose() may reset the agent's
141
+ // transcript before this call reads it back.
142
+ let finalAssistant;
143
+ // Callbacks that outlive the run (the cached agent's `beforeToolCall`)
144
+ // are built outside this function and capture only the session id;
145
+ // per-run hooks that capture `input` are detached when the run settles.
146
+ const sessionId = input.sessionId;
147
+ const runToken = {};
148
+ // Try to reuse a cached Agent for this session (and mark it most recent).
56
149
  let agent = this.agents.get(input.sessionId);
57
- const prepareNextTurnWithContext = async (context) => {
58
- const previousToolNames = new Set((context.context.tools ?? []).map((tool) => tool.name));
150
+ if (agent) {
151
+ this.agents.delete(input.sessionId);
152
+ this.agents.set(input.sessionId, agent);
153
+ }
154
+ // Pi 0.84.4+ only prepares a turn that will actually start, so steering
155
+ // admitted while the final turn streamed is drained here, after every
156
+ // completed turn, where queuing it makes Pi start another turn.
157
+ const finishTurn = (turn) => capture(async () => {
158
+ if (hookError !== undefined)
159
+ return { action: "end" };
160
+ const stopReason = turn.message.stopReason;
161
+ if (stopReason === "error" || stopReason === "aborted" || input.signal?.aborted)
162
+ return undefined;
59
163
  const steering = (await input.takeSteeringMessages?.()) ?? [];
164
+ const currentAgent = agent;
165
+ if (!currentAgent)
166
+ throw new Error("Pi agent was not initialized before turn completion.");
167
+ for (const message of convertMessagesToPi(steering, selectedModel))
168
+ currentAgent.steer(message);
169
+ return undefined;
170
+ });
171
+ const prepareNextTurnWithContext = (context) => capture(async () => {
172
+ const previousToolNames = new Set((context.context.tools ?? []).map((tool) => tool.name));
60
173
  await applyTurnRefresh();
61
174
  selectedModel = this.resolvePiModel(input.model ?? this.options.model);
62
175
  const nextTools = [...input.tools.values()].map((tool) => this.toPiTool(tool, input));
63
- const systemInstruction = input.messages
64
- .filter((message) => message.role === "system")
65
- .map((message) => message.content)
66
- .join("\n\n");
67
- context.context.tools = nextTools;
68
- context.context.systemPrompt = systemInstruction;
176
+ const systemInstruction = systemInstructionOf(input.messages);
69
177
  const currentAgent = agent;
70
178
  if (!currentAgent)
71
179
  throw new Error("Pi agent was not initialized before turn preparation.");
72
180
  currentAgent.state.model = selectedModel;
73
181
  currentAgent.state.tools = nextTools;
74
182
  currentAgent.state.thinkingLevel = input.thinkingLevel ?? "off";
75
- currentAgent.state.systemPrompt = systemInstruction;
76
183
  this.callPolicies.set(input.sessionId, input.policy);
77
- // Adapted from Flue v2.0.2: additions unlocked by a tool batch ride its
78
- // final result. Pi providers can defer those definitions beyond their
79
- // cached prefix; the durable signal below restores the same marker.
184
+ // Adapted from Flue v2.0.2: additions unlocked by a tool batch are
185
+ // recorded against its final result so replayed history restores the
186
+ // cache-safe marker. Pi 0.86+ declares the additions to the model
187
+ // itself with a transcript system message (`toolsAdded`).
80
188
  const addedToolNames = nextTools
81
189
  .map((tool) => tool.name)
82
190
  .filter((name) => !previousToolNames.has(name));
83
191
  const anchor = context.toolResults.at(-1);
84
192
  if (anchor && addedToolNames.length > 0) {
85
- anchor.addedToolNames = addedToolNames;
86
193
  await input.recordToolAdditions?.(anchor.toolCallId, addedToolNames);
87
194
  }
88
- for (const message of convertMessagesToPi(steering, selectedModel))
89
- currentAgent.steer(message);
195
+ const prepared = [];
196
+ if (systemInstruction !== declaredSystemPrompt) {
197
+ prepared.push(systemPromptUpdate(systemInstruction));
198
+ declaredSystemPrompt = systemInstruction;
199
+ }
90
200
  return {
91
- context: context.context,
201
+ context: { ...context.context, tools: nextTools },
202
+ ...(prepared.length > 0 ? { messages: prepared } : {}),
92
203
  model: selectedModel,
93
204
  thinkingLevel: input.thinkingLevel ?? "off",
94
205
  };
95
- };
206
+ });
207
+ // Same bound and error as the native loop: at most `maxIterations`
208
+ // provider requests per prompt. Tool calls from the last allowed request
209
+ // still execute; the run fails before another request would start.
210
+ const maxIterations = input.maxIterations ?? DEFAULT_MAX_ITERATIONS;
211
+ let providerRequests = 0;
212
+ // Runs before every provider request, including the first: a lagged
213
+ // external-scope budget violation stops the run before the next call.
214
+ const prepareRequest = () => capture(async () => {
215
+ providerRequests += 1;
216
+ if (providerRequests > maxIterations) {
217
+ throw new FabricError({
218
+ code: "MODEL_CONTEXT_OVERFLOW",
219
+ message: `Prompt exceeded maxIterations (${maxIterations}) without a final response.`,
220
+ retryable: true,
221
+ });
222
+ }
223
+ await Promise.resolve();
224
+ await enforcePendingScopeViolation(costContext);
225
+ return undefined;
226
+ });
96
227
  if (agent) {
97
- // Update the cached agent's tools, system prompt, and thinking level for this call
228
+ if (agent.state.isStreaming)
229
+ throw new Error(`Pi agent for session ${input.sessionId} is already processing a prompt.`);
230
+ // Update the cached agent's transcript, tools, and thinking level for this call
98
231
  agent.state.tools = tools;
99
- agent.state.systemPrompt = systemPrompt;
100
232
  agent.state.thinkingLevel = thinkingLevel;
101
233
  agent.state.model = selectedModel;
102
234
  agent.state.messages = messages;
103
- agent.prepareNextTurnWithContext = prepareNextTurnWithContext;
235
+ agent.clearAllQueues();
104
236
  }
105
237
  else {
106
238
  // Create a new agent for this session
107
239
  agent = new Agent({
108
240
  sessionId: input.sessionId,
109
241
  initialState: {
110
- systemPrompt,
111
242
  model: selectedModel,
112
243
  tools,
113
244
  messages,
@@ -115,73 +246,349 @@ export class PiAgentLoopRuntime {
115
246
  },
116
247
  ...(this.options.getApiKey ? { getApiKey: this.options.getApiKey } : {}),
117
248
  ...(this.options.toolExecution ? { toolExecution: this.options.toolExecution } : {}),
118
- streamFn: this.models.streamSimple.bind(this.models),
119
- beforeToolCall: async (context) => {
120
- const decision = evaluateToolCallPolicy({ tool: context.toolCall.name, input: context.args }, this.callPolicies.get(input.sessionId));
121
- if (!decision.allowed)
122
- return {
123
- block: true,
124
- reason: decision.reason ?? `Tool call denied by policy: ${context.toolCall.name}`,
125
- };
126
- return undefined;
127
- },
128
- prepareNextTurnWithContext,
249
+ // Replaced per run below with the request's timeout and retry controls.
250
+ streamFn: this.createStreamFn(input),
251
+ steeringMode: "all",
252
+ ...(this.options.onPayload ? { onPayload: this.options.onPayload } : {}),
253
+ beforeToolCall: this.createPolicyGate(sessionId),
129
254
  });
130
255
  this.agents.set(input.sessionId, agent);
256
+ this.evictIdleAgents(input.sessionId);
131
257
  }
258
+ RUN_OWNERS.set(agent, runToken);
259
+ agent.streamFunction = this.createStreamFn(input);
260
+ agent.finishTurn = finishTurn;
261
+ agent.prepareRequest = prepareRequest;
262
+ agent.prepareNextTurnWithContext = prepareNextTurnWithContext;
132
263
  // Subscribe to events for this call
133
264
  const unsubscribe = agent.subscribe(async (event) => {
134
265
  await emitPiEvent(event, input);
266
+ if (event.type !== "message_end" || !isAssistantMessage(event.message))
267
+ return;
268
+ const message = event.message;
269
+ finalAssistant = message;
270
+ if (message.stopReason === "error" || message.stopReason === "aborted")
271
+ return;
272
+ const modelRef = `${message.provider}/${message.model}`;
273
+ const usage = toFabricUsage(message.usage, selectedModel, producedOutput(message));
274
+ const attribution = {
275
+ ...(input.agentId ? { agentId: input.agentId } : {}),
276
+ ...(input.tenantId ? { tenantId: input.tenantId } : {}),
277
+ model: input.model ?? modelRef,
278
+ provider: message.provider,
279
+ sessionId: input.sessionId,
280
+ };
281
+ usage.attribution = attribution;
282
+ latestUsage = usage;
283
+ // Awaited before Pi executes this response's tool calls, matching the
284
+ // native loop's check between the model response and tool execution.
285
+ await capture(() => enforceCallCost(costContext, usage, input.model ?? modelRef, attribution));
135
286
  });
136
287
  // Handle abort signal
137
288
  let abortListener;
138
289
  if (input.signal) {
139
- if (input.signal.aborted)
140
- agent.abort();
141
290
  abortListener = () => agent.abort();
142
291
  input.signal.addEventListener("abort", abortListener, { once: true });
143
292
  }
293
+ const runAgent = agent;
144
294
  try {
145
- await agent.prompt(input.text);
146
- await agent.waitForIdle();
295
+ try {
296
+ if (input.signal?.aborted)
297
+ throw abortErrorFor(input.signal);
298
+ if (current?.attachments?.length) {
299
+ await runAgent.prompt({
300
+ role: "user",
301
+ content: toPiUserContent(current, selectedModel.api),
302
+ timestamp: Date.now(),
303
+ });
304
+ }
305
+ else {
306
+ await runAgent.prompt(input.text);
307
+ }
308
+ await runAgent.waitForIdle();
309
+ }
310
+ finally {
311
+ unsubscribe();
312
+ if (abortListener && input.signal) {
313
+ input.signal.removeEventListener("abort", abortListener);
314
+ }
315
+ this.callPolicies.delete(input.sessionId);
316
+ }
317
+ if (hookError !== undefined)
318
+ throw hookError;
319
+ // Extract the final assistant response from the agent's message history
320
+ const latestAssistant = finalAssistant ?? [...runAgent.state.messages].reverse().find(isAssistantMessage);
321
+ throwForPiStopReason(latestAssistant, runAgent.state.errorMessage, input.signal, [
322
+ ...collectAttachmentPayloads(input.messages),
323
+ ...piAttachmentPayloads(runAgent.state.messages),
324
+ ]);
325
+ const text = latestAssistant ? assistantText(latestAssistant) : "";
326
+ if (text)
327
+ await input.recordEntry("assistant_message", { text });
328
+ await input.recordEntry("result", { result: text });
329
+ await input.emit("prompt_end", { text: input.text, result: text });
330
+ return {
331
+ text,
332
+ raw: text,
333
+ ...(latestUsage ? { usage: latestUsage } : {}),
334
+ };
147
335
  }
148
336
  finally {
149
- unsubscribe();
150
- if (abortListener && input.signal) {
151
- input.signal.removeEventListener("abort", abortListener);
152
- }
153
- this.callPolicies.delete(input.sessionId);
337
+ // The cached agent outlives the run: detach everything that references
338
+ // this run's input (hooks, tools, queued steering) and its hydrated
339
+ // attachment bytes, then re-apply the cache bound now that this agent
340
+ // may be idle. The next run rebuilds all of it from history.
341
+ this.settleRun(runAgent, runToken, sessionId);
154
342
  }
155
- // Extract the final assistant response from the agent's message history
156
- const latestAssistant = [...agent.state.messages].reverse().find(isAssistantMessage);
157
- const text = latestAssistant ? assistantText(latestAssistant) : "";
158
- if (text)
159
- await input.recordEntry("assistant_message", { text });
160
- await input.recordEntry("result", { result: text });
161
- await input.emit("prompt_end", { text: input.text, result: text });
162
- return {
163
- text,
164
- raw: text,
165
- ...(latestAssistant?.usage ? { usage: toFabricUsage(latestAssistant.usage) } : {}),
343
+ }
344
+ /**
345
+ * The cached agent's permanent tool-policy hook. Built outside `runPrompt`
346
+ * so its closure scope holds only the session id: a closure created inside
347
+ * `runPrompt` would share that function's context, which holds the run's
348
+ * `input` and hydrated attachments, for as long as the agent is cached.
349
+ */
350
+ createPolicyGate(sessionId) {
351
+ return async (context) => {
352
+ const decision = evaluateToolCallPolicy({ tool: context.toolCall.name, input: context.args }, this.callPolicies.get(sessionId));
353
+ if (!decision.allowed)
354
+ return {
355
+ block: true,
356
+ reason: decision.reason ?? `Tool call denied by policy: ${context.toolCall.name}`,
357
+ };
358
+ return undefined;
359
+ };
360
+ }
361
+ /**
362
+ * Release one run's state from its cached agent once the agent is idle,
363
+ * and evict idle agents beyond `maxCachedAgents`. Eviction on admission
364
+ * skips busy agents, so without this a burst of concurrent sessions would
365
+ * leave the cache above its bound after every run completed. A newer run
366
+ * that already owns the agent keeps its own state.
367
+ */
368
+ settleRun(agent, runToken, sessionId) {
369
+ const release = () => {
370
+ if (agent.state.isStreaming || RUN_OWNERS.get(agent) !== runToken)
371
+ return;
372
+ RUN_OWNERS.delete(agent);
373
+ detachRunState(agent);
374
+ this.evictIdleAgents(sessionId);
375
+ };
376
+ if (!agent.state.isStreaming) {
377
+ release();
378
+ return;
379
+ }
380
+ void agent
381
+ .waitForIdle()
382
+ .then(release)
383
+ .catch(() => {
384
+ /* nothing to release on a failed run */
385
+ });
386
+ }
387
+ /**
388
+ * Stream function for one run. Rewrites documents into native provider
389
+ * blocks (or placeholders) at the one seam every request crosses, and
390
+ * applies the run's `modelTimeoutMs`, `modelRetries`, and
391
+ * `modelRetryDelayMs`.
392
+ */
393
+ createStreamFn(input) {
394
+ const timeoutMs = input.modelTimeoutMs !== undefined && input.modelTimeoutMs > 0
395
+ ? input.modelTimeoutMs
396
+ : undefined;
397
+ // Harness-level retries replace the provider SDK's own retries only when
398
+ // the caller configured them; otherwise pi-ai's defaults apply.
399
+ const harnessRetries = input.modelRetries !== undefined || input.modelRetryDelayMs !== undefined;
400
+ const retries = harnessRetries
401
+ ? Math.max(0, input.modelRetries ?? MAX_TRANSIENT_MODEL_RETRIES)
402
+ : 0;
403
+ const baseDelayMs = input.modelRetryDelayMs ?? TRANSIENT_MODEL_RETRY_BASE_DELAY_MS;
404
+ return (model, context, options) => {
405
+ const requestOptions = {
406
+ ...options,
407
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
408
+ ...(harnessRetries ? { maxRetries: 0 } : {}),
409
+ };
410
+ if (timeoutMs === undefined && retries === 0) {
411
+ const prepared = prepareDocumentRequest(model, context, requestOptions);
412
+ return this.models.streamSimple(model, prepared.context, prepared.options);
413
+ }
414
+ const out = createAssistantMessageEventStream();
415
+ void this.streamWithControls(out, model, context, requestOptions, {
416
+ input,
417
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
418
+ retries,
419
+ baseDelayMs,
420
+ });
421
+ return out;
166
422
  };
167
423
  }
424
+ /**
425
+ * Run one provider request with a per-attempt deadline and bounded retries.
426
+ * An attempt is retried only when it failed with a transient error before
427
+ * streaming any content, so a retry never duplicates visible output. The
428
+ * deadline aborts the provider request through a signal composed with the
429
+ * run's signal and ends the attempt even if the provider ignores the abort.
430
+ */
431
+ async streamWithControls(out, model, context, options, controls) {
432
+ const outer = options.signal;
433
+ const maxAttempts = controls.retries + 1;
434
+ for (let attempt = 1;; attempt += 1) {
435
+ const deadline = new AbortController();
436
+ let timedOut = false;
437
+ const timer = controls.timeoutMs !== undefined
438
+ ? setTimeout(() => {
439
+ timedOut = true;
440
+ deadline.abort(new Error(`Model call timed out after ${controls.timeoutMs}ms`));
441
+ }, controls.timeoutMs)
442
+ : undefined;
443
+ const signal = outer ? AbortSignal.any([outer, deadline.signal]) : deadline.signal;
444
+ // Ends the attempt on timeout or cancellation even when the provider
445
+ // does not honor the abort signal.
446
+ let onStop;
447
+ const stopped = new Promise((resolve) => {
448
+ onStop = () => resolve("stopped");
449
+ if (signal.aborted)
450
+ resolve("stopped");
451
+ });
452
+ signal.addEventListener("abort", () => onStop?.(), { once: true });
453
+ const held = [];
454
+ let forwarded = false;
455
+ let partial;
456
+ let terminal;
457
+ try {
458
+ const prepared = prepareDocumentRequest(model, context, { ...options, signal });
459
+ const inner = await this.models.streamSimple(model, prepared.context, prepared.options);
460
+ const iterator = inner[Symbol.asyncIterator]();
461
+ for (;;) {
462
+ const next = await Promise.race([iterator.next(), stopped]);
463
+ if (next === "stopped") {
464
+ void iterator.return?.();
465
+ break;
466
+ }
467
+ if (next.done)
468
+ break;
469
+ const event = next.value;
470
+ if (event.type === "done" || event.type === "error") {
471
+ terminal = event;
472
+ break;
473
+ }
474
+ if ("partial" in event)
475
+ partial = event.partial;
476
+ // Hold lifecycle events until the first real output, so an attempt
477
+ // that fails before producing any content can be retried unseen.
478
+ if (!forwarded && !isVisibleOutput(event)) {
479
+ held.push(event);
480
+ continue;
481
+ }
482
+ if (!forwarded) {
483
+ for (const heldEvent of held)
484
+ out.push(heldEvent);
485
+ held.length = 0;
486
+ forwarded = true;
487
+ }
488
+ out.push(event);
489
+ }
490
+ }
491
+ catch (error) {
492
+ terminal = errorEvent(model, error instanceof Error ? error.message : String(error), partial);
493
+ }
494
+ finally {
495
+ if (timer)
496
+ clearTimeout(timer);
497
+ }
498
+ if (outer?.aborted) {
499
+ const aborted = errorEvent(model, "The operation was aborted.", partial);
500
+ terminal ??= { type: "error", reason: "aborted", error: { ...aborted.error, stopReason: "aborted" } };
501
+ }
502
+ else if (timedOut) {
503
+ terminal = errorEvent(model, `Model call timed out after ${controls.timeoutMs}ms`, partial);
504
+ }
505
+ terminal ??= errorEvent(model, "Pi provider stream ended without a final response.", partial);
506
+ const errorMessage = terminal.type === "error" ? terminal.error.errorMessage : undefined;
507
+ const failure = errorMessage !== undefined ? new Error(errorMessage) : undefined;
508
+ const canRetry = terminal.type === "error" &&
509
+ terminal.reason === "error" &&
510
+ failure !== undefined &&
511
+ !forwarded &&
512
+ attempt < maxAttempts &&
513
+ !outer?.aborted &&
514
+ !isContextOverflowError(failure) &&
515
+ isRetryableModelError(failure);
516
+ if (!canRetry) {
517
+ for (const heldEvent of held)
518
+ out.push(heldEvent);
519
+ out.push(terminal);
520
+ out.end();
521
+ return;
522
+ }
523
+ const retryData = {
524
+ provider: model.provider,
525
+ model: model.id,
526
+ attempt,
527
+ maxAttempts,
528
+ status: "retry",
529
+ // Provider errors can echo request content, including attachment
530
+ // base64; the exact payloads this request carried are redacted
531
+ // regardless of length.
532
+ error: redactAttachmentPayloads(errorMessage ?? "", [
533
+ ...collectAttachmentPayloads(controls.input.messages),
534
+ ...piAttachmentPayloads(context.messages),
535
+ ]),
536
+ };
537
+ await controls.input.recordEntry("model_attempt", retryData).catch(() => undefined);
538
+ await controls.input.emit("model_attempt", retryData).catch(() => undefined);
539
+ try {
540
+ const waitMs = calculateRetryDelay(controls.baseDelayMs, attempt);
541
+ if (outer)
542
+ await sleepWithAbort(waitMs, outer);
543
+ else
544
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
545
+ }
546
+ catch {
547
+ const aborted = errorEvent(model, "The operation was aborted.", partial);
548
+ out.push({ type: "error", reason: "aborted", error: { ...aborted.error, stopReason: "aborted" } });
549
+ out.end();
550
+ return;
551
+ }
552
+ }
553
+ }
554
+ /** Drop least recently used idle agents beyond `maxCachedAgents`. */
555
+ evictIdleAgents(keep) {
556
+ const max = Math.max(1, this.options.maxCachedAgents ?? DEFAULT_MAX_CACHED_AGENTS);
557
+ if (this.agents.size <= max)
558
+ return;
559
+ for (const [id, cached] of this.agents) {
560
+ if (this.agents.size <= max)
561
+ break;
562
+ if (id === keep || cached.state.isStreaming)
563
+ continue;
564
+ this.agents.delete(id);
565
+ this.callPolicies.delete(id);
566
+ disposeAgent(cached);
567
+ }
568
+ }
569
+ /** Number of cached per-session agents (for diagnostics and tests). */
570
+ get cachedAgentCount() {
571
+ return this.agents.size;
572
+ }
168
573
  /**
169
574
  * Dispose of cached Agent instances to free resources.
170
575
  * Call with a sessionId to dispose a specific session, or call
171
576
  * without arguments to dispose all sessions.
577
+ *
578
+ * A running agent is aborted first. Pi 0.84.1+ rejects `reset()` during an
579
+ * active run, so a busy agent is dropped from the cache immediately and
580
+ * reset once its run settles.
172
581
  */
173
582
  dispose(sessionId) {
174
- if (sessionId) {
175
- const agent = this.agents.get(sessionId);
176
- if (agent) {
177
- agent.reset();
178
- this.agents.delete(sessionId);
179
- }
180
- }
181
- else {
182
- for (const agent of this.agents.values())
183
- agent.reset();
184
- this.agents.clear();
583
+ const targets = sessionId
584
+ ? [[sessionId, this.agents.get(sessionId)]]
585
+ : [...this.agents.entries()];
586
+ for (const [id, agent] of targets) {
587
+ if (!agent)
588
+ continue;
589
+ this.agents.delete(id);
590
+ this.callPolicies.delete(id);
591
+ disposeAgent(agent);
185
592
  }
186
593
  }
187
594
  resolvePiModel(model) {
@@ -196,7 +603,7 @@ export class PiAgentLoopRuntime {
196
603
  return catalogModel;
197
604
  const custom = this.options.customModels?.[model];
198
605
  if (custom)
199
- return createZeroMetadataModel(modelId, custom.provider, custom.api, custom.baseUrl);
606
+ return createZeroMetadataModel(modelId, custom.provider, custom.api, custom.baseUrl, custom.input);
200
607
  const registered = this.models.getProvider(provider);
201
608
  if (registered) {
202
609
  const template = this.models.getModels(provider)[0];
@@ -218,52 +625,282 @@ export class PiAgentLoopRuntime {
218
625
  return {
219
626
  content: [{ type: "text", text: stringifyForModel(result.output) }],
220
627
  details: result.output,
221
- ...(result.addedToolNames ? { addedToolNames: result.addedToolNames } : {}),
222
628
  ...(result.terminate ? { terminate: true } : {}),
223
629
  };
224
630
  },
225
631
  };
226
632
  }
227
633
  }
634
+ /** Whether a stream event carries model output a consumer would render. */
635
+ function isVisibleOutput(event) {
636
+ if (event.type === "toolcall_start")
637
+ return true;
638
+ if (event.type === "text_delta" || event.type === "thinking_delta" || event.type === "toolcall_delta")
639
+ return event.delta.length > 0;
640
+ return false;
641
+ }
642
+ /** Terminal error event for a request that failed inside the stream wrapper. */
643
+ function errorEvent(model, message, partial) {
644
+ return {
645
+ type: "error",
646
+ reason: "error",
647
+ error: {
648
+ role: "assistant",
649
+ content: partial?.content ?? [],
650
+ api: model.api,
651
+ provider: model.provider,
652
+ model: model.id,
653
+ usage: partial?.usage ?? zeroUsage(),
654
+ stopReason: "error",
655
+ errorMessage: message,
656
+ timestamp: Date.now(),
657
+ },
658
+ };
659
+ }
660
+ /**
661
+ * Replace attachment bytes in a cached agent's transcript with text
662
+ * placeholders once a run settles. A busy agent (a cancelled run still
663
+ * unwinding) is released when it becomes idle.
664
+ */
665
+ /** The run that currently owns each cached agent's per-run hooks. */
666
+ const RUN_OWNERS = new WeakMap();
667
+ /**
668
+ * Stream function left on an idle cached agent. It captures nothing from any
669
+ * run, and fails closed if the agent is ever driven outside `runPrompt()`.
670
+ */
671
+ const detachedStreamFn = (model) => {
672
+ const out = createAssistantMessageEventStream();
673
+ out.push(errorEvent(model, "Pi agent has no active Harness run.", undefined));
674
+ out.end();
675
+ return out;
676
+ };
677
+ /**
678
+ * Drop an idle cached agent's references to the settled run: the hooks and
679
+ * tools that close over its `PromptRunInput` (and so over the hydrated
680
+ * message attachments), queued steering, and image or PDF bytes in the
681
+ * retained transcript. Only the session-scoped `beforeToolCall`, which
682
+ * captures the session id, stays.
683
+ */
684
+ function detachRunState(agent) {
685
+ agent.streamFunction = detachedStreamFn;
686
+ const hooks = agent;
687
+ hooks.finishTurn = undefined;
688
+ hooks.prepareRequest = undefined;
689
+ hooks.prepareNextTurnWithContext = undefined;
690
+ agent.state.tools = [];
691
+ agent.clearAllQueues();
692
+ const messages = agent.state.messages;
693
+ if (messages.some(hasImageContent))
694
+ agent.state.messages = messages.map(stripImageContent);
695
+ }
696
+ /**
697
+ * Base64 payloads carried by Pi transcript messages: images, and documents
698
+ * riding the `ImageContent` carrier. Used to redact echoed request bytes from
699
+ * provider error text by exact match.
700
+ */
701
+ function piAttachmentPayloads(messages) {
702
+ const out = [];
703
+ for (const message of messages) {
704
+ const content = message?.content;
705
+ if (!Array.isArray(content))
706
+ continue;
707
+ for (const part of content) {
708
+ const block = part;
709
+ if (block?.type === "image" && typeof block.data === "string" && block.data.length > 0)
710
+ out.push(block.data);
711
+ }
712
+ }
713
+ return out;
714
+ }
715
+ function hasImageContent(message) {
716
+ const content = message.content;
717
+ return (Array.isArray(content) &&
718
+ content.some((part) => part?.type === "image"));
719
+ }
720
+ function stripImageContent(message) {
721
+ if (!hasImageContent(message))
722
+ return message;
723
+ const content = message.content.map((part) => {
724
+ if (part.type !== "image")
725
+ return part;
726
+ const filename = part.filename;
727
+ return {
728
+ type: "text",
729
+ text: attachmentOmittedPlaceholder({
730
+ kind: part.mimeType.startsWith("image/") ? "image" : "document",
731
+ api: "pi",
732
+ reason: "unavailable",
733
+ ...(typeof filename === "string" ? { filename } : {}),
734
+ }),
735
+ };
736
+ });
737
+ return { ...message, content };
738
+ }
739
+ function disposeAgent(agent) {
740
+ if (!agent.state.isStreaming) {
741
+ agent.reset();
742
+ return;
743
+ }
744
+ agent.abort();
745
+ void agent
746
+ .waitForIdle()
747
+ .then(() => {
748
+ if (!agent.state.isStreaming)
749
+ agent.reset();
750
+ })
751
+ .catch(() => {
752
+ /* the dropped agent is unreachable; nothing to recover */
753
+ });
754
+ }
755
+ /** Map a terminal Pi stop reason to the error the native loop would raise. */
756
+ function throwForPiStopReason(message, stateError, signal, payloads) {
757
+ const stopReason = message?.stopReason;
758
+ if (stopReason === "aborted" || (stopReason === "error" && signal?.aborted)) {
759
+ throw abortErrorFor(signal, message?.errorMessage ?? stateError, payloads);
760
+ }
761
+ if (stopReason === "error") {
762
+ throw mapModelError(new Error(message?.errorMessage ?? stateError ?? "Pi provider request failed."), payloads);
763
+ }
764
+ if (stopReason === "pending" || stopReason === "deferred") {
765
+ throw new FabricError({
766
+ code: "UNKNOWN",
767
+ message: `Pi provider returned an unfinished response (stopReason: ${stopReason}); deferred responses are not supported by PiAgentLoopRuntime.`,
768
+ });
769
+ }
770
+ }
771
+ /** Standard cancellation error carrying the caller's abort reason. */
772
+ function abortErrorFor(signal, fallback, payloads) {
773
+ const reason = signal?.aborted ? signal.reason : undefined;
774
+ const message = reason instanceof Error && reason.message
775
+ ? reason.message
776
+ : typeof reason === "string" && reason
777
+ ? reason
778
+ : // A fallback can be a provider error message echoing request content.
779
+ redactAttachmentPayloads(fallback ?? "The operation was aborted.", payloads);
780
+ const error = new Error(message);
781
+ error.name = "AbortError";
782
+ if (reason !== undefined)
783
+ Object.defineProperty(error, "cause", { value: reason });
784
+ return error;
785
+ }
228
786
  function historyBeforeCurrentPrompt(messages, text) {
229
787
  const history = [...messages];
230
788
  const last = history.at(-1);
231
- if (last?.role === "user" && last.content === text)
789
+ if (last?.role === "user" && last.content === text) {
232
790
  history.pop();
233
- return history;
791
+ return { history, current: last };
792
+ }
793
+ return { history };
234
794
  }
235
- function createZeroMetadataModel(id, provider, api, baseUrl = "") {
236
- return {
795
+ /**
796
+ * Map a user message's text and attachments onto pi `UserMessage` content.
797
+ * Images and documents both ride pi's `ImageContent` carrier (documents are
798
+ * rewritten per API by {@link prepareDocumentRequest}); attachments whose
799
+ * bytes are unavailable, and images whose MIME type is not one every native
800
+ * image adapter accepts, become a text placeholder.
801
+ */
802
+ function toPiUserContent(message, api) {
803
+ const content = [];
804
+ if (message.content)
805
+ content.push({ type: "text", text: message.content });
806
+ for (const attachment of message.attachments ?? []) {
807
+ if (attachment.data === undefined || attachment.data.length === 0) {
808
+ content.push({
809
+ type: "text",
810
+ text: attachmentOmittedPlaceholder({
811
+ kind: attachment.type,
812
+ api: "pi",
813
+ reason: "unavailable",
814
+ ...(attachment.filename !== undefined ? { filename: attachment.filename } : {}),
815
+ }),
816
+ });
817
+ continue;
818
+ }
819
+ if (attachment.type === "image" && !isNativeImageMimeType(attachment.mimeType)) {
820
+ // Same rule as the native adapters: only PNG, JPEG, GIF, and WebP are
821
+ // sent as image content; other image types (BMP, SVG, …) are rejected
822
+ // by providers, so the model sees a placeholder instead.
823
+ content.push({
824
+ type: "text",
825
+ text: attachmentOmittedPlaceholder({
826
+ kind: "image",
827
+ api,
828
+ reason: "unsupported-type",
829
+ mimeType: attachment.mimeType,
830
+ ...(attachment.filename !== undefined ? { filename: attachment.filename } : {}),
831
+ }),
832
+ });
833
+ continue;
834
+ }
835
+ content.push({
836
+ type: "image",
837
+ data: attachment.data,
838
+ mimeType: attachment.mimeType,
839
+ // pi ignores the extra field; the document payload rewrite reads it as the title.
840
+ ...(attachment.type === "document" && attachment.filename !== undefined
841
+ ? { filename: attachment.filename }
842
+ : {}),
843
+ });
844
+ }
845
+ if (content.length === 0)
846
+ content.push({ type: "text", text: "" });
847
+ return content;
848
+ }
849
+ function createZeroMetadataModel(id, provider, api, baseUrl = "", modalities = ["text"]) {
850
+ const model = {
237
851
  id,
238
852
  name: id,
239
853
  provider,
240
- api: api,
854
+ api,
241
855
  baseUrl,
242
856
  reasoning: false,
243
- input: ["text"],
857
+ input: [...modalities],
244
858
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
245
859
  contextWindow: 0,
246
860
  maxTokens: 0,
247
861
  };
862
+ DYNAMIC_MODELS.add(model);
863
+ return model;
248
864
  }
249
865
  export function createPiAgentLoopRuntime(options = {}) {
250
866
  return new PiAgentLoopRuntime(options);
251
867
  }
252
- function splitSystemMessages(messages, model) {
253
- const systemPrompt = messages
868
+ function systemInstructionOf(messages) {
869
+ return messages
254
870
  .filter((message) => message.role === "system")
255
871
  .map((message) => message.content)
256
872
  .join("\n\n");
257
- const nonSystem = messages.filter((message) => message.role !== "system");
873
+ }
874
+ /**
875
+ * Leading Pi transcript system message. Pi 0.86+ carries the system prompt and
876
+ * tool declarations in transcript system messages instead of request fields.
877
+ * The instruction lives in a named section so a refresh can replace it.
878
+ */
879
+ function leadingSystemMessage(systemPrompt, tools) {
880
+ if (!systemPrompt && tools.length === 0)
881
+ return [];
882
+ return [
883
+ {
884
+ role: "system",
885
+ content: "",
886
+ ...(systemPrompt ? { sections: { [FABRIC_SYSTEM_SECTION]: systemPrompt } } : {}),
887
+ ...(tools.length > 0 ? { toolsAdded: tools.map(toToolDeclaration) } : {}),
888
+ timestamp: 0,
889
+ },
890
+ ];
891
+ }
892
+ function systemPromptUpdate(systemPrompt) {
258
893
  return {
259
- systemPrompt,
260
- messages: convertMessagesToPi(nonSystem, model),
894
+ role: "system",
895
+ content: "",
896
+ sections: { [FABRIC_SYSTEM_SECTION]: systemPrompt || null },
897
+ timestamp: Date.now(),
261
898
  };
262
899
  }
263
900
  /**
264
901
  * Convert Fabric ModelMessages to pi-agent-core AgentMessages.
265
- * Handles tool-call round-trips by grouping assistant+toolCall and toolResult messages.
266
- * Uses type assertions where pi-ai's strict union types require it.
902
+ * Assistant tool calls become Pi `ToolCall` blocks (`id`/`name`/`arguments`)
903
+ * with `stopReason: "toolUse"`; tool results carry `isError` through.
267
904
  */
268
905
  function convertMessagesToPi(messages, model) {
269
906
  const result = [];
@@ -275,31 +912,31 @@ function convertMessagesToPi(messages, model) {
275
912
  continue;
276
913
  }
277
914
  if (msg.role === "assistant" && msg.toolCalls?.length) {
278
- // Assistant message with tool calls — cast through unknown for pi-ai's strict content unions
279
- const content = [
280
- ...(msg.content ? [{ type: "text", text: msg.content }] : []),
281
- ...msg.toolCalls.map((tc) => ({
282
- type: "toolCall",
283
- toolCallId: tc.id,
284
- toolName: tc.name,
285
- args: tc.input,
286
- })),
287
- ];
288
- result.push({
915
+ const toolCalls = msg.toolCalls.map((tc) => ({
916
+ type: "toolCall",
917
+ id: tc.id,
918
+ name: tc.name,
919
+ arguments: toToolArguments(tc.input),
920
+ }));
921
+ const assistant = {
289
922
  role: "assistant",
290
- content: content,
923
+ content: [
924
+ ...(msg.content ? [{ type: "text", text: msg.content }] : []),
925
+ ...toolCalls,
926
+ ],
291
927
  api: model.api,
292
928
  provider: model.provider,
293
929
  model: model.id,
294
930
  usage: zeroUsage(),
295
- stopReason: "tool_use",
931
+ stopReason: "toolUse",
296
932
  timestamp: Date.now(),
297
- });
933
+ };
934
+ result.push(assistant);
298
935
  i += 1;
299
936
  continue;
300
937
  }
301
938
  if (msg.role === "assistant") {
302
- result.push({
939
+ const assistant = {
303
940
  role: "assistant",
304
941
  content: [{ type: "text", text: msg.content }],
305
942
  api: model.api,
@@ -308,26 +945,31 @@ function convertMessagesToPi(messages, model) {
308
945
  usage: zeroUsage(),
309
946
  stopReason: "stop",
310
947
  timestamp: Date.now(),
311
- });
948
+ };
949
+ result.push(assistant);
312
950
  i += 1;
313
951
  continue;
314
952
  }
315
953
  if (msg.role === "tool") {
316
- result.push({
954
+ const toolResult = {
317
955
  role: "toolResult",
318
956
  toolCallId: msg.toolCallId ?? msg.name ?? "tool",
319
957
  toolName: msg.name ?? "tool",
320
958
  content: [{ type: "text", text: msg.content }],
321
959
  details: msg.content,
322
- isError: false,
323
- ...(msg.addedToolNames ? { addedToolNames: [...msg.addedToolNames] } : {}),
960
+ isError: msg.isError === true,
324
961
  timestamp: Date.now(),
325
- });
962
+ };
963
+ result.push(toolResult);
326
964
  i += 1;
327
965
  continue;
328
966
  }
329
967
  // user message
330
- result.push({ role: "user", content: msg.content, timestamp: Date.now() });
968
+ result.push({
969
+ role: "user",
970
+ content: msg.attachments?.length ? toPiUserContent(msg, model.api) : msg.content,
971
+ timestamp: Date.now(),
972
+ });
331
973
  i += 1;
332
974
  }
333
975
  return result;
@@ -338,8 +980,13 @@ export async function emitPiEvent(event, input) {
338
980
  await input.emit("agent_start", { runtime: "pi-agent-core" });
339
981
  if (event.type === "turn_start")
340
982
  await input.emit("turn_start", { runtime: "pi-agent-core" });
341
- if (event.type === "turn_end")
342
- await input.emit("turn_end", { runtime: "pi-agent-core" });
983
+ if (event.type === "turn_end") {
984
+ const stopReason = isAssistantMessage(event.message) ? event.message.stopReason : undefined;
985
+ await input.emit("turn_end", {
986
+ runtime: "pi-agent-core",
987
+ ...(stopReason ? { stopReason } : {}),
988
+ });
989
+ }
343
990
  if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
344
991
  await input.emit("text_delta", { delta: event.assistantMessageEvent.delta });
345
992
  }
@@ -371,13 +1018,107 @@ function assistantText(message) {
371
1018
  function stringifyForModel(value) {
372
1019
  return typeof value === "string" ? value : JSON.stringify(value ?? null);
373
1020
  }
374
- function toFabricUsage(usage) {
375
- return {
376
- inputTokens: usage.input,
1021
+ /**
1022
+ * Tool-call arguments must be a JSON object in Pi 0.86+. History stores the
1023
+ * model's arguments as-is; normalize them through JSON and fall back to an
1024
+ * empty object for values that are not objects.
1025
+ */
1026
+ function toToolArguments(input) {
1027
+ if (input === null || typeof input !== "object" || Array.isArray(input))
1028
+ return {};
1029
+ try {
1030
+ const normalized = JSON.parse(JSON.stringify(input));
1031
+ return normalized !== null && typeof normalized === "object" && !Array.isArray(normalized)
1032
+ ? normalized
1033
+ : {};
1034
+ }
1035
+ catch {
1036
+ return {};
1037
+ }
1038
+ }
1039
+ /**
1040
+ * Map Pi usage to Harness usage. Pi normalizes counts a provider did not
1041
+ * report to `0` and computes `cost.total` from those counts and its own model
1042
+ * catalog, so its cost is synthesized, not provider-reported: a Responses
1043
+ * adapter that reports only `total_tokens` yields `input: 0, output: 0` and a
1044
+ * `$0` cost. Usage whose counts do not account for its total, or that has no
1045
+ * prompt tokens ({@link hasPriceableUsage}), is marked `costUnknown` instead
1046
+ * of being recorded as a known cost, as is all-zero usage (the adapter
1047
+ * reported no usage at all) and a `$0` or invalid Pi cost for tokens on a
1048
+ * model Pi prices.
1049
+ *
1050
+ * Pi also zero-fills a missing output count, so `output: 0` cannot tell a
1051
+ * reported zero from an absent one. A response that produced text, thinking,
1052
+ * or a tool call generated output tokens, so `output: 0` beside such content
1053
+ * (`producedOutput`) means the count was not reported and the usage is marked
1054
+ * `costUnknown` instead of pricing the output at `$0`.
1055
+ */
1056
+ function toFabricUsage(usage, model, producedOutput) {
1057
+ // Pi reports cache reads outside `input`; `ModelUsage.inputTokens`
1058
+ // includes them (cache writes stay separate in both).
1059
+ const result = {
1060
+ inputTokens: usage.input + usage.cacheRead,
377
1061
  outputTokens: usage.output,
378
1062
  totalTokens: usage.totalTokens,
379
- costUsd: usage.cost.total,
1063
+ ...(usage.cacheRead > 0 ? { cachedInputTokens: usage.cacheRead } : {}),
1064
+ ...(usage.cacheWrite > 0 ? { cacheWriteTokens: usage.cacheWrite } : {}),
380
1065
  };
1066
+ // Pi starts every response at zero usage and only overwrites it when the
1067
+ // provider reports usage, so a response whose adapter sent no usage (absent
1068
+ // or `{}`) arrives as all zeros with no marker. A completed model call
1069
+ // always consumed prompt tokens, so all-zero counts mean "not reported",
1070
+ // never a known $0.
1071
+ const reportedNothing = usage.input === 0 &&
1072
+ usage.output === 0 &&
1073
+ usage.cacheRead === 0 &&
1074
+ usage.cacheWrite === 0 &&
1075
+ usage.totalTokens === 0;
1076
+ const outputDropped = producedOutput && usage.output === 0;
1077
+ if (reportedNothing || outputDropped || !hasPriceableUsage(result)) {
1078
+ result.costUnknown = true;
1079
+ return result;
1080
+ }
1081
+ if (!isDynamicModel(model)) {
1082
+ const cost = usage.cost?.total;
1083
+ const rates = model.cost;
1084
+ const priced = rates !== undefined &&
1085
+ [rates.input, rates.output, rates.cacheRead, rates.cacheWrite].some((rate) => rate > 0);
1086
+ const tokens = usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
1087
+ if (!isValidCostUsd(cost) || (priced && tokens > 0 && cost === 0)) {
1088
+ result.costUnknown = true;
1089
+ return result;
1090
+ }
1091
+ result.costUsd = cost;
1092
+ return result;
1093
+ }
1094
+ const modelRef = `${model.provider}/${model.id}`;
1095
+ const estimate = estimateModelCost(modelRef, {
1096
+ inputTokens: usage.input + usage.cacheRead,
1097
+ outputTokens: usage.output,
1098
+ cachedInputTokens: usage.cacheRead,
1099
+ cacheWriteTokens: usage.cacheWrite,
1100
+ });
1101
+ if (estimate.known) {
1102
+ result.costUsd = estimate.costUsd;
1103
+ }
1104
+ else {
1105
+ result.costUnknown = true;
1106
+ warnUnknownModelPrice(modelRef);
1107
+ }
1108
+ return result;
1109
+ }
1110
+ /**
1111
+ * Whether an assistant message carries generated content (non-empty text or
1112
+ * thinking, or a tool call), which a provider always bills as output tokens.
1113
+ */
1114
+ function producedOutput(message) {
1115
+ return message.content.some((block) => block.type === "toolCall"
1116
+ ? true
1117
+ : block.type === "text"
1118
+ ? block.text.length > 0
1119
+ : block.type === "thinking"
1120
+ ? block.thinking.length > 0 || block.redacted === true
1121
+ : false);
381
1122
  }
382
1123
  function zeroUsage() {
383
1124
  return {