@nexface/agent 0.1.20-alpha.1 → 0.1.20-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/models/k.js CHANGED
@@ -333,6 +333,63 @@ function selectModelHistory(messages, summary, options) {
333
333
  }
334
334
  return options?.pageDelegation ? projectPageDelegationHistory(entries) : entries;
335
335
  }
336
+ function strictToolSchema(schema, path) {
337
+ const fail = (reason)=>{
338
+ throw new AgentModelError("MODEL_CONFIG_INVALID", `Strict tool schema at ${path}: ${reason}`);
339
+ };
340
+ if (!schema.type) fail("an explicit type is required.");
341
+ if (schema.enum?.some((value)=>null !== value && "object" == typeof value)) fail("object and array enum values are not supported.");
342
+ if (void 0 !== schema.uniqueItems) fail("uniqueItems is not supported.");
343
+ const result = {
344
+ ...schema
345
+ };
346
+ if ("object" === schema.type) {
347
+ if (false !== schema.additionalProperties) fail("objects must set additionalProperties to false.");
348
+ const required = new Set(schema.required ?? []);
349
+ const properties = Object.entries(schema.properties ?? {}).map(([key, child])=>{
350
+ if (!required.has(key) && "null" === child.type) fail(`optional null field "${key}" cannot distinguish omission from an explicit null.`);
351
+ const converted = strictToolSchema(child, `${path}.${key}`);
352
+ return [
353
+ key,
354
+ required.has(key) ? converted : {
355
+ anyOf: [
356
+ converted,
357
+ {
358
+ type: "null"
359
+ }
360
+ ]
361
+ }
362
+ ];
363
+ });
364
+ result.properties = Object.fromEntries(properties);
365
+ result.required = properties.map(([key])=>key);
366
+ } else if ("array" === schema.type) {
367
+ if (!schema.items) fail("arrays must define items.");
368
+ result.items = strictToolSchema(schema.items, `${path}[]`);
369
+ }
370
+ return result;
371
+ }
372
+ function restoreToolArguments(value, schema) {
373
+ if ("array" === schema.type && Array.isArray(value) && schema.items) return value.map((item)=>restoreToolArguments(item, schema.items));
374
+ if ("object" !== schema.type || !value || "object" != typeof value || Array.isArray(value)) return value;
375
+ const required = new Set(schema.required ?? []);
376
+ return Object.fromEntries(Object.entries(value).flatMap(([key, entry])=>{
377
+ const child = schema.properties && Object.hasOwn(schema.properties, key) ? schema.properties[key] : void 0;
378
+ if (!child) return [
379
+ [
380
+ key,
381
+ entry
382
+ ]
383
+ ];
384
+ if (null === entry && !required.has(key) && "null" !== child.type) return [];
385
+ return [
386
+ [
387
+ key,
388
+ restoreToolArguments(entry, child)
389
+ ]
390
+ ];
391
+ }));
392
+ }
336
393
  function parseArguments(value) {
337
394
  try {
338
395
  const parsed = JSON.parse(value);
@@ -387,12 +444,13 @@ function toolIsError(content) {
387
444
  return false;
388
445
  }
389
446
  }
390
- function createPiContext(messages, tools, model, replay, historySummary, pageDelegationHistory = false) {
447
+ function createPiContext(messages, tools, model, replay, historySummary, pageDelegationHistory = false, omitRuntimeCatalog = false, strict = false) {
391
448
  const system = [];
392
449
  const piMessages = [];
393
450
  selectModelHistory(messages, historySummary, {
394
451
  pageDelegation: pageDelegationHistory
395
452
  }).forEach(({ message, index })=>{
453
+ if (omitRuntimeCatalog && "system" === message.role && message.content.startsWith("[NEXFACE_RUNTIME_V1]")) return;
396
454
  if ("system" === message.role || "application_context" === message.role) return void system.push(message.content);
397
455
  if ("user" === message.role) {
398
456
  const content = "string" == typeof message.content ? message.content : message.content.map((part)=>{
@@ -427,11 +485,27 @@ function createPiContext(messages, tools, model, replay, historySummary, pageDel
427
485
  timestamp: Date.now()
428
486
  });
429
487
  });
430
- const piTools = tools.map((tool)=>({
488
+ const piTools = tools.map((tool)=>{
489
+ const plain = {
431
490
  name: tool.name,
432
491
  description: tool.description,
433
492
  parameters: tool.inputSchema
434
- }));
493
+ };
494
+ if (!strict) return plain;
495
+ try {
496
+ return {
497
+ ...plain,
498
+ parameters: strictToolSchema(tool.inputSchema, tool.name),
499
+ constrainedSampling: {
500
+ type: "json_schema",
501
+ strict: "require"
502
+ }
503
+ };
504
+ } catch (error) {
505
+ if (error instanceof AgentModelError && "MODEL_CONFIG_INVALID" === error.code) return plain;
506
+ throw error;
507
+ }
508
+ });
435
509
  return {
436
510
  ...system.length ? {
437
511
  systemPrompt: system.join("\n\n")
@@ -561,12 +635,26 @@ async function consumeStream(stream, onTextDelta, onReasoning) {
561
635
  if (!result) throw new AgentModelError("INVALID_MODEL_RESPONSE", "Model stream ended without a final message.");
562
636
  return result;
563
637
  }
638
+ async function rejectsStrictTools(response) {
639
+ if (400 !== response.status && 422 !== response.status) return false;
640
+ try {
641
+ const body = await response.clone().json();
642
+ const error = body.error;
643
+ if (!error || "string" != typeof error.message) return false;
644
+ const unsupported = /not supported|unsupported|does not support|not available/i.test(error.message);
645
+ const strictParameter = "string" == typeof error.param && /(?:^|[.\]])strict$/.test(error.param);
646
+ return unsupported && (strictParameter || /(?:does not support\s+(?:the\s+)?strict(?:\s+mode)?\b|strict(?:\s+mode|\s+tools)?\s+(?:is |are )?(?:not supported|unsupported|not available))/i.test(error.message));
647
+ } catch {
648
+ return false;
649
+ }
650
+ }
564
651
  class PiModelBinding {
565
652
  info;
566
653
  #replay = new Map();
567
654
  #model;
568
655
  #stream;
569
656
  #options;
657
+ #strictUnsupported = false;
570
658
  constructor(info, model, stream, options){
571
659
  this.info = info;
572
660
  this.#model = model;
@@ -608,11 +696,66 @@ class PiModelBinding {
608
696
  }
609
697
  }
610
698
  async complete(request) {
611
- const raw = await consumeStream(this.#stream.streamSimple(this.#model, createPiContext(request.messages, request.tools, this.#model, this.#replay, request.historySummary, request.pageDelegationHistory), {
612
- ...this.#options,
613
- signal: request.signal,
614
- sessionId: request.agentId
615
- }), request.onTextDelta, request.onReasoning);
699
+ const compat = this.#model.compat;
700
+ const supportsStrict = "openai-completions" === this.#model.api || "openai-responses" === this.#model.api ? compat?.supportsStrictMode !== false : "anthropic-messages" === this.#model.api && compat?.supportsStrictTools === true;
701
+ let strict = supportsStrict && !this.#strictUnsupported && !request.tools.some((tool)=>"nxf_callAppTool" === tool.name);
702
+ const emptyToolNames = new Set("openai-completions" === this.#model.api && !request.tools.some((tool)=>"nxf_callAppTool" === tool.name) ? request.tools.filter(({ inputSchema })=>"object" === inputSchema.type && false === inputSchema.additionalProperties && 0 === Object.keys(inputSchema.properties ?? {}).length && (inputSchema.required?.length ?? 0) === 0 && Object.keys(inputSchema).every((key)=>[
703
+ "type",
704
+ "properties",
705
+ "required",
706
+ "additionalProperties"
707
+ ].includes(key))).map(({ name })=>name) : []);
708
+ let raw;
709
+ let strictNames = new Set();
710
+ for(;;){
711
+ request.signal.throwIfAborted();
712
+ const context = createPiContext(request.messages, request.tools, this.#model, this.#replay, request.historySummary, request.pageDelegationHistory, request.omitRuntimeCatalog, strict);
713
+ strictNames = new Set(context.tools?.filter((tool)=>tool.constrainedSampling && "json_schema" === tool.constrainedSampling.type).map((tool)=>tool.name));
714
+ let unsupported = false;
715
+ const fetchImpl = this.#options.fetch ?? globalThis.fetch;
716
+ const fetchWithDetection = async (input, init)=>{
717
+ const response = await fetchImpl(input, init);
718
+ unsupported = strictNames.size > 0 && await rejectsStrictTools(response);
719
+ return response;
720
+ };
721
+ try {
722
+ raw = await consumeStream(this.#stream.streamSimple({
723
+ ...this.#model,
724
+ ...(strict || this.#strictUnsupported) && ("openai-completions" === this.#model.api || "openai-responses" === this.#model.api) ? {
725
+ compat: {
726
+ ...this.#model.compat,
727
+ supportsStrictMode: !this.#strictUnsupported
728
+ }
729
+ } : {}
730
+ }, context, {
731
+ ...this.#options,
732
+ ...strictNames.size ? {
733
+ fetch: fetchWithDetection
734
+ } : {},
735
+ ...emptyToolNames.size ? {
736
+ onPayload: async (payload, model)=>{
737
+ const next = await this.#options.onPayload?.(payload, model) ?? payload;
738
+ const body = next;
739
+ for (const tool of body.tools ?? [])if ("function" === tool.type && tool.function && emptyToolNames.has(tool.function.name)) delete tool.function.parameters;
740
+ return next;
741
+ }
742
+ } : {},
743
+ signal: request.signal,
744
+ sessionId: request.agentId
745
+ }), request.onTextDelta, request.onReasoning);
746
+ break;
747
+ } catch (error) {
748
+ request.signal.throwIfAborted();
749
+ if (!strict || !unsupported) throw error;
750
+ this.#strictUnsupported = true;
751
+ strict = false;
752
+ }
753
+ }
754
+ for (const block of raw.content){
755
+ if ("toolCall" !== block.type || !strictNames.has(block.name)) continue;
756
+ const tool = request.tools.find((tool)=>tool.name === block.name);
757
+ if (tool) block.arguments = restoreToolArguments(block.arguments, tool.inputSchema);
758
+ }
616
759
  const response = fromPiAssistant(raw);
617
760
  const replayIndex = request.messages.length;
618
761
  let accepted = false;
package/dist/request.d.ts CHANGED
@@ -2,7 +2,7 @@ import type { PageTaskProgress } from "./page-decision.js";
2
2
  import { type Message, type RunAgentInput } from "@ag-ui/core";
3
3
  export type { Message, RunAgentInput } from "@ag-ui/core";
4
4
  import type { AgentContextEntry, AgentToolDefinition } from "@nexface/tools";
5
- import type { AgentMessage, AgentModelToolCall, AgentRun, AgentRunInput } from "./types.js";
5
+ import type { AgentMessage, AgentModelToolCall, AgentRun, AgentRunEvent, AgentRunInput } from "./types.js";
6
6
  import type { HistorySummary } from "./history-compaction.js";
7
7
  export interface AgentRequestState {
8
8
  readonly nexface: RequestContinuation;
@@ -93,5 +93,5 @@ export declare function parseResume(value: unknown, allowMetadata?: boolean): Ag
93
93
  export declare function convertMessages(values: readonly Message[]): AgentMessage[];
94
94
  export declare function decodeRequest(value: RunAgentInput): InternalRequestInput;
95
95
  export declare function toProtocolMessages(messages: AgentMessage[]): Message[];
96
- export declare function runResponse(run: AgentRun): Response;
96
+ export declare function runResponse(run: AgentRun, transform?: (event: AgentRunEvent) => AgentRunEvent): Response;
97
97
  export declare function mergeProtocolMessages(messages: Message[], previous: Message[]): Message[];
package/dist/request.js CHANGED
@@ -307,7 +307,7 @@ export function toProtocolMessages(messages) {
307
307
  return [{ id: message.id, role: "user", content: message.content }];
308
308
  });
309
309
  }
310
- export function runResponse(run) {
310
+ export function runResponse(run, transform = (event) => event) {
311
311
  const encoder = new TextEncoder();
312
312
  const iterator = run[Symbol.asyncIterator]();
313
313
  void run.result.catch(() => undefined);
@@ -318,7 +318,7 @@ export function runResponse(run) {
318
318
  if (next.done)
319
319
  controller.close();
320
320
  else
321
- controller.enqueue(encoder.encode(`data: ${JSON.stringify(next.value)}\n\n`));
321
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(transform(next.value))}\n\n`));
322
322
  }
323
323
  catch (error) {
324
324
  controller.error(error);
@@ -0,0 +1,6 @@
1
+ /** Decode the proxy envelope without changing business arguments. */
2
+ export declare function decodeToolProxy(value: Record<string, unknown>): {
3
+ name: string;
4
+ arguments: Record<string, unknown>;
5
+ progressLabel?: string;
6
+ };
@@ -0,0 +1,25 @@
1
+ // Generated from shared/tool-proxy.ts. Do not edit manually.
2
+ /** Decode the proxy envelope without changing business arguments. */
3
+ export function decodeToolProxy(value) {
4
+ if (typeof value.name !== "string" || !value.name.trim())
5
+ throw new Error("nxf_callAppTool needs a non-empty string name.");
6
+ const keys = Object.keys(value).filter((key) => !["name", "arguments", "input", "progressLabel"].includes(key));
7
+ if (keys.length)
8
+ throw new Error(`nxf_callAppTool received unexpected fields: ${keys.join(", ")}.`);
9
+ const modern = Object.hasOwn(value, "arguments");
10
+ const legacy = Object.hasOwn(value, "input");
11
+ if (modern === legacy)
12
+ throw new Error("nxf_callAppTool requires exactly one of arguments or legacy input.");
13
+ const args = modern ? value.arguments : value.input;
14
+ if (!args || typeof args !== "object" || Array.isArray(args))
15
+ throw new Error(`nxf_callAppTool arguments for "${value.name}" must be an object.`);
16
+ if (value.progressLabel !== undefined && typeof value.progressLabel !== "string")
17
+ throw new Error("nxf_callAppTool progressLabel must be a string.");
18
+ return {
19
+ name: value.name,
20
+ arguments: args,
21
+ ...(typeof value.progressLabel === "string" && value.progressLabel.trim()
22
+ ? { progressLabel: value.progressLabel.trim() }
23
+ : {}),
24
+ };
25
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nexface/agent",
3
- "version": "0.1.20-alpha.1",
3
+ "version": "0.1.20-alpha.2",
4
4
  "type": "module",
5
5
  "types": "./dist/index.d.ts",
6
6
  "engines": {
@@ -11,6 +11,10 @@
11
11
  "types": "./dist/index.d.ts",
12
12
  "default": "./dist/index.js"
13
13
  },
14
+ "./ark": {
15
+ "types": "./dist/ark.d.ts",
16
+ "node": "./dist/ark.js"
17
+ },
14
18
  "./openai-completions": {
15
19
  "types": "./dist/models/openai-completions.d.ts",
16
20
  "default": "./dist/models/openai-completions.js"
@@ -45,6 +49,9 @@
45
49
  },
46
50
  "typesVersions": {
47
51
  "*": {
52
+ "ark": [
53
+ "dist/ark.d.ts"
54
+ ],
48
55
  "openai-completions": [
49
56
  "dist/models/openai-completions.d.ts"
50
57
  ],
@@ -66,7 +73,7 @@
66
73
  }
67
74
  },
68
75
  "peerDependencies": {
69
- "@nexface/tools": "0.1.20-alpha.1"
76
+ "@nexface/tools": "0.1.20-alpha.2"
70
77
  },
71
78
  "repository": {
72
79
  "type": "git",