@osdk/aip-core 0.2.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 (131) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +211 -0
  3. package/ai-sdk.d.ts +17 -0
  4. package/build/browser/ai-sdk/convert-prompt.js +136 -0
  5. package/build/browser/ai-sdk/convert-prompt.js.map +1 -0
  6. package/build/browser/ai-sdk/foundry-chat-language-model.js +386 -0
  7. package/build/browser/ai-sdk/foundry-chat-language-model.js.map +1 -0
  8. package/build/browser/ai-sdk/map-finish-reason.js +42 -0
  9. package/build/browser/ai-sdk/map-finish-reason.js.map +1 -0
  10. package/build/browser/ai-sdk/provider.js +62 -0
  11. package/build/browser/ai-sdk/provider.js.map +1 -0
  12. package/build/browser/ai-sdk/types.js +2 -0
  13. package/build/browser/ai-sdk/types.js.map +1 -0
  14. package/build/browser/generateText.js +76 -0
  15. package/build/browser/generateText.js.map +1 -0
  16. package/build/browser/index.js +23 -0
  17. package/build/browser/index.js.map +1 -0
  18. package/build/browser/internal/__test__/mockPlatformClient.js +36 -0
  19. package/build/browser/internal/__test__/mockPlatformClient.js.map +1 -0
  20. package/build/browser/internal/ids.js +23 -0
  21. package/build/browser/internal/ids.js.map +1 -0
  22. package/build/browser/internal/openAi.js +293 -0
  23. package/build/browser/internal/openAi.js.map +1 -0
  24. package/build/browser/internal/options.js +58 -0
  25. package/build/browser/internal/options.js.map +1 -0
  26. package/build/browser/internal/runStep.js +107 -0
  27. package/build/browser/internal/runStep.js.map +1 -0
  28. package/build/browser/internal/streamStep.js +223 -0
  29. package/build/browser/internal/streamStep.js.map +1 -0
  30. package/build/browser/internal/uiMessageBridge.js +55 -0
  31. package/build/browser/internal/uiMessageBridge.js.map +1 -0
  32. package/build/browser/lmsChatTransport.js +185 -0
  33. package/build/browser/lmsChatTransport.js.map +1 -0
  34. package/build/browser/model.js +74 -0
  35. package/build/browser/model.js.map +1 -0
  36. package/build/browser/public/ai-sdk.js +18 -0
  37. package/build/browser/public/ai-sdk.js.map +1 -0
  38. package/build/browser/streamText.js +210 -0
  39. package/build/browser/streamText.js.map +1 -0
  40. package/build/browser/types.js +2 -0
  41. package/build/browser/types.js.map +1 -0
  42. package/build/browser/uiMessage.js +34 -0
  43. package/build/browser/uiMessage.js.map +1 -0
  44. package/build/cjs/index.cjs +1012 -0
  45. package/build/cjs/index.cjs.map +1 -0
  46. package/build/cjs/index.d.cts +467 -0
  47. package/build/cjs/model-B5uS56VB.d.cts +45 -0
  48. package/build/cjs/public/ai-sdk.cjs +534 -0
  49. package/build/cjs/public/ai-sdk.cjs.map +1 -0
  50. package/build/cjs/public/ai-sdk.d.cts +49 -0
  51. package/build/esm/ai-sdk/convert-prompt.js +136 -0
  52. package/build/esm/ai-sdk/convert-prompt.js.map +1 -0
  53. package/build/esm/ai-sdk/foundry-chat-language-model.js +386 -0
  54. package/build/esm/ai-sdk/foundry-chat-language-model.js.map +1 -0
  55. package/build/esm/ai-sdk/map-finish-reason.js +42 -0
  56. package/build/esm/ai-sdk/map-finish-reason.js.map +1 -0
  57. package/build/esm/ai-sdk/provider.js +62 -0
  58. package/build/esm/ai-sdk/provider.js.map +1 -0
  59. package/build/esm/ai-sdk/types.js +2 -0
  60. package/build/esm/ai-sdk/types.js.map +1 -0
  61. package/build/esm/generateText.js +76 -0
  62. package/build/esm/generateText.js.map +1 -0
  63. package/build/esm/index.js +23 -0
  64. package/build/esm/index.js.map +1 -0
  65. package/build/esm/internal/__test__/mockPlatformClient.js +36 -0
  66. package/build/esm/internal/__test__/mockPlatformClient.js.map +1 -0
  67. package/build/esm/internal/ids.js +23 -0
  68. package/build/esm/internal/ids.js.map +1 -0
  69. package/build/esm/internal/openAi.js +293 -0
  70. package/build/esm/internal/openAi.js.map +1 -0
  71. package/build/esm/internal/options.js +58 -0
  72. package/build/esm/internal/options.js.map +1 -0
  73. package/build/esm/internal/runStep.js +107 -0
  74. package/build/esm/internal/runStep.js.map +1 -0
  75. package/build/esm/internal/streamStep.js +223 -0
  76. package/build/esm/internal/streamStep.js.map +1 -0
  77. package/build/esm/internal/uiMessageBridge.js +55 -0
  78. package/build/esm/internal/uiMessageBridge.js.map +1 -0
  79. package/build/esm/lmsChatTransport.js +185 -0
  80. package/build/esm/lmsChatTransport.js.map +1 -0
  81. package/build/esm/model.js +74 -0
  82. package/build/esm/model.js.map +1 -0
  83. package/build/esm/public/ai-sdk.js +18 -0
  84. package/build/esm/public/ai-sdk.js.map +1 -0
  85. package/build/esm/streamText.js +210 -0
  86. package/build/esm/streamText.js.map +1 -0
  87. package/build/esm/types.js +2 -0
  88. package/build/esm/types.js.map +1 -0
  89. package/build/esm/uiMessage.js +34 -0
  90. package/build/esm/uiMessage.js.map +1 -0
  91. package/build/types/ai-sdk/convert-prompt.d.ts +19 -0
  92. package/build/types/ai-sdk/convert-prompt.d.ts.map +1 -0
  93. package/build/types/ai-sdk/foundry-chat-language-model.d.ts +20 -0
  94. package/build/types/ai-sdk/foundry-chat-language-model.d.ts.map +1 -0
  95. package/build/types/ai-sdk/map-finish-reason.d.ts +2 -0
  96. package/build/types/ai-sdk/map-finish-reason.d.ts.map +1 -0
  97. package/build/types/ai-sdk/provider.d.ts +46 -0
  98. package/build/types/ai-sdk/provider.d.ts.map +1 -0
  99. package/build/types/ai-sdk/types.d.ts +1 -0
  100. package/build/types/ai-sdk/types.d.ts.map +1 -0
  101. package/build/types/generateText.d.ts +56 -0
  102. package/build/types/generateText.d.ts.map +1 -0
  103. package/build/types/index.d.ts +12 -0
  104. package/build/types/index.d.ts.map +1 -0
  105. package/build/types/internal/__test__/mockPlatformClient.d.ts +13 -0
  106. package/build/types/internal/__test__/mockPlatformClient.d.ts.map +1 -0
  107. package/build/types/internal/ids.d.ts +1 -0
  108. package/build/types/internal/ids.d.ts.map +1 -0
  109. package/build/types/internal/openAi.d.ts +107 -0
  110. package/build/types/internal/openAi.d.ts.map +1 -0
  111. package/build/types/internal/options.d.ts +4 -0
  112. package/build/types/internal/options.d.ts.map +1 -0
  113. package/build/types/internal/runStep.d.ts +29 -0
  114. package/build/types/internal/runStep.d.ts.map +1 -0
  115. package/build/types/internal/streamStep.d.ts +52 -0
  116. package/build/types/internal/streamStep.d.ts.map +1 -0
  117. package/build/types/internal/uiMessageBridge.d.ts +15 -0
  118. package/build/types/internal/uiMessageBridge.d.ts.map +1 -0
  119. package/build/types/lmsChatTransport.d.ts +35 -0
  120. package/build/types/lmsChatTransport.d.ts.map +1 -0
  121. package/build/types/model.d.ts +42 -0
  122. package/build/types/model.d.ts.map +1 -0
  123. package/build/types/public/ai-sdk.d.ts +2 -0
  124. package/build/types/public/ai-sdk.d.ts.map +1 -0
  125. package/build/types/streamText.d.ts +82 -0
  126. package/build/types/streamText.d.ts.map +1 -0
  127. package/build/types/types.d.ts +189 -0
  128. package/build/types/types.d.ts.map +1 -0
  129. package/build/types/uiMessage.d.ts +85 -0
  130. package/build/types/uiMessage.d.ts.map +1 -0
  131. package/package.json +87 -0
@@ -0,0 +1,23 @@
1
+ /*
2
+ * Copyright 2026 Palantir Technologies, Inc. All rights reserved.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ export { generateText } from "./generateText.js";
18
+ export { streamText } from "./streamText.js";
19
+ export { LmsChatTransport } from "./lmsChatTransport.js";
20
+ export { foundryModel } from "./model.js";
21
+ export { generateMessageId } from "./internal/ids.js";
22
+ export { getUIMessageText } from "./uiMessage.js";
23
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["generateText","streamText","LmsChatTransport","foundryModel","generateMessageId","getUIMessageText"],"sources":["index.ts"],"sourcesContent":["/*\n * Copyright 2026 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { generateText } from \"./generateText.js\";\nexport type {\n GenerateTextOptions,\n GenerateTextResult,\n} from \"./generateText.js\";\n\nexport { streamText } from \"./streamText.js\";\nexport type {\n StreamTextOptions,\n StreamTextResult,\n TextStreamChunk,\n} from \"./streamText.js\";\n\nexport { LmsChatTransport } from \"./lmsChatTransport.js\";\nexport type { LmsChatTransportOptions } from \"./lmsChatTransport.js\";\n\nexport { foundryModel } from \"./model.js\";\nexport type {\n FoundryModelOptions,\n LanguageModel,\n ModelIdentifier,\n} from \"./model.js\";\n\nexport { generateMessageId } from \"./internal/ids.js\";\n\nexport { getUIMessageText } from \"./uiMessage.js\";\nexport type {\n ChatTransport,\n ChatTransportReconnectArgs,\n ChatTransportSendMessagesArgs,\n ChatTransportTrigger,\n UIMessage,\n UIMessageChunk,\n UIMessagePart,\n UIMessageRole,\n} from \"./uiMessage.js\";\n\nexport type {\n AssistantModelMessage,\n ContentPart,\n FilePart,\n FinishReason,\n ImagePart,\n LanguageModelUsage,\n ModelMessage,\n ProviderMetadata,\n ProviderOptions,\n ReasoningOutput,\n ReasoningPart,\n RequestMetadata,\n ResponseMetadata,\n Role,\n StepResult,\n SystemModelMessage,\n TextPart,\n Tool,\n ToolCall,\n ToolCallPart,\n ToolChoice,\n ToolModelMessage,\n ToolResult,\n ToolResultOutput,\n ToolResultPart,\n ToolSet,\n UserModelMessage,\n Warning,\n} from \"./types.js\";\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,YAAY,QAAQ,mBAAmB;AAMhD,SAASC,UAAU,QAAQ,iBAAiB;AAO5C,SAASC,gBAAgB,QAAQ,uBAAuB;AAGxD,SAASC,YAAY,QAAQ,YAAY;AAOzC,SAASC,iBAAiB,QAAQ,mBAAmB;AAErD,SAASC,gBAAgB,QAAQ,gBAAgB","ignoreList":[]}
@@ -0,0 +1,36 @@
1
+ /*
2
+ * Copyright 2026 Palantir Technologies, Inc. All rights reserved.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ /**
18
+ * Build a typed `PlatformClient` for tests. `PlatformClient` is structurally
19
+ * `{ baseUrl, fetch, tokenProvider }`; we satisfy that shape directly so
20
+ * tests don't reach for `as unknown as PlatformClient`.
21
+ */
22
+ export function mockPlatformClient(args) {
23
+ return {
24
+ baseUrl: args.baseUrl,
25
+ fetch: args.fetch,
26
+ tokenProvider: () => Promise.resolve(args.token ?? "test-token")
27
+ };
28
+ }
29
+
30
+ /** Throws with a labelled error if `value` is null/undefined. */
31
+ export function assertDefined(value, label) {
32
+ if (value == null) {
33
+ throw new Error(`${label} was unexpectedly null/undefined`);
34
+ }
35
+ }
36
+ //# sourceMappingURL=mockPlatformClient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mockPlatformClient.js","names":["mockPlatformClient","args","baseUrl","fetch","tokenProvider","Promise","resolve","token","assertDefined","value","label","Error"],"sources":["mockPlatformClient.ts"],"sourcesContent":["/*\n * Copyright 2026 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PlatformClient } from \"@osdk/client\";\n\n/**\n * Build a typed `PlatformClient` for tests. `PlatformClient` is structurally\n * `{ baseUrl, fetch, tokenProvider }`; we satisfy that shape directly so\n * tests don't reach for `as unknown as PlatformClient`.\n */\nexport function mockPlatformClient(args: {\n baseUrl: string;\n fetch: typeof globalThis.fetch;\n token?: string;\n}): PlatformClient {\n return {\n baseUrl: args.baseUrl,\n fetch: args.fetch,\n tokenProvider: () => Promise.resolve(args.token ?? \"test-token\"),\n };\n}\n\n/** Throws with a labelled error if `value` is null/undefined. */\nexport function assertDefined<T>(\n value: T,\n label: string,\n): asserts value is NonNullable<T> {\n if (value == null) {\n throw new Error(`${label} was unexpectedly null/undefined`);\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAIA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASA,kBAAkBA,CAACC,IAIlC,EAAkB;EACjB,OAAO;IACLC,OAAO,EAAED,IAAI,CAACC,OAAO;IACrBC,KAAK,EAAEF,IAAI,CAACE,KAAK;IACjBC,aAAa,EAAEA,CAAA,KAAMC,OAAO,CAACC,OAAO,CAACL,IAAI,CAACM,KAAK,IAAI,YAAY;EACjE,CAAC;AACH;;AAEA;AACA,OAAO,SAASC,aAAaA,CAC3BC,KAAQ,EACRC,KAAa,EACoB;EACjC,IAAID,KAAK,IAAI,IAAI,EAAE;IACjB,MAAM,IAAIE,KAAK,CAAC,GAAGD,KAAK,kCAAkC,CAAC;EAC7D;AACF","ignoreList":[]}
@@ -0,0 +1,23 @@
1
+ /*
2
+ * Copyright 2026 Palantir Technologies, Inc. All rights reserved.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ export function generateMessageId() {
18
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
19
+ return crypto.randomUUID();
20
+ }
21
+ return `msg-${Math.random().toString(36).slice(2, 10)}-${Date.now()}`;
22
+ }
23
+ //# sourceMappingURL=ids.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ids.js","names":["generateMessageId","crypto","randomUUID","Math","random","toString","slice","Date","now"],"sources":["ids.ts"],"sourcesContent":["/*\n * Copyright 2026 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function generateMessageId(): string {\n if (\n typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\"\n ) {\n return crypto.randomUUID();\n }\n return `msg-${Math.random().toString(36).slice(2, 10)}-${Date.now()}`;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,OAAO,SAASA,iBAAiBA,CAAA,EAAW;EAC1C,IACE,OAAOC,MAAM,KAAK,WAAW,IAAI,OAAOA,MAAM,CAACC,UAAU,KAAK,UAAU,EACxE;IACA,OAAOD,MAAM,CAACC,UAAU,CAAC,CAAC;EAC5B;EACA,OAAO,OAAOC,IAAI,CAACC,MAAM,CAAC,CAAC,CAACC,QAAQ,CAAC,EAAE,CAAC,CAACC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,IAAIC,IAAI,CAACC,GAAG,CAAC,CAAC,EAAE;AACvE","ignoreList":[]}
@@ -0,0 +1,293 @@
1
+ /*
2
+ * Copyright 2026 Palantir Technologies, Inc. All rights reserved.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ import { getOpenAiBaseUrl } from "@osdk/language-models";
18
+ import { _getFoundryInternal } from "../model.js";
19
+ export function getModelApiName(identifier) {
20
+ return identifier.type === "lmsModel" ? identifier.apiName : identifier.registeredModelRid;
21
+ }
22
+ export function mapUsage(raw) {
23
+ return {
24
+ inputTokens: raw.prompt_tokens,
25
+ outputTokens: raw.completion_tokens,
26
+ totalTokens: raw.total_tokens,
27
+ reasoningTokens: raw.completion_tokens_details?.reasoning_tokens,
28
+ cachedInputTokens: raw.prompt_tokens_details?.cached_tokens
29
+ };
30
+ }
31
+ export const EMPTY_USAGE = {
32
+ inputTokens: undefined,
33
+ outputTokens: undefined,
34
+ totalTokens: undefined
35
+ };
36
+ export function mapFinishReason(reason) {
37
+ switch (reason) {
38
+ case "stop":
39
+ return "stop";
40
+ case "length":
41
+ return "length";
42
+ case "tool_calls":
43
+ case "function_call":
44
+ return "tool-calls";
45
+ case "content_filter":
46
+ return "content-filter";
47
+ default:
48
+ return "other";
49
+ }
50
+ }
51
+ export function convertMessage(m, warnings) {
52
+ switch (m.role) {
53
+ case "system":
54
+ return [{
55
+ role: "system",
56
+ content: m.content
57
+ }];
58
+ case "user":
59
+ {
60
+ if (typeof m.content === "string") {
61
+ return [{
62
+ role: "user",
63
+ content: m.content
64
+ }];
65
+ }
66
+ const parts = [];
67
+ for (const p of m.content) {
68
+ if (p.type === "text") {
69
+ parts.push({
70
+ type: "text",
71
+ text: p.text
72
+ });
73
+ } else {
74
+ warnings.push({
75
+ type: "other",
76
+ message: `Unsupported user content part "${p.type}": ignored in v0`
77
+ });
78
+ }
79
+ }
80
+ return [{
81
+ role: "user",
82
+ content: parts
83
+ }];
84
+ }
85
+ case "assistant":
86
+ {
87
+ if (typeof m.content === "string") {
88
+ return [{
89
+ role: "assistant",
90
+ content: m.content
91
+ }];
92
+ }
93
+ let text = "";
94
+ const toolCalls = [];
95
+ for (const p of m.content) {
96
+ switch (p.type) {
97
+ case "text":
98
+ text += p.text;
99
+ break;
100
+ case "tool-call":
101
+ toolCalls.push({
102
+ id: p.toolCallId,
103
+ type: "function",
104
+ function: {
105
+ name: p.toolName,
106
+ arguments: JSON.stringify(p.input ?? {})
107
+ }
108
+ });
109
+ break;
110
+ case "reasoning":
111
+ case "file":
112
+ warnings.push({
113
+ type: "other",
114
+ message: `Unsupported assistant content part "${p.type}": ignored in v0`
115
+ });
116
+ break;
117
+ }
118
+ }
119
+ return [{
120
+ role: "assistant",
121
+ content: text.length > 0 ? text : null,
122
+ tool_calls: toolCalls.length > 0 ? toolCalls : undefined
123
+ }];
124
+ }
125
+ case "tool":
126
+ return m.content.map(part => ({
127
+ role: "tool",
128
+ content: stringifyToolResult(part, warnings),
129
+ tool_call_id: part.toolCallId
130
+ }));
131
+ }
132
+ }
133
+ function stringifyToolResult(part, warnings) {
134
+ switch (part.output.type) {
135
+ case "text":
136
+ case "error-text":
137
+ return part.output.value;
138
+ case "json":
139
+ case "error-json":
140
+ return JSON.stringify(part.output.value);
141
+ case "content":
142
+ return part.output.value.map(c => {
143
+ if (c.type === "text") {
144
+ return c.text;
145
+ }
146
+ warnings.push({
147
+ type: "other",
148
+ message: `Unsupported tool result media: ignored in v0`
149
+ });
150
+ return "";
151
+ }).filter(s => s.length > 0).join("\n");
152
+ }
153
+ }
154
+ export function convertTools(tools, warnings) {
155
+ return Object.entries(tools).map(([name, tool]) => {
156
+ const parameters = isJsonSchemaLike(tool.inputSchema) ? tool.inputSchema : (warnings.push({
157
+ type: "unsupported-tool",
158
+ details: `Tool "${name}" inputSchema is not a JSON Schema; v0 only supports plain JSON Schema objects. Defaulting to {} parameters.`
159
+ }), {
160
+ type: "object",
161
+ properties: {}
162
+ });
163
+ return {
164
+ type: "function",
165
+ function: {
166
+ name,
167
+ description: tool.description,
168
+ parameters
169
+ }
170
+ };
171
+ });
172
+ }
173
+ export function convertToolChoice(choice) {
174
+ if (choice == null) {
175
+ return undefined;
176
+ }
177
+ if (choice === "auto" || choice === "none" || choice === "required") {
178
+ return choice;
179
+ }
180
+ return {
181
+ type: "function",
182
+ function: {
183
+ name: choice.toolName
184
+ }
185
+ };
186
+ }
187
+ function isJsonSchemaLike(value) {
188
+ return typeof value === "object" && value != null && ("type" in value || "properties" in value || "$ref" in value || "oneOf" in value || "anyOf" in value || "allOf" in value);
189
+ }
190
+ export function parseToolArguments(args, warnings) {
191
+ if (args === "") {
192
+ return {};
193
+ }
194
+ try {
195
+ return JSON.parse(args);
196
+ } catch {
197
+ warnings.push({
198
+ type: "other",
199
+ message: `Tool call arguments were not valid JSON; passing through as a raw string`
200
+ });
201
+ return args;
202
+ }
203
+ }
204
+ export function buildOpenAiRequestBody(args, streaming) {
205
+ const common = {
206
+ model: args.apiName,
207
+ messages: args.messages.map(m => convertMessage(m, args.warnings)).flat(),
208
+ max_tokens: args.maxOutputTokens,
209
+ temperature: args.temperature,
210
+ top_p: args.topP,
211
+ stop: args.stopSequences,
212
+ seed: args.seed,
213
+ presence_penalty: args.presencePenalty,
214
+ frequency_penalty: args.frequencyPenalty,
215
+ tools: args.tools != null ? convertTools(args.tools, args.warnings) : undefined,
216
+ tool_choice: convertToolChoice(args.toolChoice)
217
+ };
218
+ if (streaming) {
219
+ return {
220
+ ...common,
221
+ stream: true,
222
+ stream_options: {
223
+ include_usage: true
224
+ }
225
+ };
226
+ }
227
+ return {
228
+ ...common,
229
+ stream: false
230
+ };
231
+ }
232
+ export function buildAssistantContent(text, toolCalls) {
233
+ if (toolCalls.length === 0) {
234
+ return text;
235
+ }
236
+ const parts = [];
237
+ if (text.length > 0) {
238
+ parts.push({
239
+ type: "text",
240
+ text
241
+ });
242
+ }
243
+ for (const tc of toolCalls) {
244
+ parts.push({
245
+ type: "tool-call",
246
+ toolCallId: tc.toolCallId,
247
+ toolName: tc.toolName,
248
+ input: tc.input
249
+ });
250
+ }
251
+ return parts;
252
+ }
253
+ export function filterHeaders(input) {
254
+ const out = {};
255
+ for (const [k, v] of Object.entries(input)) {
256
+ if (v != null) {
257
+ out[k] = v;
258
+ }
259
+ }
260
+ return out;
261
+ }
262
+ export async function safeReadText(res) {
263
+ try {
264
+ return await res.text();
265
+ } catch {
266
+ return undefined;
267
+ }
268
+ }
269
+ /**
270
+ * POST against the LMS OpenAI proxy's chat/completions endpoint and return
271
+ * the raw response. Throws on a non-2xx response.
272
+ */
273
+ export async function postChatCompletions(args) {
274
+ const handle = _getFoundryInternal(args.model);
275
+ const baseUrl = getOpenAiBaseUrl(handle.client);
276
+ const url = new URL("chat/completions", `${baseUrl}/`).toString();
277
+ const res = await handle.client.fetch(url, {
278
+ method: "POST",
279
+ headers: filterHeaders({
280
+ "Content-Type": "application/json",
281
+ Accept: args.accept,
282
+ ...(args.headers ?? {})
283
+ }),
284
+ body: JSON.stringify(args.body),
285
+ signal: args.abortSignal
286
+ });
287
+ if (!res.ok) {
288
+ const errBody = await safeReadText(res);
289
+ throw new Error(`LMS chat/completions request failed: ${res.status} ${res.statusText}` + (errBody ? `: ${errBody}` : ""));
290
+ }
291
+ return res;
292
+ }
293
+ //# sourceMappingURL=openAi.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openAi.js","names":["getOpenAiBaseUrl","_getFoundryInternal","getModelApiName","identifier","type","apiName","registeredModelRid","mapUsage","raw","inputTokens","prompt_tokens","outputTokens","completion_tokens","totalTokens","total_tokens","reasoningTokens","completion_tokens_details","reasoning_tokens","cachedInputTokens","prompt_tokens_details","cached_tokens","EMPTY_USAGE","undefined","mapFinishReason","reason","convertMessage","m","warnings","role","content","parts","p","push","text","message","toolCalls","id","toolCallId","function","name","toolName","arguments","JSON","stringify","input","length","tool_calls","map","part","stringifyToolResult","tool_call_id","output","value","c","filter","s","join","convertTools","tools","Object","entries","tool","parameters","isJsonSchemaLike","inputSchema","details","properties","description","convertToolChoice","choice","parseToolArguments","args","parse","buildOpenAiRequestBody","streaming","common","model","messages","flat","max_tokens","maxOutputTokens","temperature","top_p","topP","stop","stopSequences","seed","presence_penalty","presencePenalty","frequency_penalty","frequencyPenalty","tool_choice","toolChoice","stream","stream_options","include_usage","buildAssistantContent","tc","filterHeaders","out","k","v","safeReadText","res","postChatCompletions","handle","baseUrl","client","url","URL","toString","fetch","method","headers","Accept","accept","body","signal","abortSignal","ok","errBody","Error","status","statusText"],"sources":["openAi.ts"],"sourcesContent":["/*\n * Copyright 2026 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getOpenAiBaseUrl } from \"@osdk/language-models\";\nimport {\n _getFoundryInternal,\n type LanguageModel,\n type ModelIdentifier,\n} from \"../model.js\";\nimport type {\n AssistantModelMessage,\n FinishReason,\n LanguageModelUsage,\n ModelMessage,\n ToolCall,\n ToolChoice,\n ToolResultPart,\n ToolSet,\n Warning,\n} from \"../types.js\";\n\nexport interface OpenAiMessage {\n role: \"system\" | \"user\" | \"assistant\" | \"tool\";\n content: string | Array<OpenAiContentPart> | null;\n tool_calls?: Array<OpenAiAssistantToolCall>;\n tool_call_id?: string;\n}\n\ntype OpenAiContentPart = { type: \"text\"; text: string };\n\nexport interface OpenAiTool {\n type: \"function\";\n function: {\n name: string;\n description?: string;\n parameters: unknown;\n };\n}\n\nexport type OpenAiToolChoice =\n | \"auto\"\n | \"none\"\n | \"required\"\n | { type: \"function\"; function: { name: string } };\n\nexport interface OpenAiAssistantToolCall {\n id: string;\n type: \"function\";\n function: { name: string; arguments: string };\n}\n\nexport function getModelApiName(identifier: ModelIdentifier): string {\n return identifier.type === \"lmsModel\"\n ? identifier.apiName\n : identifier.registeredModelRid;\n}\n\nexport interface OpenAiUsageRaw {\n prompt_tokens: number;\n completion_tokens: number;\n total_tokens: number;\n completion_tokens_details?: { reasoning_tokens?: number };\n prompt_tokens_details?: { cached_tokens?: number };\n}\n\nexport function mapUsage(raw: OpenAiUsageRaw): LanguageModelUsage {\n return {\n inputTokens: raw.prompt_tokens,\n outputTokens: raw.completion_tokens,\n totalTokens: raw.total_tokens,\n reasoningTokens: raw.completion_tokens_details?.reasoning_tokens,\n cachedInputTokens: raw.prompt_tokens_details?.cached_tokens,\n };\n}\n\nexport const EMPTY_USAGE: LanguageModelUsage = {\n inputTokens: undefined,\n outputTokens: undefined,\n totalTokens: undefined,\n};\n\nexport function mapFinishReason(reason: string): FinishReason {\n switch (reason) {\n case \"stop\":\n return \"stop\";\n case \"length\":\n return \"length\";\n case \"tool_calls\":\n case \"function_call\":\n return \"tool-calls\";\n case \"content_filter\":\n return \"content-filter\";\n default:\n return \"other\";\n }\n}\n\nexport function convertMessage(\n m: ModelMessage,\n warnings: Array<Warning>,\n): Array<OpenAiMessage> {\n switch (m.role) {\n case \"system\":\n return [{ role: \"system\", content: m.content }];\n\n case \"user\": {\n if (typeof m.content === \"string\") {\n return [{ role: \"user\", content: m.content }];\n }\n const parts: Array<OpenAiContentPart> = [];\n for (const p of m.content) {\n if (p.type === \"text\") {\n parts.push({ type: \"text\", text: p.text });\n } else {\n warnings.push({\n type: \"other\",\n message: `Unsupported user content part \"${p.type}\": ignored in v0`,\n });\n }\n }\n return [{ role: \"user\", content: parts }];\n }\n\n case \"assistant\": {\n if (typeof m.content === \"string\") {\n return [{ role: \"assistant\", content: m.content }];\n }\n let text = \"\";\n const toolCalls: Array<OpenAiAssistantToolCall> = [];\n for (const p of m.content) {\n switch (p.type) {\n case \"text\":\n text += p.text;\n break;\n case \"tool-call\":\n toolCalls.push({\n id: p.toolCallId,\n type: \"function\",\n function: {\n name: p.toolName,\n arguments: JSON.stringify(p.input ?? {}),\n },\n });\n break;\n case \"reasoning\":\n case \"file\":\n warnings.push({\n type: \"other\",\n message:\n `Unsupported assistant content part \"${p.type}\": ignored in v0`,\n });\n break;\n }\n }\n return [{\n role: \"assistant\",\n content: text.length > 0 ? text : null,\n tool_calls: toolCalls.length > 0 ? toolCalls : undefined,\n }];\n }\n\n case \"tool\":\n return m.content.map((part: ToolResultPart) => ({\n role: \"tool\" as const,\n content: stringifyToolResult(part, warnings),\n tool_call_id: part.toolCallId,\n }));\n }\n}\n\nfunction stringifyToolResult(\n part: ToolResultPart,\n warnings: Array<Warning>,\n): string {\n switch (part.output.type) {\n case \"text\":\n case \"error-text\":\n return part.output.value;\n case \"json\":\n case \"error-json\":\n return JSON.stringify(part.output.value);\n case \"content\":\n return part.output.value\n .map((c) => {\n if (c.type === \"text\") {\n return c.text;\n }\n warnings.push({\n type: \"other\",\n message: `Unsupported tool result media: ignored in v0`,\n });\n return \"\";\n })\n .filter((s) => s.length > 0)\n .join(\"\\n\");\n }\n}\n\nexport function convertTools<TOOLS extends ToolSet>(\n tools: TOOLS,\n warnings: Array<Warning>,\n): Array<OpenAiTool> {\n return Object.entries(tools).map(([name, tool]) => {\n const parameters = isJsonSchemaLike(tool.inputSchema)\n ? tool.inputSchema\n : (warnings.push({\n type: \"unsupported-tool\",\n details:\n `Tool \"${name}\" inputSchema is not a JSON Schema; v0 only supports plain JSON Schema objects. Defaulting to {} parameters.`,\n }),\n { type: \"object\", properties: {} });\n return {\n type: \"function\" as const,\n function: {\n name,\n description: tool.description,\n parameters,\n },\n };\n });\n}\n\nexport function convertToolChoice<TOOLS extends ToolSet>(\n choice: ToolChoice<TOOLS> | undefined,\n): OpenAiToolChoice | undefined {\n if (choice == null) {\n return undefined;\n }\n if (choice === \"auto\" || choice === \"none\" || choice === \"required\") {\n return choice;\n }\n return { type: \"function\", function: { name: choice.toolName } };\n}\n\nfunction isJsonSchemaLike(value: unknown): boolean {\n return (\n typeof value === \"object\"\n && value != null\n && (\n \"type\" in value\n || \"properties\" in value\n || \"$ref\" in value\n || \"oneOf\" in value\n || \"anyOf\" in value\n || \"allOf\" in value\n )\n );\n}\n\nexport function parseToolArguments(\n args: string,\n warnings: Array<Warning>,\n): unknown {\n if (args === \"\") {\n return {};\n }\n try {\n return JSON.parse(args);\n } catch {\n warnings.push({\n type: \"other\",\n message:\n `Tool call arguments were not valid JSON; passing through as a raw string`,\n });\n return args;\n }\n}\n\nexport interface BuildRequestBodyArgs<TOOLS extends ToolSet> {\n apiName: string;\n messages: ReadonlyArray<ModelMessage>;\n tools: TOOLS | undefined;\n toolChoice: ToolChoice<TOOLS> | undefined;\n maxOutputTokens: number | undefined;\n temperature: number | undefined;\n topP: number | undefined;\n stopSequences: ReadonlyArray<string> | undefined;\n seed: number | undefined;\n presencePenalty: number | undefined;\n frequencyPenalty: number | undefined;\n warnings: Array<Warning>;\n}\n\ninterface OpenAiChatRequestCommon {\n model: string;\n messages: Array<OpenAiMessage>;\n max_tokens?: number;\n temperature?: number;\n top_p?: number;\n stop?: ReadonlyArray<string>;\n seed?: number;\n presence_penalty?: number;\n frequency_penalty?: number;\n tools?: Array<OpenAiTool>;\n tool_choice?: OpenAiToolChoice;\n}\n\nexport type OpenAiChatRequestNonStreaming = OpenAiChatRequestCommon & {\n stream: false;\n};\n\nexport type OpenAiChatRequestStreaming = OpenAiChatRequestCommon & {\n stream: true;\n stream_options?: { include_usage?: boolean };\n};\n\nexport function buildOpenAiRequestBody<TOOLS extends ToolSet>(\n args: BuildRequestBodyArgs<TOOLS>,\n streaming: false,\n): OpenAiChatRequestNonStreaming;\nexport function buildOpenAiRequestBody<TOOLS extends ToolSet>(\n args: BuildRequestBodyArgs<TOOLS>,\n streaming: true,\n): OpenAiChatRequestStreaming;\nexport function buildOpenAiRequestBody<TOOLS extends ToolSet>(\n args: BuildRequestBodyArgs<TOOLS>,\n streaming: boolean,\n): OpenAiChatRequestNonStreaming | OpenAiChatRequestStreaming {\n const common: OpenAiChatRequestCommon = {\n model: args.apiName,\n messages: args.messages.map((m) => convertMessage(m, args.warnings)).flat(),\n max_tokens: args.maxOutputTokens,\n temperature: args.temperature,\n top_p: args.topP,\n stop: args.stopSequences,\n seed: args.seed,\n presence_penalty: args.presencePenalty,\n frequency_penalty: args.frequencyPenalty,\n tools: args.tools != null\n ? convertTools(args.tools, args.warnings)\n : undefined,\n tool_choice: convertToolChoice(args.toolChoice),\n };\n if (streaming) {\n return { ...common, stream: true, stream_options: { include_usage: true } };\n }\n return { ...common, stream: false };\n}\n\nexport function buildAssistantContent(\n text: string,\n toolCalls: ReadonlyArray<ToolCall>,\n): AssistantModelMessage[\"content\"] {\n if (toolCalls.length === 0) {\n return text;\n }\n const parts: Array<\n { type: \"text\"; text: string } | {\n type: \"tool-call\";\n toolCallId: string;\n toolName: string;\n input: unknown;\n }\n > = [];\n if (text.length > 0) {\n parts.push({ type: \"text\", text });\n }\n for (const tc of toolCalls) {\n parts.push({\n type: \"tool-call\",\n toolCallId: tc.toolCallId,\n toolName: tc.toolName,\n input: tc.input,\n });\n }\n return parts;\n}\n\nexport function filterHeaders(\n input: Record<string, string | undefined>,\n): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(input)) {\n if (v != null) {\n out[k] = v;\n }\n }\n return out;\n}\n\nexport async function safeReadText(\n res: Response,\n): Promise<string | undefined> {\n try {\n return await res.text();\n } catch {\n return undefined;\n }\n}\n\nexport interface PostChatCompletionsArgs {\n model: LanguageModel;\n body: OpenAiChatRequestNonStreaming | OpenAiChatRequestStreaming;\n accept: \"application/json\" | \"text/event-stream\";\n headers: Record<string, string | undefined> | undefined;\n abortSignal: AbortSignal | undefined;\n}\n\n/**\n * POST against the LMS OpenAI proxy's chat/completions endpoint and return\n * the raw response. Throws on a non-2xx response.\n */\nexport async function postChatCompletions(\n args: PostChatCompletionsArgs,\n): Promise<Response> {\n const handle = _getFoundryInternal(args.model);\n const baseUrl = getOpenAiBaseUrl(handle.client);\n const url = new URL(\"chat/completions\", `${baseUrl}/`).toString();\n\n const res = await handle.client.fetch(url, {\n method: \"POST\",\n headers: filterHeaders({\n \"Content-Type\": \"application/json\",\n Accept: args.accept,\n ...(args.headers ?? {}),\n }),\n body: JSON.stringify(args.body),\n signal: args.abortSignal,\n });\n\n if (!res.ok) {\n const errBody = await safeReadText(res);\n throw new Error(\n `LMS chat/completions request failed: ${res.status} ${res.statusText}`\n + (errBody ? `: ${errBody}` : \"\"),\n );\n }\n\n return res;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,gBAAgB,QAAQ,uBAAuB;AACxD,SACEC,mBAAmB,QAGd,aAAa;AA2CpB,OAAO,SAASC,eAAeA,CAACC,UAA2B,EAAU;EACnE,OAAOA,UAAU,CAACC,IAAI,KAAK,UAAU,GACjCD,UAAU,CAACE,OAAO,GAClBF,UAAU,CAACG,kBAAkB;AAC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M,CAAC;EAC/C,MAAMC,GAAG,GAAG,IAAIC,GAAG,CAAC,kBAAkB,EAAE,GAAGH,OAAO,GAAG,CAAC,CAACI,QAAQ,CAAC,CAAC;EAEjE,MAAMP,GAAG,GAAG,MAAME,MAAM,CAACE,MAAM,CAACI,KAAK,CAACH,GAAG,EAAE;IACzCI,MAAM,EAAE,MAAM;IACdC,OAAO,EAAEf,aAAa,CAAC;MACrB,cAAc,EAAE,kBAAkB;MAClCgB,MAAM,EAAE3C,IAAI,CAAC4C,MAAM;MACnB,IAAI5C,IAAI,CAAC0C,OAAO,IAAI,CAAC,CAAC;IACxB,CAAC,CAAC;IACFG,IAAI,EAAE1E,IAAI,CAACC,SAAS,CAAC4B,IAAI,CAAC6C,IAAI,CAAC;IAC/BC,MAAM,EAAE9C,IAAI,CAAC+C;EACf,CAAC,CAAC;EAEF,IAAI,CAACf,GAAG,CAACgB,EAAE,EAAE;IACX,MAAMC,OAAO,GAAG,MAAMlB,YAAY,CAACC,GAAG,CAAC;IACvC,MAAM,IAAIkB,KAAK,CACb,wCAAwClB,GAAG,CAACmB,MAAM,IAAInB,GAAG,CAACoB,UAAU,EAAE,IACjEH,OAAO,GAAG,KAAKA,OAAO,EAAE,GAAG,EAAE,CACpC,CAAC;EACH;EAEA,OAAOjB,GAAG;AACZ","ignoreList":[]}
@@ -0,0 +1,58 @@
1
+ /*
2
+ * Copyright 2026 Palantir Technologies, Inc. All rights reserved.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ export function resolveMessages(callerLabel, system, prompt, messages) {
18
+ if (prompt != null && messages != null) {
19
+ throw new Error(`${callerLabel}: cannot specify both \`prompt\` and \`messages\`: choose one.`);
20
+ }
21
+ const sys = resolveSystem(system);
22
+ const body = resolveBody(prompt, messages);
23
+ if (sys.length === 0 && body.length === 0) {
24
+ throw new Error(`${callerLabel}: must provide at least one of \`system\`, \`prompt\`, or \`messages\`.`);
25
+ }
26
+ return [...sys, ...body];
27
+ }
28
+ function resolveSystem(system) {
29
+ if (system == null) {
30
+ return [];
31
+ }
32
+ if (typeof system === "string") {
33
+ return system === "" ? [] : [{
34
+ role: "system",
35
+ content: system
36
+ }];
37
+ }
38
+ if (Array.isArray(system)) {
39
+ return system;
40
+ }
41
+ return [system];
42
+ }
43
+ function resolveBody(prompt, messages) {
44
+ if (messages != null) {
45
+ return messages;
46
+ }
47
+ if (prompt == null) {
48
+ return [];
49
+ }
50
+ if (typeof prompt === "string") {
51
+ return [{
52
+ role: "user",
53
+ content: prompt
54
+ }];
55
+ }
56
+ return prompt;
57
+ }
58
+ //# sourceMappingURL=options.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"options.js","names":["resolveMessages","callerLabel","system","prompt","messages","Error","sys","resolveSystem","body","resolveBody","length","role","content","Array","isArray"],"sources":["options.ts"],"sourcesContent":["/*\n * Copyright 2026 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { ModelMessage, SystemModelMessage } from \"../types.js\";\n\nexport type SystemOption =\n | string\n | SystemModelMessage\n | Array<SystemModelMessage>\n | undefined;\n\nexport type PromptOption = string | Array<ModelMessage> | undefined;\n\nexport function resolveMessages(\n callerLabel: string,\n system: SystemOption,\n prompt: PromptOption,\n messages: Array<ModelMessage> | undefined,\n): Array<ModelMessage> {\n if (prompt != null && messages != null) {\n throw new Error(\n `${callerLabel}: cannot specify both \\`prompt\\` and \\`messages\\`: choose one.`,\n );\n }\n\n const sys: Array<SystemModelMessage> = resolveSystem(system);\n const body: Array<ModelMessage> = resolveBody(prompt, messages);\n\n if (sys.length === 0 && body.length === 0) {\n throw new Error(\n `${callerLabel}: must provide at least one of \\`system\\`, \\`prompt\\`, or \\`messages\\`.`,\n );\n }\n\n return [...sys, ...body];\n}\n\nfunction resolveSystem(system: SystemOption): Array<SystemModelMessage> {\n if (system == null) {\n return [];\n }\n if (typeof system === \"string\") {\n return system === \"\" ? [] : [{ role: \"system\", content: system }];\n }\n if (Array.isArray(system)) {\n return system;\n }\n return [system];\n}\n\nfunction resolveBody(\n prompt: PromptOption,\n messages: Array<ModelMessage> | undefined,\n): Array<ModelMessage> {\n if (messages != null) {\n return messages;\n }\n if (prompt == null) {\n return [];\n }\n if (typeof prompt === \"string\") {\n return [{ role: \"user\", content: prompt }];\n }\n return prompt;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAYA,OAAO,SAASA,eAAeA,CAC7BC,WAAmB,EACnBC,MAAoB,EACpBC,MAAoB,EACpBC,QAAyC,EACpB;EACrB,IAAID,MAAM,IAAI,IAAI,IAAIC,QAAQ,IAAI,IAAI,EAAE;IACtC,MAAM,IAAIC,KAAK,CACb,GAAGJ,WAAW,gEAChB,CAAC;EACH;EAEA,MAAMK,GAA8B,GAAGC,aAAa,CAACL,MAAM,CAAC;EAC5D,MAAMM,IAAyB,GAAGC,WAAW,CAACN,MAAM,EAAEC,QAAQ,CAAC;EAE/D,IAAIE,GAAG,CAACI,MAAM,KAAK,CAAC,IAAIF,IAAI,CAACE,MAAM,KAAK,CAAC,EAAE;IACzC,MAAM,IAAIL,KAAK,CACb,GAAGJ,WAAW,yEAChB,CAAC;EACH;EAEA,OAAO,CAAC,GAAGK,GAAG,EAAE,GAAGE,IAAI,CAAC;AAC1B;AAEA,SAASD,aAAaA,CAACL,MAAoB,EAA6B;EACtE,IAAIA,MAAM,IAAI,IAAI,EAAE;IAClB,OAAO,EAAE;EACX;EACA,IAAI,OAAOA,MAAM,KAAK,QAAQ,EAAE;IAC9B,OAAOA,MAAM,KAAK,EAAE,GAAG,EAAE,GAAG,CAAC;MAAES,IAAI,EAAE,QAAQ;MAAEC,OAAO,EAAEV;IAAO,CAAC,CAAC;EACnE;EACA,IAAIW,KAAK,CAACC,OAAO,CAACZ,MAAM,CAAC,EAAE;IACzB,OAAOA,MAAM;EACf;EACA,OAAO,CAACA,MAAM,CAAC;AACjB;AAEA,SAASO,WAAWA,CAClBN,MAAoB,EACpBC,QAAyC,EACpB;EACrB,IAAIA,QAAQ,IAAI,IAAI,EAAE;IACpB,OAAOA,QAAQ;EACjB;EACA,IAAID,MAAM,IAAI,IAAI,EAAE;IAClB,OAAO,EAAE;EACX;EACA,IAAI,OAAOA,MAAM,KAAK,QAAQ,EAAE;IAC9B,OAAO,CAAC;MAAEQ,IAAI,EAAE,MAAM;MAAEC,OAAO,EAAET;IAAO,CAAC,CAAC;EAC5C;EACA,OAAOA,MAAM;AACf","ignoreList":[]}
@@ -0,0 +1,107 @@
1
+ /*
2
+ * Copyright 2026 Palantir Technologies, Inc. All rights reserved.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ import { _getFoundryInternal } from "../model.js";
18
+ import { buildAssistantContent, buildOpenAiRequestBody, EMPTY_USAGE, getModelApiName, mapFinishReason, mapUsage, parseToolArguments, postChatCompletions } from "./openAi.js";
19
+ /**
20
+ * Performs a single non-streaming chat completion against the LMS OpenAI proxy
21
+ * and returns a {@link StepResult}. Caller is responsible for prepending any
22
+ * system messages before invoking.
23
+ */
24
+ export async function runStep(input) {
25
+ const apiName = getModelApiName(_getFoundryInternal(input.model).identifier);
26
+ const body = buildOpenAiRequestBody({
27
+ apiName,
28
+ ...input
29
+ }, false);
30
+ const res = await postChatCompletions({
31
+ model: input.model,
32
+ body,
33
+ accept: "application/json",
34
+ headers: input.headers,
35
+ abortSignal: input.abortSignal
36
+ });
37
+ const data = await res.json();
38
+ return parseResponse(data, body, input.warnings);
39
+ }
40
+ function parseResponse(res, request, warnings) {
41
+ const choice = res.choices[0];
42
+ if (choice == null) {
43
+ throw new Error("LMS chat/completions response did not include any choices");
44
+ }
45
+ const message = choice.message;
46
+ const text = message.content ?? "";
47
+ const reasoningText = message.reasoning ?? message.reasoning_content;
48
+ const toolCalls = (message.tool_calls ?? []).map(c => ({
49
+ type: "tool-call",
50
+ toolCallId: c.id,
51
+ toolName: c.function.name,
52
+ input: parseToolArguments(c.function.arguments, warnings)
53
+ }));
54
+ const reasoning = reasoningText != null ? [{
55
+ type: "reasoning",
56
+ text: reasoningText
57
+ }] : [];
58
+ const content = [];
59
+ if (text.length > 0) {
60
+ content.push({
61
+ type: "text",
62
+ text
63
+ });
64
+ }
65
+ for (const r of reasoning) {
66
+ content.push({
67
+ type: "reasoning",
68
+ text: r.text
69
+ });
70
+ }
71
+ for (const tc of toolCalls) {
72
+ content.push({
73
+ ...tc,
74
+ type: "tool-call"
75
+ });
76
+ }
77
+ const usage = res.usage != null ? mapUsage(res.usage) : EMPTY_USAGE;
78
+ const finishReason = mapFinishReason(choice.finish_reason);
79
+ const responseMessages = [{
80
+ role: "assistant",
81
+ content: buildAssistantContent(text, toolCalls)
82
+ }];
83
+ return {
84
+ content,
85
+ text,
86
+ reasoning,
87
+ reasoningText,
88
+ toolCalls,
89
+ toolResults: [],
90
+ finishReason,
91
+ rawFinishReason: choice.finish_reason,
92
+ usage,
93
+ warnings: warnings.length > 0 ? warnings : undefined,
94
+ request: {
95
+ body: request
96
+ },
97
+ response: {
98
+ id: res.id,
99
+ modelId: res.model,
100
+ timestamp: new Date(res.created * 1000),
101
+ body: res,
102
+ messages: responseMessages
103
+ },
104
+ providerMetadata: undefined
105
+ };
106
+ }
107
+ //# sourceMappingURL=runStep.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runStep.js","names":["_getFoundryInternal","buildAssistantContent","buildOpenAiRequestBody","EMPTY_USAGE","getModelApiName","mapFinishReason","mapUsage","parseToolArguments","postChatCompletions","runStep","input","apiName","model","identifier","body","res","accept","headers","abortSignal","data","json","parseResponse","warnings","request","choice","choices","Error","message","text","content","reasoningText","reasoning","reasoning_content","toolCalls","tool_calls","map","c","type","toolCallId","id","toolName","function","name","arguments","length","push","r","tc","usage","finishReason","finish_reason","responseMessages","role","toolResults","rawFinishReason","undefined","response","modelId","timestamp","Date","created","messages","providerMetadata"],"sources":["runStep.ts"],"sourcesContent":["/*\n * Copyright 2026 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { LanguageModel } from \"../model.js\";\nimport { _getFoundryInternal } from \"../model.js\";\nimport type {\n AssistantModelMessage,\n ContentPart,\n LanguageModelUsage,\n ModelMessage,\n ReasoningOutput,\n StepResult,\n ToolCall,\n ToolChoice,\n ToolSet,\n Warning,\n} from \"../types.js\";\nimport {\n buildAssistantContent,\n buildOpenAiRequestBody,\n EMPTY_USAGE,\n getModelApiName,\n mapFinishReason,\n mapUsage,\n type OpenAiAssistantToolCall,\n type OpenAiChatRequestNonStreaming,\n parseToolArguments,\n postChatCompletions,\n} from \"./openAi.js\";\n\nexport interface RunStepInput<TOOLS extends ToolSet> {\n model: LanguageModel;\n /** System messages flattened into the head of this list. */\n messages: ReadonlyArray<ModelMessage>;\n tools: TOOLS | undefined;\n toolChoice: ToolChoice<TOOLS> | undefined;\n maxOutputTokens: number | undefined;\n temperature: number | undefined;\n topP: number | undefined;\n stopSequences: ReadonlyArray<string> | undefined;\n seed: number | undefined;\n presencePenalty: number | undefined;\n frequencyPenalty: number | undefined;\n abortSignal: AbortSignal | undefined;\n headers: Record<string, string | undefined> | undefined;\n /**\n * Mutated in place — additional warnings discovered while building the\n * request are appended here.\n */\n warnings: Array<Warning>;\n}\n\n/**\n * Performs a single non-streaming chat completion against the LMS OpenAI proxy\n * and returns a {@link StepResult}. Caller is responsible for prepending any\n * system messages before invoking.\n */\nexport async function runStep<TOOLS extends ToolSet>(\n input: RunStepInput<TOOLS>,\n): Promise<StepResult<TOOLS>> {\n const apiName = getModelApiName(_getFoundryInternal(input.model).identifier);\n\n const body = buildOpenAiRequestBody<TOOLS>({ apiName, ...input }, false);\n\n const res = await postChatCompletions({\n model: input.model,\n body,\n accept: \"application/json\",\n headers: input.headers,\n abortSignal: input.abortSignal,\n });\n\n const data = (await res.json()) as OpenAiChatCompletionResponse;\n\n return parseResponse<TOOLS>(data, body, input.warnings);\n}\n\ninterface OpenAiChatCompletionResponse {\n id: string;\n object: string;\n created: number;\n model: string;\n choices: Array<{\n index: number;\n message: {\n role: \"assistant\";\n content: string | null;\n tool_calls?: Array<OpenAiAssistantToolCall>;\n reasoning?: string;\n reasoning_content?: string;\n };\n finish_reason: string;\n }>;\n usage?: {\n prompt_tokens: number;\n completion_tokens: number;\n total_tokens: number;\n completion_tokens_details?: {\n reasoning_tokens?: number;\n };\n prompt_tokens_details?: {\n cached_tokens?: number;\n };\n };\n}\n\nfunction parseResponse<TOOLS extends ToolSet>(\n res: OpenAiChatCompletionResponse,\n request: OpenAiChatRequestNonStreaming,\n warnings: Array<Warning>,\n): StepResult<TOOLS> {\n const choice = res.choices[0];\n if (choice == null) {\n throw new Error(\n \"LMS chat/completions response did not include any choices\",\n );\n }\n\n const message = choice.message;\n const text = message.content ?? \"\";\n const reasoningText = message.reasoning ?? message.reasoning_content;\n\n const toolCalls: Array<ToolCall<keyof TOOLS & string>> = (message.tool_calls\n ?? [])\n .map((c) => ({\n type: \"tool-call\",\n toolCallId: c.id,\n toolName: c.function.name as keyof TOOLS & string,\n input: parseToolArguments(c.function.arguments, warnings),\n }));\n\n const reasoning: Array<ReasoningOutput> = reasoningText != null\n ? [{ type: \"reasoning\", text: reasoningText }]\n : [];\n\n const content: Array<ContentPart<TOOLS>> = [];\n if (text.length > 0) {\n content.push({ type: \"text\", text });\n }\n for (const r of reasoning) {\n content.push({ type: \"reasoning\", text: r.text });\n }\n for (const tc of toolCalls) {\n content.push({ ...tc, type: \"tool-call\" });\n }\n\n const usage: LanguageModelUsage = res.usage != null\n ? mapUsage(res.usage)\n : EMPTY_USAGE;\n\n const finishReason = mapFinishReason(choice.finish_reason);\n\n const responseMessages: Array<AssistantModelMessage> = [{\n role: \"assistant\",\n content: buildAssistantContent(text, toolCalls),\n }];\n\n return {\n content,\n text,\n reasoning,\n reasoningText,\n toolCalls,\n toolResults: [],\n finishReason,\n rawFinishReason: choice.finish_reason,\n usage,\n warnings: warnings.length > 0 ? warnings : undefined,\n request: { body: request },\n response: {\n id: res.id,\n modelId: res.model,\n timestamp: new Date(res.created * 1000),\n body: res,\n messages: responseMessages,\n },\n providerMetadata: undefined,\n };\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA,SAASA,mBAAmB,QAAQ,aAAa;AAajD,SACEC,qBAAqB,EACr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