Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Tell the agent when a newer 67js exists (#907)

Nguyen Xuan An38c05ea431b3
diff --git a/SECURITY.md b/SECURITY.md
index 548d0225..c6674081 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -16,6 +16,7 @@ The MCP server takes input from AI agents, and that input can come from a prompt
- It reads assets only from the configured catalog, and it fetches no remote URLs for assets.
- It writes render output and GLB exports (`scene_export_glb`, under `exports/`, server-chosen names) only to the configured jobs folder.
- It bounds every collection, count and size before it allocates memory.
+- Its one outbound request is a fixed GET to the npm registry for the latest version number, in the background, at most once a day, off with `SIXTYSEVENJS_NO_UPDATE_CHECK=1`, `NO_UPDATE_NOTIFIER=1` or `CI`. No tool call can change the URL or send data ([docs/mcp.md](docs/mcp.md#updates)).
`docs/mcp.md` describes each limit and its boundary tests.
diff --git a/bin/67js-mcp.mjs b/bin/67js-mcp.mjs
index bb48f57c..48f6104a 100644
--- a/bin/67js-mcp.mjs
+++ b/bin/67js-mcp.mjs
@@ -5,11 +5,15 @@ import packageMetadata from '../package.json' with { type: 'json' };
const argumentsValue = process.argv.slice(2);
if (argumentsValue.length === 1 && argumentsValue[0] === '--version') {
console.log(packageMetadata.version);
+} else if (argumentsValue.length === 1 && argumentsValue[0] === '--check-update') {
+ const { runCheckUpdateCli } = await import('../build/mcp/server.mjs');
+ await runCheckUpdateCli({ version: packageMetadata.version });
} else if (argumentsValue.length === 1 && argumentsValue[0] === '--help') {
console.log(`67js-mcp ${packageMetadata.version}
Usage: 67js-mcp [--backend gpu|cpu] [--memory 32..384]
[--browser <Chrome/Chromium executable>] [--assets <absolute GLB directory>]
[--jobs <absolute private output directory>] [--ffmpeg <absolute executable>]
+ 67js-mcp --version | --check-update
Connect an MCP client over stdin/stdout. Chrome starts on the first scene.
Uses installed Chrome by default; supply --browser for another Chromium executable.
diff --git a/changes/907-mcp-update-notice.md b/changes/907-mcp-update-notice.md
new file mode 100644
index 00000000..ba37aecf
--- /dev/null
+++ b/changes/907-mcp-update-notice.md
@@ -0,0 +1 @@
+- The MCP server checks the npm registry once a day in the background and tells the agent when a newer 67js exists, so it can ask the user to update; `67js-mcp --check-update` asks by hand and `SIXTYSEVENJS_NO_UPDATE_CHECK=1`, `NO_UPDATE_NOTIFIER=1` or `CI` turn it off (#907)
diff --git a/changes/907-mcp-update-notice.size.md b/changes/907-mcp-update-notice.size.md
new file mode 100644
index 00000000..03b7053a
--- /dev/null
+++ b/changes/907-mcp-update-notice.size.md
@@ -0,0 +1 @@
+- entry:mcp-server: the update check module and the notice, a few hundred bytes of server code outside the library entries.
diff --git a/docs/mcp.md b/docs/mcp.md
index 3e82687c..b429b672 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -217,6 +217,17 @@ References must resolve after the complete batch. Removing a parent leaves its c
Reparent or remove those children before the parent removal command to avoid rejection.
The [scene contract](agent-scene.md) defines the geometry fields, transforms, materials, and atomic validation rules.
+## Updates
+
+`npx -y -p @codepawlhq/67js 67js-mcp` reuses the copy npx cached on the first run, so a server can stay on an old version without anyone noticing. Each start therefore asks the npm registry once whether a newer version exists:
+
+- **What is sent:** one `GET https://registry.npmjs.org/@codepawlhq/67js/latest`, the same request `npm view` makes. It has no body and no identifier of ours. The registry sees what any HTTP request shows.
+- **When:** in the background, so startup is never slower. The answer is cached in `<user cache folder>/67js/update-check.json` (`$XDG_CACHE_HOME`, else `%LOCALAPPDATA%` on Windows, else `~/.cache`), and the registry is asked at most once a day. A timeout of 2 seconds ends a slow request. Offline or a registry error is silent.
+- **What the agent sees:** when a newer stable version exists, the server `instructions` gain a short notice and the first `scene_capabilities` result carries `updateAvailable` with `current`, `latest`, `releaseNotes`, and the `update` command for each install route (`plugin`, `npx`, `project`). The first start after a new release may show the notice only in `scene_capabilities`, because `instructions` are read once and the answer can arrive after that. The agent tells the user and updates only after a yes.
+- **Turn it off:** set `SIXTYSEVENJS_NO_UPDATE_CHECK=1` or `NO_UPDATE_NOTIFIER=1`, or run with `CI` set. Nothing is requested or written then.
+- **Ask by hand:** `67js-mcp --version` prints the running version. `67js-mcp --check-update` asks the registry now, prints the current and latest versions and exits.
+- **Update:** plugin, `/plugin marketplace update 67js` then `/plugin update 67js@67js`; `npx`, run `npx -y -p @codepawlhq/67js@latest 67js-mcp --version` once; project, `npm install @codepawlhq/67js@latest`. Restart the client afterwards. The library itself makes no network request, and the plugin keeps its pinned start command.
+
## Call log
To see which tools agents use, set `SIXTYSEVENJS_MCP_LOG=<file path>` before starting the server. It appends one JSON line per tool call: `time`, `tool`, `durationMs`, `ok`, `error` (`tool_error` or `thrown`, only on failure) and `resultBytes`. It never writes arguments, scene content or paths. With the variable unset nothing is written.
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index 3abd8131..8d3fc2f3 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -17,6 +17,7 @@ import { MATERIAL_LAYER_SCALAR_RANGES, MATERIAL_LAYER_COLOR_RANGES } from '../sr
import { SUBSURFACE_RANGES } from '../src/subsurface-limits.js';
import { responseFormatField, chosenFormat, conciseReview, conciseJobStatus, conciseJobResult, withoutNotes } from './mcp-response-format.mjs';
import { createCallLogger, CALL_LOG_ENVIRONMENT_VARIABLE } from './mcp-call-log.mjs';
+import { startUpdateCheck, updateNoticeText, describeUpdateCheck } from '../src/mcp-update-check.js';
import { MAX_POINT_LIGHTS, MAX_SPOT_LIGHTS, MAX_AREA_LIGHTS } from '../src/light-limits.js';
describeSchemaInputsWithReceivedValues();
@@ -858,7 +859,9 @@ function jsonResult(value) {
return { content: [{ type: 'text', text: JSON.stringify(value) }], structuredContent: value };
}
-export function createAgentMcpServer(runtime, { version = packageMetadata.version, branches = true, relations = true, callLogPath = process.env[CALL_LOG_ENVIRONMENT_VARIABLE] } = {}) {
+export function createAgentMcpServer(runtime, { version = packageMetadata.version, branches = true, relations = true, callLogPath = process.env[CALL_LOG_ENVIRONMENT_VARIABLE], updateAvailable = () => null } = {}) {
+ const newerVersion = updateAvailable();
+ let updateReported = false;
const logCall = createCallLogger(callLogPath);
// Without branches the schemas carry no branch field and the instructions do not mention variants (a benchmark switch).
const branchField = branches ? { branch: branchName.optional().describe('Fork: store the result as this branch (up to 8), leaving the scene unchanged.') } : {};
@@ -867,7 +870,7 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versio
const restoreCheckpointId = checkpointFields.checkpointId.optional();
const branchInstructions = branches ? ' To try variants, give scene_apply a branch name for each (the scene stays put), compare them in one scene_review with a branch per shot, then keep the best with scene_restore and its branch.' : '';
const server = new McpServer({ name: '67js-scene', version }, {
- instructions: 'Start with scene_capabilities. Create a procedural recipe with scene_create, or select a configured GLB digest from scene_asset_catalog and use scene_create_asset. Pass its sessionId to work on several open scenes; without it the last used scene is used. Inspect stable IDs and save a checkpoint before editing. Apply small batches with the current expectedRevision and check committed, revision and renderSucceeded. A committed edit can have a separate renderError; do not retry it with an old revision.'+branchInstructions+' Pass labels: true to scene_look or scene_review to match part names to the image. Use scene_look to judge the actual image, or scene_review with the current expectedRevision to compare independent camera and motion samples in one grid while preserving the source pose. When jobs are configured, scene_render_submit captures an immutable snapshot. Poll scene_render_status, cancel when needed, and retrieve verified local artifact metadata with scene_render_result after completion. Preview rendering and edits pause during a job; source revision and checkpoints survive. Release outputs with scene_render_release. Export the final recipe and dispose the scene when finished. No arbitrary JavaScript, remote URLs or caller-selected output paths are exposed.',
+ instructions: 'Start with scene_capabilities. Create a procedural recipe with scene_create, or select a configured GLB digest from scene_asset_catalog and use scene_create_asset. Pass its sessionId to work on several open scenes; without it the last used scene is used. Inspect stable IDs and save a checkpoint before editing. Apply small batches with the current expectedRevision and check committed, revision and renderSucceeded. A committed edit can have a separate renderError; do not retry it with an old revision.'+branchInstructions+' Pass labels: true to scene_look or scene_review to match part names to the image. Use scene_look to judge the actual image, or scene_review with the current expectedRevision to compare independent camera and motion samples in one grid while preserving the source pose. When jobs are configured, scene_render_submit captures an immutable snapshot. Poll scene_render_status, cancel when needed, and retrieve verified local artifact metadata with scene_render_result after completion. Preview rendering and edits pause during a job; source revision and checkpoints survive. Release outputs with scene_render_release. Export the final recipe and dispose the scene when finished. No arbitrary JavaScript, remote URLs or caller-selected output paths are exposed.'+(newerVersion ? updateNoticeText(newerVersion) : ''),
});
let closePromise;
server.server.onclose = () => {
@@ -903,7 +906,11 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versio
}
register('scene_capabilities', 'Index of supported recipe features and runtime budgets; pass topic for the detail of one. Read it before authoring. Does not launch a browser.', z.strictObject({ topic: z.string().min(1).max(64).optional().describe('A name from the index, or name.branch such as meshEdit.bevel. Leave out for the index.'), response_format: responseFormatField }), readOnly, async ({ topic, response_format }) => {
const answer = answerCapabilities(relations ? await runtime.capabilities() : withoutRelationsAdvice(await runtime.capabilities()), topic, outlineSources);
- return jsonResult(chosenFormat('scene_capabilities', response_format) === 'concise' && answer.fields !== undefined ? { ...answer, fields: withoutNotes(answer.fields) } : answer);
+ const shown = chosenFormat('scene_capabilities', response_format) === 'concise' && answer.fields !== undefined ? { ...answer, fields: withoutNotes(answer.fields) } : answer;
+ // Once per server: the first answer carries the update offer, later ones stay unchanged.
+ const pendingUpdate = updateReported ? null : updateAvailable();
+ updateReported = updateReported || pendingUpdate !== null;
+ return jsonResult(pendingUpdate === null ? shown : { ...shown, updateAvailable: pendingUpdate });
});
register('scene_create', 'Create a render scene from a JSON recipe; the result has its sessionId. Several scenes stay open; past the cap the least recently used one is closed.', z.strictObject({ recipe: relations ? recipe : recipeWithoutRelations }), { ...edit, destructiveHint: false }, async argumentsValue => jsonResult(await runtime.create(argumentsValue)));
register('scene_asset_catalog', 'List content-bound GLB and PNG, JPEG or WebP image IDs from the configured local asset directory. No arbitrary paths or downloads.', z.strictObject({}), readOnly, async () => jsonResult(await runtime.assetCatalog()));
@@ -958,6 +965,10 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versio
return server;
}
+export async function runCheckUpdateCli({ version = packageMetadata.version } = {}) {
+ console.log(await describeUpdateCheck({ currentVersion: version }));
+}
+
export async function runMcpCli({ argumentsValue = process.argv.slice(2),
previewUrl = new URL(/* @vite-ignore */ '../build/mcp/preview.js', import.meta.url), version = packageMetadata.version } = {}) {
const options = { backend: 'gpu', memory: 192 };
@@ -973,8 +984,10 @@ export async function runMcpCli({ argumentsValue = process.argv.slice(2),
throw new Error(`Backend must be cpu or gpu, and memory must be an integer from 32 to ${MAXIMUM_MEMORY_MIB} MiB.`);
}
setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+ // Not awaited: the check fills in while the client connects and never delays or fails the start.
+ const updateCheck = startUpdateCheck({ currentVersion: version });
const { createAgentRuntime } = await import('./agent-runtime.mjs');
- const handle = serveStdio(() => createAgentMcpServer(createAgentRuntime({ ...options, previewUrl }), { version, branches: options.branches !== 'off', relations: options.relations !== 'off' }), {
+ const handle = serveStdio(() => createAgentMcpServer(createAgentRuntime({ ...options, previewUrl }), { version, branches: options.branches !== 'off', relations: options.relations !== 'off', updateAvailable: updateCheck.current }), {
transport: new StdioServerTransport(process.stdin, process.stdout, { maxBufferSize: 2 * 1024 * 1024 }),
onerror: error => console.error(`67js MCP error: ${error.message}`),
});
diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index 522979af..d8a10187 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -12,6 +12,8 @@ Start the server with `npx --package @codepawlhq/67js 67js-mcp --backend gpu --a
## Loop
+When the instructions or the first `scene_capabilities` result carry `updateAvailable`, tell the user a newer 67js exists and ask whether to update; run the command for their install route only after a yes.
+
1. `scene_capabilities`: with no arguments it returns a short index of features, limits and topic names. Pass
`topic` for the field list of one feature (`environment`, `materialFields`, `geometries`, `meshEdit.bevel`,
`motion`) or `examples.scene_apply` for a complete call of a hard tool. Tool schemas list only common fields, so read the topic before a feature you have not used.
diff --git a/skills/render-67js-media/SKILL.md b/skills/render-67js-media/SKILL.md
index 6a3f058f..50a56116 100644
--- a/skills/render-67js-media/SKILL.md
+++ b/skills/render-67js-media/SKILL.md
@@ -35,6 +35,7 @@ submit call fails: tell the user which launch option is missing.
## Rules
+- When `scene_capabilities` returns `updateAvailable`, tell the user and ask whether to update; run the command only after a yes.
- Smallest output that meets the need: a still before a video, a 2 second slice before the full film.
Every film round starts as a small, low-quality preview with sound; full quality only after sign-off.
- Time is deterministic. A frame depends on its time only, so a seek gives the same pixels as the frame in a video.
diff --git a/src/mcp-update-check.js b/src/mcp-update-check.js
new file mode 100644
index 00000000..aa2b2bf3
--- /dev/null
+++ b/src/mcp-update-check.js
@@ -0,0 +1,145 @@
+// Tells the MCP server whether a newer @codepawlhq/67js exists on npm. The one request goes to a fixed URL, runs in the
+// background, is cached for a day and never throws: offline, a slow registry or a bad answer leave the server as it was.
+import { readFileSync } from 'node:fs';
+import { mkdir, writeFile } from 'node:fs/promises';
+import { homedir } from 'node:os';
+import { dirname, join } from 'node:path';
+
+export const UPDATE_CHECK_URL = 'https://registry.npmjs.org/@codepawlhq/67js/latest';
+export const UPDATE_CHECK_TIMEOUT_MS = 2000;
+export const UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
+const RELEASE_NOTES_BASE = 'https://github.com/codepawl/67.js/releases/tag/v';
+const STABLE_VERSION = /^\d{1,9}\.\d{1,9}\.\d{1,9}$/;
+
+// Any one of these turns the check off. CI counts as set when it holds any text other than 0 or false.
+export function updateCheckDisabled(env = process.env) {
+ const flagged = name => env[name] !== undefined && env[name] !== '' && env[name] !== '0';
+ return flagged('SIXTYSEVENJS_NO_UPDATE_CHECK') || flagged('NO_UPDATE_NOTIFIER') || (flagged('CI') && env.CI !== 'false');
+}
+
+function versionParts(version) {
+ return version.split('.').map(Number);
+}
+
+// True when `latest` is a newer stable x.y.z than `current`. A pre-release or odd string on either side is never newer.
+export function isNewerVersion(latest, current) {
+ const currentCore = String(current).split('-')[0];
+ if (!STABLE_VERSION.test(latest) || !STABLE_VERSION.test(currentCore)) {
+ return false;
+ }
+ const latestParts = versionParts(latest);
+ const currentParts = versionParts(currentCore);
+ for (let index = 0; index < 3; index += 1) {
+ if (latestParts[index] !== currentParts[index]) {
+ return latestParts[index] > currentParts[index];
+ }
+ }
+ return String(current).includes('-');
+}
+
+export function updateCachePath(env = process.env, platform = process.platform) {
+ const base = env.XDG_CACHE_HOME
+ || (platform === 'win32' && env.LOCALAPPDATA ? env.LOCALAPPDATA : join(homedir(), '.cache'));
+ return join(base, '67js', 'update-check.json');
+}
+
+export function buildUpdateAvailable(current, latest) {
+ return {
+ current,
+ latest,
+ releaseNotes: `${RELEASE_NOTES_BASE}${latest}`,
+ update: {
+ plugin: 'Run /plugin marketplace update 67js, then /plugin update 67js@67js, then restart the client.',
+ npx: 'Run npx -y -p @codepawlhq/67js@latest 67js-mcp --version once, then restart the client.',
+ project: 'Run npm install @codepawlhq/67js@latest (or 67js@npm:@codepawlhq/67js@latest) in the project, then restart the client.',
+ },
+ ask: 'Tell the user a newer 67js exists and ask whether to update. Run an update command only after they say yes.',
+ };
+}
+
+export function updateNoticeText(updateAvailable) {
+ return ` A newer 67js is out (running ${updateAvailable.current}, latest ${updateAvailable.latest}; notes ${updateAvailable.releaseNotes}). Tell the user and ask whether to update; do not update on your own. Commands per install route are in the updateAvailable field of the first scene_capabilities result.`;
+}
+
+function readCache(cachePath) {
+ try {
+ const cached = JSON.parse(readFileSync(cachePath, 'utf8'));
+ if (typeof cached.checkedAt === 'number' && STABLE_VERSION.test(cached.latest)) {
+ return cached;
+ }
+ } catch {
+ // A missing or damaged cache is the same as no cache.
+ }
+ return null;
+}
+
+async function fetchLatestVersion(fetchImpl, timeoutMs) {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
+ try {
+ const response = await fetchImpl(UPDATE_CHECK_URL, { signal: controller.signal, headers: { accept: 'application/json' } });
+ if (!response.ok) {
+ return null;
+ }
+ const body = await response.json();
+ return typeof body.version === 'string' && STABLE_VERSION.test(body.version) ? body.version : null;
+ } catch {
+ return null;
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+// Reads the cache at once and refreshes it in the background when it is over a day old. `current()` gives the newest
+// answer so far (null when up to date or unknown); `settled` resolves when the refresh ends and never rejects.
+export function startUpdateCheck({
+ currentVersion,
+ env = process.env,
+ fetchImpl = globalThis.fetch,
+ now = Date.now,
+ cachePath = updateCachePath(env),
+ timeoutMs = UPDATE_CHECK_TIMEOUT_MS,
+} = {}) {
+ let latest = null;
+ let settled = Promise.resolve();
+ if (!updateCheckDisabled(env) && typeof fetchImpl === 'function') {
+ const cached = readCache(cachePath);
+ latest = cached?.latest ?? null;
+ if (cached === null || now() - cached.checkedAt >= UPDATE_CHECK_INTERVAL_MS || cached.checkedAt > now()) {
+ settled = refreshCache({ fetchImpl, now, cachePath, timeoutMs }).then(found => {
+ latest = found ?? latest;
+ }).catch(() => {});
+ }
+ }
+ return {
+ current: () => (latest !== null && isNewerVersion(latest, currentVersion) ? buildUpdateAvailable(currentVersion, latest) : null),
+ settled,
+ };
+}
+
+async function refreshCache({ fetchImpl, now, cachePath, timeoutMs }) {
+ const found = await fetchLatestVersion(fetchImpl, timeoutMs);
+ if (found === null) {
+ return null;
+ }
+ try {
+ await mkdir(dirname(cachePath), { recursive: true });
+ await writeFile(cachePath, JSON.stringify({ checkedAt: now(), latest: found }));
+ } catch {
+ // An unwritable cache only means the next start asks again.
+ }
+ return found;
+}
+
+// `67js-mcp --check-update`: one explicit request, ignores the cache and the off switches, prints and returns.
+export async function describeUpdateCheck({ currentVersion, fetchImpl = globalThis.fetch, timeoutMs = UPDATE_CHECK_TIMEOUT_MS }) {
+ const found = await fetchLatestVersion(fetchImpl, timeoutMs);
+ const lines = [`current ${currentVersion}`];
+ if (found === null) {
+ lines.push('latest unknown (the npm registry did not answer)');
+ } else {
+ lines.push(`latest ${found}`);
+ lines.push(isNewerVersion(found, currentVersion) ? `update available: ${RELEASE_NOTES_BASE}${found}` : 'up to date');
+ }
+ return lines.join('\n');
+}
diff --git a/tests/mcp-update-check.test.js b/tests/mcp-update-check.test.js
new file mode 100644
index 00000000..54b8d5a0
--- /dev/null
+++ b/tests/mcp-update-check.test.js
@@ -0,0 +1,192 @@
+import './support/load-agent-scene-modules.mjs';
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { Client } from '@modelcontextprotocol/client';
+import { InMemoryTransport } from '@modelcontextprotocol/server';
+import { createAgentMcpServer } from '../scripts/mcp-server.mjs';
+import {
+ UPDATE_CHECK_URL, UPDATE_CHECK_INTERVAL_MS, isNewerVersion, updateCheckDisabled, startUpdateCheck, describeUpdateCheck, buildUpdateAvailable,
+} from '../src/mcp-update-check.js';
+
+const NOW = 1_800_000_000_000;
+
+function registryAnswer(version) {
+ return async () => ({ ok: true, json: async () => ({ version }) });
+}
+
+function countingFetch(inner) {
+ const calls = [];
+ const fetchImpl = async (url, options) => {
+ calls.push(url);
+ return inner(url, options);
+ };
+ fetchImpl.calls = calls;
+ return fetchImpl;
+}
+
+async function withCacheFolder(run) {
+ const folder = await mkdtemp(join(tmpdir(), '67js-update-'));
+ try {
+ await run(join(folder, 'nested', 'update-check.json'));
+ } finally {
+ await rm(folder, { recursive: true, force: true });
+ }
+}
+
+test('versions compare numerically and ignore anything that is not a stable x.y.z', () => {
+ assert.equal(isNewerVersion('0.20.0', '0.19.0'), true);
+ assert.equal(isNewerVersion('0.10.0', '0.9.0'), true);
+ assert.equal(isNewerVersion('0.19.0', '0.19.0'), false);
+ assert.equal(isNewerVersion('0.18.9', '0.19.0'), false);
+ assert.equal(isNewerVersion('0.20.0-beta.1', '0.19.0'), false);
+ assert.equal(isNewerVersion('latest', '0.19.0'), false);
+ assert.equal(isNewerVersion('0.19.0', '0.19.0-beta.1'), true);
+});
+
+test('each off switch disables the check', () => {
+ assert.equal(updateCheckDisabled({}), false);
+ assert.equal(updateCheckDisabled({ SIXTYSEVENJS_NO_UPDATE_CHECK: '1' }), true);
+ assert.equal(updateCheckDisabled({ NO_UPDATE_NOTIFIER: '1' }), true);
+ assert.equal(updateCheckDisabled({ CI: 'true' }), true);
+ assert.equal(updateCheckDisabled({ CI: '1' }), true);
+ assert.equal(updateCheckDisabled({ CI: 'false' }), false);
+ assert.equal(updateCheckDisabled({ SIXTYSEVENJS_NO_UPDATE_CHECK: '0' }), false);
+});
+
+test('a newer version is found, written to the cache and reported', async () => {
+ await withCacheFolder(async cachePath => {
+ const fetchImpl = countingFetch(registryAnswer('0.20.0'));
+ const check = startUpdateCheck({ currentVersion: '0.19.0', env: {}, fetchImpl, now: () => NOW, cachePath });
+ assert.equal(check.current(), null);
+ await check.settled;
+ const found = check.current();
+ assert.equal(found.current, '0.19.0');
+ assert.equal(found.latest, '0.20.0');
+ assert.match(found.releaseNotes, /\/releases\/tag\/v0\.20\.0$/);
+ assert.deepEqual(Object.keys(found.update), ['plugin', 'npx', 'project']);
+ assert.deepEqual(fetchImpl.calls, [UPDATE_CHECK_URL]);
+ assert.deepEqual(JSON.parse(await readFile(cachePath, 'utf8')), { checkedAt: NOW, latest: '0.20.0' });
+ });
+});
+
+test('the same version reports nothing', async () => {
+ await withCacheFolder(async cachePath => {
+ const check = startUpdateCheck({ currentVersion: '0.19.0', env: {}, fetchImpl: registryAnswer('0.19.0'), now: () => NOW, cachePath });
+ await check.settled;
+ assert.equal(check.current(), null);
+ });
+});
+
+test('registry errors, bad bodies and thrown fetches stay silent', async () => {
+ const failures = [
+ async () => ({ ok: false, json: async () => ({}) }),
+ async () => ({ ok: true, json: async () => ({ version: 'not-a-version' }) }),
+ async () => ({ ok: true, json: async () => { throw new SyntaxError('bad json'); } }),
+ async () => { throw new Error('offline'); },
+ ];
+ for (const failing of failures) {
+ await withCacheFolder(async cachePath => {
+ const check = startUpdateCheck({ currentVersion: '0.19.0', env: {}, fetchImpl: failing, now: () => NOW, cachePath });
+ await check.settled;
+ assert.equal(check.current(), null);
+ });
+ }
+});
+
+test('a registry that never answers is cut off at the timeout', async () => {
+ await withCacheFolder(async cachePath => {
+ const hanging = (url, { signal }) => new Promise((resolve, reject) => {
+ signal.addEventListener('abort', () => reject(new Error('aborted')));
+ });
+ const started = Date.now();
+ const check = startUpdateCheck({ currentVersion: '0.19.0', env: {}, fetchImpl: hanging, now: () => NOW, cachePath, timeoutMs: 30 });
+ await check.settled;
+ assert.equal(check.current(), null);
+ assert.ok(Date.now() - started < 1500);
+ });
+});
+
+test('a cache under a day old answers without a request, an older one refreshes', async () => {
+ await withCacheFolder(async cachePath => {
+ const fetchImpl = countingFetch(registryAnswer('0.21.0'));
+ await startUpdateCheck({ currentVersion: '0.19.0', env: {}, fetchImpl, now: () => NOW, cachePath }).settled;
+ assert.equal(fetchImpl.calls.length, 1);
+ const fresh = startUpdateCheck({ currentVersion: '0.19.0', env: {}, fetchImpl, now: () => NOW + UPDATE_CHECK_INTERVAL_MS - 1, cachePath });
+ assert.equal(fresh.current().latest, '0.21.0', 'the cached answer is available before any request');
+ await fresh.settled;
+ assert.equal(fetchImpl.calls.length, 1);
+ const stale = startUpdateCheck({ currentVersion: '0.19.0', env: {}, fetchImpl, now: () => NOW + UPDATE_CHECK_INTERVAL_MS, cachePath });
+ await stale.settled;
+ assert.equal(fetchImpl.calls.length, 2);
+ });
+});
+
+test('a damaged cache is ignored', async () => {
+ await withCacheFolder(async cachePath => {
+ await mkdir(dirname(cachePath), { recursive: true });
+ await writeFile(cachePath, '{not json');
+ const check = startUpdateCheck({ currentVersion: '0.19.0', env: {}, fetchImpl: registryAnswer('0.20.0'), now: () => NOW, cachePath });
+ await check.settled;
+ assert.equal(check.current().latest, '0.20.0');
+ });
+});
+
+test('every off switch makes no request and no cache file', async () => {
+ for (const env of [{ SIXTYSEVENJS_NO_UPDATE_CHECK: '1' }, { NO_UPDATE_NOTIFIER: '1' }, { CI: 'true' }]) {
+ await withCacheFolder(async cachePath => {
+ const fetchImpl = countingFetch(registryAnswer('0.20.0'));
+ const check = startUpdateCheck({ currentVersion: '0.19.0', env, fetchImpl, now: () => NOW, cachePath });
+ await check.settled;
+ assert.equal(check.current(), null);
+ assert.equal(fetchImpl.calls.length, 0);
+ await assert.rejects(readFile(cachePath, 'utf8'));
+ });
+ }
+});
+
+test('--check-update text names current and latest', async () => {
+ assert.equal(await describeUpdateCheck({ currentVersion: '0.19.0', fetchImpl: registryAnswer('0.20.0') }),
+ 'current 0.19.0\nlatest 0.20.0\nupdate available: https://github.com/codepawl/67.js/releases/tag/v0.20.0');
+ assert.match(await describeUpdateCheck({ currentVersion: '0.19.0', fetchImpl: registryAnswer('0.19.0') }), /up to date$/);
+ assert.match(await describeUpdateCheck({ currentVersion: '0.19.0', fetchImpl: async () => { throw new Error('offline'); } }), /latest unknown/);
+});
+
+const runtime = {
+ activeSessionId: () => null,
+ async close() {},
+ async capabilities() { return { scene: {}, phase: 'idle', availableIn: 'test' }; },
+};
+
+async function connect(context, options) {
+ const server = createAgentMcpServer(runtime, options);
+ const client = new Client({ name: 'update-check-test', version: '1' });
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+ await server.connect(serverTransport);
+ await client.connect(clientTransport);
+ context.after(async () => {
+ await client.close();
+ await server.close();
+ });
+ return client;
+}
+
+test('an older running version puts the notice in instructions and the first scene_capabilities result only', async context => {
+ const client = await connect(context, { updateAvailable: () => buildUpdateAvailable('0.19.0', '0.20.0') });
+ assert.match(client.getInstructions(), /A newer 67js is out \(running 0\.19\.0, latest 0\.20\.0/);
+ const first = (await client.callTool({ name: 'scene_capabilities', arguments: {} })).structuredContent;
+ assert.equal(first.updateAvailable.latest, '0.20.0');
+ assert.equal(first.updateAvailable.current, '0.19.0');
+ assert.ok(first.updateAvailable.update.plugin && first.updateAvailable.update.npx && first.updateAvailable.update.project);
+ const second = (await client.callTool({ name: 'scene_capabilities', arguments: {} })).structuredContent;
+ assert.equal('updateAvailable' in second, false);
+});
+
+test('without a newer version the instructions and results carry no notice', async context => {
+ const client = await connect(context, {});
+ assert.doesNotMatch(client.getInstructions(), /newer 67js/);
+ const result = (await client.callTool({ name: 'scene_capabilities', arguments: {} })).structuredContent;
+ assert.equal('updateAvailable' in result, false);
+});