@nexface/agent 0.1.14 → 0.1.15-alpha.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 (99) hide show
  1. package/dist/agent.d.ts +2 -1
  2. package/dist/agent.js +323 -877
  3. package/dist/agent.js.map +1 -0
  4. package/dist/browser-policy/gpt.js +12 -36
  5. package/dist/browser-policy/gpt.js.map +1 -0
  6. package/dist/browser-policy/jev.js +9 -21
  7. package/dist/browser-policy/jev.js.map +1 -0
  8. package/dist/browser-policy/response-error.js +2 -4
  9. package/dist/browser-policy/response-error.js.map +1 -0
  10. package/dist/browser-policy/shared.js +21 -49
  11. package/dist/browser-policy/shared.js.map +1 -0
  12. package/dist/browser-prompt.generated.js +1 -0
  13. package/dist/browser-prompt.generated.js.map +1 -0
  14. package/dist/browser-prompt.js +1 -0
  15. package/dist/browser-prompt.js.map +1 -0
  16. package/dist/errors.d.ts +2 -2
  17. package/dist/errors.js +4 -3
  18. package/dist/errors.js.map +1 -0
  19. package/dist/history-compaction.js +26 -47
  20. package/dist/history-compaction.js.map +1 -0
  21. package/dist/history-version.js +4 -11
  22. package/dist/history-version.js.map +1 -0
  23. package/dist/index.js +1 -0
  24. package/dist/index.js.map +1 -0
  25. package/dist/model/binding.js +1 -0
  26. package/dist/model/binding.js.map +1 -0
  27. package/dist/model/error.js +1 -0
  28. package/dist/model/error.js.map +1 -0
  29. package/dist/model/internal-adapter.js +2 -1
  30. package/dist/model/internal-adapter.js.map +1 -0
  31. package/dist/model/types.js +1 -0
  32. package/dist/model/types.js.map +1 -0
  33. package/dist/models/{k.js → 39.js} +336 -168
  34. package/dist/models/851.js +10 -0
  35. package/dist/models/_chunks/360-7e580bb2.js +1189 -0
  36. package/dist/models/_chunks/474-e1813138.js +8304 -0
  37. package/dist/models/_chunks/86-c0c5ac98.js +453 -0
  38. package/dist/models/_chunks/anthropic-messages~1-d35e3e7d.js +8057 -0
  39. package/dist/models/_chunks/deferred-tools-90f3c977.js +37 -0
  40. package/dist/models/_chunks/error-body-8bee35c2.js +134 -0
  41. package/dist/models/_chunks/google-generative-ai~1-2ba71457.js +22104 -0
  42. package/dist/models/_chunks/openai-completions~1-b340f0e0.js +1285 -0
  43. package/dist/models/_chunks/openai-responses~1-b53c65c2.js +958 -0
  44. package/dist/models/anthropic-messages.js +20 -5
  45. package/dist/models/google-generative-ai.js +19 -4
  46. package/dist/models/openai-completions.js +10 -3
  47. package/dist/models/openai-responses.js +10 -3
  48. package/dist/models/rslib-runtime.js +56 -32
  49. package/dist/page-decision.js +59 -197
  50. package/dist/page-decision.js.map +1 -0
  51. package/dist/page-decisions/gpt.js +1 -0
  52. package/dist/page-decisions/gpt.js.map +1 -0
  53. package/dist/page-decisions/jev.js +1 -0
  54. package/dist/page-decisions/jev.js.map +1 -0
  55. package/dist/page-decisions/shared.js +9 -26
  56. package/dist/page-decisions/shared.js.map +1 -0
  57. package/dist/page-diagnostics.js +3 -8
  58. package/dist/page-diagnostics.js.map +1 -0
  59. package/dist/page-observation.js +6 -11
  60. package/dist/page-observation.js.map +1 -0
  61. package/dist/request.js +41 -169
  62. package/dist/request.js.map +1 -0
  63. package/dist/shared/definition.js +1 -0
  64. package/dist/shared/definition.js.map +1 -0
  65. package/dist/shared/errors.d.ts +1 -1
  66. package/dist/shared/errors.js +1 -0
  67. package/dist/shared/errors.js.map +1 -0
  68. package/dist/shared/page-protocol.js +1 -0
  69. package/dist/shared/page-protocol.js.map +1 -0
  70. package/dist/shared/page-tools.js +1 -0
  71. package/dist/shared/page-tools.js.map +1 -0
  72. package/dist/shared/runtime-controller.d.ts +0 -1
  73. package/dist/shared/runtime-controller.js +1 -0
  74. package/dist/shared/runtime-controller.js.map +1 -0
  75. package/dist/shared/runtime-execution.js +1 -0
  76. package/dist/shared/runtime-execution.js.map +1 -0
  77. package/dist/shared/schema.js +19 -45
  78. package/dist/shared/schema.js.map +1 -0
  79. package/dist/shared/tool-registry.d.ts +6 -0
  80. package/dist/shared/tool-registry.js +10 -0
  81. package/dist/shared/tool-registry.js.map +1 -0
  82. package/dist/tool-catalog.js +25 -23
  83. package/dist/tool-catalog.js.map +1 -0
  84. package/dist/tool-result.js +3 -7
  85. package/dist/tool-result.js.map +1 -0
  86. package/dist/types.js +1 -0
  87. package/dist/types.js.map +1 -0
  88. package/package.json +2 -6
  89. package/dist/models/3.js +0 -5553
  90. package/dist/models/3e.js +0 -4
  91. package/dist/models/6.js +0 -506
  92. package/dist/models/anthropic-messages~1.js +0 -5629
  93. package/dist/models/deferred-tools.js +0 -28
  94. package/dist/models/error-body.js +0 -64
  95. package/dist/models/google-generative-ai~1.js +0 -18305
  96. package/dist/models/google-generative-ai~1.js.LICENSE.txt +0 -5
  97. package/dist/models/openai-completions~1.js +0 -987
  98. package/dist/models/openai-responses~1.js +0 -848
  99. package/dist/models/v.js +0 -346
@@ -1,7 +1,10 @@
1
1
  import { defineAgentModelConfig } from "../model/binding.js";
2
+
2
3
  function flattenModelCatalog(_provider, groups) {
3
4
  return Object.assign({}, ...Object.values(groups));
4
5
  }
6
+ //# sourceMappingURL=model-catalog.js.map
7
+ // Generic event stream class for async iteration
5
8
  class EventStream {
6
9
  queue = [];
7
10
  waiting = [];
@@ -10,44 +13,54 @@ class EventStream {
10
13
  resolveFinalResult;
11
14
  isComplete;
12
15
  extractResult;
13
- constructor(isComplete, extractResult){
16
+ constructor(isComplete, extractResult) {
14
17
  this.isComplete = isComplete;
15
18
  this.extractResult = extractResult;
16
- this.finalResultPromise = new Promise((resolve)=>{
19
+ this.finalResultPromise = new Promise((resolve) => {
17
20
  this.resolveFinalResult = resolve;
18
21
  });
19
22
  }
20
23
  push(event) {
21
- if (this.done) return;
24
+ if (this.done)
25
+ return;
22
26
  if (this.isComplete(event)) {
23
27
  this.done = true;
24
28
  this.resolveFinalResult(this.extractResult(event));
25
29
  }
30
+ // Deliver to waiting consumer or queue it
26
31
  const waiter = this.waiting.shift();
27
- if (waiter) waiter({
28
- value: event,
29
- done: false
30
- });
31
- else this.queue.push(event);
32
+ if (waiter) {
33
+ waiter({ value: event, done: false });
34
+ }
35
+ else {
36
+ this.queue.push(event);
37
+ }
32
38
  }
33
39
  end(result) {
34
40
  this.done = true;
35
- if (void 0 !== result) this.resolveFinalResult(result);
36
- while(this.waiting.length > 0){
41
+ if (result !== undefined) {
42
+ this.resolveFinalResult(result);
43
+ }
44
+ // Notify all waiting consumers that we're done
45
+ while (this.waiting.length > 0) {
37
46
  const waiter = this.waiting.shift();
38
- waiter({
39
- value: void 0,
40
- done: true
41
- });
47
+ waiter({ value: undefined, done: true });
42
48
  }
43
49
  }
44
50
  async *[Symbol.asyncIterator]() {
45
- while(true)if (this.queue.length > 0) yield this.queue.shift();
46
- else {
47
- if (this.done) return;
48
- const result = await new Promise((resolve)=>this.waiting.push(resolve));
49
- if (result.done) return;
50
- yield result.value;
51
+ while (true) {
52
+ if (this.queue.length > 0) {
53
+ yield this.queue.shift();
54
+ }
55
+ else if (this.done) {
56
+ return;
57
+ }
58
+ else {
59
+ const result = await new Promise((resolve) => this.waiting.push(resolve));
60
+ if (result.done)
61
+ return;
62
+ yield result.value;
63
+ }
51
64
  }
52
65
  }
53
66
  result() {
@@ -55,14 +68,24 @@ class EventStream {
55
68
  }
56
69
  }
57
70
  class AssistantMessageEventStream extends EventStream {
58
- constructor(){
59
- super((event)=>"done" === event.type || "error" === event.type, (event)=>{
60
- if ("done" === event.type) return event.message;
61
- else if ("error" === event.type) return event.error;
71
+ constructor() {
72
+ super((event) => event.type === "done" || event.type === "error", (event) => {
73
+ if (event.type === "done") {
74
+ return event.message;
75
+ }
76
+ else if (event.type === "error") {
77
+ return event.error;
78
+ }
62
79
  throw new Error("Unexpected event type for final result");
63
80
  });
64
81
  }
65
82
  }
83
+ /** Factory function for AssistantMessageEventStream (for use in extensions) */
84
+ function createAssistantMessageEventStream() {
85
+ return new AssistantMessageEventStream();
86
+ }
87
+ //# sourceMappingURL=event-stream.js.map
88
+
66
89
  function createSetupErrorMessage(model, error) {
67
90
  return {
68
91
  role: "assistant",
@@ -76,56 +99,62 @@ function createSetupErrorMessage(model, error) {
76
99
  cacheRead: 0,
77
100
  cacheWrite: 0,
78
101
  totalTokens: 0,
79
- cost: {
80
- input: 0,
81
- output: 0,
82
- cacheRead: 0,
83
- cacheWrite: 0,
84
- total: 0
85
- }
102
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
86
103
  },
87
104
  stopReason: "error",
88
105
  errorMessage: error instanceof Error ? error.message : String(error),
89
- timestamp: Date.now()
106
+ timestamp: Date.now(),
90
107
  };
91
108
  }
92
109
  function hasResult(source) {
93
- return "function" == typeof source.result;
110
+ return typeof source.result === "function";
94
111
  }
95
112
  async function forwardStream(target, source) {
96
- for await (const event of source)target.push(event);
97
- target.end(hasResult(source) ? await source.result() : void 0);
113
+ for await (const event of source) {
114
+ target.push(event);
115
+ }
116
+ target.end(hasResult(source) ? await source.result() : undefined);
98
117
  }
118
+ /**
119
+ * Returns a stream synchronously while running async setup (auth resolution,
120
+ * lazy module loading) behind it. Setup failures terminate the stream with an
121
+ * error event.
122
+ */
99
123
  function lazyStream(model, setup) {
100
124
  const outer = new AssistantMessageEventStream();
101
- setup().then((inner)=>forwardStream(outer, inner)).catch((error)=>{
125
+ setup()
126
+ .then((inner) => forwardStream(outer, inner))
127
+ .catch((error) => {
102
128
  const message = createSetupErrorMessage(model, error);
103
- outer.push({
104
- type: "error",
105
- reason: "error",
106
- error: message
107
- });
129
+ outer.push({ type: "error", reason: "error", error: message });
108
130
  outer.end(message);
109
131
  });
110
132
  return outer;
111
133
  }
112
134
  function lazyApi(load, capabilities) {
113
135
  const api = {
114
- stream: (model, context, options)=>lazyStream(model, async ()=>(await load()).stream(model, context, options)),
115
- streamSimple: (model, context, options)=>lazyStream(model, async ()=>(await load()).streamSimple(model, context, options))
136
+ stream: (model, context, options) => lazyStream(model, async () => (await load()).stream(model, context, options)),
137
+ streamSimple: (model, context, options) => lazyStream(model, async () => (await load()).streamSimple(model, context, options)),
116
138
  };
117
- if (capabilities?.fetchDeferred) api.fetchDeferred = (model, handle, options)=>lazyStream(model, async ()=>{
139
+ if (capabilities?.fetchDeferred) {
140
+ api.fetchDeferred = (model, handle, options) => lazyStream(model, async () => {
118
141
  const implementation = await load();
119
- if (!implementation.fetchDeferred) throw new Error("API does not support deferred responses");
142
+ if (!implementation.fetchDeferred)
143
+ throw new Error("API does not support deferred responses");
120
144
  return implementation.fetchDeferred(model, handle, options);
121
145
  });
122
- if (capabilities?.cancelDeferred) api.cancelDeferred = async (model, handle, options)=>{
123
- const implementation = await load();
124
- if (!implementation.cancelDeferred) throw new Error("API cannot cancel deferred responses");
125
- await implementation.cancelDeferred(model, handle, options);
126
- };
146
+ }
147
+ if (capabilities?.cancelDeferred) {
148
+ api.cancelDeferred = async (model, handle, options) => {
149
+ const implementation = await load();
150
+ if (!implementation.cancelDeferred)
151
+ throw new Error("API cannot cancel deferred responses");
152
+ await implementation.cancelDeferred(model, handle, options);
153
+ };
154
+ }
127
155
  return api;
128
156
  }
157
+ //# sourceMappingURL=lazy.js.map
129
158
  const LEGACY_TOOL_NAMES = new Set([
130
159
  "callAppTool",
131
160
  "getSnapshot",
@@ -136,8 +165,12 @@ const LEGACY_TOOL_NAMES = new Set([
136
165
  ]);
137
166
  const HISTORY_VERSION_ERROR = "Unsupported Nexface history version. Upgrade client and server together and start a new conversation.";
138
167
  function assertCurrentHistory(messages) {
139
- for (const message of messages)if ("assistant" === message.role && message.toolCalls.some((call)=>LEGACY_TOOL_NAMES.has(call.name)) || "tool" === message.role && LEGACY_TOOL_NAMES.has(message.name)) throw new Error(HISTORY_VERSION_ERROR);
168
+ for (const message of messages){
169
+ if (message.role === "assistant" && message.toolCalls.some((call)=>LEGACY_TOOL_NAMES.has(call.name)) || message.role === "tool" && LEGACY_TOOL_NAMES.has(message.name)) throw new Error(HISTORY_VERSION_ERROR);
170
+ }
140
171
  }
172
+
173
+
141
174
  const AGENT_ERROR_CODES = [
142
175
  "EXECUTION_OUTCOME_UNKNOWN",
143
176
  "AGENT_RUN_ACTIVE",
@@ -161,8 +194,22 @@ const AGENT_MODEL_ERROR_CODES = [
161
194
  "MODEL_REQUEST_FAILED",
162
195
  "MODEL_INPUT_UNSUPPORTED"
163
196
  ];
164
- new Set(AGENT_ERROR_CODES);
165
- new Set(AGENT_MODEL_ERROR_CODES);
197
+ const AGENT_ERROR_CODE_SET = new Set(AGENT_ERROR_CODES);
198
+ const AGENT_MODEL_ERROR_CODE_SET = new Set(AGENT_MODEL_ERROR_CODES);
199
+ function isAgentError(error) {
200
+ if (!error || typeof error !== "object") return false;
201
+ const candidate = error;
202
+ if (candidate.type !== "agent_error" || typeof candidate.code !== "string" || typeof candidate.message !== "string") {
203
+ return false;
204
+ }
205
+ if (candidate.domain === "agent") {
206
+ return AGENT_ERROR_CODE_SET.has(candidate.code);
207
+ }
208
+ if (candidate.domain === "model") {
209
+ return AGENT_MODEL_ERROR_CODE_SET.has(candidate.code);
210
+ }
211
+ return false;
212
+ }
166
213
  class AgentError extends Error {
167
214
  code;
168
215
  details;
@@ -173,13 +220,16 @@ class AgentError extends Error {
173
220
  this.name = "AgentError";
174
221
  }
175
222
  }
223
+
224
+
176
225
  class AgentModelError extends AgentError {
177
226
  code;
178
227
  constructor(code, message){
179
- super(code, message, void 0, "model"), this.code = code;
228
+ super(code, message, undefined, "model"), this.code = code;
180
229
  this.name = "AgentModelError";
181
230
  }
182
231
  }
232
+
183
233
  const HOST_PAGE_TOOLS = new Set([
184
234
  "nxf_getSnapshot",
185
235
  "nxf_applyAction",
@@ -190,32 +240,40 @@ function hideHostPageToolNames(content) {
190
240
  }
191
241
  function projectPageDelegationHistory(entries) {
192
242
  const hiddenCallIds = new Set();
193
- for (const { message } of entries)if ("assistant" === message.role) {
243
+ for (const { message } of entries){
244
+ if (message.role !== "assistant") continue;
194
245
  for (const call of message.toolCalls)if (HOST_PAGE_TOOLS.has(call.name)) hiddenCallIds.add(call.id);
195
246
  }
196
247
  const visible = [];
197
248
  for (const entry of entries){
198
249
  const { message, index } = entry;
199
- if ("assistant" === message.role) {
250
+ if (message.role === "assistant") {
200
251
  const toolCalls = message.toolCalls.filter((call)=>!HOST_PAGE_TOOLS.has(call.name));
201
252
  const removedPageCall = toolCalls.length !== message.toolCalls.length;
202
- const content = "string" == typeof message.content && index < 0 ? hideHostPageToolNames(message.content) : message.content;
253
+ const content = typeof message.content === "string" && index < 0 ? hideHostPageToolNames(message.content) : message.content;
203
254
  if (removedPageCall && !toolCalls.length && !content) continue;
204
- if (removedPageCall || content !== message.content) visible.push({
205
- message: {
206
- ...message,
207
- content,
208
- toolCalls
209
- },
210
- index: -1
211
- });
212
- else visible.push(entry);
213
- } else if ("tool" !== message.role || !hiddenCallIds.has(message.toolCallId) && !HOST_PAGE_TOOLS.has(message.name)) visible.push(entry);
255
+ if (removedPageCall || content !== message.content) {
256
+ visible.push({
257
+ message: {
258
+ ...message,
259
+ content,
260
+ toolCalls
261
+ },
262
+ index: -1
263
+ });
264
+ } else visible.push(entry);
265
+ } else if (message.role !== "tool" || !hiddenCallIds.has(message.toolCallId) && !HOST_PAGE_TOOLS.has(message.name)) {
266
+ visible.push(entry);
267
+ }
214
268
  }
215
269
  return visible;
216
270
  }
271
+ const HISTORY_COMPACTION_TRIGGER_BYTES = (/* unused pure expression or super */ null && (128 * 1024));
272
+ const HISTORY_COMPACTION_MIN_NEW_BYTES = (/* unused pure expression or super */ null && (32 * 1024));
273
+ const HISTORY_COMPACTION_MIN_SAVINGS_BYTES = (/* unused pure expression or super */ null && (16 * 1024));
274
+ const HISTORY_SUMMARY_MAX_BYTES = (/* unused pure expression or super */ null && (16 * 1024));
217
275
  const RECENT_BATCHES = 2;
218
- new TextEncoder();
276
+ const encoder = new TextEncoder();
219
277
  function historyLayout(messages) {
220
278
  const batches = [];
221
279
  const unsafeIndices = [];
@@ -227,45 +285,48 @@ function historyLayout(messages) {
227
285
  let latestDelegationBatch;
228
286
  const settle = ()=>{
229
287
  if (current) {
230
- current.complete = valid && 0 === pending.size;
288
+ current.complete = valid && pending.size === 0;
231
289
  if (!current.complete) unsafeIndices.push(current.start);
232
290
  }
233
- current = void 0;
291
+ current = undefined;
234
292
  };
235
- for (const [index, message] of messages.entries())if ("user" === message.role) {
236
- settle();
237
- latestUser = index;
238
- } else if ("assistant" === message.role) {
239
- settle();
240
- current = {
241
- start: index,
242
- indices: [
243
- index
244
- ],
245
- complete: false
246
- };
247
- batches.push(current);
248
- pending = new Map(message.toolCalls.map((call)=>[
249
- call.id,
250
- call.name
251
- ]));
252
- valid = pending.size === message.toolCalls.length;
253
- } else if ("tool" === message.role) {
254
- if (!current) {
255
- unsafeIndices.push(index);
256
- continue;
293
+ for (const [index, message] of messages.entries()){
294
+ if (message.role === "user") {
295
+ settle();
296
+ latestUser = index;
297
+ } else if (message.role === "assistant") {
298
+ settle();
299
+ current = {
300
+ start: index,
301
+ indices: [
302
+ index
303
+ ],
304
+ complete: false
305
+ };
306
+ batches.push(current);
307
+ pending = new Map(message.toolCalls.map((call)=>[
308
+ call.id,
309
+ call.name
310
+ ]));
311
+ valid = pending.size === message.toolCalls.length;
312
+ } else if (message.role === "tool") {
313
+ if (!current) {
314
+ unsafeIndices.push(index);
315
+ continue;
316
+ }
317
+ current.indices.push(index);
318
+ if (pending.get(message.toolCallId) !== message.name) valid = false;
319
+ pending.delete(message.toolCallId);
320
+ if (message.name === "nxf_getSnapshot" || message.name === "nxf_executeAction" || message.name === "nxf_applyAction") latestBrowserBatch = current;
321
+ if (message.name === "nxf_delegatePageTask") latestDelegationBatch = current;
257
322
  }
258
- current.indices.push(index);
259
- if (pending.get(message.toolCallId) !== message.name) valid = false;
260
- pending.delete(message.toolCallId);
261
- if ("nxf_getSnapshot" === message.name || "nxf_executeAction" === message.name || "nxf_applyAction" === message.name) latestBrowserBatch = current;
262
- if ("nxf_delegatePageTask" === message.name) latestDelegationBatch = current;
263
323
  }
264
324
  settle();
265
325
  const protectedIndices = new Set(latestUser < 0 ? [] : [
266
326
  latestUser
267
327
  ]);
268
328
  const recent = batches.filter((batch)=>batch.complete).slice(-RECENT_BATCHES);
329
+ // A page stage updates its original delegation receipt after internal steps finish.
269
330
  for (const batch of [
270
331
  ...recent,
271
332
  ...latestBrowserBatch ? [
@@ -274,7 +335,9 @@ function historyLayout(messages) {
274
335
  ...latestDelegationBatch ? [
275
336
  latestDelegationBatch
276
337
  ] : []
277
- ])for (const index of batch.indices)protectedIndices.add(index);
338
+ ]){
339
+ for (const index of batch.indices)protectedIndices.add(index);
340
+ }
278
341
  return {
279
342
  batches,
280
343
  latestUser,
@@ -283,14 +346,17 @@ function historyLayout(messages) {
283
346
  };
284
347
  }
285
348
  function boundaryIndex(messages, messageId, layout) {
286
- const index = messages.findIndex((message)=>message.id === messageId && ("user" === message.role || "assistant" === message.role));
287
- if (index < 0 || layout.unsafeIndices.some((unsafe)=>unsafe < index) || "assistant" === messages[index].role && !layout.batches.some((batch)=>batch.start === index && batch.complete)) throw new Error("History compaction boundary does not reference a complete batch or user message.");
349
+ const index = messages.findIndex((message)=>message.id === messageId && (message.role === "user" || message.role === "assistant"));
350
+ if (index < 0 || layout.unsafeIndices.some((unsafe)=>unsafe < index) || messages[index].role === "assistant" && !layout.batches.some((batch)=>batch.start === index && batch.complete)) {
351
+ throw new Error("History compaction boundary does not reference a complete batch or user message.");
352
+ }
288
353
  return index;
289
354
  }
290
355
  function summaryMessage(summary, messages, boundary) {
291
356
  let latestUser = -1;
292
357
  let coveredUser = -1;
293
- for (const [index, message] of messages.entries())if ("user" === message.role) {
358
+ for (const [index, message] of messages.entries()){
359
+ if (message.role !== "user") continue;
294
360
  latestUser = index;
295
361
  if (index < boundary) coveredUser = index;
296
362
  }
@@ -303,27 +369,51 @@ function summaryMessage(summary, messages, boundary) {
303
369
  }
304
370
  function latestContextIndex(messages) {
305
371
  let latest = -1;
306
- let revision = -1 / 0;
307
- for (const [index, message] of messages.entries())if ("application_context" === message.role && message.revision >= revision) {
308
- latest = index;
309
- revision = message.revision;
372
+ let revision = -Infinity;
373
+ for (const [index, message] of messages.entries()){
374
+ if (message.role === "application_context" && message.revision >= revision) {
375
+ latest = index;
376
+ revision = message.revision;
377
+ }
310
378
  }
311
379
  return latest;
312
380
  }
381
+ function validateHistorySummary(value, canonicalMessages) {
382
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid history summary.");
383
+ const summary = value;
384
+ if (Object.keys(summary).some((key)=>key !== "beforeMessageId" && key !== "content") || typeof summary.beforeMessageId !== "string" || !summary.beforeMessageId || typeof summary.content !== "string" || !summary.content.trim() || encoder.encode(summary.content).byteLength > HISTORY_SUMMARY_MAX_BYTES) {
385
+ throw new Error("Invalid history summary.");
386
+ }
387
+ const validated = {
388
+ beforeMessageId: summary.beforeMessageId,
389
+ content: summary.content.trim()
390
+ };
391
+ boundaryIndex(canonicalMessages, validated.beforeMessageId, historyLayout(canonicalMessages));
392
+ return validated;
393
+ }
394
+ function validateCompactionAttempt(value, messages, summary) {
395
+ if (typeof value !== "string" || !value) throw new Error("Invalid history compaction attempt.");
396
+ const layout = historyLayout(messages);
397
+ const index = boundaryIndex(messages, value, layout);
398
+ if (summary && index < boundaryIndex(messages, summary.beforeMessageId, layout)) {
399
+ throw new Error("History compaction attempt precedes the summary.");
400
+ }
401
+ return value;
402
+ }
313
403
  function selectModelHistory(messages, summary, options) {
314
404
  const layout = historyLayout(messages);
315
405
  const boundary = summary ? boundaryIndex(messages, summary.beforeMessageId, layout) : 0;
316
406
  const contextIndex = latestContextIndex(messages);
317
- const catalogIndex = messages.reduce((last, message, index)=>"system" === message.role && message.content.startsWith("[NEXFACE_RUNTIME_V1]") ? index : last, -1);
407
+ const catalogIndex = messages.reduce((last, message, index)=>message.role === "system" && message.content.startsWith("[NEXFACE_RUNTIME_V1]") ? index : last, -1);
318
408
  const entries = [];
319
409
  for (const [index, message] of messages.entries()){
320
410
  if (summary && index === boundary) entries.push({
321
411
  message: summaryMessage(summary, messages, boundary),
322
412
  index: -1
323
413
  });
324
- if ("system" === message.role) {
414
+ if (message.role === "system") {
325
415
  if (message.content.startsWith("[NEXFACE_RUNTIME_V1]") && index !== catalogIndex) continue;
326
- } else if ("application_context" === message.role) {
416
+ } else if (message.role === "application_context") {
327
417
  if (index !== contextIndex) continue;
328
418
  } else if (index < boundary && !layout.protectedIndices.has(index)) continue;
329
419
  entries.push({
@@ -333,10 +423,49 @@ function selectModelHistory(messages, summary, options) {
333
423
  }
334
424
  return options?.pageDelegation ? projectPageDelegationHistory(entries) : entries;
335
425
  }
426
+ function serializedBytes(messages) {
427
+ return encoder.encode(JSON.stringify(messages)).byteLength;
428
+ }
429
+ function modelHistoryBytes(messages, summary, options) {
430
+ return serializedBytes(selectModelHistory(messages, summary, options).map((entry)=>entry.message));
431
+ }
432
+ function getHistoryCompactionInput(messages, previous, attemptBeforeMessageId, options) {
433
+ const layout = historyLayout(messages);
434
+ // A pending or malformed tool batch must be settled before choosing any new cut.
435
+ if (layout.unsafeIndices.length || layout.batches.length <= RECENT_BATCHES) return undefined;
436
+ const boundary = layout.batches[layout.batches.length - RECENT_BATCHES].start;
437
+ const beforeMessageId = messages[boundary].id;
438
+ const start = previous ? boundaryIndex(messages, previous.beforeMessageId, layout) : 0;
439
+ const attemptStart = attemptBeforeMessageId ? boundaryIndex(messages, attemptBeforeMessageId, layout) : start;
440
+ if (!beforeMessageId || boundary <= Math.max(start, attemptStart) || modelHistoryBytes(messages, previous, options) <= HISTORY_COMPACTION_TRIGGER_BYTES) return undefined;
441
+ const removable = messages.slice(attemptStart, boundary).filter((message, offset)=>message.role !== "system" && message.role !== "application_context" && !layout.protectedIndices.has(offset + attemptStart));
442
+ const visibleRemovable = options?.pageDelegation ? projectPageDelegationHistory(removable.map((message, index)=>({
443
+ message,
444
+ index
445
+ }))).map(({ message })=>message) : removable;
446
+ if (serializedBytes(visibleRemovable) < HISTORY_COMPACTION_MIN_NEW_BYTES) return undefined;
447
+ const prefix = previous ? [
448
+ summaryMessage(previous, messages, start)
449
+ ] : [];
450
+ for(let index = start; index < boundary; index += 1){
451
+ const message = messages[index];
452
+ if (message.role !== "system" && message.role !== "application_context") prefix.push(message);
453
+ }
454
+ return {
455
+ beforeMessageId,
456
+ messages: prefix,
457
+ ...layout.latestUser < 0 ? {} : {
458
+ latestUser: messages[layout.latestUser]
459
+ }
460
+ };
461
+ }
462
+
463
+
464
+
336
465
  function parseArguments(value) {
337
466
  try {
338
467
  const parsed = JSON.parse(value);
339
- return parsed && "object" == typeof parsed && !Array.isArray(parsed) ? parsed : {};
468
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
340
469
  } catch {
341
470
  return {};
342
471
  }
@@ -388,17 +517,22 @@ function toolIsError(content) {
388
517
  }
389
518
  }
390
519
  function createPiContext(messages, tools, model, replay, historySummary, pageDelegationHistory = false) {
520
+ // pi-ai exposes one trusted systemPrompt rather than chronological system messages.
521
+ // Keep canonical checkpoints append-only, then consolidate them in their original order.
391
522
  const system = [];
392
523
  const piMessages = [];
393
524
  selectModelHistory(messages, historySummary, {
394
525
  pageDelegation: pageDelegationHistory
395
526
  }).forEach(({ message, index })=>{
396
- if ("system" === message.role || "application_context" === message.role) return void system.push(message.content);
397
- if ("user" === message.role) {
398
- const content = "string" == typeof message.content ? message.content : message.content.map((part)=>{
399
- if ("text" === part.type) return part;
527
+ if (message.role === "system" || message.role === "application_context") {
528
+ system.push(message.content);
529
+ return;
530
+ }
531
+ if (message.role === "user") {
532
+ const content = typeof message.content === "string" ? message.content : message.content.map((part)=>{
533
+ if (part.type === "text") return part;
400
534
  if (!model.input.includes("image")) throw new AgentModelError("MODEL_INPUT_UNSUPPORTED", "The configured model does not support image input.");
401
- if ("data" !== part.source.type) throw new AgentModelError("MODEL_INPUT_UNSUPPORTED", "Only inline image data is supported.");
535
+ if (part.source.type !== "data") throw new AgentModelError("MODEL_INPUT_UNSUPPORTED", "Only inline image data is supported.");
402
536
  return {
403
537
  type: "image",
404
538
  data: part.source.value,
@@ -412,20 +546,25 @@ function createPiContext(messages, tools, model, replay, historySummary, pageDel
412
546
  });
413
547
  return;
414
548
  }
415
- if ("assistant" === message.role) return void piMessages.push(replay.get(index) ?? genericAssistant(message, model));
416
- if ("tool" === message.role) piMessages.push({
417
- role: "toolResult",
418
- toolCallId: message.toolCallId,
419
- toolName: message.name,
420
- content: [
421
- {
422
- type: "text",
423
- text: message.content
424
- }
425
- ],
426
- isError: toolIsError(message.content),
427
- timestamp: Date.now()
428
- });
549
+ if (message.role === "assistant") {
550
+ piMessages.push(replay.get(index) ?? genericAssistant(message, model));
551
+ return;
552
+ }
553
+ if (message.role === "tool") {
554
+ piMessages.push({
555
+ role: "toolResult",
556
+ toolCallId: message.toolCallId,
557
+ toolName: message.name,
558
+ content: [
559
+ {
560
+ type: "text",
561
+ text: message.content
562
+ }
563
+ ],
564
+ isError: toolIsError(message.content),
565
+ timestamp: Date.now()
566
+ });
567
+ }
429
568
  });
430
569
  const piTools = tools.map((tool)=>({
431
570
  name: tool.name,
@@ -441,10 +580,10 @@ function createPiContext(messages, tools, model, replay, historySummary, pageDel
441
580
  };
442
581
  }
443
582
  function fromPiAssistant(message) {
444
- const text = message.content.filter((block)=>"text" === block.type).map((block)=>block.text).join("");
583
+ const text = message.content.filter((block)=>block.type === "text").map((block)=>block.text).join("");
445
584
  return {
446
585
  content: text || null,
447
- toolCalls: message.content.filter((block)=>"toolCall" === block.type).map((block)=>({
586
+ toolCalls: message.content.filter((block)=>block.type === "toolCall").map((block)=>({
448
587
  id: block.id,
449
588
  name: block.name,
450
589
  arguments: JSON.stringify(block.arguments)
@@ -458,6 +597,11 @@ function fromPiAssistant(message) {
458
597
  }
459
598
  };
460
599
  }
600
+
601
+
602
+
603
+
604
+
461
605
  const DEFAULT_CAPABILITIES = {
462
606
  reasoning: false,
463
607
  input: [
@@ -471,7 +615,7 @@ function invalid(message) {
471
615
  throw new AgentModelError("MODEL_CONFIG_INVALID", message);
472
616
  }
473
617
  function assertNonEmpty(value, name) {
474
- if ("string" != typeof value || !value.trim()) invalid(`${name} must be a non-empty string.`);
618
+ if (typeof value !== "string" || !value.trim()) invalid(`${name} must be a non-empty string.`);
475
619
  }
476
620
  function normalizedBaseURL(value, fallback) {
477
621
  const candidate = value ?? fallback;
@@ -484,7 +628,9 @@ function normalizedBaseURL(value, fallback) {
484
628
  return invalid("baseURL must be absolute outside a browser environment.");
485
629
  }
486
630
  if (url.search || url.hash) invalid("baseURL must not contain a query or hash.");
487
- if ("http:" !== url.protocol && "https:" !== url.protocol) invalid("baseURL must use http or https.");
631
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
632
+ invalid("baseURL must use http or https.");
633
+ }
488
634
  if (url.username || url.password) invalid("baseURL must not contain credentials.");
489
635
  url.pathname = url.pathname.replace(/\/+$/, "") || "/";
490
636
  return url.toString().replace(/\/$/, "");
@@ -495,14 +641,17 @@ function hasAuthenticationHeader(headers) {
495
641
  "x-api-key",
496
642
  "x-goog-api-key"
497
643
  ]);
498
- for (const [name, value] of Object.entries(headers ?? {}))if (authenticationHeaders.has(name.toLowerCase())) {
644
+ for (const [name, value] of Object.entries(headers ?? {})){
645
+ if (!authenticationHeaders.has(name.toLowerCase())) continue;
499
646
  assertNonEmpty(value, `headers.${name}`);
500
647
  return true;
501
648
  }
502
649
  return false;
503
650
  }
504
651
  function assertFiniteNumber(value, name, minimum) {
505
- if (void 0 !== value && (!Number.isFinite(value) || value < minimum)) invalid(`${name} must be a finite number greater than or equal to ${minimum}.`);
652
+ if (value !== undefined && (!Number.isFinite(value) || value < minimum)) {
653
+ invalid(`${name} must be a finite number greater than or equal to ${minimum}.`);
654
+ }
506
655
  }
507
656
  function stripKeylessSecret(input, init) {
508
657
  const headers = new Headers(init?.headers);
@@ -512,7 +661,9 @@ function stripKeylessSecret(input, init) {
512
661
  "x-goog-api-key"
513
662
  ]){
514
663
  const value = headers.get(name);
515
- if (value === KEYLESS_GATEWAY_API_KEY || value === `Bearer ${KEYLESS_GATEWAY_API_KEY}`) headers.delete(name);
664
+ if (value === KEYLESS_GATEWAY_API_KEY || value === `Bearer ${KEYLESS_GATEWAY_API_KEY}`) {
665
+ headers.delete(name);
666
+ }
516
667
  }
517
668
  let nextInput = input;
518
669
  const rawURL = input instanceof Request ? input.url : String(input);
@@ -521,9 +672,13 @@ function stripKeylessSecret(input, init) {
521
672
  for (const name of [
522
673
  "key",
523
674
  "api_key"
524
- ])if (url.searchParams.get(name) === KEYLESS_GATEWAY_API_KEY) url.searchParams.delete(name);
675
+ ]){
676
+ if (url.searchParams.get(name) === KEYLESS_GATEWAY_API_KEY) url.searchParams.delete(name);
677
+ }
525
678
  nextInput = input instanceof Request ? new Request(url, input) : url;
526
- } catch {}
679
+ } catch {
680
+ // Keep non-URL RequestInfo unchanged.
681
+ }
527
682
  return [
528
683
  nextInput,
529
684
  {
@@ -541,24 +696,28 @@ function createKeylessFetch(fetchImpl) {
541
696
  async function consumeStream(stream, onTextDelta, onReasoning) {
542
697
  let result;
543
698
  for await (const event of stream){
544
- if ("text_delta" === event.type) onTextDelta?.(event.delta);
545
- if ("thinking_start" === event.type) onReasoning?.({
699
+ if (event.type === "text_delta") onTextDelta?.(event.delta);
700
+ if (event.type === "thinking_start") onReasoning?.({
546
701
  type: "start"
547
702
  });
548
- if ("thinking_delta" === event.type) onReasoning?.({
703
+ if (event.type === "thinking_delta") onReasoning?.({
549
704
  type: "delta",
550
705
  delta: event.delta
551
706
  });
552
- if ("thinking_end" === event.type) onReasoning?.({
707
+ if (event.type === "thinking_end") onReasoning?.({
553
708
  type: "end"
554
709
  });
555
- if ("done" === event.type) result = event.message;
556
- if ("error" === event.type) {
557
- if ("aborted" === event.reason) throw new DOMException("The model request was aborted.", "AbortError");
710
+ if (event.type === "done") result = event.message;
711
+ if (event.type === "error") {
712
+ if (event.reason === "aborted") {
713
+ throw new DOMException("The model request was aborted.", "AbortError");
714
+ }
558
715
  throw new AgentModelError("MODEL_REQUEST_FAILED", "The model request failed.");
559
716
  }
560
717
  }
561
- if (!result) throw new AgentModelError("INVALID_MODEL_RESPONSE", "Model stream ended without a final message.");
718
+ if (!result) {
719
+ throw new AgentModelError("INVALID_MODEL_RESPONSE", "Model stream ended without a final message.");
720
+ }
562
721
  return result;
563
722
  }
564
723
  class PiModelBinding {
@@ -589,7 +748,7 @@ class PiModelBinding {
589
748
  restoreReplay(replay, messages) {
590
749
  if (!Array.isArray(replay)) throw new Error("Invalid model replay.");
591
750
  for (const entry of replay){
592
- const index = "string" == typeof entry?.messageId ? messages.findIndex((message)=>message.id === entry.messageId) : -1;
751
+ const index = typeof entry?.messageId === "string" ? messages.findIndex((message)=>message.id === entry.messageId) : -1;
593
752
  const canonical = messages[index];
594
753
  const raw = entry?.message;
595
754
  if (canonical?.role !== "assistant" || raw?.role !== "assistant" || !Array.isArray(raw.content)) throw new Error("Invalid replay message association.");
@@ -601,8 +760,8 @@ class PiModelBinding {
601
760
  toolCalls: converted.toolCalls
602
761
  }
603
762
  ]);
604
- const finish = 1 === converted.toolCalls.length && converted.toolCalls[0]?.name === "nxf_finish" ? JSON.parse(converted.toolCalls[0].arguments) : void 0;
605
- const expectedContent = finish?.status === "completed" && "string" == typeof finish.output ? finish.output.trim() : converted.content;
763
+ const finish = converted.toolCalls.length === 1 && converted.toolCalls[0]?.name === "nxf_finish" ? JSON.parse(converted.toolCalls[0].arguments) : undefined;
764
+ const expectedContent = finish?.status === "completed" && typeof finish.output === "string" ? finish.output.trim() : converted.content;
606
765
  if (JSON.stringify(converted.toolCalls) !== JSON.stringify(canonical.toolCalls) || expectedContent !== canonical.content) throw new Error("Replay does not match its assistant message.");
607
766
  this.#replay.set(index + 1, structuredClone(raw));
608
767
  }
@@ -630,10 +789,10 @@ function resolveModel(definition, config, baseURL) {
630
789
  const catalogModel = definition.resolveCatalogModel?.(config.model);
631
790
  const capabilities = config.capabilities;
632
791
  return {
633
- ...definition.preserveCatalogCompat && catalogModel?.compat !== void 0 ? {
792
+ ...definition.preserveCatalogCompat && catalogModel?.compat !== undefined ? {
634
793
  compat: catalogModel.compat
635
794
  } : {},
636
- ...catalogModel?.thinkingLevelMap === void 0 ? {} : {
795
+ ...catalogModel?.thinkingLevelMap === undefined ? {} : {
637
796
  thinkingLevelMap: catalogModel.thinkingLevelMap
638
797
  },
639
798
  id: config.model,
@@ -656,32 +815,40 @@ function resolveModel(definition, config, baseURL) {
656
815
  };
657
816
  }
658
817
  function createProtocolModelConfig(definition, config) {
659
- if (!config || "object" != typeof config) invalid("model config must be an object.");
818
+ if (!config || typeof config !== "object") invalid("model config must be an object.");
660
819
  assertNonEmpty(config.model, "model");
661
- if (void 0 !== config.apiKey) assertNonEmpty(config.apiKey, "apiKey");
662
- if (hasAuthenticationHeader(config.headers) && config.apiKey) invalid("apiKey and an authentication header cannot be configured together.");
663
- if (false === definition.supportsCustomFetch && config.fetch) invalid(`Custom fetch is not supported for provider "${definition.provider}".`);
820
+ if (config.apiKey !== undefined) assertNonEmpty(config.apiKey, "apiKey");
821
+ if (hasAuthenticationHeader(config.headers) && config.apiKey) {
822
+ invalid("apiKey and an authentication header cannot be configured together.");
823
+ }
824
+ if (definition.supportsCustomFetch === false && config.fetch) {
825
+ invalid(`Custom fetch is not supported for provider "${definition.provider}".`);
826
+ }
664
827
  assertFiniteNumber(config.temperature, "temperature", 0);
665
828
  assertFiniteNumber(config.maxTokens, "maxTokens", 1);
666
829
  assertFiniteNumber(config.timeoutMs, "timeoutMs", 1);
667
830
  assertFiniteNumber(config.maxRetries, "maxRetries", 0);
668
- if (void 0 !== config.maxRetries && !Number.isInteger(config.maxRetries)) invalid("maxRetries must be an integer.");
831
+ if (config.maxRetries !== undefined && !Number.isInteger(config.maxRetries)) {
832
+ invalid("maxRetries must be an integer.");
833
+ }
669
834
  assertFiniteNumber(config.capabilities?.contextWindow, "capabilities.contextWindow", 1);
670
835
  assertFiniteNumber(config.capabilities?.maxOutputTokens, "capabilities.maxOutputTokens", 1);
671
836
  const baseURL = normalizedBaseURL(config.baseURL, definition.defaultBaseURL);
672
- if (("openai-completions" === definition.api || "openai-responses" === definition.api) && /\/(?:chat\/completions|responses)$/i.test(new URL(baseURL).pathname)) invalid("baseURL must be an API root and must not include the final endpoint.");
837
+ if ((definition.api === "openai-completions" || definition.api === "openai-responses") && /\/(?:chat\/completions|responses)$/i.test(new URL(baseURL).pathname)) {
838
+ invalid("baseURL must be an API root and must not include the final endpoint.");
839
+ }
673
840
  const preparedConfig = {
674
841
  ...config,
675
842
  baseURL,
676
- ...void 0 === config.headers ? {} : {
843
+ ...config.headers === undefined ? {} : {
677
844
  headers: {
678
845
  ...config.headers
679
846
  }
680
847
  },
681
- ...void 0 === config.capabilities ? {} : {
848
+ ...config.capabilities === undefined ? {} : {
682
849
  capabilities: {
683
850
  ...config.capabilities,
684
- ...void 0 === config.capabilities.input ? {} : {
851
+ ...config.capabilities.input === undefined ? {} : {
685
852
  input: [
686
853
  ...config.capabilities.input
687
854
  ]
@@ -699,30 +866,30 @@ function createProtocolModelConfig(definition, config) {
699
866
  const model = resolveModel(definition, preparedConfig, baseURL);
700
867
  const configuredFetch = preparedConfig.fetch ?? globalThis.fetch;
701
868
  const options = {
702
- ...void 0 === preparedConfig.temperature ? {} : {
869
+ ...preparedConfig.temperature === undefined ? {} : {
703
870
  temperature: preparedConfig.temperature
704
871
  },
705
- ...void 0 === preparedConfig.maxTokens ? {} : {
872
+ ...preparedConfig.maxTokens === undefined ? {} : {
706
873
  maxTokens: preparedConfig.maxTokens
707
874
  },
708
- ...model.reasoning && void 0 !== preparedConfig.reasoning ? {
875
+ ...model.reasoning && preparedConfig.reasoning !== undefined ? {
709
876
  reasoning: preparedConfig.reasoning
710
877
  } : {},
711
- ...void 0 === preparedConfig.timeoutMs ? {} : {
878
+ ...preparedConfig.timeoutMs === undefined ? {} : {
712
879
  timeoutMs: preparedConfig.timeoutMs
713
880
  },
714
- ...void 0 === preparedConfig.maxRetries ? {} : {
881
+ ...preparedConfig.maxRetries === undefined ? {} : {
715
882
  maxRetries: preparedConfig.maxRetries
716
883
  },
717
- ...void 0 === preparedConfig.headers ? {} : {
884
+ ...preparedConfig.headers === undefined ? {} : {
718
885
  headers: preparedConfig.headers
719
886
  },
720
- ...false === definition.supportsCustomFetch || void 0 === preparedConfig.apiKey ? {} : {
887
+ ...definition.supportsCustomFetch === false || preparedConfig.apiKey === undefined ? {} : {
721
888
  fetch: configuredFetch
722
889
  },
723
- ...void 0 === preparedConfig.apiKey ? {
890
+ ...preparedConfig.apiKey === undefined ? {
724
891
  apiKey: KEYLESS_GATEWAY_API_KEY,
725
- ...false === definition.supportsCustomFetch ? {} : {
892
+ ...definition.supportsCustomFetch === false ? {} : {
726
893
  fetch: createKeylessFetch(configuredFetch)
727
894
  }
728
895
  } : {
@@ -733,4 +900,5 @@ function createProtocolModelConfig(definition, config) {
733
900
  }
734
901
  });
735
902
  }
903
+
736
904
  export { AgentModelError, AssistantMessageEventStream, createProtocolModelConfig, flattenModelCatalog, lazyApi };