@inneranimalmedia/agentsam-sdk 2.5.0 → 2.6.1

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 (211) hide show
  1. package/AGENTSAM.md +55 -0
  2. package/README.md +12 -8
  3. package/bin/agentsam +2 -0
  4. package/docs/AGENTSAM_ASTRA_OPENAI_INTEGRATION.md +1363 -0
  5. package/docs/CLI_SHELL.md +163 -53
  6. package/docs/PLATFORM_RUNTIME_EVENTS.md +48 -0
  7. package/docs/RELEASES.md +16 -7
  8. package/docs/SOURCE_ARCHITECTURE.md +58 -0
  9. package/docs/TEST_TIERS.md +26 -0
  10. package/migrations/runtime/0001_cli_runtime.sql +298 -0
  11. package/package.json +45 -12
  12. package/packages/agentsam-repository/README.md +15 -0
  13. package/packages/agentsam-repository/package.json +25 -0
  14. package/packages/agentsam-repository/src/contracts.js +113 -0
  15. package/packages/agentsam-repository/src/index.js +3 -0
  16. package/{src/lib → packages/agentsam-repository/src}/merkle/cloudflare-persistence.js +14 -24
  17. package/{src/lib → packages/agentsam-repository/src}/merkle/index.js +1 -0
  18. package/{src/lib → packages/agentsam-repository/src}/merkle/persistence.js +6 -4
  19. package/{src/lib → packages/agentsam-repository/src}/merkle/policy.js +1 -0
  20. package/packages/agentsam-repository/test/contracts.test.mjs +40 -0
  21. package/packages/agentsam-repository/test/git-context.test.mjs +24 -0
  22. package/{test/merkle.test.mjs → packages/agentsam-repository/test/merkle-core.test.mjs} +2 -32
  23. package/{test → packages/agentsam-repository/test}/merkle-persistence.test.mjs +11 -6
  24. package/packages/connectors/cloudflare/package.json +10 -0
  25. package/packages/connectors/cloudflare/src/index.js +127 -0
  26. package/packages/connectors/cloudflare/src/owner.js +76 -0
  27. package/packages/connectors/cloudflare/src/routes.js +223 -0
  28. package/packages/connectors/cloudflare/src/vault.js +80 -0
  29. package/packages/connectors/cloudflare/tests/connector.test.mjs +44 -0
  30. package/packages/identity/package.json +2 -2
  31. package/packages/identity/src/contracts/auth-config.js +18 -7
  32. package/packages/identity/tests/auth-config.test.mjs +9 -5
  33. package/packages/identity/tests/oauth-credentials.test.mjs +4 -4
  34. package/protocol/COMPANY_REPOSITORY_GRAPH_V1.md +91 -0
  35. package/protocol/MERKLE_PERSISTENCE_V1.md +2 -0
  36. package/protocol/MERKLE_PERSISTENCE_V2.md +40 -0
  37. package/protocol/README.md +1 -0
  38. package/protocol/capabilities/cloudflare-cpu-audit-input.schema.json +19 -0
  39. package/protocol/capabilities/cloudflare-cpu-profile-input.schema.json +13 -0
  40. package/protocol/capabilities/cloudflare-wrangler-native-input.schema.json +19 -0
  41. package/protocol/capabilities/manifest.json +47 -0
  42. package/protocol/context/context-budget.schema.json +10 -15
  43. package/protocol/context/context-item.schema.json +4 -5
  44. package/protocol/context/resolved-context-pack.schema.json +19 -14
  45. package/protocol/models/README.md +373 -0
  46. package/protocol/models/model-inventory-v2.schema.json +212 -0
  47. package/protocol/repository/repository-contract.schema.json +24 -0
  48. package/protocol/repository/repository-dependency.schema.json +24 -0
  49. package/protocol/repository/repository-identity.schema.json +17 -0
  50. package/protocol/rpc/v1/common.proto +16 -0
  51. package/protocol/rpc/v1/errors.proto +35 -0
  52. package/protocol/rpc/v1/knowledge.proto +77 -0
  53. package/services/knowledge/package-lock.json +333 -0
  54. package/services/knowledge/package.json +5 -1
  55. package/skills/agentsam-cloudflare-workers/SKILL.md +53 -0
  56. package/skills/agentsam-cloudflare-workers/references/cpu-profiling.md +16 -0
  57. package/skills/agentsam-cloudflare-workers/references/errors-and-observability.md +29 -0
  58. package/skills/agentsam-cloudflare-workers/references/wrangler-native-map.md +28 -0
  59. package/skills/catalog.json +18 -0
  60. package/src/agent/capability-adapter.js +25 -13
  61. package/src/agent/index.js +1 -0
  62. package/src/agent/responses-runner.js +353 -0
  63. package/src/capabilities/repository-snapshot.js +3 -3
  64. package/src/cli.js +118 -31
  65. package/src/cloudflare/cpu-profile.js +115 -0
  66. package/src/cloudflare/index.js +14 -0
  67. package/src/cloudflare/wrangler.js +132 -0
  68. package/src/commands/account-auth.js +47 -0
  69. package/src/commands/cloudflare.js +58 -0
  70. package/src/commands/connections.js +93 -0
  71. package/src/commands/context-economics.js +129 -0
  72. package/src/commands/context.js +1 -1
  73. package/src/commands/db.js +20 -3
  74. package/src/commands/deploy.js +39 -3
  75. package/src/commands/env.js +90 -0
  76. package/src/commands/eval.js +63 -0
  77. package/src/commands/interactive.js +2 -5
  78. package/src/commands/knowledge.js +12 -4
  79. package/src/commands/merkle-persist.js +30 -11
  80. package/src/commands/merkle.js +1 -1
  81. package/src/commands/models.js +149 -46
  82. package/src/commands/ollama.js +26 -0
  83. package/src/commands/preferences.js +130 -61
  84. package/src/commands/resume.js +67 -0
  85. package/src/commands/security.js +5 -3
  86. package/src/commands/shell.js +568 -119
  87. package/src/commands/tunnel.js +2 -2
  88. package/src/commands/whoami.js +86 -0
  89. package/src/context/budget.js +68 -6
  90. package/src/context/index.js +3 -1
  91. package/src/context/rehydrate.js +35 -0
  92. package/src/context/resolve.js +44 -12
  93. package/src/errors/contract.js +236 -0
  94. package/src/errors/diagnostic.js +160 -0
  95. package/src/errors/index.js +23 -0
  96. package/src/eval/context.js +191 -0
  97. package/src/eval/index.js +1 -0
  98. package/src/index.js +68 -2
  99. package/src/knowledge/service/auth.js +13 -0
  100. package/src/knowledge/service/grpc-client.js +115 -0
  101. package/src/knowledge/service/grpc-codec.js +237 -0
  102. package/src/knowledge/service/grpc-server.js +83 -0
  103. package/src/knowledge/service/job-engine.js +248 -0
  104. package/src/knowledge/service/server.js +87 -135
  105. package/src/knowledge/source.js +1 -1
  106. package/src/lib/account-session.js +98 -0
  107. package/src/lib/agent-instructions.js +73 -0
  108. package/src/lib/auth.js +4 -0
  109. package/src/lib/cli-preferences.js +55 -24
  110. package/src/lib/deploy/git-guard.js +69 -0
  111. package/src/lib/deploy/health.js +57 -0
  112. package/src/lib/deploy/local-studio.js +283 -0
  113. package/src/lib/deploy/secret-scan.js +65 -0
  114. package/src/lib/deploy-receipt/index.js +2 -2
  115. package/src/lib/detect-context.js +2 -2
  116. package/src/lib/execution-approvals.js +59 -0
  117. package/src/lib/knowledge-docker.js +6 -3
  118. package/src/lib/local-sessions.js +148 -0
  119. package/src/lib/local-status.js +1 -1
  120. package/src/lib/project-config.js +1 -1
  121. package/src/lib/provider-credentials.js +183 -0
  122. package/src/lib/scaffold/templates/worker-api/index.js +101 -20
  123. package/src/lib/scaffold/wizards/worker-api.js +27 -11
  124. package/src/lib/slash-commands.js +23 -16
  125. package/src/local/migrations.js +93 -0
  126. package/src/local/runtime-store.js +141 -0
  127. package/src/local/sqlite.js +2 -0
  128. package/src/local-pty/server.js +113 -51
  129. package/src/models/catalog.js +135 -0
  130. package/src/models/discovery.js +292 -0
  131. package/src/models/index.js +7 -0
  132. package/src/providers/anthropic-messages.js +192 -0
  133. package/src/providers/cloudflare-chat.js +183 -0
  134. package/src/providers/factory.js +69 -0
  135. package/src/providers/gemini-generate-content.js +208 -0
  136. package/src/providers/index.js +10 -0
  137. package/src/providers/ollama-chat.js +148 -0
  138. package/src/providers/openai-responses.js +426 -0
  139. package/src/repository/index.js +14 -2
  140. package/src/rpc/generated/common_grpc_pb.js +1 -0
  141. package/src/rpc/generated/common_pb.js +536 -0
  142. package/src/rpc/generated/errors_grpc_pb.js +1 -0
  143. package/src/rpc/generated/errors_pb.js +482 -0
  144. package/src/rpc/generated/knowledge_grpc_pb.js +135 -0
  145. package/src/rpc/generated/knowledge_pb.js +2168 -0
  146. package/src/rpc/generated/package.json +3 -0
  147. package/src/security/process.js +35 -9
  148. package/src/security/trust-boundary.js +2 -2
  149. package/src/telemetry/contracts.js +203 -0
  150. package/src/telemetry/events.js +51 -0
  151. package/src/telemetry/index.js +8 -0
  152. package/src/tools/hydrate.js +35 -0
  153. package/src/tools/index.js +1 -0
  154. package/src/ui/boot.js +15 -17
  155. package/src/ui/cli/activity.js +76 -0
  156. package/src/ui/cli/compaction.js +15 -0
  157. package/src/ui/cli/footer.js +39 -0
  158. package/src/ui/cli/help.js +192 -0
  159. package/src/ui/cli/plan.js +20 -0
  160. package/src/ui/cli/runtime-events.js +110 -0
  161. package/src/ui/cli/waiting.js +16 -0
  162. package/src/ui/merkle/render.js +1 -1
  163. package/test/account-session.test.mjs +36 -0
  164. package/test/cli/preferences-runtime.test.mjs +11 -0
  165. package/test/cli/runtime-ui.test.mjs +74 -0
  166. package/test/cli-preferences.test.mjs +26 -5
  167. package/test/cloudflare-connector.test.mjs +96 -0
  168. package/test/cloudflare-runtime.test.mjs +75 -0
  169. package/test/context.test.mjs +61 -12
  170. package/test/deploy-health-scan.test.mjs +67 -0
  171. package/test/error-diagnostics.test.mjs +115 -0
  172. package/test/eval-context.test.mjs +37 -0
  173. package/test/execution-approvals.test.mjs +27 -0
  174. package/test/fixtures/knowledge-rpc-worker.mjs +16 -0
  175. package/test/integration/cli-help.test.mjs +37 -0
  176. package/test/integration/knowledge-rpc.test.mjs +112 -0
  177. package/test/integration/merkle-cli.test.mjs +61 -0
  178. package/test/integration/merkle-persistence-identity.test.mjs +48 -0
  179. package/test/integration/provider-env-cli.test.mjs +49 -0
  180. package/test/integration/provider-factory.test.mjs +197 -0
  181. package/test/integration/repository-company-graph.test.mjs +90 -0
  182. package/test/integration/runtime-migrations.test.mjs +82 -0
  183. package/test/knowledge-service.test.mjs +5 -0
  184. package/test/knowledge.test.mjs +16 -0
  185. package/test/live/terminal-transport.live.test.mjs +24 -0
  186. package/test/local-sessions.test.mjs +48 -0
  187. package/test/local-studio-deploy.test.mjs +83 -0
  188. package/test/model-catalog.test.mjs +43 -0
  189. package/test/models.test.mjs +127 -16
  190. package/test/npm10-lock.test.mjs +29 -0
  191. package/test/ollama.test.mjs +21 -0
  192. package/test/openai-responses.test.mjs +95 -0
  193. package/test/portable-context.test.mjs +1 -1
  194. package/test/provider-credentials.test.mjs +96 -0
  195. package/test/rehydrate.test.mjs +25 -0
  196. package/test/release-hygiene.test.mjs +13 -5
  197. package/test/responses-runner.test.mjs +150 -0
  198. package/test/shell.test.mjs +92 -23
  199. package/test/smoke.mjs +4 -1
  200. package/test/telemetry.test.mjs +79 -0
  201. package/test/terminal/local-pty.mock.test.mjs +151 -0
  202. package/test/tools-search.test.mjs +14 -1
  203. package/test/whoami-resume.test.mjs +56 -0
  204. /package/{src/lib → packages/agentsam-repository/src}/git-context.js +0 -0
  205. /package/{src/lib → packages/agentsam-repository/src}/merkle/diff.js +0 -0
  206. /package/{src/lib → packages/agentsam-repository/src}/merkle/filemeta.js +0 -0
  207. /package/{src/lib → packages/agentsam-repository/src}/merkle/git-ignore.js +0 -0
  208. /package/{src/lib → packages/agentsam-repository/src}/merkle/hash.js +0 -0
  209. /package/{src/lib → packages/agentsam-repository/src}/merkle/semantic.js +0 -0
  210. /package/{src/lib → packages/agentsam-repository/src}/merkle/snapshot.js +0 -0
  211. /package/{src/lib → packages/agentsam-repository/src}/merkle/tree.js +0 -0
@@ -0,0 +1,426 @@
1
+ import { calculateModelCost, getModelRecord } from '../models/index.js';
2
+ import { createAgentEvent, createUsageSnapshot } from '../telemetry/index.js';
3
+ import { createOpenAIHttpError, diagnosticFromError } from '../errors/index.js';
4
+
5
+ const DEFAULT_BASE_URL = 'https://api.openai.com/v1';
6
+
7
+ function clean(value) { return value == null ? '' : String(value).trim(); }
8
+ function integer(value) {
9
+ const n = Number(value ?? 0);
10
+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 0;
11
+ }
12
+ function optionalSignal(timeoutMs) {
13
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return undefined;
14
+ return typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(Math.floor(timeoutMs)) : undefined;
15
+ }
16
+ function normalizeServiceTier(value, requested = 'default') {
17
+ const tier = clean(value).toLowerCase();
18
+ if (tier === 'priority') return 'fast';
19
+ if (tier === 'auto' || !tier) return requested === 'auto' ? 'default' : requested;
20
+ return tier;
21
+ }
22
+
23
+ function historyItems(input) {
24
+ if (input == null) return [];
25
+ if (Array.isArray(input)) return structuredClone(input);
26
+ if (typeof input === 'string') return [{ role: 'user', content: input }];
27
+ return [structuredClone(input)];
28
+ }
29
+
30
+ function xaiCompactionHistory(params = {}, response = {}) {
31
+ const prior = Array.isArray(params.providerState?.compaction_input)
32
+ ? structuredClone(params.providerState.compaction_input)
33
+ : [];
34
+ const current = historyItems(params.input);
35
+ const currentAlreadyStartsWithPrior = prior.length > 0
36
+ && current.length >= prior.length
37
+ && JSON.stringify(current.slice(0, prior.length)) === JSON.stringify(prior);
38
+ if (prior.length) {
39
+ return [
40
+ ...(currentAlreadyStartsWithPrior ? [] : prior),
41
+ ...current,
42
+ ...structuredClone(response.output || []),
43
+ ];
44
+ }
45
+ const prefix = clean(params.instructions)
46
+ ? [{ role: 'system', content: String(params.instructions) }]
47
+ : [];
48
+ return [
49
+ ...prefix,
50
+ ...current,
51
+ ...structuredClone(response.output || []),
52
+ ];
53
+ }
54
+
55
+ export function extractOpenAIOutputText(response = {}) {
56
+ if (typeof response.output_text === 'string') return response.output_text;
57
+ const chunks = [];
58
+ for (const item of response.output || []) {
59
+ if (item?.type !== 'message') continue;
60
+ for (const content of item.content || []) {
61
+ if (content?.type === 'output_text' && typeof content.text === 'string') chunks.push(content.text);
62
+ }
63
+ }
64
+ return chunks.join('');
65
+ }
66
+
67
+ export function extractOpenAIFunctionCalls(response = {}) {
68
+ return (response.output || [])
69
+ .filter((item) => item?.type === 'function_call')
70
+ .map((item) => Object.freeze({
71
+ id: item.id || null,
72
+ call_id: item.call_id,
73
+ name: item.name,
74
+ arguments: item.arguments || '{}',
75
+ status: item.status || null,
76
+ }));
77
+ }
78
+
79
+ function usageParts(response = {}) {
80
+ const usage = response.usage || {};
81
+ return {
82
+ input_tokens: integer(usage.input_tokens),
83
+ cached_input_tokens: integer(usage.input_tokens_details?.cached_tokens),
84
+ cache_write_tokens: integer(usage.input_tokens_details?.cache_write_tokens),
85
+ output_tokens: integer(usage.output_tokens),
86
+ reasoning_tokens: integer(usage.output_tokens_details?.reasoning_tokens),
87
+ };
88
+ }
89
+
90
+ function normalizeTools(tools = []) {
91
+ if (!Array.isArray(tools)) throw new TypeError('tools must be an array');
92
+ return tools.map((tool) => {
93
+ if (tool?.type !== 'function' || !clean(tool.name)) {
94
+ throw new TypeError('OpenAI-compatible adapter tools must be Responses function tool descriptors');
95
+ }
96
+ return {
97
+ type: 'function',
98
+ name: clean(tool.name),
99
+ description: clean(tool.description) || undefined,
100
+ parameters: tool.parameters || { type: 'object', properties: {} },
101
+ strict: tool.strict !== false,
102
+ ...(tool.async === true ? { async: true } : {}),
103
+ };
104
+ });
105
+ }
106
+
107
+ function assertRuntimeConfig(model, reasoningEffort, serviceTier, explicitRecord, expectedProvider) {
108
+ const record = explicitRecord || getModelRecord(model);
109
+ if (!record || record.provider !== expectedProvider) {
110
+ throw new RangeError(`unsupported ${expectedProvider} model record: ${model}`);
111
+ }
112
+ const reasoning = Array.isArray(record.reasoning_efforts) && record.reasoning_efforts.length
113
+ ? record.reasoning_efforts
114
+ : ['auto'];
115
+ const tiers = Array.isArray(record.service_tiers) && record.service_tiers.length
116
+ ? record.service_tiers
117
+ : ['default'];
118
+ if (reasoningEffort !== 'auto' && !reasoning.includes(reasoningEffort)) {
119
+ throw new RangeError(`unsupported reasoning effort for ${record.provider_model_id}: ${reasoningEffort}`);
120
+ }
121
+ if (!tiers.includes(serviceTier)) {
122
+ throw new RangeError(`unsupported service tier for ${record.provider_model_id}: ${serviceTier}`);
123
+ }
124
+ return record;
125
+ }
126
+
127
+ function emitEvent(emit, type, payload, meta = {}) {
128
+ if (typeof emit !== 'function') return;
129
+ emit(createAgentEvent(type, payload, meta));
130
+ }
131
+
132
+ function genericHttpError(providerId, response, parsed, rawText) {
133
+ const error = new Error(
134
+ clean(parsed?.error?.message || parsed?.message) ||
135
+ `${providerId} Responses API returned HTTP ${response.status}`,
136
+ );
137
+ error.status = response.status;
138
+ error.provider = providerId;
139
+ error.body = parsed;
140
+ error.rawText = rawText;
141
+ return error;
142
+ }
143
+
144
+ export function createOpenAIResponsesAdapter(options = {}) {
145
+ const providerId = clean(options.providerId || 'openai').toLowerCase();
146
+ const apiKey = clean(
147
+ options.apiKey ||
148
+ (providerId === 'openai' ? process.env.OPENAI_API_KEY : providerId === 'grok' ? process.env.XAI_API_KEY : ''),
149
+ );
150
+ const baseUrl = clean(options.baseUrl || DEFAULT_BASE_URL).replace(/\/$/, '');
151
+ const fetchImpl = options.fetchImpl || fetch;
152
+ const defaultEmit = options.emit;
153
+ const timeoutMs = options.timeoutMs;
154
+
155
+ async function request(pathname, body, runtime = {}) {
156
+ if (!apiKey) throw new Error(`${providerId}_api_key_required`);
157
+ const response = await fetchImpl(`${baseUrl}${pathname}`, {
158
+ method: 'POST',
159
+ headers: { authorization: `Bearer ${apiKey}`, 'content-type': 'application/json' },
160
+ body: JSON.stringify(body),
161
+ signal: optionalSignal(runtime.timeoutMs ?? timeoutMs),
162
+ });
163
+
164
+ let rawText = '';
165
+ let parsed = null;
166
+ if (typeof response.text === 'function') {
167
+ try { rawText = await response.text(); } catch { rawText = ''; }
168
+ if (rawText) {
169
+ try { parsed = JSON.parse(rawText); } catch { parsed = null; }
170
+ }
171
+ } else if (typeof response.json === 'function') {
172
+ try {
173
+ parsed = await response.json();
174
+ rawText = JSON.stringify(parsed ?? null);
175
+ } catch {
176
+ parsed = null;
177
+ }
178
+ }
179
+
180
+ if (!response.ok) {
181
+ if (providerId === 'openai') {
182
+ throw createOpenAIHttpError({
183
+ status: response.status,
184
+ body: parsed,
185
+ rawText,
186
+ headers: response.headers,
187
+ requestedServiceTier: body?.service_tier,
188
+ });
189
+ }
190
+ throw genericHttpError(providerId, response, parsed, rawText);
191
+ }
192
+
193
+ return Object.freeze({
194
+ data: parsed ?? {},
195
+ http: Object.freeze({
196
+ status: response.status,
197
+ request_id: clean(
198
+ response.headers?.get?.('x-request-id') ||
199
+ response.headers?.get?.('openai-request-id'),
200
+ ) || null,
201
+ ray_id: clean(response.headers?.get?.('cf-ray')) || null,
202
+ }),
203
+ });
204
+ }
205
+
206
+ async function create(params = {}) {
207
+ const suppliedRecord = params.modelRecord || options.modelRecord || null;
208
+ const modelRecord = suppliedRecord || getModelRecord(params.model);
209
+ const model = modelRecord?.provider_model_id || clean(params.model);
210
+ const reasoningEffort = clean(params.reasoningEffort || params.reasoning_effort || 'auto');
211
+ const serviceTier = clean(params.serviceTier || params.service_tier || 'default');
212
+ const record = assertRuntimeConfig(model, reasoningEffort, serviceTier, modelRecord, providerId);
213
+ const emit = params.emit || defaultEmit;
214
+ const meta = { runId: params.runId, sequence: params.sequence };
215
+ const tools = normalizeTools(params.tools || []);
216
+ const previousResponseId = clean(params.previousResponseId || params.providerState?.previous_response_id);
217
+ const requestInput = providerId === 'grok'
218
+ && !previousResponseId
219
+ && Array.isArray(params.providerState?.compaction_input)
220
+ && params.providerState.compaction_input.length
221
+ ? [...structuredClone(params.providerState.compaction_input), ...historyItems(params.input)]
222
+ : params.input ?? '';
223
+
224
+ const body = {
225
+ model,
226
+ input: requestInput,
227
+ ...(reasoningEffort !== 'auto' ? { reasoning: { effort: reasoningEffort } } : {}),
228
+ ...(providerId === 'openai' || serviceTier !== 'default' ? { service_tier: serviceTier } : {}),
229
+ store: params.store !== false,
230
+ truncation: 'disabled',
231
+ parallel_tool_calls: params.parallelToolCalls !== false,
232
+ ...(clean(params.instructions) ? { instructions: String(params.instructions) } : {}),
233
+ ...(tools.length ? { tools } : {}),
234
+ ...(previousResponseId ? { previous_response_id: previousResponseId } : {}),
235
+ ...(Number.isInteger(params.maxOutputTokens) && params.maxOutputTokens > 0
236
+ ? { max_output_tokens: params.maxOutputTokens }
237
+ : {}),
238
+ ...(clean(params.promptCacheKey) ? { prompt_cache_key: clean(params.promptCacheKey) } : {}),
239
+ ...(params.promptCacheOptions ? { prompt_cache_options: params.promptCacheOptions } : {}),
240
+ ...(params.metadata ? { metadata: params.metadata } : {}),
241
+ ...(params.background === true ? { background: true } : {}),
242
+ };
243
+
244
+ emitEvent(emit, 'model.started', {
245
+ provider: providerId,
246
+ model,
247
+ reasoning_effort: reasoningEffort,
248
+ requested_service_tier: serviceTier,
249
+ }, meta);
250
+
251
+ let response;
252
+ let http;
253
+ try {
254
+ const result = await request('/responses', body, params);
255
+ response = result.data;
256
+ http = result.http;
257
+ } catch (error) {
258
+ const diagnostic = diagnosticFromError(error, { source: providerId, kind: 'provider_error' });
259
+ emitEvent(emit, 'error.observed', diagnostic, meta);
260
+ emitEvent(emit, 'run.failed', { stage: 'model', provider: providerId, model, error: diagnostic }, meta);
261
+ throw error;
262
+ }
263
+
264
+ const delta = usageParts(response);
265
+ const actualServiceTier = normalizeServiceTier(response.service_tier, serviceTier);
266
+ const cost = record.pricing
267
+ ? calculateModelCost(record, { ...delta, estimate_kind: 'provider' }, { serviceTier: actualServiceTier })
268
+ : null;
269
+ const usageSnapshot = createUsageSnapshot({
270
+ current_context: {
271
+ input_tokens: delta.input_tokens,
272
+ window_tokens: Number(record.context_window) || 0,
273
+ },
274
+ cumulative: params.cumulativeUsage ? {
275
+ input_tokens: integer(params.cumulativeUsage.input_tokens) + delta.input_tokens,
276
+ output_tokens: integer(params.cumulativeUsage.output_tokens) + delta.output_tokens,
277
+ cached_input_tokens: integer(params.cumulativeUsage.cached_input_tokens) + delta.cached_input_tokens,
278
+ cache_write_tokens: integer(params.cumulativeUsage.cache_write_tokens) + delta.cache_write_tokens,
279
+ reasoning_tokens: integer(params.cumulativeUsage.reasoning_tokens) + delta.reasoning_tokens,
280
+ } : delta,
281
+ estimate_kind: 'provider',
282
+ });
283
+
284
+ emitEvent(emit, 'usage.snapshot', usageSnapshot, meta);
285
+ if (cost) emitEvent(emit, 'cost.snapshot', cost, meta);
286
+ emitEvent(emit, 'model.completed', {
287
+ provider: providerId,
288
+ model,
289
+ response_id: response.id,
290
+ status: response.status,
291
+ request_id: http?.request_id || null,
292
+ ray_id: http?.ray_id || null,
293
+ requested_service_tier: serviceTier,
294
+ actual_service_tier: actualServiceTier,
295
+ }, meta);
296
+
297
+ const providerState = providerId === 'grok'
298
+ ? Object.freeze({
299
+ previous_response_id: response.id || null,
300
+ compaction_input: xaiCompactionHistory(params, response),
301
+ })
302
+ : Object.freeze({ previous_response_id: response.id || null });
303
+
304
+ return Object.freeze({
305
+ provider: providerId,
306
+ model,
307
+ response_id: response.id || null,
308
+ status: response.status || 'completed',
309
+ request_id: http?.request_id || null,
310
+ ray_id: http?.ray_id || null,
311
+ output_text: extractOpenAIOutputText(response),
312
+ tool_calls: Object.freeze(extractOpenAIFunctionCalls(response)),
313
+ usage_delta: Object.freeze(delta),
314
+ usage_snapshot: usageSnapshot,
315
+ cost,
316
+ provider_state: providerState,
317
+ requested_service_tier: serviceTier,
318
+ actual_service_tier: actualServiceTier,
319
+ raw: response,
320
+ });
321
+ }
322
+
323
+ async function continueWithToolOutputs(params = {}) {
324
+ const previousResponseId = clean(params.previousResponseId || params.providerState?.previous_response_id);
325
+ if (!previousResponseId) throw new TypeError('previousResponseId is required');
326
+ const outputs = (params.toolOutputs || []).map((row) => {
327
+ const callId = clean(row.call_id || row.callId);
328
+ if (!callId) throw new TypeError('tool output call_id is required');
329
+ const output = typeof row.output === 'string' ? row.output : JSON.stringify(row.output ?? null);
330
+ return { type: 'function_call_output', call_id: callId, output };
331
+ });
332
+ if (!outputs.length) throw new TypeError('at least one tool output is required');
333
+ return create({ ...params, previousResponseId, input: outputs });
334
+ }
335
+
336
+ async function compact(params = {}) {
337
+ if (providerId !== 'openai' && providerId !== 'grok') throw new Error(`native_compaction_unavailable:${providerId}`);
338
+ const modelRecord = params.modelRecord || options.modelRecord || getModelRecord(params.model);
339
+ const model = modelRecord?.provider_model_id || clean(params.model);
340
+ if (!modelRecord || modelRecord.provider !== providerId) {
341
+ throw new RangeError(`unsupported ${providerId} model record: ${params.model}`);
342
+ }
343
+
344
+ const emit = params.emit || defaultEmit;
345
+ const meta = { runId: params.runId, sequence: params.sequence };
346
+ const previousResponseId = clean(params.previousResponseId || params.providerState?.previous_response_id);
347
+ const xaiHistory = Array.isArray(params.providerState?.compaction_input)
348
+ ? structuredClone(params.providerState.compaction_input)
349
+ : [];
350
+ if (providerId === 'grok' && !xaiHistory.length) {
351
+ throw new Error('xai_compaction_history_unavailable');
352
+ }
353
+ const body = providerId === 'grok'
354
+ ? {
355
+ model,
356
+ input: xaiHistory,
357
+ }
358
+ : {
359
+ model,
360
+ ...(previousResponseId ? { previous_response_id: previousResponseId } : {}),
361
+ ...(params.input != null ? { input: params.input } : {}),
362
+ ...(clean(params.instructions) ? { instructions: String(params.instructions) } : {}),
363
+ ...(clean(params.promptCacheKey) ? { prompt_cache_key: clean(params.promptCacheKey) } : {}),
364
+ ...(params.promptCacheOptions ? { prompt_cache_options: params.promptCacheOptions } : {}),
365
+ };
366
+
367
+ const compactStartedAt = Date.now();
368
+ emitEvent(emit, 'context.compaction.started', {
369
+ provider: providerId,
370
+ model,
371
+ previous_response_id: previousResponseId || null,
372
+ }, meta);
373
+
374
+ let response;
375
+ let http;
376
+ try {
377
+ const result = await request('/responses/compact', body, params);
378
+ response = result.data;
379
+ http = result.http;
380
+ } catch (error) {
381
+ const diagnostic = diagnosticFromError(error, { source: providerId, kind: 'provider_error' });
382
+ emitEvent(emit, 'error.observed', diagnostic, meta);
383
+ emitEvent(emit, 'run.failed', { stage: 'compaction', provider: providerId, model, error: diagnostic }, meta);
384
+ throw error;
385
+ }
386
+
387
+ const compactUsage = usageParts(response);
388
+ const compactCost = modelRecord.pricing
389
+ ? calculateModelCost(modelRecord, { ...compactUsage, estimate_kind: 'provider' }, { serviceTier: 'default' })
390
+ : null;
391
+ if (compactCost) emitEvent(emit, 'cost.snapshot', compactCost, meta);
392
+ emitEvent(emit, 'context.compaction.completed', {
393
+ provider: providerId,
394
+ model,
395
+ compaction_id: response.id,
396
+ usage: response.usage || null,
397
+ tokens_before: Number(params.tokensBefore || compactUsage.input_tokens || 0),
398
+ tokens_after: Number(compactUsage.output_tokens || 0),
399
+ duration_ms: Date.now() - compactStartedAt,
400
+ request_id: http?.request_id || null,
401
+ ray_id: http?.ray_id || null,
402
+ }, meta);
403
+
404
+ return Object.freeze({
405
+ provider: providerId,
406
+ model,
407
+ compaction_id: response.id,
408
+ request_id: http?.request_id || null,
409
+ ray_id: http?.ray_id || null,
410
+ output: Object.freeze(response.output || []),
411
+ provider_state: providerId === 'grok'
412
+ ? Object.freeze({ previous_response_id: null, compaction_input: structuredClone(response.output || []) })
413
+ : Object.freeze({ previous_response_id: null }),
414
+ usage: response.usage || null,
415
+ cost: compactCost,
416
+ raw: response,
417
+ });
418
+ }
419
+
420
+ return Object.freeze({
421
+ provider: providerId,
422
+ create,
423
+ continueWithToolOutputs,
424
+ ...(['openai', 'grok'].includes(providerId) ? { compact } : {}),
425
+ });
426
+ }
@@ -1,4 +1,16 @@
1
1
  export { repositorySnapshot } from '../capabilities/repository-snapshot.js';
2
- export { buildMerkleTree, diffTrees, readSnapshot, saveSnapshot, validateSnapshot } from '../lib/merkle/index.js';
3
- export { resolveGitContext, tryResolveGitContext, normalizeGitRemote } from '../lib/git-context.js';
2
+ export { buildMerkleTree, diffTrees, readSnapshot, saveSnapshot, validateSnapshot } from '../../packages/agentsam-repository/src/merkle/index.js';
3
+ export { resolveGitContext, tryResolveGitContext, normalizeGitRemote } from '../../packages/agentsam-repository/src/git-context.js';
4
4
  export { buildRetrievalPlan, createContextPack } from '../knowledge/index.js';
5
+ export {
6
+ COMPANY_REPOSITORY_GRAPH_SCHEMA_VERSION,
7
+ REPOSITORY_STATUSES,
8
+ REPOSITORY_CONTRACT_TYPES,
9
+ REPOSITORY_CONTRACT_STATUSES,
10
+ REPOSITORY_DEPENDENCY_TYPES,
11
+ REPOSITORY_DEPENDENCY_CRITICALITIES,
12
+ REPOSITORY_FAILURE_POLICIES,
13
+ createRepositoryIdentity,
14
+ createRepositoryContract,
15
+ createRepositoryDependency,
16
+ } from '../../packages/agentsam-repository/src/contracts.js';
@@ -0,0 +1 @@
1
+ // GENERATED CODE -- NO SERVICES IN PROTO