fix(arch): Enforce cycle, vendor SDK and env AST boundaries (#1750)
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
ff4ce8cd29
commit
2ca7c85629
11 files changed
+764
-488
No files matched your search
@@ -1,3 +1,4 @@
|
||||
import { spawn } from 'node:child_process';
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import { constants, createReadStream, createWriteStream } from 'node:fs';
|
||||
import {
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
statfs,
|
||||
writeFile,
|
||||
} from 'node:fs/promises';
|
||||
import { createServer } from 'node:net';
|
||||
import { homedir } from 'node:os';
|
||||
import { dirname, isAbsolute, join, resolve } from 'node:path';
|
||||
import { Readable, Transform, Writable } from 'node:stream';
|
||||
@@ -32,6 +34,109 @@ const criticalFiles = [
|
||||
'docker-guest.tar.gz',
|
||||
];
|
||||
|
||||
function commandText(chunks) {
|
||||
const bytes = Buffer.concat(chunks);
|
||||
return bytes.toString(bytes.includes(0) ? 'utf16le' : 'utf8').replaceAll('\uFEFF', '');
|
||||
}
|
||||
|
||||
export function execute(command, args, { env, signal, timeout = 120_000, input } = {}) {
|
||||
signal?.throwIfAborted();
|
||||
return new Promise((resolveRun, reject) => {
|
||||
const child = spawn(command, args, {
|
||||
env,
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
shell: false,
|
||||
windowsHide: true,
|
||||
});
|
||||
const stdout = [];
|
||||
const tails = { stdout: { chunks: [], bytes: 0 }, stderr: { chunks: [], bytes: 0 } };
|
||||
let stdoutBytes = 0;
|
||||
let timedOut = false;
|
||||
let spawnError;
|
||||
let killTimer;
|
||||
const stop = () => {
|
||||
child.kill('SIGTERM');
|
||||
killTimer ??= setTimeout(() => {
|
||||
child.kill('SIGKILL');
|
||||
child.stdin.destroy();
|
||||
child.stdout.destroy();
|
||||
child.stderr.destroy();
|
||||
}, 5000);
|
||||
};
|
||||
const timer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
stop();
|
||||
}, timeout);
|
||||
const keep = (tail, chunk) => {
|
||||
tail.chunks.push(chunk);
|
||||
tail.bytes += chunk.length;
|
||||
while (tail.bytes - tail.chunks[0].length > 128 * 1024) {
|
||||
const dropped = tail.chunks.shift().length;
|
||||
tail.bytes -= dropped;
|
||||
if (dropped % 2) {
|
||||
tail.chunks[0] = tail.chunks[0].subarray(1);
|
||||
tail.bytes -= 1;
|
||||
}
|
||||
}
|
||||
};
|
||||
child.stdout.on('data', (chunk) => {
|
||||
stdoutBytes += chunk.length;
|
||||
if (stdoutBytes <= 8 * 1024 * 1024) stdout.push(chunk);
|
||||
keep(tails.stdout, chunk);
|
||||
});
|
||||
child.stderr.on('data', (chunk) => keep(tails.stderr, chunk));
|
||||
child.on('error', (error) => {
|
||||
spawnError = error;
|
||||
});
|
||||
signal?.addEventListener('abort', stop, { once: true });
|
||||
child.stdin.on('error', () => {});
|
||||
if (input?.pipe)
|
||||
pipeline(input, child.stdin).catch((error) => {
|
||||
spawnError = error;
|
||||
stop();
|
||||
});
|
||||
else child.stdin.end(input);
|
||||
child.on('close', (code) => {
|
||||
clearTimeout(timer);
|
||||
clearTimeout(killTimer);
|
||||
signal?.removeEventListener('abort', stop);
|
||||
if (signal?.aborted) return reject(new Error('Nod setup was cancelled.'));
|
||||
const output = [commandText(tails.stdout.chunks), commandText(tails.stderr.chunks)]
|
||||
.map((text) => text.trim())
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
const failure = (message, facts) =>
|
||||
Object.assign(new Error(message), facts, {
|
||||
details: [spawnError?.stack, output].filter(Boolean).join('\n'),
|
||||
});
|
||||
if (timedOut)
|
||||
return reject(
|
||||
failure('Nod runtime setup took too long. Please retry.', { name: 'TimeoutError' }),
|
||||
);
|
||||
if (spawnError)
|
||||
return reject(
|
||||
failure(`Nod could not launch its bundled runtime (${spawnError.code || 'unknown'}).`, {
|
||||
errno: spawnError.code,
|
||||
}),
|
||||
);
|
||||
if (code !== 0) {
|
||||
const detail = output.replace(/\s+/g, ' ');
|
||||
return reject(
|
||||
failure(
|
||||
`Nod runtime command failed (${code})${
|
||||
detail ? `: ${detail.length > 300 ? '…' : ''}${detail.slice(-300)}` : '.'
|
||||
}`,
|
||||
{ exitCode: code },
|
||||
),
|
||||
);
|
||||
}
|
||||
if (stdoutBytes > 8 * 1024 * 1024)
|
||||
return reject(failure('Nod runtime command produced too much output.'));
|
||||
resolveRun(commandText(stdout).trim());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function assetHash(path, signal) {
|
||||
const hash = createHash('sha256');
|
||||
for await (const bytes of createReadStream(path, { signal })) hash.update(bytes);
|
||||
@@ -803,3 +908,14 @@ export async function prepareRuntimeUpdate(release, options) {
|
||||
}
|
||||
return ensureRuntimeAssets({ ...options, release });
|
||||
}
|
||||
|
||||
export async function availablePort() {
|
||||
const server = createServer();
|
||||
await new Promise((resolvePort, reject) => {
|
||||
server.once('error', reject);
|
||||
server.listen(0, '127.0.0.1', resolvePort);
|
||||
});
|
||||
const port = server.address().port;
|
||||
await new Promise((resolveClose) => server.close(resolveClose));
|
||||
return port;
|
||||
}
|
||||
@@ -16,7 +16,7 @@ import { homedir } from 'node:os';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { pipeline } from 'node:stream/promises';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { availablePort, execute } from './index.mjs';
|
||||
import { availablePort, execute } from './assets.mjs';
|
||||
|
||||
const stateVersion = 1;
|
||||
|
||||
|
||||
+4
-118
@@ -1,4 +1,3 @@
|
||||
import { spawn } from 'node:child_process';
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import { constants, createReadStream, createWriteStream } from 'node:fs';
|
||||
import {
|
||||
@@ -14,7 +13,6 @@ import {
|
||||
rmdir,
|
||||
writeFile,
|
||||
} from 'node:fs/promises';
|
||||
import { createServer } from 'node:net';
|
||||
import { cpus as hostCpus, homedir, totalmem } from 'node:os';
|
||||
import { delimiter, join, resolve } from 'node:path';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
@@ -23,12 +21,14 @@ import { moveDatabase } from './database.mjs';
|
||||
import { guestConfiguration, protectGuest, protectNetworks } from './guest-config.mjs';
|
||||
import {
|
||||
assetHash,
|
||||
availablePort,
|
||||
execute,
|
||||
findRuntimeAssets,
|
||||
openRuntimeAssets,
|
||||
removeUnusedRuntimes,
|
||||
} from './assets.mjs';
|
||||
|
||||
export { installRuntimeArchive } from './assets.mjs';
|
||||
export { availablePort, execute, installRuntimeArchive } from './assets.mjs';
|
||||
|
||||
const preparing = new Map();
|
||||
const shellQuote = (value) => `'${String(value).replaceAll("'", "'\\''")}'`;
|
||||
@@ -103,120 +103,6 @@ export async function retainStopExecutable(lima, controlRoot) {
|
||||
}
|
||||
}
|
||||
|
||||
function commandText(chunks) {
|
||||
const bytes = Buffer.concat(chunks);
|
||||
return bytes.toString(bytes.includes(0) ? 'utf16le' : 'utf8').replaceAll('\uFEFF', '');
|
||||
}
|
||||
|
||||
export function execute(command, args, { env, signal, timeout = 120_000, input } = {}) {
|
||||
signal?.throwIfAborted();
|
||||
return new Promise((resolveRun, reject) => {
|
||||
const child = spawn(command, args, {
|
||||
env,
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
shell: false,
|
||||
windowsHide: true,
|
||||
});
|
||||
const stdout = [];
|
||||
const tails = { stdout: { chunks: [], bytes: 0 }, stderr: { chunks: [], bytes: 0 } };
|
||||
let stdoutBytes = 0;
|
||||
let timedOut = false;
|
||||
let spawnError;
|
||||
let killTimer;
|
||||
const stop = () => {
|
||||
child.kill('SIGTERM');
|
||||
killTimer ??= setTimeout(() => {
|
||||
child.kill('SIGKILL');
|
||||
child.stdin.destroy();
|
||||
child.stdout.destroy();
|
||||
child.stderr.destroy();
|
||||
}, 5000);
|
||||
};
|
||||
const timer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
stop();
|
||||
}, timeout);
|
||||
const keep = (tail, chunk) => {
|
||||
tail.chunks.push(chunk);
|
||||
tail.bytes += chunk.length;
|
||||
while (tail.bytes - tail.chunks[0].length > 128 * 1024) {
|
||||
const dropped = tail.chunks.shift().length;
|
||||
tail.bytes -= dropped;
|
||||
if (dropped % 2) {
|
||||
tail.chunks[0] = tail.chunks[0].subarray(1);
|
||||
tail.bytes -= 1;
|
||||
}
|
||||
}
|
||||
};
|
||||
child.stdout.on('data', (chunk) => {
|
||||
stdoutBytes += chunk.length;
|
||||
if (stdoutBytes <= 8 * 1024 * 1024) stdout.push(chunk);
|
||||
keep(tails.stdout, chunk);
|
||||
});
|
||||
child.stderr.on('data', (chunk) => keep(tails.stderr, chunk));
|
||||
child.on('error', (error) => {
|
||||
spawnError = error;
|
||||
});
|
||||
signal?.addEventListener('abort', stop, { once: true });
|
||||
child.stdin.on('error', () => {});
|
||||
if (input?.pipe)
|
||||
pipeline(input, child.stdin).catch((error) => {
|
||||
spawnError = error;
|
||||
stop();
|
||||
});
|
||||
else child.stdin.end(input);
|
||||
child.on('close', (code) => {
|
||||
clearTimeout(timer);
|
||||
clearTimeout(killTimer);
|
||||
signal?.removeEventListener('abort', stop);
|
||||
if (signal?.aborted) return reject(new Error('Nod setup was cancelled.'));
|
||||
const output = [commandText(tails.stdout.chunks), commandText(tails.stderr.chunks)]
|
||||
.map((text) => text.trim())
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
const failure = (message, facts) =>
|
||||
Object.assign(new Error(message), facts, {
|
||||
details: [spawnError?.stack, output].filter(Boolean).join('\n'),
|
||||
});
|
||||
if (timedOut)
|
||||
return reject(
|
||||
failure('Nod runtime setup took too long. Please retry.', { name: 'TimeoutError' }),
|
||||
);
|
||||
if (spawnError)
|
||||
return reject(
|
||||
failure(`Nod could not launch its bundled runtime (${spawnError.code || 'unknown'}).`, {
|
||||
errno: spawnError.code,
|
||||
}),
|
||||
);
|
||||
if (code !== 0) {
|
||||
const detail = output.replace(/\s+/g, ' ');
|
||||
return reject(
|
||||
failure(
|
||||
`Nod runtime command failed (${code})${
|
||||
detail ? `: ${detail.length > 300 ? '…' : ''}${detail.slice(-300)}` : '.'
|
||||
}`,
|
||||
{ exitCode: code },
|
||||
),
|
||||
);
|
||||
}
|
||||
if (stdoutBytes > 8 * 1024 * 1024)
|
||||
return reject(failure('Nod runtime command produced too much output.'));
|
||||
resolveRun(commandText(stdout).trim());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function availablePort() {
|
||||
const server = createServer();
|
||||
await new Promise((resolvePort, reject) => {
|
||||
server.once('error', reject);
|
||||
server.listen(0, '127.0.0.1', resolvePort);
|
||||
});
|
||||
const port = server.address().port;
|
||||
await new Promise((resolveClose) => server.close(resolveClose));
|
||||
return port;
|
||||
}
|
||||
|
||||
export async function waitFor(operation, { signal, attempts = 240, interval = 250 } = {}) {
|
||||
let failure;
|
||||
for (let attempt = 0; attempt < attempts; attempt++) {
|
||||
@@ -235,7 +121,7 @@ export async function waitFor(operation, { signal, attempts = 240, interval = 25
|
||||
async function prepare(options, onComputerStart, progress = {}) {
|
||||
if (process.platform === 'win32' && process.arch === 'x64') {
|
||||
const { prepareWindowsRuntime } = await import('./windows.mjs');
|
||||
return prepareWindowsRuntime(options, onComputerStart);
|
||||
return prepareWindowsRuntime({ ...options, finishRuntime }, onComputerStart);
|
||||
}
|
||||
if (!['darwin', 'linux'].includes(process.platform) || !['arm64', 'x64'].includes(process.arch))
|
||||
throw new Error('This Nod build requires a Mac or a 64-bit Linux computer.');
|
||||
|
||||
@@ -18,8 +18,7 @@ import { basename, isAbsolute, join, resolve } from 'node:path';
|
||||
import { Writable } from 'node:stream';
|
||||
import { pipeline } from 'node:stream/promises';
|
||||
import { createGunzip } from 'node:zlib';
|
||||
import { assetHash, resumableDownload, timeLeft } from './assets.mjs';
|
||||
import { execute, finishRuntime } from './index.mjs';
|
||||
import { assetHash, execute, resumableDownload, timeLeft } from './assets.mjs';
|
||||
import { startupWslCode } from '../../src/shared/startup-feedback-facts.mjs';
|
||||
|
||||
const holders = new Map();
|
||||
@@ -565,7 +564,9 @@ async function prepareWindows(options, onComputerStart, progress) {
|
||||
};
|
||||
await mkdir(dockerEnvironment.TEMP, { recursive: true });
|
||||
await mkdir(dockerEnvironment.DOCKER_CONFIG, { recursive: true });
|
||||
return finishRuntime({
|
||||
if (typeof options.finishRuntime !== 'function')
|
||||
throw new Error('Nod runtime finisher is unavailable.');
|
||||
return options.finishRuntime({
|
||||
dataRoot,
|
||||
resourcesPath,
|
||||
assets,
|
||||
|
||||
@@ -184,7 +184,7 @@ if (process.env.WORKSPACE_CONTAINER) {
|
||||
const profile = join(installation, 'synthetic-profile');
|
||||
const runtime = await import('../runtime/windows.mjs');
|
||||
const { openDatabase } = await import('../runtime/database.mjs');
|
||||
const { availablePort, computerNames } = await import('../runtime/index.mjs');
|
||||
const { availablePort, computerNames, finishRuntime } = await import('../runtime/index.mjs');
|
||||
const names = computerNames(profile);
|
||||
const system = (name) => join(process.env.SYSTEMROOT, 'System32', name);
|
||||
console.log('Checking that a WSL failure offers its repair and keeps the Windows error.');
|
||||
@@ -303,6 +303,7 @@ if (process.env.WORKSPACE_CONTAINER) {
|
||||
dataRoot: profile,
|
||||
resourcesPath: engine,
|
||||
computerDirectory: elsewhere,
|
||||
finishRuntime,
|
||||
onStatus: (value) => value.phase === 'downloading' || console.log(value.message),
|
||||
resolveDownloadUrl: async () =>
|
||||
'https://runtime.example.invalid/nod-Runtime-win32-x64.tar.gz',
|
||||
@@ -399,6 +400,7 @@ if (process.env.WORKSPACE_CONTAINER) {
|
||||
{
|
||||
dataRoot: profile,
|
||||
resourcesPath: engine,
|
||||
finishRuntime,
|
||||
onStatus: (value) => console.log(value.message),
|
||||
},
|
||||
() => {},
|
||||
@@ -430,6 +432,7 @@ if (process.env.WORKSPACE_CONTAINER) {
|
||||
dataRoot: profile,
|
||||
resourcesPath: engine,
|
||||
database,
|
||||
finishRuntime,
|
||||
onMoved: () => moved++,
|
||||
onStatus: (value) => console.log(value.message),
|
||||
},
|
||||
|
||||
+244
-28
@@ -1,3 +1,4 @@
|
||||
import { existsSync } from 'node:fs';
|
||||
import { readdir, readFile } from 'node:fs/promises';
|
||||
import { dirname, relative, resolve } from 'node:path';
|
||||
import ts from 'typescript';
|
||||
@@ -15,14 +16,148 @@ async function files(directory) {
|
||||
).flat();
|
||||
}
|
||||
|
||||
const sourceRoot = resolve('src');
|
||||
const root = resolve(import.meta.dirname, '..');
|
||||
const sourceRoot = resolve(root, 'src');
|
||||
const desktopRoot = resolve(root, 'desktop');
|
||||
const failures = [];
|
||||
const vendor =
|
||||
/^(?:@earendil-works\/|@composio\/|@chat-adapter\/|@whiskeysockets\/|chat$|agent-browser$)/;
|
||||
for (const file of await files(sourceRoot)) {
|
||||
if (!/\.[cm]?[jt]sx?$/.test(file)) continue;
|
||||
const name = relative(sourceRoot, file).replaceAll('\\', '/');
|
||||
const layer = name.split('/')[0];
|
||||
/^(?:@earendil-works\/|@composio\/|@chat-adapter\/|@whiskeysockets\/|@1password\/|@modelcontextprotocol\/|@huggingface\/|@pedrobef\/|@spelling-creator\/|@audio\/|chat$|agent-browser$|posthog-node$|pi-web-access(?:\/|$))/;
|
||||
|
||||
function resolveLocal(fromFile, specifier) {
|
||||
if (!specifier.startsWith('.')) return null;
|
||||
const base = resolve(dirname(fromFile), specifier);
|
||||
const candidates = [
|
||||
base,
|
||||
base.replace(/\.js$/, '.ts'),
|
||||
base.replace(/\.js$/, '.tsx'),
|
||||
base.replace(/\.mjs$/, '.mts'),
|
||||
`${base}.ts`,
|
||||
`${base}.tsx`,
|
||||
`${base}.js`,
|
||||
`${base}.mjs`,
|
||||
`${base}.cjs`,
|
||||
resolve(base, 'index.ts'),
|
||||
resolve(base, 'index.tsx'),
|
||||
resolve(base, 'index.mjs'),
|
||||
resolve(base, 'index.js'),
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
if (existsSync(candidate)) return relative(root, candidate).replaceAll('\\', '/');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function isProcessNode(node, source, aliases) {
|
||||
if (ts.isIdentifier(node) && (node.text === 'process' || aliases.has(node.text))) return true;
|
||||
if (
|
||||
ts.isPropertyAccessExpression(node) &&
|
||||
ts.isIdentifier(node.expression) &&
|
||||
node.expression.text === 'globalThis' &&
|
||||
node.name.text === 'process'
|
||||
)
|
||||
return true;
|
||||
return node.getText(source) === 'globalThis.process';
|
||||
}
|
||||
|
||||
function readsProcessEnv(node, source, aliases) {
|
||||
if (
|
||||
ts.isPropertyAccessExpression(node) &&
|
||||
node.name.text === 'env' &&
|
||||
isProcessNode(node.expression, source, aliases)
|
||||
)
|
||||
return true;
|
||||
if (
|
||||
ts.isElementAccessExpression(node) &&
|
||||
node.argumentExpression &&
|
||||
ts.isStringLiteralLike(node.argumentExpression) &&
|
||||
node.argumentExpression.text === 'env' &&
|
||||
isProcessNode(node.expression, source, aliases)
|
||||
)
|
||||
return true;
|
||||
if (
|
||||
ts.isVariableDeclaration(node) &&
|
||||
ts.isObjectBindingPattern(node.name) &&
|
||||
node.initializer &&
|
||||
isProcessNode(node.initializer, source, aliases) &&
|
||||
node.name.elements.some((el) => (el.propertyName ?? el.name).getText(source) === 'env')
|
||||
)
|
||||
return true;
|
||||
if (
|
||||
ts.isImportDeclaration(node) &&
|
||||
ts.isStringLiteralLike(node.moduleSpecifier) &&
|
||||
(node.moduleSpecifier.text === 'node:process' || node.moduleSpecifier.text === 'process') &&
|
||||
node.importClause?.namedBindings &&
|
||||
ts.isNamedImports(node.importClause?.namedBindings) &&
|
||||
node.importClause.namedBindings.elements.some(
|
||||
(el) => (el.propertyName ?? el.name).text === 'env',
|
||||
)
|
||||
)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
function processImportAliases(source) {
|
||||
const aliases = new Set();
|
||||
for (const statement of source.statements) {
|
||||
if (
|
||||
ts.isImportDeclaration(statement) &&
|
||||
ts.isStringLiteralLike(statement.moduleSpecifier) &&
|
||||
(statement.moduleSpecifier.text === 'node:process' ||
|
||||
statement.moduleSpecifier.text === 'process')
|
||||
) {
|
||||
const clause = statement.importClause;
|
||||
if (clause?.name) aliases.add(clause.name.text);
|
||||
if (clause?.namedBindings && ts.isNamespaceImport(clause.namedBindings))
|
||||
aliases.add(clause.namedBindings.name.text);
|
||||
}
|
||||
}
|
||||
return aliases;
|
||||
}
|
||||
|
||||
function importIsTypeOnly(node) {
|
||||
if (ts.isImportDeclaration(node)) {
|
||||
const clause = node.importClause;
|
||||
if (!clause) return false;
|
||||
if (clause.isTypeOnly) return true;
|
||||
if (clause.name) return false;
|
||||
const bindings = clause.namedBindings;
|
||||
return Boolean(
|
||||
bindings &&
|
||||
ts.isNamedImports(bindings) &&
|
||||
bindings.elements.length &&
|
||||
bindings.elements.every((el) => el.isTypeOnly),
|
||||
);
|
||||
}
|
||||
if (ts.isExportDeclaration(node)) {
|
||||
if (node.isTypeOnly) return true;
|
||||
const clause = node.exportClause;
|
||||
return Boolean(
|
||||
clause &&
|
||||
ts.isNamedExports(clause) &&
|
||||
clause.elements.length &&
|
||||
clause.elements.every((el) => el.isTypeOnly),
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const srcFiles = (await files(sourceRoot)).filter(
|
||||
(file) => /\.[cm]?[jt]sx?$/.test(file) && !file.endsWith('.d.ts') && !file.endsWith('.d.mts'),
|
||||
);
|
||||
const desktopDirs = ['main', 'preload', 'runtime', 'ui'];
|
||||
const desktopFiles = (await Promise.all(desktopDirs.map((dir) => files(resolve(desktopRoot, dir)))))
|
||||
.flat()
|
||||
.filter(
|
||||
(file) => /\.[cm]?[jt]sx?$/.test(file) && !file.endsWith('.d.ts') && !file.endsWith('.d.mts'),
|
||||
);
|
||||
|
||||
const runtimeGraph = new Map();
|
||||
|
||||
for (const file of [...srcFiles, ...desktopFiles]) {
|
||||
const relRoot = relative(root, file).replaceAll('\\', '/');
|
||||
const isSrc = relRoot.startsWith('src/');
|
||||
const name = isSrc ? relative(sourceRoot, file).replaceAll('\\', '/') : relRoot;
|
||||
const layer = isSrc ? name.split('/')[0] : `desktop/${relRoot.split('/')[1]}`;
|
||||
const source = ts.createSourceFile(
|
||||
file,
|
||||
await readFile(file, 'utf8'),
|
||||
@@ -30,6 +165,9 @@ for (const file of await files(sourceRoot)) {
|
||||
true,
|
||||
);
|
||||
const problem = (message) => failures.push(`${name}: ${message}`);
|
||||
const runtimeEdges = new Set();
|
||||
const processAliases = processImportAliases(source);
|
||||
|
||||
function inspect(node) {
|
||||
const specifier =
|
||||
(ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier;
|
||||
@@ -40,40 +178,118 @@ for (const file of await files(sourceRoot)) {
|
||||
const literal = specifier || dynamic;
|
||||
if (literal && ts.isStringLiteralLike(literal)) {
|
||||
const dependency = literal.text;
|
||||
const isTypeOnly = importIsTypeOnly(node);
|
||||
if (vendor.test(dependency) && layer !== 'providers')
|
||||
problem(`Vendor dependency ${dependency} belongs in providers.`);
|
||||
if (
|
||||
/^posthog-js(?:\/|$)/.test(dependency) &&
|
||||
name !== 'web/lib/analytics-client.ts' &&
|
||||
name !== 'web/lib/analytics.ts'
|
||||
)
|
||||
problem(`Analytics SDK ${dependency} belongs in web/lib/analytics-client.ts.`);
|
||||
if (dependency.startsWith('.')) {
|
||||
const target = relative(sourceRoot, resolve(dirname(file), dependency))
|
||||
.replaceAll('\\', '/')
|
||||
.split('/')[0];
|
||||
const allowed = {
|
||||
web: ['web', 'shared'],
|
||||
shared: ['shared'],
|
||||
ports: ['ports', 'shared'],
|
||||
runtime: ['runtime', 'ports', 'shared'],
|
||||
providers: ['providers', 'ports', 'shared'],
|
||||
server:
|
||||
name === 'server/composition.ts'
|
||||
? ['server', 'runtime', 'providers', 'ports', 'shared']
|
||||
: ['server', 'ports', 'shared'],
|
||||
}[layer];
|
||||
if (
|
||||
!allowed?.includes(target) &&
|
||||
!(name === 'server/feedback-delivery.ts' && dependency === '../providers/n8n/feedback.ts')
|
||||
)
|
||||
problem(`Import of ${dependency} crosses the ${layer} boundary.`);
|
||||
const resolvedRel = resolveLocal(file, dependency);
|
||||
if (resolvedRel && !isTypeOnly) runtimeEdges.add(resolvedRel);
|
||||
if (isSrc) {
|
||||
const target = relative(sourceRoot, resolve(dirname(file), dependency))
|
||||
.replaceAll('\\', '/')
|
||||
.split('/')[0];
|
||||
const allowed = {
|
||||
web: ['web', 'shared'],
|
||||
shared: ['shared'],
|
||||
ports: ['ports', 'shared'],
|
||||
runtime: ['runtime', 'ports', 'shared'],
|
||||
providers: ['providers', 'ports', 'shared'],
|
||||
server:
|
||||
name === 'server/composition.ts'
|
||||
? ['server', 'runtime', 'providers', 'ports', 'shared']
|
||||
: ['server', 'ports', 'shared'],
|
||||
}[layer];
|
||||
if (
|
||||
!allowed?.includes(target) &&
|
||||
!(
|
||||
name === 'server/feedback-delivery.ts' &&
|
||||
dependency === '../providers/n8n/feedback.ts'
|
||||
)
|
||||
)
|
||||
problem(`Import of ${dependency} crosses the ${layer} boundary.`);
|
||||
} else {
|
||||
const targetPath = relative(root, resolve(dirname(file), dependency)).replaceAll(
|
||||
'\\',
|
||||
'/',
|
||||
);
|
||||
const targetTop = targetPath.startsWith('src/')
|
||||
? `src/${targetPath.split('/')[1]}`
|
||||
: `desktop/${targetPath.split('/')[1]}`;
|
||||
const desktopAllowed = {
|
||||
'desktop/preload': ['desktop/preload'],
|
||||
'desktop/runtime': ['desktop/runtime', 'src/shared'],
|
||||
'desktop/ui': ['desktop/ui', 'src/web', 'src/shared'],
|
||||
'desktop/main': ['desktop/main', 'desktop/runtime', 'src/shared'],
|
||||
}[layer];
|
||||
const allowedHelperBridge =
|
||||
(relRoot === 'desktop/main/feedback.mjs' &&
|
||||
(targetPath === 'src/server/feedback-delivery.ts' ||
|
||||
targetPath === 'src/server/startup-feedback.ts')) ||
|
||||
(relRoot === 'desktop/main/engine.mjs' && targetPath === 'src/server/index.ts') ||
|
||||
(relRoot === 'desktop/main/onepassword.mjs' &&
|
||||
targetPath === 'src/providers/onepassword/helper.ts');
|
||||
if (!desktopAllowed?.includes(targetTop) && !allowedHelperBridge)
|
||||
problem(`Import of ${dependency} crosses the ${layer} boundary.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (
|
||||
ts.isPropertyAccessExpression(node) &&
|
||||
node.getText(source) === 'process.env' &&
|
||||
['runtime', 'ports', 'shared', 'web'].includes(layer)
|
||||
readsProcessEnv(node, source, processAliases) &&
|
||||
['runtime', 'ports', 'shared', 'web', 'desktop/ui'].includes(layer)
|
||||
)
|
||||
problem('Environment configuration belongs in server composition.');
|
||||
ts.forEachChild(node, inspect);
|
||||
}
|
||||
inspect(source);
|
||||
runtimeGraph.set(relRoot, [...runtimeEdges]);
|
||||
}
|
||||
|
||||
let tarjanIndex = 0;
|
||||
const indices = new Map();
|
||||
const lowlink = new Map();
|
||||
const onStack = new Set();
|
||||
const stack = [];
|
||||
|
||||
function strongConnect(node) {
|
||||
indices.set(node, tarjanIndex);
|
||||
lowlink.set(node, tarjanIndex);
|
||||
tarjanIndex++;
|
||||
stack.push(node);
|
||||
onStack.add(node);
|
||||
for (const next of runtimeGraph.get(node) ?? []) {
|
||||
if (!runtimeGraph.has(next)) continue;
|
||||
if (!indices.has(next)) {
|
||||
strongConnect(next);
|
||||
lowlink.set(node, Math.min(lowlink.get(node), lowlink.get(next)));
|
||||
} else if (onStack.has(next)) {
|
||||
lowlink.set(node, Math.min(lowlink.get(node), indices.get(next)));
|
||||
}
|
||||
}
|
||||
if (lowlink.get(node) === indices.get(node)) {
|
||||
const scc = [];
|
||||
let member;
|
||||
do {
|
||||
member = stack.pop();
|
||||
onStack.delete(member);
|
||||
scc.push(member);
|
||||
} while (member !== node);
|
||||
if (scc.length > 1)
|
||||
failures.push(`Runtime circular dependency: ${scc.reverse().join(' <-> ')}`);
|
||||
else if ((runtimeGraph.get(node) ?? []).includes(node))
|
||||
failures.push(`Runtime circular dependency: ${node} <-> ${node}`);
|
||||
}
|
||||
}
|
||||
|
||||
for (const node of runtimeGraph.keys()) {
|
||||
if (!indices.has(node)) strongConnect(node);
|
||||
}
|
||||
|
||||
if (failures.length) {
|
||||
console.error(failures.join('\n'));
|
||||
process.exitCode = 1;
|
||||
|
||||
+23
-8
@@ -44,20 +44,35 @@ export interface DiscoveredTransport {
|
||||
signal?: AbortSignal,
|
||||
): Promise<unknown>;
|
||||
}
|
||||
import type { OAuthDiscoveryState } from '@modelcontextprotocol/sdk/client/auth.js';
|
||||
import type {
|
||||
OAuthClientInformationMixed,
|
||||
OAuthTokens,
|
||||
} from '@modelcontextprotocol/sdk/shared/auth.js';
|
||||
export interface DiscoveredOAuthTokens {
|
||||
access_token: string;
|
||||
token_type: string;
|
||||
expires_in?: number;
|
||||
scope?: string;
|
||||
refresh_token?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface DiscoveredOAuthServerMetadata {
|
||||
issuer: string;
|
||||
authorization_response_iss_parameter_supported?: boolean;
|
||||
}
|
||||
|
||||
export interface DiscoveredOAuthDiscovery {
|
||||
authorizationServerUrl: string;
|
||||
resourceMetadataUrl?: string;
|
||||
resourceMetadata?: Record<string, unknown>;
|
||||
authorizationServerMetadata?: DiscoveredOAuthServerMetadata;
|
||||
}
|
||||
|
||||
export type DiscoveredOAuthState = {
|
||||
redirectUri: string;
|
||||
scope?: string;
|
||||
clientInformation?: OAuthClientInformationMixed;
|
||||
tokens?: OAuthTokens;
|
||||
clientInformation?: { client_id: string; [key: string]: unknown };
|
||||
tokens?: DiscoveredOAuthTokens;
|
||||
expiresAt?: number;
|
||||
verifier?: string;
|
||||
discovery?: OAuthDiscoveryState;
|
||||
discovery?: DiscoveredOAuthDiscovery;
|
||||
};
|
||||
|
||||
export interface DiscoveredOAuth {
|
||||
|
||||
@@ -2,7 +2,13 @@ import {
|
||||
auth,
|
||||
refreshAuthorization,
|
||||
type OAuthClientProvider,
|
||||
type OAuthDiscoveryState,
|
||||
} from '@modelcontextprotocol/sdk/client/auth.js';
|
||||
import type {
|
||||
OAuthClientInformationMixed,
|
||||
OAuthMetadata,
|
||||
OAuthTokens,
|
||||
} from '@modelcontextprotocol/sdk/shared/auth.js';
|
||||
import type { FetchLike } from '@modelcontextprotocol/sdk/shared/transport.js';
|
||||
import {
|
||||
OAuthError,
|
||||
@@ -53,13 +59,13 @@ export function createDiscoveredOAuth(
|
||||
...(saved.scope ? { scope: saved.scope } : {}),
|
||||
},
|
||||
state: () => options.state ?? '',
|
||||
clientInformation: () => saved.clientInformation,
|
||||
clientInformation: () => saved.clientInformation as OAuthClientInformationMixed | undefined,
|
||||
saveClientInformation: (value) => {
|
||||
saved.clientInformation = value;
|
||||
saved.clientInformation = value as DiscoveredOAuthState['clientInformation'];
|
||||
},
|
||||
tokens: () => saved.tokens,
|
||||
tokens: () => saved.tokens as OAuthTokens | undefined,
|
||||
saveTokens: (value) => {
|
||||
saved.tokens = value;
|
||||
saved.tokens = value as DiscoveredOAuthState['tokens'];
|
||||
saved.expiresAt =
|
||||
value.expires_in === undefined ? undefined : Date.now() + value.expires_in * 1000;
|
||||
},
|
||||
@@ -74,9 +80,9 @@ export function createDiscoveredOAuth(
|
||||
return saved.verifier;
|
||||
},
|
||||
saveDiscoveryState: (value) => {
|
||||
saved.discovery = value;
|
||||
saved.discovery = value as unknown as DiscoveredOAuthState['discovery'];
|
||||
},
|
||||
discoveryState: () => saved.discovery,
|
||||
discoveryState: () => saved.discovery as unknown as OAuthDiscoveryState | undefined,
|
||||
};
|
||||
const result = await auth(provider, {
|
||||
serverUrl: endpoint,
|
||||
@@ -126,10 +132,10 @@ export function createDiscoveredOAuth(
|
||||
if (!refreshToken || !clientInformation || !discovery) throw new DiscoveredSignInRequired();
|
||||
signal?.throwIfAborted();
|
||||
const tokens = await refreshAuthorization(discovery.authorizationServerUrl, {
|
||||
metadata: discovery.authorizationServerMetadata,
|
||||
clientInformation,
|
||||
metadata: discovery.authorizationServerMetadata as OAuthMetadata | undefined,
|
||||
clientInformation: clientInformation as OAuthClientInformationMixed,
|
||||
refreshToken,
|
||||
resource: discovery.resourceMetadata?.resource,
|
||||
resource: discovery.resourceMetadata?.resource as URL | undefined,
|
||||
fetchFn: bound(signal),
|
||||
}).catch((cause: unknown) => {
|
||||
if (!(cause instanceof OAuthError)) throw cause;
|
||||
|
||||
@@ -1,325 +1,10 @@
|
||||
import { Fragment } from 'react';
|
||||
import type { Schedule, Task } from '../../shared/contracts';
|
||||
import {
|
||||
canReuseWorkCost,
|
||||
repriceUsd,
|
||||
routeModel,
|
||||
type ModelLane,
|
||||
type ModelSelection,
|
||||
type ModelsResponse,
|
||||
type WorkKind,
|
||||
type WorkUsage,
|
||||
type WorkUsageResponse,
|
||||
} from '../../shared/models';
|
||||
import { routeModel, type WorkUsageResponse } from '../../shared/models';
|
||||
import { useModels } from '../hooks/use-models';
|
||||
import { usePageData } from '../hooks/use-page-data';
|
||||
import { api, errorMessage } from '../lib/api';
|
||||
import { money } from '../lib/money';
|
||||
import { pageDataCache } from '../lib/page-data-cache';
|
||||
import { schedulesPath } from '../lib/schedule-reconciliation';
|
||||
import { ModelPicker, type ModelTarget } from './models';
|
||||
|
||||
const workUsagePath = '/api/usage/work';
|
||||
const kindNames: Record<WorkKind, string> = {
|
||||
chat: 'chat',
|
||||
schedule: 'schedules',
|
||||
background: 'Nod’s own work',
|
||||
};
|
||||
|
||||
function modelOf(data: ModelsResponse, choice: ModelSelection | null | undefined) {
|
||||
return data.connections
|
||||
.find((item) => item.id === choice?.connectionId)
|
||||
?.models.find((item) => item.id === choice?.modelId);
|
||||
}
|
||||
|
||||
const unavailableLabel = 'an unavailable model';
|
||||
|
||||
function kept(data: ModelsResponse, choice: ModelSelection | null | undefined) {
|
||||
return choice && data.connections.some((item) => item.id === choice.connectionId) ? choice : null;
|
||||
}
|
||||
|
||||
function same(a: ModelSelection | null | undefined, b: ModelSelection | null | undefined) {
|
||||
return (
|
||||
a?.connectionId === b?.connectionId && a?.modelId === b?.modelId && a?.effort === b?.effort
|
||||
);
|
||||
}
|
||||
|
||||
async function saved<T>(path: string, body: unknown, update: (value: T) => void) {
|
||||
try {
|
||||
update(await api<T>(path, { method: 'PUT', body: JSON.stringify(body) }));
|
||||
void pageDataCache.refresh(workUsagePath, true);
|
||||
return true as const;
|
||||
} catch (cause) {
|
||||
return errorMessage(cause);
|
||||
}
|
||||
}
|
||||
|
||||
function laneTarget(
|
||||
data: ModelsResponse,
|
||||
lane: ModelLane,
|
||||
usage: WorkUsage | undefined,
|
||||
): ModelTarget {
|
||||
const value = data.routes?.[lane] ?? null;
|
||||
return {
|
||||
title: lane === 'schedule' ? 'Model for schedules' : 'Model for work Nod starts on its own',
|
||||
value: value === 'light' ? value : kept(data, value),
|
||||
defaults: [
|
||||
{ value: null, label: 'The same model', model: data.selection },
|
||||
...(data.light
|
||||
? [{ value: 'light' as const, label: 'The light model', model: data.light }]
|
||||
: []),
|
||||
],
|
||||
usage,
|
||||
save: (route) =>
|
||||
saved<ModelsResponse>('/api/models/routes', { lane, route }, (result) =>
|
||||
pageDataCache.update('/api/models', () => result),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function backupTarget(data: ModelsResponse, index: number): ModelTarget {
|
||||
const list = data.backups ?? [];
|
||||
return {
|
||||
title: index < list.length ? `Backup model ${index + 1}` : 'Add a backup model',
|
||||
value: list[index] ?? null,
|
||||
defaults: index < list.length ? [{ value: null, label: 'No backup', model: null }] : [],
|
||||
save: (choice) => {
|
||||
const next = [...list];
|
||||
if (choice && choice !== 'light') next[index] = choice;
|
||||
else next.splice(index, 1);
|
||||
return saved<ModelsResponse>('/api/models/backups', { backups: next }, (result) =>
|
||||
pageDataCache.update('/api/models', () => result),
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function scheduleTarget(
|
||||
data: ModelsResponse,
|
||||
schedule: Schedule,
|
||||
usage: WorkUsage | undefined,
|
||||
): ModelTarget {
|
||||
return {
|
||||
title: `Model for ${schedule.title}`,
|
||||
value: kept(data, schedule.model),
|
||||
defaults: [
|
||||
{
|
||||
value: null,
|
||||
label: 'Same as schedules',
|
||||
model: routeModel(data, 'schedule')?.selection ?? null,
|
||||
},
|
||||
],
|
||||
usage,
|
||||
save: (model) =>
|
||||
saved<Schedule>(
|
||||
`${schedulesPath}/${encodeURIComponent(schedule.id)}/model`,
|
||||
{ model },
|
||||
(result) =>
|
||||
pageDataCache.update<Schedule[]>(
|
||||
schedulesPath,
|
||||
(items) => items?.map((item) => (item.id === result.id ? result : item)) ?? items,
|
||||
),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function taskTarget(
|
||||
data: ModelsResponse,
|
||||
task: Task & { work: WorkKind },
|
||||
usage: WorkUsage | undefined,
|
||||
): ModelTarget {
|
||||
return {
|
||||
title: `Model for ${task.title}`,
|
||||
value: kept(data, task.model),
|
||||
defaults: [
|
||||
{
|
||||
value: null,
|
||||
label: task.scheduleModel ? 'Same as its schedule' : `Same as ${kindNames[task.work]}`,
|
||||
model: routeModel(data, task.work, { schedule: task.scheduleModel })?.selection ?? null,
|
||||
},
|
||||
],
|
||||
usage,
|
||||
save: (model) =>
|
||||
saved<Task>(`/api/tasks/${encodeURIComponent(task.id)}/model`, { model }, (result) =>
|
||||
pageDataCache.update<Task[]>(
|
||||
'/api/tasks',
|
||||
(items) => items?.map((item) => (item.id === result.id ? result : item)) ?? items,
|
||||
),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function estimate(
|
||||
data: ModelsResponse,
|
||||
parts: Array<{ usage: WorkUsage | undefined; model: ModelSelection | null | undefined }>,
|
||||
) {
|
||||
let recorded = 0;
|
||||
let projected = 0;
|
||||
const unpriced = new Set<string>();
|
||||
for (const { usage, model } of parts) {
|
||||
const spent = usage ? usage.agentUsd + usage.otherUsd : 0;
|
||||
if (!usage || spent <= 0) continue;
|
||||
recorded += spent;
|
||||
const choice = modelOf(data, model);
|
||||
if (choice && canReuseWorkCost(usage, choice.id, choice.pricing)) {
|
||||
projected += spent;
|
||||
continue;
|
||||
}
|
||||
const value = choice && repriceUsd(usage, choice.pricing, choice.audio);
|
||||
if (value === null || value === undefined) unpriced.add(choice?.name ?? unavailableLabel);
|
||||
else projected += value;
|
||||
}
|
||||
return { recorded, projected, unpriced: [...unpriced] };
|
||||
}
|
||||
|
||||
export function ModelSentences() {
|
||||
const models = useModels();
|
||||
const usage = usePageData<WorkUsageResponse>(workUsagePath);
|
||||
const schedules = usePageData<Schedule[]>(schedulesPath);
|
||||
const tasks = usePageData<Task[]>('/api/tasks');
|
||||
const data = models.data;
|
||||
if (!data) return null;
|
||||
const chat = modelOf(data, data.selection);
|
||||
const backups = data.backups ?? [];
|
||||
const lane = (kind: ModelLane) => {
|
||||
const value = data.routes?.[kind];
|
||||
const light = value === 'light' && data.light && modelOf(data, data.light);
|
||||
const own = value === 'light' ? null : kept(data, value);
|
||||
return (
|
||||
<>
|
||||
<ModelPicker
|
||||
appearance="statement"
|
||||
manageConnections={false}
|
||||
target={laneTarget(data, kind, usage.data?.lanes[kind])}
|
||||
label={
|
||||
light
|
||||
? 'the light model'
|
||||
: own
|
||||
? (modelOf(data, own)?.name ?? unavailableLabel)
|
||||
: 'the same model'
|
||||
}
|
||||
/>
|
||||
{light ? `, ${light.name}` : ''}
|
||||
</>
|
||||
);
|
||||
};
|
||||
const ownSchedules = (schedules.data ?? []).filter(
|
||||
(schedule) =>
|
||||
kept(data, schedule.model) &&
|
||||
!same(
|
||||
routeModel(data, 'schedule', { schedule: schedule.model })?.selection,
|
||||
routeModel(data, 'schedule')?.selection,
|
||||
),
|
||||
);
|
||||
const ownTasks = (tasks.data ?? []).filter(
|
||||
(task): task is Task & { work: WorkKind } =>
|
||||
Boolean(task.work && kept(data, task.model)) &&
|
||||
!task.closedAt &&
|
||||
!same(task.model, routeModel(data, task.work!, { schedule: task.scheduleModel })?.selection),
|
||||
);
|
||||
const work = usage.data;
|
||||
const price =
|
||||
work &&
|
||||
estimate(data, [
|
||||
{ usage: work.lanes.chat, model: data.selection },
|
||||
{ usage: work.lanes.schedule, model: routeModel(data, 'schedule')?.selection },
|
||||
{ usage: work.lanes.background, model: routeModel(data, 'background')?.selection },
|
||||
...(work.own ?? []).map(({ kind, task, schedule, ...usage }) => ({
|
||||
usage,
|
||||
model: routeModel(data, kind, { task, schedule })?.selection,
|
||||
})),
|
||||
]);
|
||||
return (
|
||||
<section className="model-current-section" aria-label="Your models">
|
||||
<div className="statement-summary model-sentences">
|
||||
<p>
|
||||
When you talk to Nod, it uses{' '}
|
||||
<ModelPicker
|
||||
appearance="statement"
|
||||
manageConnections={false}
|
||||
usage={work?.lanes.chat}
|
||||
label={chat?.name ?? 'no model yet'}
|
||||
/>
|
||||
.
|
||||
</p>
|
||||
{chat && (
|
||||
<p>
|
||||
If it’s busy or unavailable, Nod tries{' '}
|
||||
{backups.length
|
||||
? backups.map((choice, index) => (
|
||||
<Fragment key={index}>
|
||||
{index ? ', then ' : ''}
|
||||
<ModelPicker
|
||||
appearance="statement"
|
||||
manageConnections={false}
|
||||
target={backupTarget(data, index)}
|
||||
label={`${modelOf(data, choice)?.name ?? unavailableLabel}${
|
||||
choice.connectionId === data.selection?.connectionId &&
|
||||
choice.modelId === data.selection?.modelId
|
||||
? ' (already your chat model)'
|
||||
: ''
|
||||
}`}
|
||||
/>
|
||||
</Fragment>
|
||||
))
|
||||
: 'no other model'}
|
||||
.
|
||||
</p>
|
||||
)}
|
||||
<p>Schedules use {lane('schedule')}.</p>
|
||||
<p>Work Nod starts on its own uses {lane('background')}.</p>
|
||||
{ownSchedules.map((schedule) => (
|
||||
<p key={schedule.id}>
|
||||
{schedule.title} uses{' '}
|
||||
<ModelPicker
|
||||
appearance="statement"
|
||||
manageConnections={false}
|
||||
target={scheduleTarget(data, schedule, work?.schedules[schedule.id])}
|
||||
label={modelOf(data, schedule.model)?.name ?? unavailableLabel}
|
||||
/>
|
||||
.
|
||||
</p>
|
||||
))}
|
||||
{ownTasks.map((task) => (
|
||||
<p key={task.id}>
|
||||
{task.title} uses{' '}
|
||||
<ModelPicker
|
||||
appearance="statement"
|
||||
manageConnections={false}
|
||||
target={taskTarget(data, task, work?.tasks[task.id])}
|
||||
label={modelOf(data, task.model)?.name ?? unavailableLabel}
|
||||
/>
|
||||
.
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
{chat && backups.length < 3 && (
|
||||
<p className="model-sentences-note">
|
||||
<ModelPicker
|
||||
appearance="statement"
|
||||
manageConnections={false}
|
||||
target={backupTarget(data, backups.length)}
|
||||
label="Add a backup model"
|
||||
/>
|
||||
</p>
|
||||
)}
|
||||
{chat?.audio && (
|
||||
<p className="model-sentences-note">
|
||||
{chat.textModelName ? `Text support: ${chat.textModelName}` : 'Text model unavailable'}
|
||||
</p>
|
||||
)}
|
||||
{price && price.recorded > 0 && (
|
||||
<p className="model-sentences-note" role="status">
|
||||
{price.unpriced.length
|
||||
? `Work on ${price.unpriced.join(' and ')} has no price in Nod.`
|
||||
: Math.abs(price.projected - price.recorded) >= 0.01
|
||||
? `With these choices, the last 30 days would have cost about ${money(price.projected)} instead of ${money(price.recorded)}.`
|
||||
: `Last 30 days: ${money(price.recorded)}.`}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
import { ModelPicker } from './models';
|
||||
import { kindNames, modelOf, scheduleTarget, taskTarget, workUsagePath } from './model-targets';
|
||||
|
||||
export function WorkModel({ task }: { task: Task }) {
|
||||
const models = useModels();
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
import type { Schedule, Task } from '../../shared/contracts';
|
||||
import {
|
||||
canReuseWorkCost,
|
||||
repriceUsd,
|
||||
routeModel,
|
||||
type ModelLane,
|
||||
type ModelSelection,
|
||||
type ModelsResponse,
|
||||
type WorkKind,
|
||||
type WorkUsage,
|
||||
} from '../../shared/models';
|
||||
import { api, errorMessage } from '../lib/api';
|
||||
import { pageDataCache } from '../lib/page-data-cache';
|
||||
import { schedulesPath } from '../lib/schedule-reconciliation';
|
||||
import type { ModelTarget } from './models';
|
||||
|
||||
export const workUsagePath = '/api/usage/work';
|
||||
export const kindNames: Record<WorkKind, string> = {
|
||||
chat: 'chat',
|
||||
schedule: 'schedules',
|
||||
background: 'Nod’s own work',
|
||||
};
|
||||
|
||||
export function modelOf(data: ModelsResponse, choice: ModelSelection | null | undefined) {
|
||||
return data.connections
|
||||
.find((item) => item.id === choice?.connectionId)
|
||||
?.models.find((item) => item.id === choice?.modelId);
|
||||
}
|
||||
|
||||
export const unavailableLabel = 'an unavailable model';
|
||||
|
||||
export function kept(data: ModelsResponse, choice: ModelSelection | null | undefined) {
|
||||
return choice && data.connections.some((item) => item.id === choice.connectionId) ? choice : null;
|
||||
}
|
||||
|
||||
export function sameModelSelection(
|
||||
a: ModelSelection | null | undefined,
|
||||
b: ModelSelection | null | undefined,
|
||||
) {
|
||||
return (
|
||||
a?.connectionId === b?.connectionId && a?.modelId === b?.modelId && a?.effort === b?.effort
|
||||
);
|
||||
}
|
||||
|
||||
async function saved<T>(path: string, body: unknown, update: (value: T) => void) {
|
||||
try {
|
||||
update(await api<T>(path, { method: 'PUT', body: JSON.stringify(body) }));
|
||||
void pageDataCache.refresh(workUsagePath, true);
|
||||
return true as const;
|
||||
} catch (cause) {
|
||||
return errorMessage(cause);
|
||||
}
|
||||
}
|
||||
|
||||
export function laneTarget(
|
||||
data: ModelsResponse,
|
||||
lane: ModelLane,
|
||||
usage: WorkUsage | undefined,
|
||||
): ModelTarget {
|
||||
const value = data.routes?.[lane] ?? null;
|
||||
return {
|
||||
title: lane === 'schedule' ? 'Model for schedules' : 'Model for work Nod starts on its own',
|
||||
value: value === 'light' ? value : kept(data, value),
|
||||
defaults: [
|
||||
{ value: null, label: 'The same model', model: data.selection },
|
||||
...(data.light
|
||||
? [{ value: 'light' as const, label: 'The light model', model: data.light }]
|
||||
: []),
|
||||
],
|
||||
usage,
|
||||
save: (route) =>
|
||||
saved<ModelsResponse>('/api/models/routes', { lane, route }, (result) =>
|
||||
pageDataCache.update('/api/models', () => result),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function backupTarget(data: ModelsResponse, index: number): ModelTarget {
|
||||
const list = data.backups ?? [];
|
||||
return {
|
||||
title: index < list.length ? `Backup model ${index + 1}` : 'Add a backup model',
|
||||
value: list[index] ?? null,
|
||||
defaults: index < list.length ? [{ value: null, label: 'No backup', model: null }] : [],
|
||||
save: (choice) => {
|
||||
const next = [...list];
|
||||
if (choice && choice !== 'light') next[index] = choice;
|
||||
else next.splice(index, 1);
|
||||
return saved<ModelsResponse>('/api/models/backups', { backups: next }, (result) =>
|
||||
pageDataCache.update('/api/models', () => result),
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function scheduleTarget(
|
||||
data: ModelsResponse,
|
||||
schedule: Schedule,
|
||||
usage: WorkUsage | undefined,
|
||||
): ModelTarget {
|
||||
return {
|
||||
title: `Model for ${schedule.title}`,
|
||||
value: kept(data, schedule.model),
|
||||
defaults: [
|
||||
{
|
||||
value: null,
|
||||
label: 'Same as schedules',
|
||||
model: routeModel(data, 'schedule')?.selection ?? null,
|
||||
},
|
||||
],
|
||||
usage,
|
||||
save: (model) =>
|
||||
saved<Schedule>(
|
||||
`${schedulesPath}/${encodeURIComponent(schedule.id)}/model`,
|
||||
{ model },
|
||||
(result) =>
|
||||
pageDataCache.update<Schedule[]>(
|
||||
schedulesPath,
|
||||
(items) => items?.map((item) => (item.id === result.id ? result : item)) ?? items,
|
||||
),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function taskTarget(
|
||||
data: ModelsResponse,
|
||||
task: Task & { work: WorkKind },
|
||||
usage: WorkUsage | undefined,
|
||||
): ModelTarget {
|
||||
return {
|
||||
title: `Model for ${task.title}`,
|
||||
value: kept(data, task.model),
|
||||
defaults: [
|
||||
{
|
||||
value: null,
|
||||
label: task.scheduleModel ? 'Same as its schedule' : `Same as ${kindNames[task.work]}`,
|
||||
model: routeModel(data, task.work, { schedule: task.scheduleModel })?.selection ?? null,
|
||||
},
|
||||
],
|
||||
usage,
|
||||
save: (model) =>
|
||||
saved<Task>(`/api/tasks/${encodeURIComponent(task.id)}/model`, { model }, (result) =>
|
||||
pageDataCache.update<Task[]>(
|
||||
'/api/tasks',
|
||||
(items) => items?.map((item) => (item.id === result.id ? result : item)) ?? items,
|
||||
),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function estimateModelChoices(
|
||||
data: ModelsResponse,
|
||||
parts: Array<{ usage: WorkUsage | undefined; model: ModelSelection | null | undefined }>,
|
||||
) {
|
||||
let recorded = 0;
|
||||
let projected = 0;
|
||||
const unpriced = new Set<string>();
|
||||
for (const { usage, model } of parts) {
|
||||
const spent = usage ? usage.agentUsd + usage.otherUsd : 0;
|
||||
if (!usage || spent <= 0) continue;
|
||||
recorded += spent;
|
||||
const choice = modelOf(data, model);
|
||||
if (choice && canReuseWorkCost(usage, choice.id, choice.pricing)) {
|
||||
projected += spent;
|
||||
continue;
|
||||
}
|
||||
const value = choice && repriceUsd(usage, choice.pricing, choice.audio);
|
||||
if (value === null || value === undefined) unpriced.add(choice?.name ?? unavailableLabel);
|
||||
else projected += value;
|
||||
}
|
||||
return { recorded, projected, unpriced: [...unpriced] };
|
||||
}
|
||||
@@ -1,4 +1,12 @@
|
||||
import { useEffect, useId, useRef, useState, type CSSProperties, type KeyboardEvent } from 'react';
|
||||
import {
|
||||
Fragment,
|
||||
useEffect,
|
||||
useId,
|
||||
useRef,
|
||||
useState,
|
||||
type CSSProperties,
|
||||
type KeyboardEvent,
|
||||
} from 'react';
|
||||
import {
|
||||
Brain,
|
||||
Check,
|
||||
@@ -13,14 +21,18 @@ import {
|
||||
UserRound,
|
||||
Trash2,
|
||||
} from './icons';
|
||||
import type { Schedule, Task } from '../../shared/contracts';
|
||||
import type {
|
||||
ModelChoice,
|
||||
ModelConnection,
|
||||
ModelLane,
|
||||
ModelProvider,
|
||||
ModelRoute,
|
||||
ModelSelection,
|
||||
ModelWorkspace,
|
||||
WorkKind,
|
||||
WorkUsage,
|
||||
WorkUsageResponse,
|
||||
} from '../../shared/models';
|
||||
import { describeModelFailure } from '../../shared/model-quota';
|
||||
import { modelKeyError } from '../../shared/model-keys';
|
||||
@@ -35,10 +47,23 @@ import {
|
||||
usesServerAddress,
|
||||
canReuseWorkCost,
|
||||
repriceUsd,
|
||||
routeModel,
|
||||
} from '../../shared/models';
|
||||
import { analyticsForCurrentSession } from '../lib/analytics';
|
||||
import { money } from '../lib/money';
|
||||
import { ModelSentences } from './model-choices';
|
||||
import { schedulesPath } from '../lib/schedule-reconciliation';
|
||||
import {
|
||||
backupTarget,
|
||||
estimateModelChoices,
|
||||
kept,
|
||||
laneTarget,
|
||||
modelOf,
|
||||
sameModelSelection,
|
||||
scheduleTarget,
|
||||
taskTarget,
|
||||
unavailableLabel,
|
||||
workUsagePath,
|
||||
} from './model-targets';
|
||||
import {
|
||||
keyConnection,
|
||||
keySettingsReady,
|
||||
@@ -445,6 +470,158 @@ type ModelPanel =
|
||||
| { type: 'manage'; provider: ModelProvider }
|
||||
| { type: 'connect'; provider: ModelProvider; connectionId?: string };
|
||||
|
||||
function ModelSentences() {
|
||||
const models = useModels();
|
||||
const usage = usePageData<WorkUsageResponse>(workUsagePath);
|
||||
const schedules = usePageData<Schedule[]>(schedulesPath);
|
||||
const tasks = usePageData<Task[]>('/api/tasks');
|
||||
const data = models.data;
|
||||
if (!data) return null;
|
||||
const chat = modelOf(data, data.selection);
|
||||
const backups = data.backups ?? [];
|
||||
const lane = (kind: ModelLane) => {
|
||||
const value = data.routes?.[kind];
|
||||
const light = value === 'light' && data.light && modelOf(data, data.light);
|
||||
const own = value === 'light' ? null : kept(data, value);
|
||||
return (
|
||||
<>
|
||||
<ModelPicker
|
||||
appearance="statement"
|
||||
manageConnections={false}
|
||||
target={laneTarget(data, kind, usage.data?.lanes[kind])}
|
||||
label={
|
||||
light
|
||||
? 'the light model'
|
||||
: own
|
||||
? (modelOf(data, own)?.name ?? unavailableLabel)
|
||||
: 'the same model'
|
||||
}
|
||||
/>
|
||||
{light ? `, ${light.name}` : ''}
|
||||
</>
|
||||
);
|
||||
};
|
||||
const ownSchedules = (schedules.data ?? []).filter(
|
||||
(schedule) =>
|
||||
kept(data, schedule.model) &&
|
||||
!sameModelSelection(
|
||||
routeModel(data, 'schedule', { schedule: schedule.model })?.selection,
|
||||
routeModel(data, 'schedule')?.selection,
|
||||
),
|
||||
);
|
||||
const ownTasks = (tasks.data ?? []).filter(
|
||||
(task): task is Task & { work: WorkKind } =>
|
||||
Boolean(task.work && kept(data, task.model)) &&
|
||||
!task.closedAt &&
|
||||
!sameModelSelection(
|
||||
task.model,
|
||||
routeModel(data, task.work!, { schedule: task.scheduleModel })?.selection,
|
||||
),
|
||||
);
|
||||
const work = usage.data;
|
||||
const price =
|
||||
work &&
|
||||
estimateModelChoices(data, [
|
||||
{ usage: work.lanes.chat, model: data.selection },
|
||||
{ usage: work.lanes.schedule, model: routeModel(data, 'schedule')?.selection },
|
||||
{ usage: work.lanes.background, model: routeModel(data, 'background')?.selection },
|
||||
...(work.own ?? []).map(({ kind, task, schedule, ...ownUsage }) => ({
|
||||
usage: ownUsage,
|
||||
model: routeModel(data, kind, { task, schedule })?.selection,
|
||||
})),
|
||||
]);
|
||||
return (
|
||||
<section className="model-current-section" aria-label="Your models">
|
||||
<div className="statement-summary model-sentences">
|
||||
<p>
|
||||
When you talk to Nod, it uses{' '}
|
||||
<ModelPicker
|
||||
appearance="statement"
|
||||
manageConnections={false}
|
||||
usage={work?.lanes.chat}
|
||||
label={chat?.name ?? 'no model yet'}
|
||||
/>
|
||||
.
|
||||
</p>
|
||||
{chat && (
|
||||
<p>
|
||||
If it’s busy or unavailable, Nod tries{' '}
|
||||
{backups.length
|
||||
? backups.map((choice, index) => (
|
||||
<Fragment key={index}>
|
||||
{index ? ', then ' : ''}
|
||||
<ModelPicker
|
||||
appearance="statement"
|
||||
manageConnections={false}
|
||||
target={backupTarget(data, index)}
|
||||
label={`${modelOf(data, choice)?.name ?? unavailableLabel}${
|
||||
choice.connectionId === data.selection?.connectionId &&
|
||||
choice.modelId === data.selection?.modelId
|
||||
? ' (already your chat model)'
|
||||
: ''
|
||||
}`}
|
||||
/>
|
||||
</Fragment>
|
||||
))
|
||||
: 'no other model'}
|
||||
.
|
||||
</p>
|
||||
)}
|
||||
<p>Schedules use {lane('schedule')}.</p>
|
||||
<p>Work Nod starts on its own uses {lane('background')}.</p>
|
||||
{ownSchedules.map((schedule) => (
|
||||
<p key={schedule.id}>
|
||||
{schedule.title} uses{' '}
|
||||
<ModelPicker
|
||||
appearance="statement"
|
||||
manageConnections={false}
|
||||
target={scheduleTarget(data, schedule, work?.schedules[schedule.id])}
|
||||
label={modelOf(data, schedule.model)?.name ?? unavailableLabel}
|
||||
/>
|
||||
.
|
||||
</p>
|
||||
))}
|
||||
{ownTasks.map((task) => (
|
||||
<p key={task.id}>
|
||||
{task.title} uses{' '}
|
||||
<ModelPicker
|
||||
appearance="statement"
|
||||
manageConnections={false}
|
||||
target={taskTarget(data, task, work?.tasks[task.id])}
|
||||
label={modelOf(data, task.model)?.name ?? unavailableLabel}
|
||||
/>
|
||||
.
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
{chat && backups.length < 3 && (
|
||||
<p className="model-sentences-note">
|
||||
<ModelPicker
|
||||
appearance="statement"
|
||||
manageConnections={false}
|
||||
target={backupTarget(data, backups.length)}
|
||||
label="Add a backup model"
|
||||
/>
|
||||
</p>
|
||||
)}
|
||||
{chat?.audio && (
|
||||
<p className="model-sentences-note">
|
||||
{chat.textModelName ? `Text support: ${chat.textModelName}` : 'Text model unavailable'}
|
||||
</p>
|
||||
)}
|
||||
{price && price.recorded > 0 && (
|
||||
<p className="model-sentences-note" role="status">
|
||||
{price.unpriced.length
|
||||
? `Work on ${price.unpriced.join(' and ')} has no price in Nod.`
|
||||
: Math.abs(price.projected - price.recorded) >= 0.01
|
||||
? `With these choices, the last 30 days would have cost about ${money(price.projected)} instead of ${money(price.recorded)}.`
|
||||
: `Last 30 days: ${money(price.recorded)}.`}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function ModelSettings({ onDirtyChange }: { onDirtyChange?(dirty: boolean): void } = {}) {
|
||||
const models = useModels();
|
||||
const keyErrorId = useId();
|
||||
|
||||
Reference in new issue
Block a user