@inneranimalmedia/agentsam-sdk 2.6.8 → 2.6.9

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 (104) hide show
  1. package/apps/README.md +25 -0
  2. package/apps/cad-creator/shared/cad/package.json +1 -1
  3. package/apps/client-cms-editor/backend/package.json +4 -6
  4. package/apps/client-cms-editor/frontend/package.json +6 -8
  5. package/apps/client-cms-editor/frontend/tsconfig.json +27 -8
  6. package/apps/client-cms-editor/package.json +1 -1
  7. package/apps/client-cms-editor/shared/cms/package.json +4 -6
  8. package/docs/LOCAL_ENGINE_COMPUTE_AUDIT_PLAN.md +299 -0
  9. package/package.json +18 -7
  10. package/packages/agentsam-brand/package.json +1 -1
  11. package/packages/agentsam-contracts/package.json +71 -20
  12. package/packages/agentsam-contracts/scripts/build.mjs +18 -0
  13. package/packages/agentsam-contracts/test/contracts.test.mjs +4 -1
  14. package/packages/agentsam-contracts/test/repository.test.mjs +4 -1
  15. package/packages/agentsam-contracts/tsconfig.build.json +10 -0
  16. package/packages/agentsam-errors/package.json +3 -2
  17. package/packages/agentsam-goap/package.json +2 -2
  18. package/packages/agentsam-knowledge/package.json +3 -2
  19. package/packages/agentsam-nav/package.json +1 -1
  20. package/packages/agentsam-queue-control/package.json +1 -1
  21. package/packages/agentsam-rapid-rust/src/main.rs +1 -0
  22. package/packages/agentsam-repository/package.json +3 -2
  23. package/packages/agentsam-vault/package.json +8 -5
  24. package/packages/agentsam-workbench/package.json +44 -17
  25. package/packages/connectors/cloudflare/package.json +1 -1
  26. package/packages/heuristic-theme/package.json +1 -1
  27. package/packages/identity/package.json +4 -3
  28. package/packages/identity/tests/lane1-packed-consumer.test.mjs +9 -1
  29. package/packages/providers/completeful/package.json +1 -1
  30. package/packages/theme-church-site/README.md +2 -2
  31. package/packages/theme-church-site/package.json +3 -4
  32. package/packages/theme-church-site/src/index.js +1 -1
  33. package/packages/theme-church-site/test/theme.test.mjs +1 -1
  34. package/packages/theme-companions-site/README.md +2 -2
  35. package/packages/theme-companions-site/package.json +3 -4
  36. package/packages/theme-companions-site/src/index.js +1 -1
  37. package/packages/theme-companions-site/test/theme.test.mjs +1 -1
  38. package/packages/theme-floors-site/README.md +2 -2
  39. package/packages/theme-floors-site/package.json +3 -4
  40. package/packages/theme-floors-site/src/index.js +1 -1
  41. package/packages/theme-floors-site/test/theme.test.mjs +1 -1
  42. package/packages/theme-fuelnfree-site/README.md +2 -2
  43. package/packages/theme-fuelnfree-site/package.json +3 -4
  44. package/packages/theme-fuelnfree-site/src/index.js +1 -1
  45. package/packages/theme-fuelnfree-site/test/theme.test.mjs +1 -1
  46. package/packages/theme-handyman-site/README.md +2 -2
  47. package/packages/theme-handyman-site/package.json +3 -4
  48. package/packages/theme-handyman-site/src/index.js +1 -1
  49. package/packages/theme-handyman-site/test/theme.test.mjs +1 -1
  50. package/packages/theme-insurance-site/README.md +2 -2
  51. package/packages/theme-insurance-site/package.json +3 -4
  52. package/packages/theme-insurance-site/src/index.js +1 -1
  53. package/packages/theme-insurance-site/test/theme.test.mjs +1 -1
  54. package/packages/theme-scenes/package.json +1 -1
  55. package/packages/theme-shinshu-site/README.md +2 -2
  56. package/packages/theme-shinshu-site/package.json +3 -4
  57. package/packages/theme-shinshu-site/src/index.js +1 -1
  58. package/packages/theme-shinshu-site/test/theme.test.mjs +1 -1
  59. package/packages/work-graph/package.json +3 -2
  60. package/protocol/local-engine/benchmark.v1.schema.json +14 -0
  61. package/protocol/local-engine/engine.v1.schema.json +17 -0
  62. package/src/cli/command-catalog.js +1 -0
  63. package/src/cli.js +10 -0
  64. package/src/commands/app.js +10 -0
  65. package/src/commands/engine.js +10 -0
  66. package/src/commands/machine.js +71 -38
  67. package/src/commands/package.js +10 -3
  68. package/src/commands/runtime.js +25 -10
  69. package/src/commands/setup.js +30 -6
  70. package/src/commands/terminal.js +20 -8
  71. package/src/errors/contract.js +4 -4
  72. package/src/errors/diagnostic.js +1 -1
  73. package/src/errors/index.js +1 -1
  74. package/src/index.js +20 -0
  75. package/src/indexing/ingest/materials.js +237 -30
  76. package/src/lib/setup/runtime.js +4 -2
  77. package/src/local-engine/assets.js +37 -0
  78. package/src/local-engine/audit.js +133 -0
  79. package/src/local-engine/benchmark.js +26 -0
  80. package/src/local-engine/contracts.js +101 -0
  81. package/src/local-engine/engines.js +142 -0
  82. package/src/local-engine/index.js +18 -0
  83. package/src/local-engine/runtime.js +39 -0
  84. package/packages/agentsam-nav/dist/Nav.d.ts +0 -43
  85. package/packages/agentsam-nav/dist/NavCollapsible.d.ts +0 -10
  86. package/packages/agentsam-nav/dist/NavContent.d.ts +0 -2
  87. package/packages/agentsam-nav/dist/NavFooter.d.ts +0 -2
  88. package/packages/agentsam-nav/dist/NavGroup.d.ts +0 -3
  89. package/packages/agentsam-nav/dist/NavHeader.d.ts +0 -2
  90. package/packages/agentsam-nav/dist/NavMenu.d.ts +0 -22
  91. package/packages/agentsam-nav/dist/NavProvider.d.ts +0 -35
  92. package/packages/agentsam-nav/dist/NavTrigger.d.ts +0 -2
  93. package/packages/agentsam-nav/dist/Surfaces.d.ts +0 -41
  94. package/packages/agentsam-nav/dist/browser.d.ts +0 -11
  95. package/packages/agentsam-nav/dist/browser.global.js +0 -135
  96. package/packages/agentsam-nav/dist/browser.js +0 -7290
  97. package/packages/agentsam-nav/dist/contracts.d.ts +0 -76
  98. package/packages/agentsam-nav/dist/index.d.ts +0 -11
  99. package/packages/agentsam-nav/dist/index.js +0 -7291
  100. package/packages/agentsam-nav/dist/legacy.css +0 -83
  101. package/packages/agentsam-nav/dist/shell.css +0 -113
  102. package/packages/agentsam-nav/dist/theme.css +0 -113
  103. package/packages/agentsam-nav/dist/utils.d.ts +0 -1
  104. package/packages/agentsam-repository/src/goap.js.bak-20260922011251 +0 -670
@@ -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
+ }
@@ -1,43 +0,0 @@
1
- import { type HTMLAttributes } from 'react';
2
- import { NavCollapsible, NavCollapsibleContent, NavCollapsibleTrigger } from './NavCollapsible.js';
3
- import { NavContent } from './NavContent.js';
4
- import { NavFooter } from './NavFooter.js';
5
- import { NavGroup, NavGroupLabel } from './NavGroup.js';
6
- import { NavHeader } from './NavHeader.js';
7
- import { NavMenu, NavMenuButton, NavMenuChevron, NavMenuItem, NavMenuSub, NavMenuSubButton } from './NavMenu.js';
8
- import { NavProvider } from './NavProvider.js';
9
- import { NavTrigger } from './NavTrigger.js';
10
- import { NavScope, NavSidenav, NavTopbar, NavTopbarLogo, NavTopbarSpacer, NavProjectContext, NavAccountSwitcher, NavFilesResources, NavPinnedSummary, NavConversationActions, NavShareButton, NavOverflowMenu, NavModeSwitcher } from './Surfaces.js';
11
- declare function NavRoot({ className, children, ...props }: HTMLAttributes<HTMLElement>): import("react").JSX.Element;
12
- export declare const Nav: typeof NavRoot & {
13
- Scope: typeof NavScope;
14
- Sidenav: typeof NavSidenav;
15
- Topbar: typeof NavTopbar;
16
- TopbarLogo: typeof NavTopbarLogo;
17
- TopbarSpacer: typeof NavTopbarSpacer;
18
- ProjectContext: typeof NavProjectContext;
19
- AccountSwitcher: typeof NavAccountSwitcher;
20
- FilesResources: typeof NavFilesResources;
21
- PinnedSummary: typeof NavPinnedSummary;
22
- ConversationActions: typeof NavConversationActions;
23
- ShareButton: typeof NavShareButton;
24
- OverflowMenu: typeof NavOverflowMenu;
25
- ModeSwitcher: typeof NavModeSwitcher;
26
- Provider: typeof NavProvider;
27
- Header: typeof NavHeader;
28
- Content: typeof NavContent;
29
- Footer: typeof NavFooter;
30
- Group: typeof NavGroup;
31
- GroupLabel: typeof NavGroupLabel;
32
- Menu: typeof NavMenu;
33
- MenuItem: typeof NavMenuItem;
34
- MenuButton: typeof NavMenuButton;
35
- MenuSub: typeof NavMenuSub;
36
- MenuSubButton: typeof NavMenuSubButton;
37
- MenuChevron: typeof NavMenuChevron;
38
- Collapsible: typeof NavCollapsible;
39
- CollapsibleTrigger: typeof NavCollapsibleTrigger;
40
- CollapsibleContent: typeof NavCollapsibleContent;
41
- Trigger: typeof NavTrigger;
42
- };
43
- export {};
@@ -1,10 +0,0 @@
1
- import { type ButtonHTMLAttributes, type HTMLAttributes, type ReactElement, type ReactNode } from 'react';
2
- export declare function NavCollapsible({ children, defaultOpen }: {
3
- children: ReactNode;
4
- defaultOpen?: boolean;
5
- }): import("react").JSX.Element;
6
- export declare function NavCollapsibleTrigger({ render, children, className, ...props }: ButtonHTMLAttributes<HTMLButtonElement> & {
7
- render?: ReactElement;
8
- children?: ReactNode;
9
- }): import("react").JSX.Element;
10
- export declare function NavCollapsibleContent({ className, ...props }: HTMLAttributes<HTMLDivElement>): import("react").JSX.Element;
@@ -1,2 +0,0 @@
1
- import type { HTMLAttributes } from 'react';
2
- export declare function NavContent({ className, ...props }: HTMLAttributes<HTMLDivElement>): import("react").JSX.Element;
@@ -1,2 +0,0 @@
1
- import type { HTMLAttributes } from 'react';
2
- export declare function NavFooter({ className, ...props }: HTMLAttributes<HTMLDivElement>): import("react").JSX.Element;
@@ -1,3 +0,0 @@
1
- import type { HTMLAttributes } from 'react';
2
- export declare function NavGroup({ className, ...props }: HTMLAttributes<HTMLElement>): import("react").JSX.Element;
3
- export declare function NavGroupLabel({ className, ...props }: HTMLAttributes<HTMLParagraphElement>): import("react").JSX.Element;
@@ -1,2 +0,0 @@
1
- import type { HTMLAttributes } from 'react';
2
- export declare function NavHeader({ className, ...props }: HTMLAttributes<HTMLDivElement>): import("react").JSX.Element;
@@ -1,22 +0,0 @@
1
- import type { ButtonHTMLAttributes, HTMLAttributes, ReactNode } from 'react';
2
- export declare function NavMenu({ className, ...props }: HTMLAttributes<HTMLUListElement>): import("react").JSX.Element;
3
- export declare function NavMenuItem({ className, ...props }: HTMLAttributes<HTMLLIElement>): import("react").JSX.Element;
4
- export type NavMenuButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
5
- icon?: unknown;
6
- active?: boolean;
7
- itemId?: string;
8
- children: ReactNode;
9
- };
10
- export declare function NavMenuButton({ icon: Icon, active, itemId, className, children, ...props }: NavMenuButtonProps): import("react").JSX.Element;
11
- export declare function NavMenuSub({ className, ...props }: HTMLAttributes<HTMLUListElement>): import("react").JSX.Element;
12
- export type NavMenuSubButtonProps = {
13
- href?: string;
14
- active?: boolean;
15
- className?: string;
16
- children?: unknown;
17
- onClick?: (event: React.MouseEvent<HTMLAnchorElement>) => void;
18
- };
19
- export declare function NavMenuSubButton({ active, className, children, ...props }: NavMenuSubButtonProps): import("react").JSX.Element;
20
- export declare function NavMenuChevron({ className }: {
21
- className?: string;
22
- }): import("react").JSX.Element;
@@ -1,35 +0,0 @@
1
- import { type PropsWithChildren } from 'react';
2
- import type { NavTheme, NavValue, NavTokens } from './contracts.js';
3
- export type NavContextValue = {
4
- data: NavValue;
5
- tokens: NavTokens;
6
- theme: NavTheme;
7
- accentColor: string;
8
- menu: string | null;
9
- setMenu: (menu: string | null) => void;
10
- open: boolean;
11
- isMobile: boolean;
12
- isPeeking: boolean;
13
- peekable: boolean;
14
- resizable: boolean;
15
- width: number;
16
- mobileBreakpoint: number;
17
- setOpen: (open: boolean) => void;
18
- toggle: () => void;
19
- close: () => void;
20
- setPeeking: (peeking: boolean) => void;
21
- setWidth: (width: number) => void;
22
- scrollToItem: (itemId: string) => void;
23
- };
24
- export type NavProviderProps = PropsWithChildren<{
25
- value?: NavValue;
26
- tokens?: NavTokens;
27
- theme?: NavTheme;
28
- accentColor?: string;
29
- defaultOpen?: boolean;
30
- mobileBreakpoint?: number;
31
- peekable?: boolean;
32
- resizable?: boolean;
33
- }>;
34
- export declare function NavProvider({ children, value: data, tokens, theme, accentColor, defaultOpen, mobileBreakpoint, peekable, resizable, }: NavProviderProps): import("react").JSX.Element;
35
- export declare function useNav(): NavContextValue;
@@ -1,2 +0,0 @@
1
- import type { ButtonHTMLAttributes } from 'react';
2
- export declare function NavTrigger({ className, 'aria-label': ariaLabel, ...props }: ButtonHTMLAttributes<HTMLButtonElement>): import("react").JSX.Element;
@@ -1,41 +0,0 @@
1
- import { type CSSProperties, type HTMLAttributes, type ReactNode } from 'react';
2
- import type { NavAccount, NavAction } from './contracts.js';
3
- export declare function useNavStyle(): CSSProperties;
4
- export declare function NavScope({ className, style, ...props }: HTMLAttributes<HTMLDivElement>): import("react").JSX.Element;
5
- /** The portal carries its own theme, so standalone surfaces never depend on body CSS. */
6
- export declare function NavOverflowMenu({ label, actions, children, id: suppliedId, align }: {
7
- label?: string;
8
- actions?: NavAction[];
9
- children?: ReactNode;
10
- id?: string;
11
- align?: 'start' | 'center' | 'end';
12
- }): import("react").JSX.Element;
13
- export declare function NavTopbarLogo({ variant, onClick, toggle }: {
14
- variant?: 'mark' | 'expanded';
15
- onClick?: () => void;
16
- toggle?: boolean;
17
- }): import("react").JSX.Element;
18
- export declare function NavProjectContext(): import("react").JSX.Element;
19
- export declare function NavTopbarSpacer(): import("react").JSX.Element;
20
- export declare function NavFilesResources(): import("react").JSX.Element;
21
- export declare function NavPinnedSummary(): import("react").JSX.Element | null;
22
- export declare function NavConversationActions(): import("react").JSX.Element;
23
- export declare function NavShareButton(): import("react").JSX.Element | null;
24
- export declare function NavAccountSwitcher({ accounts, activeAccountId, onAccountChange, expanded }: {
25
- accounts?: NavAccount[];
26
- activeAccountId?: string;
27
- onAccountChange?: (id: string) => void;
28
- expanded?: boolean;
29
- }): import("react").JSX.Element;
30
- export declare function NavModeSwitcher(): import("react").JSX.Element;
31
- export declare function NavTopbar({ children, rightSlot, modeSlot, contextSlot, startup, className, showNavigationTrigger, showAccount, }: {
32
- children?: ReactNode;
33
- rightSlot?: ReactNode;
34
- modeSlot?: ReactNode;
35
- contextSlot?: ReactNode;
36
- startup?: boolean;
37
- className?: string;
38
- showNavigationTrigger?: boolean;
39
- showAccount?: boolean;
40
- }): import("react").JSX.Element;
41
- export declare function NavSidenav(): import("react").JSX.Element;