@inneranimalmedia/agentsam-sdk 2.6.8 → 2.6.10

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 (203) hide show
  1. package/README.md +18 -0
  2. package/apps/README.md +25 -0
  3. package/apps/cad-creator/shared/cad/package.json +1 -1
  4. package/apps/client-cms-editor/backend/package.json +5 -7
  5. package/apps/client-cms-editor/frontend/package.json +5 -7
  6. package/apps/client-cms-editor/frontend/tsconfig.json +27 -8
  7. package/apps/client-cms-editor/package-lock.json +8 -8
  8. package/apps/client-cms-editor/package.json +1 -1
  9. package/apps/client-cms-editor/shared/cms/package.json +3 -5
  10. package/docs/LOCAL_ENGINE_COMPUTE_AUDIT_PLAN.md +299 -0
  11. package/docs/architecture/HOOKS-MODELS-SELF-HOSTING-PLAN.md +199 -0
  12. package/examples/hyperspace-demo/index.html +16 -0
  13. package/examples/hyperspace-demo/package.json +21 -0
  14. package/examples/hyperspace-demo/src/main.tsx +160 -0
  15. package/examples/hyperspace-demo/tsconfig.json +9 -0
  16. package/examples/hyperspace-demo/vite.config.ts +24 -0
  17. package/migrations/runtime/0005_agentsam_hooks.sql +87 -0
  18. package/package.json +37 -10
  19. package/packages/agentsam-brand/package.json +1 -1
  20. package/packages/agentsam-brand/src/core/v2/compile.js +1 -1
  21. package/packages/agentsam-brand/src/core/v2/schema.js +1 -1
  22. package/packages/agentsam-contracts/package.json +71 -20
  23. package/packages/agentsam-contracts/scripts/build.mjs +18 -0
  24. package/packages/agentsam-contracts/src/errors.ts +19 -10
  25. package/packages/agentsam-contracts/test/contracts.test.mjs +4 -1
  26. package/packages/agentsam-contracts/test/repository.test.mjs +4 -1
  27. package/packages/agentsam-contracts/tsconfig.build.json +10 -0
  28. package/packages/agentsam-errors/package.json +13 -4
  29. package/packages/agentsam-errors/protocol/agentsam.error.v2.schema.json +821 -0
  30. package/packages/agentsam-errors/protocol/error-catalog.json +3512 -0
  31. package/packages/agentsam-errors/src/envelope.js +63 -11
  32. package/packages/agentsam-errors/src/error.js +6 -0
  33. package/packages/agentsam-errors/src/fingerprint.js +9 -1
  34. package/packages/agentsam-errors/src/normalize.js +51 -6
  35. package/packages/agentsam-errors/src/recovery.js +9 -35
  36. package/packages/agentsam-errors/src/transport.js +6 -1
  37. package/packages/agentsam-errors/src/vocabulary.js +515 -126
  38. package/packages/agentsam-errors/test/catalog-v2.test.mjs +106 -0
  39. package/packages/agentsam-errors/types/index.d.ts +157 -0
  40. package/packages/agentsam-goap/package.json +2 -2
  41. package/packages/agentsam-hooks/README.md +206 -0
  42. package/packages/agentsam-hooks/bin/agentsam-hooks.mjs +64 -0
  43. package/packages/agentsam-hooks/bindings/go/command.go +55 -0
  44. package/packages/agentsam-hooks/bindings/go/errors_generated.go +402 -0
  45. package/packages/agentsam-hooks/bindings/go/go.mod +3 -0
  46. package/packages/agentsam-hooks/bindings/go/hooks.go +285 -0
  47. package/packages/agentsam-hooks/bindings/go/hooks_test.go +48 -0
  48. package/packages/agentsam-hooks/bindings/rust/Cargo.toml +11 -0
  49. package/packages/agentsam-hooks/bindings/rust/src/errors_generated.rs +396 -0
  50. package/packages/agentsam-hooks/bindings/rust/src/lib.rs +397 -0
  51. package/packages/agentsam-hooks/package.json +69 -0
  52. package/packages/agentsam-hooks/schema/manifest.json +54 -0
  53. package/packages/agentsam-hooks/scripts/clean-protocol.mjs +17 -0
  54. package/packages/agentsam-hooks/scripts/sync-protocol.mjs +27 -0
  55. package/packages/agentsam-hooks/src/adapters/agents.js +82 -0
  56. package/packages/agentsam-hooks/src/adapters/callback.js +4 -0
  57. package/packages/agentsam-hooks/src/adapters/capability.js +122 -0
  58. package/packages/agentsam-hooks/src/adapters/command.js +104 -0
  59. package/packages/agentsam-hooks/src/adapters/composite.js +31 -0
  60. package/packages/agentsam-hooks/src/adapters/http.js +58 -0
  61. package/packages/agentsam-hooks/src/adapters/lsp.js +116 -0
  62. package/packages/agentsam-hooks/src/adapters/mcp.js +76 -0
  63. package/packages/agentsam-hooks/src/adapters/provider.js +129 -0
  64. package/packages/agentsam-hooks/src/config.js +143 -0
  65. package/packages/agentsam-hooks/src/contracts.js +284 -0
  66. package/packages/agentsam-hooks/src/errors-generated.js +2732 -0
  67. package/packages/agentsam-hooks/src/index.d.ts +193 -0
  68. package/packages/agentsam-hooks/src/index.js +14 -0
  69. package/packages/agentsam-hooks/src/policy.js +34 -0
  70. package/packages/agentsam-hooks/src/runtime.js +312 -0
  71. package/packages/agentsam-hooks/src/store.js +264 -0
  72. package/packages/agentsam-hooks/test/adapters.test.mjs +216 -0
  73. package/packages/agentsam-hooks/test/runtime.test.mjs +258 -0
  74. package/packages/agentsam-knowledge/package.json +3 -2
  75. package/packages/agentsam-nav/package.json +1 -1
  76. package/packages/agentsam-queue-control/package.json +1 -1
  77. package/packages/agentsam-rapid-rust/src/main.rs +1 -0
  78. package/packages/agentsam-repository/package.json +3 -2
  79. package/packages/agentsam-vault/package.json +8 -5
  80. package/packages/agentsam-workbench/package.json +45 -18
  81. package/packages/connectors/cloudflare/package.json +1 -1
  82. package/packages/heuristic-theme/package.json +1 -1
  83. package/packages/identity/package.json +3 -2
  84. package/packages/identity/tests/lane1-packed-consumer.test.mjs +9 -1
  85. package/packages/providers/completeful/package.json +1 -1
  86. package/packages/theme-church-site/README.md +2 -2
  87. package/packages/theme-church-site/package.json +2 -3
  88. package/packages/theme-church-site/src/index.js +1 -1
  89. package/packages/theme-church-site/test/theme.test.mjs +1 -1
  90. package/packages/theme-companions-site/README.md +2 -2
  91. package/packages/theme-companions-site/package.json +2 -3
  92. package/packages/theme-companions-site/src/index.js +1 -1
  93. package/packages/theme-companions-site/test/theme.test.mjs +1 -1
  94. package/packages/theme-floors-site/README.md +2 -2
  95. package/packages/theme-floors-site/package.json +2 -3
  96. package/packages/theme-floors-site/src/index.js +1 -1
  97. package/packages/theme-floors-site/test/theme.test.mjs +1 -1
  98. package/packages/theme-fuelnfree-site/README.md +2 -2
  99. package/packages/theme-fuelnfree-site/package.json +2 -3
  100. package/packages/theme-fuelnfree-site/src/index.js +1 -1
  101. package/packages/theme-fuelnfree-site/test/theme.test.mjs +1 -1
  102. package/packages/theme-handyman-site/README.md +2 -2
  103. package/packages/theme-handyman-site/package.json +2 -3
  104. package/packages/theme-handyman-site/src/index.js +1 -1
  105. package/packages/theme-handyman-site/test/theme.test.mjs +1 -1
  106. package/packages/theme-insurance-site/README.md +2 -2
  107. package/packages/theme-insurance-site/package.json +2 -3
  108. package/packages/theme-insurance-site/src/index.js +1 -1
  109. package/packages/theme-insurance-site/test/theme.test.mjs +1 -1
  110. package/packages/theme-scenes/package.json +1 -1
  111. package/packages/theme-shinshu-site/README.md +2 -2
  112. package/packages/theme-shinshu-site/package.json +2 -3
  113. package/packages/theme-shinshu-site/src/index.js +1 -1
  114. package/packages/theme-shinshu-site/test/theme.test.mjs +1 -1
  115. package/packages/work-graph/package.json +3 -2
  116. package/protocol/apps/agentsam.app.v1.schema.json +1 -1
  117. package/protocol/apps/agentsam.host-install.v1.schema.json +1 -1
  118. package/protocol/assets/asset-record.v1.schema.json +1 -1
  119. package/protocol/brand/brandpack.v1.schema.json +1 -1
  120. package/protocol/capabilities/capability-manifest.schema.json +1 -1
  121. package/protocol/capabilities/knowledge-search-input.schema.json +1 -0
  122. package/protocol/credentials/issue.v1.schema.json +1 -1
  123. package/protocol/database/agentsam.schema-pack.v1.schema.json +1 -1
  124. package/protocol/database/connection.v1.schema.json +1 -1
  125. package/protocol/embeddings/embedding-profile.v1.schema.json +1 -1
  126. package/protocol/errors/README.md +36 -0
  127. package/protocol/errors/agentsam.error.v2.schema.json +821 -0
  128. package/protocol/errors/error-catalog.json +3506 -158
  129. package/protocol/errors/error-envelope.schema.json +195 -52
  130. package/protocol/errors/recovery.v1.schema.json +1 -1
  131. package/protocol/features/agentsam.feature.v1.schema.json +1 -1
  132. package/protocol/hooks/README.md +18 -0
  133. package/protocol/hooks/agentsam.hook.output.v1.schema.json +27 -0
  134. package/protocol/hooks/agentsam.hook.receipt.v1.schema.json +61 -0
  135. package/protocol/hooks/agentsam.hook.v1.schema.json +35 -0
  136. package/protocol/hooks/agentsam.hooks.config.v1.schema.json +78 -0
  137. package/protocol/local-engine/benchmark.v1.schema.json +14 -0
  138. package/protocol/local-engine/engine.v1.schema.json +17 -0
  139. package/protocol/models/model-inventory-v2.schema.json +1 -1
  140. package/protocol/models/provider-model-snapshot.v1.schema.json +22 -0
  141. package/protocol/rpc/v1/errors.proto +1 -0
  142. package/protocol/runtime/agentsam.runtime.v1.schema.json +1 -1
  143. package/protocol/runtime/workspace-fs.v1.schema.json +1 -1
  144. package/protocol/sam/activity.v1.schema.json +1 -1
  145. package/protocol/sam/answer.v1.schema.json +1 -1
  146. package/protocol/sam/calibration.v1.schema.json +1 -1
  147. package/protocol/sam/decision-receipt.v1.schema.json +1 -1
  148. package/protocol/sam/evaluation.v1.schema.json +1 -1
  149. package/protocol/sam/operation.schema.json +1 -1
  150. package/protocol/sam/outcome.v1.schema.json +1 -1
  151. package/protocol/sam/question.v1.schema.json +1 -1
  152. package/protocol/sam/result.schema.json +1 -1
  153. package/protocol/sam/state.v1.schema.json +1 -1
  154. package/protocol/scoring/scorecard.v1.schema.json +1 -1
  155. package/protocol/skills/agentsam.interaction.v1.schema.json +1 -1
  156. package/protocol/skills/agentsam.skill.v1.schema.json +1 -1
  157. package/protocol/theme-refinery/product-metadata.schema.json +1 -1
  158. package/protocol/theme-refinery/reconciliation-receipt.schema.json +1 -1
  159. package/protocol/ui/icon.v1.schema.json +1 -1
  160. package/python/README.md +20 -0
  161. package/python/agentsam_sdk/errors/__init__.py +4 -0
  162. package/python/agentsam_sdk/errors/vocabulary.py +2730 -0
  163. package/python/agentsam_sdk/hooks/__init__.py +32 -0
  164. package/python/agentsam_sdk/hooks/adapters.py +132 -0
  165. package/python/agentsam_sdk/hooks/contracts.py +121 -0
  166. package/python/agentsam_sdk/hooks/runtime.py +253 -0
  167. package/python/tests/test_hooks.py +115 -0
  168. package/src/agent/responses-runner.js +145 -1
  169. package/src/cli/command-catalog.js +2 -0
  170. package/src/cli.js +19 -0
  171. package/src/commands/app.js +10 -0
  172. package/src/commands/cheat-sheet.js +1 -0
  173. package/src/commands/engine.js +10 -0
  174. package/src/commands/hooks.js +260 -0
  175. package/src/commands/machine.js +71 -38
  176. package/src/commands/models.js +1 -1
  177. package/src/commands/package.js +10 -3
  178. package/src/commands/runtime.js +25 -10
  179. package/src/commands/setup.js +30 -6
  180. package/src/commands/shell.js +114 -9
  181. package/src/commands/terminal.js +20 -8
  182. package/src/errors/contract.js +4 -4
  183. package/src/errors/diagnostic.js +10 -10
  184. package/src/errors/index.js +1 -1
  185. package/src/index.js +52 -0
  186. package/src/indexing/ingest/materials.js +237 -30
  187. package/src/knowledge/service/grpc-codec.js +2 -0
  188. package/src/lib/setup/runtime.js +4 -2
  189. package/src/lib/slash-commands.js +1 -0
  190. package/src/local/runtime-store.js +46 -0
  191. package/src/local-engine/assets.js +37 -0
  192. package/src/local-engine/audit.js +133 -0
  193. package/src/local-engine/benchmark.js +26 -0
  194. package/src/local-engine/contracts.js +101 -0
  195. package/src/local-engine/engines.js +142 -0
  196. package/src/local-engine/index.js +18 -0
  197. package/src/local-engine/runtime.js +39 -0
  198. package/src/models/catalog.js +0 -49
  199. package/src/models/inventory-core.js +69 -0
  200. package/src/plugins/index.js +8 -1
  201. package/src/plugins/registry.js +56 -0
  202. package/src/rpc/generated/errors_pb.js +49 -1
  203. package/src/tools/runtime.js +13 -5
@@ -0,0 +1,133 @@
1
+ import os from 'node:os';
2
+ import { spawnSync } from 'node:child_process';
3
+ import { executable, runCommand } from './runtime.js';
4
+
5
+ export const COMPUTE_AUDIT_SCHEMA = 'agentsam.compute.audit.v1';
6
+
7
+ function command(command, args = [], runner = spawnSync) {
8
+ const result = runner(command, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 5000 });
9
+ return { ok: result.status === 0, stdout: String(result.stdout || '').trim(), stderr: String(result.stderr || '').trim(), status: result.status };
10
+ }
11
+
12
+ function value(text, key) {
13
+ const match = String(text || '').match(new RegExp(`^${key}:\\s*(.+)$`, 'mi'));
14
+ return match?.[1]?.trim() || null;
15
+ }
16
+
17
+ function bytes(valueText) {
18
+ const n = Number(valueText);
19
+ if (Number.isFinite(n) && n > 0) return Math.floor(n);
20
+ const match = String(valueText || '').match(/([\d.]+)\s*(GB|TB|MB)/i);
21
+ if (!match) return null;
22
+ const factor = { mb: 1024 ** 2, gb: 1024 ** 3, tb: 1024 ** 4 }[match[2].toLowerCase()];
23
+ return Math.floor(Number(match[1]) * factor);
24
+ }
25
+
26
+ export function parseSystemProfilerHardware(text) {
27
+ const chip = text.match(/Chip:\s*(.+)/i)?.[1]?.trim() || text.match(/Processor Name:\s*(.+)/i)?.[1]?.trim() || null;
28
+ const memory = text.match(/Memory:\s*(.+)/i)?.[1]?.trim() || null;
29
+ const cores = text.match(/Total Number of Cores:\s*(.+)/i)?.[1]?.trim() || null;
30
+ return { chip, unified_memory_bytes: bytes(memory), core_summary: cores };
31
+ }
32
+
33
+ export function parseAppleAudit({ sysctlText = '', profilerText = '', platform = process.platform, arch = process.arch } = {}) {
34
+ const hardware = parseSystemProfilerHardware(profilerText);
35
+ const chip = hardware.chip || value(sysctlText, 'machdep.cpu.brand_string') || value(sysctlText, 'hw.model');
36
+ const memory = hardware.unified_memory_bytes || bytes(value(sysctlText, 'hw.memsize'));
37
+ const appleSilicon = platform === 'darwin' && (arch === 'arm64' || /apple\s*m[1-9]/i.test(chip || ''));
38
+ return {
39
+ schema_version: COMPUTE_AUDIT_SCHEMA,
40
+ generated_at: new Date().toISOString(),
41
+ host: { platform, arch, hostname: os.hostname() },
42
+ apple_silicon: appleSilicon,
43
+ chip: { name: chip, family: chip?.match(/Apple\s+(M\d[^ ]*)/i)?.[1] || null, cores: hardware.core_summary },
44
+ memory: { unified_memory_bytes: memory, vram_bytes: null, model: appleSilicon ? 'unified' : 'unknown' },
45
+ metal: { available: appleSilicon ? null : false, features: [], evidence: appleSilicon ? 'not_probed' : 'non_apple_host' },
46
+ evidence: [],
47
+ warnings: appleSilicon ? ['Metal feature probing requires the macOS native helper and is not inferred from chip identity.'] : ['Apple Silicon audit is unavailable on this host.'],
48
+ };
49
+ }
50
+
51
+ export function auditAppleHost(options = {}) {
52
+ const env = options.env || process.env;
53
+ const platform = options.platform || process.platform;
54
+ const arch = options.arch || process.arch;
55
+ if (platform !== 'darwin') return parseAppleAudit({ platform, arch });
56
+ const sysctl = command('sysctl', ['-n', 'hw.model', 'hw.memsize'], options.runner || spawnSync);
57
+ const profiler = command('system_profiler', ['SPHardwareDataType', 'SPDisplaysDataType'], options.runner || spawnSync);
58
+ const audit = parseAppleAudit({ sysctlText: sysctl.stdout, profilerText: profiler.stdout, platform, arch });
59
+ audit.evidence.push({ source: 'sysctl', ok: sysctl.ok });
60
+ audit.evidence.push({ source: 'system_profiler', ok: profiler.ok });
61
+ audit.host.env_override = Boolean(env.AGENTSAM_HOME);
62
+ return audit;
63
+ }
64
+
65
+ export function auditTools(options = {}) {
66
+ const engines = [
67
+ { id: 'ollama', commands: ['ollama'] },
68
+ { id: 'llama.cpp', commands: ['llama-server', 'llama-cli'] },
69
+ { id: 'mlx-lm', commands: ['mlx_lm.server', 'mlx_lm'] },
70
+ ];
71
+ return engines.map((engine) => {
72
+ const hits = engine.commands.map((name) => ({ name, path: executable(name, options.env || process.env) })).filter((row) => row.path);
73
+ const version = hits[0] ? runCommand(hits[0].name, ['--version'], options).stdout.trim() : null;
74
+ return { engine_id: engine.id, installed: hits.length > 0, commands: hits, version: version || null };
75
+ });
76
+ }
77
+
78
+ function auditLinuxHost(options = {}) {
79
+ const env = options.env || process.env;
80
+ const memory = command('free', ['-b'], options.runner || spawnSync);
81
+ const cpu = command('lscpu', [], options.runner || spawnSync);
82
+ const osRelease = command('uname', ['-a'], options.runner || spawnSync);
83
+ const memoryLine = memory.stdout.split(/\n/).find((line) => /^Mem:/i.test(line));
84
+ const memoryBytes = memoryLine ? Number(memoryLine.trim().split(/\s+/)[1]) || null : null;
85
+ return {
86
+ schema_version: COMPUTE_AUDIT_SCHEMA,
87
+ generated_at: new Date().toISOString(),
88
+ host: { platform: 'linux', arch: options.arch || process.arch, hostname: os.hostname() },
89
+ apple_silicon: false,
90
+ chip: { name: value(cpu.stdout, 'Model name') || value(cpu.stdout, 'Architecture'), family: null, cores: value(cpu.stdout, 'CPU\\(s\\)') },
91
+ memory: { unified_memory_bytes: null, system_memory_bytes: memoryBytes, vram_bytes: null, model: 'system' },
92
+ accelerators: [{ id: 'nvidia-smi', available: Boolean(executable('nvidia-smi', env)), evidence: 'optional' }],
93
+ shells: auditShells(options),
94
+ evidence: [{ source: 'uname', ok: osRelease.ok }, { source: 'lscpu', ok: cpu.ok }, { source: 'free', ok: memory.ok }],
95
+ warnings: ['Linux accelerator memory is engine/vendor-specific and is not inferred as system VRAM.'],
96
+ };
97
+ }
98
+
99
+ function auditWindowsHost(options = {}) {
100
+ const env = options.env || process.env;
101
+ const powershell = executable('pwsh', env) || executable('powershell.exe', env);
102
+ const result = powershell ? command(powershell, ['-NoProfile', '-NonInteractive', '-Command', '$c=Get-CimInstance Win32_ComputerSystem; $g=Get-CimInstance Win32_VideoController; [pscustomobject]@{model=$c.Model;memory=$c.TotalPhysicalMemory;gpu=($g.Name -join ";")}|ConvertTo-Json -Compress'], options.runner || spawnSync) : { ok: false, stdout: '' };
103
+ let facts = {}; try { facts = JSON.parse(result.stdout || '{}'); } catch {}
104
+ return {
105
+ schema_version: COMPUTE_AUDIT_SCHEMA,
106
+ generated_at: new Date().toISOString(),
107
+ host: { platform: 'windows', arch: options.arch || process.arch, hostname: os.hostname() },
108
+ apple_silicon: false,
109
+ chip: { name: facts.model || null, family: null, cores: null },
110
+ memory: { unified_memory_bytes: null, system_memory_bytes: Number(facts.memory) || null, vram_bytes: null, model: 'system' },
111
+ accelerators: [{ id: 'video-controller', available: Boolean(facts.gpu), name: facts.gpu || null }],
112
+ shells: auditShells(options),
113
+ evidence: [{ source: powershell || 'powershell', ok: result.ok }],
114
+ warnings: ['Windows GPU memory is reported only when the vendor API exposes it; no VRAM estimate is made.'],
115
+ };
116
+ }
117
+
118
+ function auditShells(options = {}) {
119
+ const env = options.env || process.env;
120
+ return ['pwsh', 'powershell.exe', 'bash', 'zsh', 'sh'].map((name) => ({ id: name, path: executable(name, env), available: Boolean(executable(name, env)) }));
121
+ }
122
+
123
+ export function auditHost(options = {}) {
124
+ const platform = options.platform || process.platform;
125
+ if (platform === 'darwin') return { ...auditAppleHost(options), shells: auditShells(options) };
126
+ if (platform === 'win32') return auditWindowsHost(options);
127
+ if (platform === 'linux') return auditLinuxHost(options);
128
+ return { ...parseAppleAudit({ platform, arch: options.arch || process.arch }), shells: auditShells(options) };
129
+ }
130
+
131
+ export function auditLocalCompute(options = {}) {
132
+ return { schema_version: COMPUTE_AUDIT_SCHEMA, generated_at: new Date().toISOString(), hardware: auditHost(options), engines: auditTools(options) };
133
+ }
@@ -0,0 +1,26 @@
1
+ import { LOCAL_ENGINE_BENCHMARK_SCHEMA } from './contracts.js';
2
+
3
+ function tokenCount(result) { return Number(result?.usage?.output_tokens || result?.usage?.completion_tokens || String(result?.output_text || '').trim().split(/\s+/).filter(Boolean).length); }
4
+ function validateShape(value, schema) {
5
+ if (!schema || typeof schema !== 'object') return { valid: true, error: null };
6
+ if (schema.type === 'object' && (value === null || typeof value !== 'object' || Array.isArray(value))) return { valid: false, error: 'expected_object' };
7
+ if (schema.type === 'array' && !Array.isArray(value)) return { valid: false, error: 'expected_array' };
8
+ if (schema.required) for (const key of schema.required) if (!(key in value)) return { valid: false, error: `missing_required:${key}` };
9
+ if (schema.properties && value && typeof value === 'object') for (const [key, child] of Object.entries(schema.properties)) if (key in value) { const result = validateShape(value[key], child); if (!result.valid) return { valid: false, error: `${key}.${result.error}` }; }
10
+ return { valid: true, error: null };
11
+ }
12
+ export function validateStructuredOutput(text, schema = null) {
13
+ try { const value = JSON.parse(String(text || '')); const shape = validateShape(value, schema); return { valid: shape.valid, parse_error: null, schema_error: shape.valid ? null : shape.error, value: shape.valid ? value : null, grammar_enforced: false, tool_arguments_valid: shape.valid }; } catch (error) { return { valid: false, parse_error: error.message, schema_error: null, value: null, grammar_enforced: false, tool_arguments_valid: false }; }
14
+ }
15
+ export async function benchmarkEngine(engine, options = {}) {
16
+ const runs = Math.max(1, Number(options.runs) || 1); const prompt = options.prompt || 'Reply with a short JSON object containing an answer field.'; const results = [];
17
+ for (let i = 0; i < runs; i += 1) {
18
+ const started = performance.now();
19
+ const result = await engine.chat({ model: options.model, messages: [{ role: 'user', content: prompt }], responseFormat: options.schema ? { type: 'json_object' } : null });
20
+ const ended = performance.now(); const outputTokens = tokenCount(result); const ttft = Number.isFinite(result?.timing?.ttft_ms) ? result.timing.ttft_ms : null; const elapsed = ended - started;
21
+ results.push({ run: i + 1, ttft_ms: ttft, elapsed_ms: elapsed, output_tokens: outputTokens, tokens_per_second: elapsed > 0 ? outputTokens / (elapsed / 1000) : null, structured_output: options.schema ? validateStructuredOutput(result.output_text, options.schema) : null });
22
+ }
23
+ return { schema_version: LOCAL_ENGINE_BENCHMARK_SCHEMA, engine_id: engine.id, model: options.model || null, generated_at: new Date().toISOString(), fixture: { id: options.fixtureId || 'default-json', prompt_hash: cryptoHash(prompt) }, runs: results, summary: summarize(results), resource: { memory: null, source: 'not_available' }, warnings: ['Memory utilization requires an engine/platform sampler.', 'TTFT is null unless the engine adapter reports a measured first-token time.'] };
24
+ }
25
+ function cryptoHash(value) { let h = 2166136261; for (const char of String(value)) h = Math.imul(h ^ char.charCodeAt(0), 16777619); return (h >>> 0).toString(16); }
26
+ function summarize(rows) { const average = (key) => { const values = rows.map((row) => row[key]).filter((x) => Number.isFinite(x)); return values.length ? values.reduce((a, b) => a + b, 0) / values.length : null; }; return { average_ttft_ms: average('ttft_ms'), average_tokens_per_second: average('tokens_per_second'), valid_structured_outputs: rows.filter((row) => row.structured_output?.valid === true).length, run_count: rows.length }; }
@@ -0,0 +1,101 @@
1
+ import { createToolError, ERROR_CODE, ERROR_REASON } from '@inneranimalmedia/agentsam-errors';
2
+
3
+ export const LOCAL_ENGINE_SCHEMA = 'agentsam.local-engine.v1';
4
+ export const LOCAL_ENGINE_BENCHMARK_SCHEMA = 'agentsam.engine.benchmark.v1';
5
+
6
+ export const ENGINE_CAPABILITIES = Object.freeze([
7
+ 'chat', 'chat.streaming', 'chat.tools', 'embed', 'embed.batch',
8
+ 'output.json', 'output.json_schema', 'output.grammar', 'model.load',
9
+ 'model.unload', 'metrics.ttft', 'metrics.tokens_per_second', 'metrics.memory',
10
+ 'runtime.metal', 'runtime.mlx', 'format.gguf', 'format.safetensors',
11
+ ]);
12
+
13
+ export const ENGINE_STATUS = Object.freeze(['installed', 'available', 'unavailable', 'unknown']);
14
+
15
+ export function clean(value) { return value == null ? '' : String(value).trim(); }
16
+
17
+ export function normalizeCapability(value) {
18
+ const id = clean(value).toLowerCase();
19
+ return ENGINE_CAPABILITIES.includes(id) ? id : null;
20
+ }
21
+
22
+ export function capabilityCard({ engineId, version = null, model = null, capabilities = {}, evidence = [], status = 'unknown', warnings = [] } = {}) {
23
+ if (!engineId) throw new TypeError('engineId is required');
24
+ const normalized = Object.fromEntries(ENGINE_CAPABILITIES.map((id) => [id, capabilities[id] === true]));
25
+ return Object.freeze({
26
+ schema_version: LOCAL_ENGINE_SCHEMA,
27
+ engine_id: clean(engineId),
28
+ version: version || null,
29
+ model: model || null,
30
+ status: ENGINE_STATUS.includes(status) ? status : 'unknown',
31
+ capabilities: Object.freeze(normalized),
32
+ evidence: Object.freeze(Array.isArray(evidence) ? evidence.map((row) => ({ ...row })) : []),
33
+ warnings: Object.freeze(Array.isArray(warnings) ? [...warnings] : []),
34
+ });
35
+ }
36
+
37
+ export function engineInventory({ engineId, version = null, installed = false, reachable = false, endpoint = null, models = [], capabilities = {}, evidence = [], warnings = [] } = {}) {
38
+ return Object.freeze({
39
+ schema_version: LOCAL_ENGINE_SCHEMA,
40
+ engine_id: clean(engineId),
41
+ version: version || null,
42
+ installed: installed === true,
43
+ reachable: reachable === true,
44
+ endpoint: endpoint || null,
45
+ models: Object.freeze((Array.isArray(models) ? models : []).map((row) => ({ ...row }))),
46
+ capabilities: Object.freeze({ ...capabilities }),
47
+ evidence: Object.freeze(Array.isArray(evidence) ? evidence.map((row) => ({ ...row })) : []),
48
+ warnings: Object.freeze(Array.isArray(warnings) ? [...warnings] : []),
49
+ });
50
+ }
51
+
52
+ export function engineError(localCode, message, details = {}) {
53
+ const unsupported = localCode === 'LOCAL_ENGINE_UNSUPPORTED';
54
+ const engineId = details.engine_id || details.engineId || 'unknown';
55
+ return createToolError({
56
+ tool: `local-engine.${engineId}`,
57
+ domain: 'runtime',
58
+ stage: details.operation || 'execute',
59
+ code: unsupported ? ERROR_CODE.UNIMPLEMENTED : ERROR_CODE.UNAVAILABLE,
60
+ reason: unsupported ? ERROR_REASON.UNSUPPORTED_OPERATION : ERROR_REASON.PROVIDER_UNAVAILABLE,
61
+ message: message || localCode,
62
+ retryable: !unsupported,
63
+ provider: engineId,
64
+ native: { code: localCode },
65
+ details: { ...details, local_code: localCode },
66
+ });
67
+ }
68
+
69
+ export function assertEngineContract(engine) {
70
+ for (const method of ['discover', 'capabilities', 'chat', 'embed', 'unload']) {
71
+ if (typeof engine?.[method] !== 'function') throw new TypeError(`local engine ${method}() is required`);
72
+ }
73
+ return engine;
74
+ }
75
+
76
+ export function normalizeChatResult(result = {}, engineId = null) {
77
+ return Object.freeze({
78
+ schema_version: LOCAL_ENGINE_SCHEMA,
79
+ engine_id: result.engine_id || engineId,
80
+ model: result.model || null,
81
+ status: result.status || 'completed',
82
+ output_text: String(result.output_text || ''),
83
+ tool_calls: Object.freeze(Array.isArray(result.tool_calls) ? result.tool_calls.map((row) => ({ ...row })) : []),
84
+ usage: Object.freeze({ ...(result.usage || {}) }),
85
+ timing: Object.freeze({ ...(result.timing || {}) }),
86
+ evidence: Object.freeze(Array.isArray(result.evidence) ? [...result.evidence] : []),
87
+ });
88
+ }
89
+
90
+ export function normalizeEmbedResult(result = {}, engineId = null) {
91
+ return Object.freeze({
92
+ schema_version: LOCAL_ENGINE_SCHEMA,
93
+ engine_id: result.engine_id || engineId,
94
+ model: result.model || null,
95
+ status: result.status || 'completed',
96
+ embeddings: Object.freeze(Array.isArray(result.embeddings) ? result.embeddings : []),
97
+ dimensions: Number(result.dimensions) || 0,
98
+ usage: Object.freeze({ ...(result.usage || {}) }),
99
+ evidence: Object.freeze(Array.isArray(result.evidence) ? [...result.evidence] : []),
100
+ });
101
+ }
@@ -0,0 +1,142 @@
1
+ import { resolveOllamaConfig, probeOllama, probeOllamaModel } from '../commands/ollama.js';
2
+ import { createOllamaChatAdapter } from '../providers/ollama-chat.js';
3
+ import { capabilityCard, engineInventory, engineError, normalizeChatResult, normalizeEmbedResult } from './contracts.js';
4
+ import { executable, fetchJson, runCommand, unsupported } from './runtime.js';
5
+
6
+ function modelNames(body) {
7
+ return Array.isArray(body?.models) ? body.models.map((row) => ({ name: row.name || row.model || '', size: row.size || null, digest: row.digest || null })).filter((row) => row.name) : [];
8
+ }
9
+
10
+ export function createOllamaEngine(options = {}) {
11
+ const env = options.env || process.env;
12
+ const fetchImpl = options.fetchImpl || fetch;
13
+ const config = resolveOllamaConfig(options, env);
14
+ return {
15
+ id: 'ollama',
16
+ async discover() {
17
+ const api = await probeOllama(config, fetchImpl);
18
+ const binary = runCommand('ollama', ['--version'], { env });
19
+ return engineInventory({
20
+ engineId: 'ollama', version: binary.ok ? String(binary.stdout || binary.stderr).trim() : null,
21
+ installed: binary.installed, reachable: api.online, endpoint: config.baseUrl,
22
+ models: api.models || [],
23
+ capabilities: { chat: api.chat_ready, embed: api.embed_ready, 'chat.streaming': false, 'chat.tools': true, 'model.unload': true },
24
+ evidence: [{ source: 'ollama', endpoint: config.baseUrl, status: api.status }],
25
+ warnings: api.error ? [api.error] : [],
26
+ });
27
+ },
28
+ async capabilities({ model } = {}) {
29
+ const probe = await probeOllamaModel(model || config.model, config, fetchImpl);
30
+ return capabilityCard({ engineId: 'ollama', model: model || config.model, status: probe.ok ? 'available' : 'unavailable', capabilities: {
31
+ chat: probe.ok, 'chat.streaming': false, 'chat.tools': probe.capabilities?.includes('tools') === true,
32
+ embed: false, 'output.json': true, 'output.json_schema': false, 'model.unload': true, 'metrics.ttft': true,
33
+ }, evidence: [{ source: 'ollama/api/show', context_window: probe.context_window, capabilities: probe.capabilities || [] }], warnings: probe.error ? [probe.error] : [] });
34
+ },
35
+ async chat(params = {}) {
36
+ const adapter = createOllamaChatAdapter({ endpoint: config.baseUrl, env, fetchImpl });
37
+ const result = await adapter.create({ ...params, modelRecord: { provider: 'ollama', provider_model_id: params.model || config.model, context_window: params.context_window || 0 } });
38
+ return normalizeChatResult({ ...result, timing: result.timing || {} }, 'ollama');
39
+ },
40
+ async embed({ model = config.embedModel, inputs = [] } = {}) {
41
+ const values = Array.isArray(inputs) ? inputs : [inputs];
42
+ const response = await fetchJson(`${config.baseUrl}/api/embed`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ model, input: values }) }, fetchImpl);
43
+ if (!response.ok) throw engineError('LOCAL_ENGINE_EMBED_FAILED', response.error || 'Ollama embedding failed', { engine_id: 'ollama' });
44
+ const embeddings = response.body?.embeddings || (response.body?.embedding ? [response.body.embedding] : []);
45
+ return normalizeEmbedResult({ model, embeddings, dimensions: embeddings[0]?.length || 0 }, 'ollama');
46
+ },
47
+ async unload({ model } = {}) {
48
+ const response = await fetchJson(`${config.baseUrl}/api/generate`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ model: model || config.model, prompt: '', keep_alive: 0 }) }, fetchImpl);
49
+ return { schema_version: 'agentsam.local-engine.v1', engine_id: 'ollama', model: model || config.model, unloaded: response.ok, status: response.ok ? 'completed' : 'unavailable', error: response.error || null };
50
+ },
51
+ };
52
+ }
53
+
54
+ function openAiEndpoint(options, defaultUrl) {
55
+ const env = options.env || process.env;
56
+ return String(options.endpoint || env[options.envKey || 'AGENTSAM_LOCAL_ENGINE_ENDPOINT'] || defaultUrl).replace(/\/$/, '');
57
+ }
58
+
59
+ function createOpenAiCompatibleEngine({ id, endpoint, command, versionArgs = ['--version'], env = process.env, capabilities = {}, options = {} }) {
60
+ const fetchImpl = options.fetchImpl || fetch;
61
+ return {
62
+ id,
63
+ async discover() {
64
+ const binary = runCommand(command, versionArgs, { env });
65
+ const health = await fetchJson(`${endpoint}/v1/models`, {}, fetchImpl);
66
+ return engineInventory({
67
+ engineId: id,
68
+ version: binary.ok ? String(binary.stdout || binary.stderr).trim() : null,
69
+ installed: binary.ok,
70
+ reachable: health.ok,
71
+ endpoint,
72
+ models: modelNames(health.body?.data ? { models: health.body.data.map((row) => ({ name: row.id })) } : health.body),
73
+ capabilities,
74
+ evidence: [
75
+ { source: 'binary-probe', command, binary: binary.binary || null, ok: binary.ok, exit_status: binary.status },
76
+ { source: 'openai-compatible', endpoint, ok: health.ok, status: health.status },
77
+ ],
78
+ warnings: health.error ? [health.error] : [],
79
+ });
80
+ },
81
+ async capabilities({ model = null } = {}) { return capabilityCard({ engineId: id, model, status: 'unknown', capabilities, evidence: [{ source: 'adapter declaration', endpoint }], warnings: ['Model-specific capabilities require a live probe.'] }); },
82
+ async chat({ model, messages = [], tools = [], responseFormat = null, onEvent, signal } = {}) {
83
+ const started = performance.now();
84
+ const response = await fetchJson(`${endpoint}/v1/chat/completions`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ model, messages, tools: tools.length ? tools : undefined, response_format: responseFormat || undefined, stream: false }), signal }, fetchImpl);
85
+ if (!response.ok) throw engineError('LOCAL_ENGINE_CHAT_FAILED', response.error || `${id} chat failed`, { engine_id: id });
86
+ const choice = response.body?.choices?.[0] || {};
87
+ const text = choice.message?.content || '';
88
+ return normalizeChatResult({ model, output_text: text, tool_calls: choice.message?.tool_calls || [], usage: response.body?.usage || {}, timing: { elapsed_ms: performance.now() - started, ttft_ms: null } }, id);
89
+ },
90
+ async embed({ model, inputs = [], signal } = {}) {
91
+ const response = await fetchJson(`${endpoint}/v1/embeddings`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ model, input: inputs }), signal }, fetchImpl);
92
+ if (!response.ok) throw engineError('LOCAL_ENGINE_EMBED_FAILED', response.error || `${id} embedding failed`, { engine_id: id });
93
+ const embeddings = (response.body?.data || []).sort((a, b) => a.index - b.index).map((row) => row.embedding);
94
+ return normalizeEmbedResult({ model, embeddings, dimensions: embeddings[0]?.length || 0, usage: response.body?.usage || {} }, id);
95
+ },
96
+ async unload({ model, signal } = {}) { return { schema_version: 'agentsam.local-engine.v1', engine_id: id, model, unloaded: false, status: 'unsupported', error: unsupported(id, 'unload').message, signal: Boolean(signal) }; },
97
+ };
98
+ }
99
+
100
+ export function createMlxLmEngine(options = {}) {
101
+ const endpoint = openAiEndpoint(options, 'http://127.0.0.1:8080');
102
+ return createOpenAiCompatibleEngine({
103
+ id: 'mlx-lm',
104
+ endpoint,
105
+ command: options.command || 'python3',
106
+ versionArgs: options.versionArgs || ['-c', 'import importlib.metadata as m; print(m.version("mlx-lm"))'],
107
+ env: options.env || process.env,
108
+ capabilities: {
109
+ chat: true,
110
+ 'chat.streaming': false,
111
+ embed: false,
112
+ 'runtime.mlx': process.platform === 'darwin' && process.arch === 'arm64',
113
+ 'runtime.metal': process.platform === 'darwin' && process.arch === 'arm64',
114
+ 'output.json': true,
115
+ },
116
+ options,
117
+ });
118
+ }
119
+
120
+ export function createLlamaCppEngine(options = {}) {
121
+ const endpoint = openAiEndpoint(options, 'http://127.0.0.1:8080');
122
+ return createOpenAiCompatibleEngine({
123
+ id: 'llama.cpp',
124
+ endpoint,
125
+ command: options.command || 'llama-server',
126
+ env: options.env || process.env,
127
+ capabilities: {
128
+ chat: true,
129
+ 'chat.streaming': false,
130
+ 'chat.tools': true,
131
+ embed: true,
132
+ 'format.gguf': true,
133
+ 'runtime.metal': process.platform === 'darwin',
134
+ 'output.grammar': true,
135
+ 'output.json_schema': true,
136
+ 'model.unload': false,
137
+ },
138
+ options,
139
+ });
140
+ }
141
+
142
+ export function defaultLocalEngines(options = {}) { return [createOllamaEngine(options), createMlxLmEngine(options.mlx || options), createLlamaCppEngine(options.llamaCpp || options)]; }
@@ -0,0 +1,18 @@
1
+ import { assertEngineContract } from './contracts.js';
2
+ import { defaultLocalEngines } from './engines.js';
3
+
4
+ export class LocalEngineRegistry {
5
+ constructor(engines = defaultLocalEngines()) { this.engines = new Map(engines.map((engine) => [engine.id, assertEngineContract(engine)])); }
6
+ register(engine) { this.engines.set(engine.id, assertEngineContract(engine)); return this; }
7
+ get(id) { const engine = this.engines.get(id); if (!engine) throw new Error(`unknown_local_engine:${id}`); return engine; }
8
+ list() { return [...this.engines.values()].map((engine) => engine.id); }
9
+ async discover() { return Promise.all([...this.engines.values()].map((engine) => engine.discover())); }
10
+ async capabilities(request = {}) { return this.get(request.engine_id || request.engineId).capabilities(request); }
11
+ }
12
+
13
+ export function createLocalEngineRegistry(options = {}) { return new LocalEngineRegistry(options.engines || defaultLocalEngines(options)); }
14
+ export * from './contracts.js';
15
+ export * from './engines.js';
16
+ export * from './audit.js';
17
+ export * from './assets.js';
18
+ export * from './benchmark.js';
@@ -0,0 +1,39 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { engineError } from './contracts.js';
3
+
4
+ export function executable(command, env = process.env) {
5
+ if (!command) return null;
6
+ const finder = process.platform === 'win32' ? 'where' : 'which';
7
+ const result = spawnSync(finder, [command], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], env });
8
+ return result.status === 0 ? String(result.stdout || '').split(/\r?\n/).map((x) => x.trim()).find(Boolean) || null : null;
9
+ }
10
+
11
+ export function runCommand(command, args = [], options = {}) {
12
+ const binary = options.binary || executable(command, options.env || process.env);
13
+ if (!binary) return { ok: false, installed: false, command, args, stdout: '', stderr: '', status: null };
14
+ const result = spawnSync(binary, args, {
15
+ encoding: 'utf8',
16
+ env: options.env || process.env,
17
+ timeout: options.timeout || 3000,
18
+ stdio: ['ignore', 'pipe', 'pipe'],
19
+ maxBuffer: options.maxBuffer || 4 * 1024 * 1024,
20
+ });
21
+ return { ok: result.status === 0, installed: true, command, args, binary, stdout: String(result.stdout || ''), stderr: String(result.stderr || ''), status: result.status, error: result.error || null };
22
+ }
23
+
24
+ export async function fetchJson(url, init = {}, fetchImpl = fetch) {
25
+ try {
26
+ const response = await fetchImpl(url, { ...init, signal: init.signal || AbortSignal.timeout(3000) });
27
+ const text = await response.text();
28
+ let body = null;
29
+ try { body = text ? JSON.parse(text) : null; } catch { body = null; }
30
+ if (!response.ok) return { ok: false, status: response.status, body, error: `HTTP ${response.status}` };
31
+ return { ok: true, status: response.status, body };
32
+ } catch (error) {
33
+ return { ok: false, status: null, body: null, error: error?.message || String(error) };
34
+ }
35
+ }
36
+
37
+ export function unsupported(engineId, operation) {
38
+ return engineError('LOCAL_ENGINE_UNSUPPORTED', `${engineId} does not support ${operation}`, { engine_id: engineId, operation });
39
+ }
@@ -7,7 +7,6 @@ const DOCS = Object.freeze({
7
7
  gpt56Sol: 'https://developers.openai.com/api/docs/models/gpt-5.6-sol',
8
8
  gpt56Terra: 'https://developers.openai.com/api/docs/models/gpt-5.6-terra',
9
9
  gpt56Luna: 'https://developers.openai.com/api/docs/models/gpt-5.6-luna',
10
- gpt53Codex: 'https://developers.openai.com/api/docs/models/gpt-5.3-codex',
11
10
  embeddingLarge: 'https://developers.openai.com/api/docs/models/text-embedding-3-large',
12
11
  embeddingSmall: 'https://developers.openai.com/api/docs/models/text-embedding-3-small',
13
12
  });
@@ -226,53 +225,6 @@ const GPT_56_LUNA = openAiAgentModel({
226
225
  pricing: freezePricing({ input: 0.2, cachedInput: 0.02, cacheWrite: 0.25, output: 1.2, source: DOCS.gpt56Luna }),
227
226
  });
228
227
 
229
- const GPT_53_CODEX = openAiAgentModel({
230
- id: 'gpt-5.3-codex',
231
- label: 'GPT-5.3-Codex',
232
- source: DOCS.gpt53Codex,
233
- reasoning: ['low', 'medium', 'high', 'xhigh'],
234
- contextWindow: 400_000,
235
- maxOutputTokens: 128_000,
236
- knowledgeCutoff: '2025-08-31',
237
- description: 'Agentic coding model for Codex-style software workflows.',
238
- pricing: freezePricing({
239
- input: 1.75,
240
- cachedInput: 0.175,
241
- cacheWrite: 0,
242
- output: 14,
243
- source: DOCS.gpt53Codex,
244
- longContext: false,
245
- processing: false,
246
- }),
247
- capabilities: {
248
- web_search: false,
249
- file_search: false,
250
- image_generation: false,
251
- code_interpreter: false,
252
- hosted_shell: false,
253
- apply_patch: false,
254
- skills: false,
255
- computer_use: false,
256
- mcp: false,
257
- tool_search: false,
258
- async_tool_calls: false,
259
- mid_turn_steering: false,
260
- configuration_update: false,
261
- fast: false,
262
- flex: false,
263
- },
264
- serviceTiers: ['default'],
265
- contextPolicy: Object.freeze({
266
- target_input_tokens: 100_000,
267
- compact_at_tokens: 160_000,
268
- intervene_at_tokens: 210_000,
269
- max_normal_input_tokens: 240_000,
270
- pricing_threshold_tokens: null,
271
- max_cumulative_input_tokens: 400_000,
272
- safety_margin_tokens: 20_000,
273
- }),
274
- });
275
-
276
228
  const TEXT_EMBEDDING_3_LARGE = openAiEmbeddingModel({
277
229
  id: 'text-embedding-3-large',
278
230
  label: 'text-embedding-3-large',
@@ -296,7 +248,6 @@ export const MODEL_CATALOG = Object.freeze([
296
248
  GPT_56_LUNA,
297
249
  GPT_56_TERRA,
298
250
  GPT_56_SOL,
299
- GPT_53_CODEX,
300
251
  TEXT_EMBEDDING_3_LARGE,
301
252
  TEXT_EMBEDDING_3_SMALL,
302
253
  ]);
@@ -24,6 +24,75 @@ export const WORKERS_AI_CURATED_MODEL_IDS = Object.freeze([
24
24
  ]);
25
25
 
26
26
  const CURATED = new Set(WORKERS_AI_CURATED_MODEL_IDS);
27
+ export const PROVIDER_MODEL_SNAPSHOT_SCHEMA = 'agentsam.provider-model-snapshot.v1';
28
+
29
+ function modelSnapshotHash(modelIds) {
30
+ const source = modelIds.join('\n');
31
+ let hash = 2166136261;
32
+ for (let index = 0; index < source.length; index += 1) {
33
+ hash ^= source.charCodeAt(index);
34
+ hash = Math.imul(hash, 16777619);
35
+ }
36
+ return `fnv1a32:${(hash >>> 0).toString(16).padStart(8, '0')}`;
37
+ }
38
+
39
+ /**
40
+ * Compact credential-scoped availability evidence for an existing
41
+ * `agentsam_plugins` AI installation. The global catalog remains curated
42
+ * reference data; discovery never creates one model row per user.
43
+ */
44
+ export function createProviderModelSnapshot(provider, models = [], options = {}) {
45
+ const providerId = String(provider || '').trim().toLowerCase();
46
+ if (!providerId) throw new TypeError('provider_required');
47
+ const modelIds = [...new Set(models.map((row) => String(
48
+ typeof row === 'string' ? row : row?.provider_model_id || row?.model_id || '',
49
+ ).trim()).filter(Boolean))].sort();
50
+ const fetchedAtUnix = Number.isFinite(Number(options.fetchedAtUnix))
51
+ ? Math.max(0, Math.floor(Number(options.fetchedAtUnix)))
52
+ : Math.floor(Date.now() / 1000);
53
+ return Object.freeze({
54
+ schema: PROVIDER_MODEL_SNAPSHOT_SCHEMA,
55
+ provider: providerId,
56
+ model_ids: Object.freeze(modelIds),
57
+ model_count: modelIds.length,
58
+ models_hash: modelSnapshotHash(modelIds),
59
+ fetched_at_unix: fetchedAtUnix,
60
+ authority: 'credential_scoped_provider_discovery',
61
+ });
62
+ }
63
+
64
+ /**
65
+ * Produce fields for the existing `agentsam_plugins` row. Failed probes keep
66
+ * the last good snapshot while updating health evidence; no secret or model
67
+ * catalog rows are written.
68
+ */
69
+ export function createAiPluginProbePatch(previousMetadata = {}, discovery = {}, options = {}) {
70
+ const now = Number.isFinite(Number(options.fetchedAtUnix))
71
+ ? Math.max(0, Math.floor(Number(options.fetchedAtUnix)))
72
+ : Math.floor(Date.now() / 1000);
73
+ const metadata = previousMetadata && typeof previousMetadata === 'object' && !Array.isArray(previousMetadata)
74
+ ? { ...previousMetadata }
75
+ : {};
76
+ if (discovery.ok === true) {
77
+ metadata.model_snapshot = createProviderModelSnapshot(
78
+ options.provider || discovery.provider,
79
+ discovery.models || [],
80
+ { fetchedAtUnix: now },
81
+ );
82
+ }
83
+ const error = String(discovery.error || '').trim();
84
+ const authFailure = /\b(?:401|403)\b|unauthoriz|forbidden|invalid[_ -]?(?:api[_ -]?)?key|credential.*reject/i.test(error);
85
+ return Object.freeze({
86
+ metadata,
87
+ health_status: discovery.ok === true ? 'healthy' : authFailure ? 'auth_error' : 'unreachable',
88
+ last_health_at: now,
89
+ ...(discovery.ok === true ? { last_healthy_at: now, consecutive_failures: 0, last_error_code: null, last_error_message: null } : {
90
+ consecutive_failures_delta: 1,
91
+ last_error_code: authFailure ? 'provider_credential_rejected' : 'provider_discovery_failed',
92
+ last_error_message: authFailure ? 'Provider credential rejected' : 'Provider model discovery failed',
93
+ }),
94
+ });
95
+ }
27
96
 
28
97
  const SERVICE_TO_PROVIDER = Object.freeze({
29
98
  openai: 'openai',
@@ -5,7 +5,14 @@ export {
5
5
  INNERANIMALMEDIA_CLOUDFLARE_OAUTH_PLUGIN_MANIFEST,
6
6
  } from './cloudflare.js';
7
7
  export { COMPLETEFUL_PLUGIN_MANIFEST } from './completeful.js';
8
- export { installPlugin, listPlugins, listPluginTools, recordPluginHealthCheck, recordToolCall } from './registry.js';
8
+ export {
9
+ installPlugin,
10
+ listPlugins,
11
+ listPluginTools,
12
+ recordPluginHealthCheck,
13
+ recordAiPluginModelDiscovery,
14
+ recordToolCall,
15
+ } from './registry.js';
9
16
  export { createPluginRuntime, createPluginCapabilityAdapter, executeAgentSamTool } from './runtime.js';
10
17
  export { resolveProjectPluginScope, resolveProjectPluginResources, resolveProjectRuntimeResources, resolveProjectVectorizeScope } from './resource-scope.js';
11
18
  export { resolveVectorizeConfig, executeVectorizeTool } from './vectorize.js';