@aiwg/cli 2026.10.19 → 2026.11.0

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 (67) hide show
  1. package/README.md +1 -0
  2. package/dist/src/cli/handlers/bundle-declaration.js +55 -0
  3. package/dist/src/cli/handlers/bundle-deployment-mode.js +71 -0
  4. package/dist/src/cli/handlers/bundle-hash-prune.js +37 -0
  5. package/dist/src/cli/handlers/bundle-reconciliation.js +140 -0
  6. package/dist/src/cli/handlers/refresh-bundles.js +35 -0
  7. package/dist/src/cli/handlers/refresh-rule-inventory.js +10 -0
  8. package/dist/src/cli/handlers/refresh.js +15 -52
  9. package/dist/src/cli/handlers/remove-bundled.js +7 -4
  10. package/dist/src/cli/handlers/remove-flue-modules.js +19 -0
  11. package/dist/src/cli/handlers/remove-historical-bundle.js +18 -0
  12. package/dist/src/cli/handlers/remove.js +8 -0
  13. package/dist/src/cli/handlers/script-runner.js +10 -0
  14. package/dist/src/cli/handlers/subcommands-list-format.js +4 -4
  15. package/dist/src/cli/handlers/update.js +18 -8
  16. package/dist/src/cli/handlers/use-additive-bundles.js +87 -0
  17. package/dist/src/cli/handlers/use-bundle-counts.js +5 -1
  18. package/dist/src/cli/handlers/use-owned-counts.js +75 -0
  19. package/dist/src/cli/handlers/use.js +44 -99
  20. package/dist/src/cli/services/deployment-verification.js +2 -1
  21. package/dist/src/config/aiwg-config.js +10 -5
  22. package/dist/src/config/framework-aliases.js +14 -0
  23. package/dist/src/config/installed-selection.js +9 -1
  24. package/dist/src/config/installed-validation.js +35 -0
  25. package/dist/src/extensions/project-local-doctor.js +1 -1
  26. package/dist/src/extensions/project-local-remove.js +3 -3
  27. package/dist/src/mcp/cli.mjs +12 -7
  28. package/dist/src/mcp/helpers.mjs +5 -1
  29. package/dist/src/mcp/http-options.mjs +101 -0
  30. package/dist/src/mcp/http-tools.mjs +51 -0
  31. package/dist/src/mcp/http-transport.mjs +201 -0
  32. package/dist/src/mcp/server.mjs +9 -7
  33. package/dist/src/mcp/tool-context.mjs +25 -0
  34. package/dist/src/mcp/tools/orchestration.mjs +2 -1
  35. package/dist/src/providers/deployment-ownership.mjs +15 -1
  36. package/dist/src/providers/deployment-preservation.d.mts +5 -0
  37. package/dist/src/providers/deployment-preservation.mjs +110 -0
  38. package/dist/src/providers/deployment-removal.js +4 -2
  39. package/dist/src/providers/flue-package-mode.js +19 -0
  40. package/dist/src/providers/skill-ownership.mjs +1 -0
  41. package/dist/src/research/reference-match.js +4 -0
  42. package/package.json +2 -1
  43. package/tools/agents/deploy-agents.mjs +6 -1
  44. package/tools/agents/deploy-options.mjs +2 -0
  45. package/tools/agents/providers/base-inventory.mjs +6 -1
  46. package/tools/agents/providers/base-kernel-skills.mjs +9 -5
  47. package/tools/agents/providers/base-migrations.mjs +1 -0
  48. package/tools/agents/providers/base-skill-copy.mjs +9 -1
  49. package/tools/agents/providers/claude.mjs +2 -1
  50. package/tools/agents/providers/codex.mjs +5 -1
  51. package/tools/agents/providers/flue-bundles.mjs +42 -0
  52. package/tools/agents/providers/flue-cloudflare.mjs +20 -0
  53. package/tools/agents/providers/flue-project.mjs +45 -6
  54. package/tools/agents/providers/flue-skill-copy.mjs +25 -0
  55. package/tools/agents/providers/flue-skills.mjs +45 -0
  56. package/tools/agents/providers/flue-specialists.mjs +36 -18
  57. package/tools/agents/providers/flue-validation.mjs +14 -0
  58. package/tools/agents/providers/flue.mjs +12 -8
  59. package/tools/agents/providers/hermes-skill-lifecycle.mjs +1 -0
  60. package/tools/agents/providers/rule-delivery-surface.mjs +15 -1
  61. package/tools/agents/providers/rule-deployment-commit.mjs +14 -0
  62. package/tools/agents/providers/rule-deployment-prepare.mjs +4 -0
  63. package/tools/agents/providers/skill-copy-prune.mjs +49 -0
  64. package/tools/agents/providers/stale-artifact-prune.mjs +1 -0
  65. package/tools/skills/codex-skill-metadata.mjs +22 -0
  66. package/tools/skills/deploy-skills-codex.mjs +8 -7
  67. package/vscode-extension/schemas/aiwg.config.v1.json +44 -19
@@ -1,7 +1,7 @@
1
1
  // Keep automatic redeployment from changing the explicitly installed selection.
2
2
  import { AsyncLocalStorage } from 'node:async_hooks';
3
3
  import { resolve } from 'node:path';
4
- import { REGISTRY_ID_TO_USE_NAME } from './framework-aliases.js';
4
+ import { REGISTRY_ID_TO_USE_NAME, frameworkRegistryId } from './framework-aliases.js';
5
5
  const selection = new AsyncLocalStorage();
6
6
  export function withInstalledSelection(project, installed, deploy) {
7
7
  return selection.run({ project: resolve(project), installed: structuredClone(installed) }, deploy);
@@ -19,4 +19,12 @@ export function preserveInstalledSelection(project, config) {
19
19
  ]));
20
20
  return guarded;
21
21
  }
22
+ /** Automatic framework passes cannot reinstall a local bundle the operator undeclared. */
23
+ export function permitsBundleDeployment(project, id, provider) {
24
+ const current = selection.getStore();
25
+ if (!current || current.project !== resolve(project) || current.installed === undefined)
26
+ return true;
27
+ const entry = Object.entries(current.installed).find(([key]) => frameworkRegistryId(key) === frameworkRegistryId(id))?.[1];
28
+ return Boolean(entry?.deployedTo?.[provider]);
29
+ }
22
30
  //# sourceMappingURL=installed-selection.js.map
@@ -0,0 +1,35 @@
1
+ // Validate new declarations and deployment writes without rejecting historical reads.
2
+ const object = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
3
+ const kinds = ['agents', 'commands', 'skills', 'rules'];
4
+ export function validateInstalled(installed) {
5
+ if (installed === undefined)
6
+ return;
7
+ if (!object(installed))
8
+ throw new Error('installed must be an object');
9
+ for (const [id, entry] of Object.entries(installed)) {
10
+ if (!object(entry) || !object(entry.deployedTo))
11
+ throw new Error(`installed.${id}.deployedTo must be an object`);
12
+ let deployed = false;
13
+ for (const [provider, counts] of Object.entries(entry.deployedTo)) {
14
+ if (!object(counts))
15
+ throw new Error(`installed.${id}.deployedTo.${provider} must be an object`);
16
+ for (const flag of ['copy', 'skipUtils', 'kernelOnly']) {
17
+ if (counts[flag] !== undefined && typeof counts[flag] !== 'boolean')
18
+ throw new Error(`installed.${id}.deployedTo.${provider}.${flag} must be boolean`);
19
+ }
20
+ if (counts.package !== undefined && (typeof counts.package !== 'boolean' || provider !== 'flue'))
21
+ throw new Error(`installed.${id}.deployedTo.${provider}.package requires Flue and a boolean`);
22
+ if (!Object.keys(counts).some(key => !['copy', 'package', 'skipUtils', 'kernelOnly'].includes(key)))
23
+ continue;
24
+ if (kinds.some(kind => !Number.isSafeInteger(counts[kind]) || counts[kind] < 0)) {
25
+ throw new Error(`installed.${id}.deployedTo.${provider} requires all four nonnegative artifact counts or {}`);
26
+ }
27
+ deployed = true;
28
+ }
29
+ if (deployed || ['version', 'source', 'installedAt'].some(key => entry[key] !== undefined)) {
30
+ if (['version', 'source', 'installedAt'].some(key => typeof entry[key] !== 'string' || !entry[key]))
31
+ throw new Error(`installed.${id} requires version, source and installedAt after deployment`);
32
+ }
33
+ }
34
+ }
35
+ //# sourceMappingURL=installed-validation.js.map
@@ -332,7 +332,7 @@ export async function buildProjectLocalDoctorSection(opts) {
332
332
  const c = entry.deployedTo[p];
333
333
  if (!c)
334
334
  return '-'.padEnd(8);
335
- const total = c.agents + c.commands + c.skills + c.rules;
335
+ const total = (c.agents ?? 0) + (c.commands ?? 0) + (c.skills ?? 0) + (c.rules ?? 0);
336
336
  return `✓ ${total}`.padEnd(8);
337
337
  }).join('');
338
338
  lines.push(` ${name.padEnd(20)}${cells}`);
@@ -13,7 +13,7 @@
13
13
  * @implements #1037
14
14
  */
15
15
  import { lstat, readdir, readFile, stat, unlink, rmdir } from 'fs/promises';
16
- import { resolve, join, relative, dirname, isAbsolute } from 'path';
16
+ import { resolve, join, relative, dirname, isAbsolute, sep } from 'path';
17
17
  import { deployedSkillRoots } from '../providers/deployed-skill-roots.js';
18
18
  import { releaseSkillOwnership } from '../providers/skill-ownership.mjs';
19
19
  import { appendProjectLocalActivity } from './project-local-activity.js';
@@ -263,7 +263,7 @@ export async function removeProjectLocalBundle(config, projectDir, bundleId, opt
263
263
  // retired skills no longer present in the source inventory.
264
264
  const receiptSkills = new Set();
265
265
  const sourceRoot = installedEntry.localPath ? resolve(projectDir, installedEntry.localPath) : undefined;
266
- for (const root of deployedSkillRoots(projectDir, provider)) {
266
+ for (const root of deployedSkillRoots(projectDir, provider).filter(root => !opts.preserveRoots?.includes(root))) {
267
267
  for (const name of await readdir(root).catch(() => [])) {
268
268
  const skillDir = join(root, name);
269
269
  try {
@@ -314,7 +314,7 @@ export async function removeProjectLocalBundle(config, projectDir, bundleId, opt
314
314
  }
315
315
  continue;
316
316
  }
317
- const candidates = candidateDeployedPaths(projectDir, provider, sourceRel);
317
+ const candidates = candidateDeployedPaths(projectDir, provider, sourceRel).filter(file => !opts.preserveRoots?.some(root => file === root || file.startsWith(`${root}${sep}`)));
318
318
  let resolvedAbs = null;
319
319
  let detectedCase = 'missing';
320
320
  for (const c of candidates) {
@@ -201,6 +201,14 @@ Inject Options:
201
201
  Serve Options:
202
202
  --transport <type> Transport type: stdio (default), http
203
203
  --port <number> Port for HTTP transport (default: 3100)
204
+ --project <dir> Required HTTP project; pinned at startup
205
+ --token-env <NAME> HTTP bearer token environment variable (choose one source)
206
+ --token-file <path> HTTP bearer token file; re-read per request for rotation
207
+ --host <address> HTTP bind address (default: 127.0.0.1)
208
+ --allow-remote-bind Required for non-loopback binds; emits a warning
209
+ --allowed-host <h> Additional HTTP Host/Origin hostname (repeatable)
210
+ --max-sessions <n> HTTP session cap (default: 8; idle timeout: 300 seconds)
211
+ --tools <csv> Narrow HTTP tools: discover, *-show, artifact-write
204
212
  --toolsets <csv> Opt-in toolsets: flows, missions, memory, kb, research,
205
213
  activity-log, index, ralph, mc, ops, sandbox, decision, workers
206
214
  all excludes workers; enable explicitly with --toolsets all,workers
@@ -1619,15 +1627,12 @@ export async function main(args = process.argv.slice(2)) {
1619
1627
  switch (command) {
1620
1628
  case 'serve': {
1621
1629
  // Parse options
1622
- const transportIdx = args.indexOf('--transport');
1623
- const transport = transportIdx !== -1 ? args[transportIdx + 1] : 'stdio';
1630
+ const transport = requireFlagValue(args, { rejectEmpty: true }, '--transport') ?? 'stdio';
1624
1631
 
1625
1632
  if (transport === 'http') {
1626
- const portIdx = args.indexOf('--port');
1627
- const port = portIdx !== -1 ? parseInt(args[portIdx + 1], 10) : 3100;
1628
- console.error(`HTTP transport not yet implemented. Use stdio for now.`);
1629
- console.error(`Would start on port ${port}`);
1630
- process.exit(1);
1633
+ const { serveHttp } = await import('./http-transport.mjs');
1634
+ await serveHttp(subArgs);
1635
+ break;
1631
1636
  }
1632
1637
 
1633
1638
  // --toolsets flag overrides AIWG_MCP_TOOLSETS env (#1332 / S18)
@@ -5,6 +5,7 @@
5
5
  * @issues #1311 (scope split), #1312 (command-run), #1313 (discover + pairs)
6
6
  */
7
7
 
8
+ import { cliExecutionOptions, bindCliCancellation } from './tool-context.mjs';
8
9
  import { signalChild } from '../process/signal-child.mjs';
9
10
  import { spawn } from 'node:child_process';
10
11
  import { StringDecoder } from 'node:string_decoder';
@@ -266,7 +267,9 @@ export function isGlobalAllowed(toolName) {
266
267
  * @param {{ cwd?: string, env?: object, timeoutMs?: number, input?: string }} [options]
267
268
  * @returns {Promise<{ stdout: string, stderr: string, code: number }>}
268
269
  */
269
- export function runAiwgCli(args, { cwd, env, timeoutMs = 120_000, input } = {}) {
270
+ export function runAiwgCli(args, options = {}) {
271
+ const { cwd, env, timeoutMs = 120_000, input, signal } = cliExecutionOptions(options);
272
+ signal?.throwIfAborted();
270
273
  return new Promise((resolve, reject) => {
271
274
  const proc = spawn('aiwg', args, {
272
275
  shell: false,
@@ -298,6 +301,7 @@ export function runAiwgCli(args, { cwd, env, timeoutMs = 120_000, input } = {})
298
301
  rejectAndTerminate(new Error(`aiwg ${args[0] || ''} timed out after ${timeoutMs}ms`));
299
302
  }, timeoutMs);
300
303
 
304
+ bindCliCancellation(proc, signal, rejectAndTerminate);
301
305
  proc.stdout.on('data', (chunk) => { stdout += stdoutDecoder.write(chunk); });
302
306
  proc.stderr.on('data', (chunk) => { stderr += stderrDecoder.write(chunk); });
303
307
 
@@ -0,0 +1,101 @@
1
+ // Parse remote MCP configuration and enforce credential and DNS-rebinding policy.
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { createHash, timingSafeEqual } from 'node:crypto';
5
+
6
+ export function parseHttpOptions(args) {
7
+ const values = new Map();
8
+ const booleans = new Set(['allow-remote-bind']);
9
+ const known = new Set(['transport', 'project', 'token-env', 'token-file', 'host', 'allowed-host', 'port', 'max-sessions', 'tools', 'toolsets']);
10
+ for (let i = 0; i < args.length; i++) {
11
+ const match = /^--([a-z-]+)(?:=(.*))?$/.exec(args[i]);
12
+ if (!match) throw new Error('Expected an HTTP serve option');
13
+ const [, name, inline] = match;
14
+ if (booleans.has(name)) {
15
+ if (inline !== undefined) throw new Error(`--${name} takes no value`);
16
+ values.set(name, [true]);
17
+ continue;
18
+ }
19
+ if (!known.has(name)) throw new Error(`Unknown HTTP serve option --${name}`);
20
+ const value = inline ?? args[++i];
21
+ if (!value || value.startsWith('--')) throw new Error(`--${name} requires a value`);
22
+ if (values.has(name) && name !== 'allowed-host') throw new Error(`--${name} may only be supplied once`);
23
+ values.set(name, [...(values.get(name) ?? []), value]);
24
+ }
25
+ const one = name => values.get(name)?.[0];
26
+ const csv = name => one(name)?.split(',').map(value => value.trim()).filter(Boolean);
27
+ return {
28
+ projectDir: one('project'), tokenEnv: one('token-env'), tokenFile: one('token-file'),
29
+ host: one('host') ?? '127.0.0.1', port: one('port') ?? 3100,
30
+ maxSessions: one('max-sessions') ?? 8, tools: csv('tools'), toolsets: one('toolsets') ?? '',
31
+ allowedHosts: values.get('allowed-host') ?? [], allowRemoteBind: !!one('allow-remote-bind'),
32
+ };
33
+ }
34
+
35
+ export function boundedInteger(value, name, minimum, maximum) {
36
+ if (!/^\d+$/.test(String(value)) || !Number.isSafeInteger(Number(value))
37
+ || Number(value) < minimum || Number(value) > maximum) {
38
+ throw new Error(`${name} must be an integer from ${minimum} to ${maximum}`);
39
+ }
40
+ return Number(value);
41
+ }
42
+
43
+ export function tokenDigest(token) {
44
+ return createHash('sha256').update(token).digest();
45
+ }
46
+
47
+ export async function tokenSource({ tokenEnv, tokenFile }) {
48
+ if (!!tokenEnv === !!tokenFile) throw new Error('HTTP requires exactly one of --token-env or --token-file');
49
+ if (tokenEnv && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(tokenEnv)) throw new Error('Invalid --token-env name');
50
+ const filename = tokenFile && path.resolve(tokenFile);
51
+ const environmentToken = tokenEnv && process.env[tokenEnv];
52
+ const read = async () => {
53
+ let value;
54
+ try { value = filename ? await fs.readFile(filename, 'utf8') : environmentToken; }
55
+ catch { throw new Error('HTTP token source is unavailable'); }
56
+ value = value?.trim();
57
+ if (!value || value.length > 4096 || !/^[A-Za-z0-9\-._~+/]+=*$/.test(value)) {
58
+ throw new Error('HTTP token source must contain a nonempty bearer token');
59
+ }
60
+ return tokenDigest(value);
61
+ };
62
+ await read(); // Refuse startup with a missing/empty/unreadable credential.
63
+ return async authorization => {
64
+ const match = typeof authorization === 'string' && /^Bearer ([A-Za-z0-9\-._~+/]+=*)$/i.exec(authorization);
65
+ if (!match || match[1].length > 4096) return undefined;
66
+ try {
67
+ const actual = tokenDigest(match[1]);
68
+ return timingSafeEqual(actual, await read()) ? actual : undefined;
69
+ } catch { return undefined; }
70
+ };
71
+ }
72
+
73
+ function authority(value) {
74
+ if (typeof value !== 'string' || !/^(?:\[[a-fA-F0-9:]+\]|[A-Za-z0-9.-]+)(?::\d+)?$/.test(value)) {
75
+ throw new Error('Invalid allowed host');
76
+ }
77
+ const url = new URL(`http://${value}`);
78
+ return { hostname: url.hostname.toLowerCase(), port: /:\d+$/.test(value) ? String(Number(value.match(/:(\d+)$/)[1])) : undefined };
79
+ }
80
+
81
+ export function hostPolicy(host, additional = []) {
82
+ const bindHost = host.includes(':') && !host.startsWith('[') ? `[${host}]` : host;
83
+ const aliases = ['127.0.0.1', '::1', '[::1]'].includes(host) ? ['localhost'] : [];
84
+ const allowed = [bindHost, ...aliases, ...additional].map(authority);
85
+ const accepts = value => {
86
+ try {
87
+ const candidate = authority(value);
88
+ return allowed.some(entry => candidate.hostname === entry.hostname
89
+ && (entry.port === undefined || candidate.port === entry.port));
90
+ } catch { return false; }
91
+ };
92
+ return headers => {
93
+ if (!accepts(headers.host)) return false;
94
+ if (headers.origin === undefined) return true;
95
+ try {
96
+ const origin = new URL(headers.origin);
97
+ return ['http:', 'https:'].includes(origin.protocol) && !origin.username && !origin.password
98
+ && origin.pathname === '/' && !origin.search && !origin.hash && accepts(origin.host);
99
+ } catch { return false; }
100
+ };
101
+ }
@@ -0,0 +1,51 @@
1
+ // Project-bound, strict schema projection and tool authorization for remote MCP.
2
+ import { z } from 'zod';
3
+ import { toolContext } from './tool-context.mjs';
4
+
5
+ const scopeFields = new Set([
6
+ 'project_dir', 'projectDir', 'project_root', 'projectRoot', 'project',
7
+ 'cwd', 'root', 'workdir', 'working_directory', 'scope',
8
+ 'artifact_root', 'artifacts_path', 'aiwg_dir',
9
+ ]);
10
+
11
+ function containsCliOption(value) {
12
+ if (typeof value === 'string') return value.startsWith('--');
13
+ if (value && typeof value === 'object') return Object.values(value).some(containsCliOption);
14
+ return false;
15
+ }
16
+
17
+ export function remoteToolPolicy(projectDir, tools) {
18
+ const selected = tools === undefined ? undefined : new Set(tools);
19
+ const exposed = new Set();
20
+ const children = new Set();
21
+ let active = 0;
22
+ return {
23
+ configureTool(name, config, handler) {
24
+ const allowed = name === 'discover' || name.endsWith('-show') || name === 'artifact-write';
25
+ if (!allowed || (selected && !selected.has(name))) return undefined;
26
+ exposed.add(name);
27
+ const shape = config.inputSchema?.shape ?? {};
28
+ const inputSchema = z.strictObject(Object.fromEntries(
29
+ Object.entries(shape).filter(([key]) => !scopeFields.has(key)),
30
+ ));
31
+ return { config: { ...config, inputSchema }, handler: async (args, extra) => {
32
+ extra.signal.throwIfAborted();
33
+ // CLI-backed cards must not reinterpret data values as scope/source flags.
34
+ // artifact-write uses openArtifact directly and spawns no CLI.
35
+ if (name !== 'artifact-write' && containsCliOption(args)) {
36
+ throw new Error('Tool arguments must not contain CLI options');
37
+ }
38
+ active++;
39
+ try { return await toolContext.run({ projectDir, signal: extra.signal, children }, () => handler(args, extra)); }
40
+ finally { active--; }
41
+ } };
42
+ },
43
+ busy: () => active > 0 || children.size > 0,
44
+ drain: () => Promise.allSettled([...children]),
45
+ validate() {
46
+ if (selected && [...selected].some(name => !exposed.has(name))) {
47
+ throw new Error('--tools must name only available discover, *-show or artifact-write tools; enable required --toolsets explicitly');
48
+ }
49
+ },
50
+ };
51
+ }
@@ -0,0 +1,201 @@
1
+ // Dedicated authenticated Streamable HTTP listener; one SDK server per session.
2
+ import http from 'node:http';
3
+ import fs from 'node:fs/promises';
4
+ import { randomUUID, timingSafeEqual } from 'node:crypto';
5
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
6
+ import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
7
+ import { createServer } from './server.mjs';
8
+ import { resolveProjectAiwgDir } from './helpers.mjs';
9
+ import { pinContainedRoot } from '../utils/contained-filesystem.mjs';
10
+ import { remoteToolPolicy } from './http-tools.mjs';
11
+ import { parseHttpOptions, boundedInteger, tokenSource, hostPolicy } from './http-options.mjs';
12
+
13
+ const BODY_LIMIT = 1024 * 1024;
14
+
15
+ function reply(response, status, message) {
16
+ if (response.headersSent || response.destroyed) return;
17
+ response.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
18
+ response.end(JSON.stringify({ error: message }));
19
+ }
20
+
21
+ async function readBody(request, response) {
22
+ let size = 0;
23
+ const chunks = [];
24
+ for await (const chunk of request) {
25
+ size += chunk.length;
26
+ if (size > BODY_LIMIT) {
27
+ // Close this connection after the response, rather than drain an unlimited body.
28
+ response.setHeader('Connection', 'close');
29
+ reply(response, 413, 'Request body exceeds 1 MiB');
30
+ return undefined;
31
+ }
32
+ chunks.push(chunk);
33
+ }
34
+ try { return JSON.parse(Buffer.concat(chunks).toString('utf8')); }
35
+ catch { reply(response, 400, 'Invalid JSON'); }
36
+ }
37
+
38
+ export async function startHttpServer(options) {
39
+ const host = options.host === '[::1]' ? '::1' : options.host ?? '127.0.0.1';
40
+ const loopback = host === '127.0.0.1' || host === '::1' || host === 'localhost';
41
+ if (!loopback && !options.allowRemoteBind) {
42
+ throw new Error('A non-loopback --host requires --allow-remote-bind');
43
+ }
44
+ const port = boundedInteger(options.port ?? 3100, '--port', 0, 65535);
45
+ const maxSessions = boundedInteger(options.maxSessions ?? 8, '--max-sessions', 1, 65535);
46
+ if (!options.projectDir) throw new Error('HTTP requires --project <dir>');
47
+ const projectDir = await fs.realpath(options.projectDir);
48
+ const projectIdentity = await fs.stat(projectDir);
49
+ if (!projectIdentity.isDirectory()) throw new Error('--project must be a directory');
50
+ const authenticate = await tokenSource(options);
51
+ const permittedHost = hostPolicy(host, options.allowedHosts);
52
+ const artifactStore = await pinContainedRoot(await resolveProjectAiwgDir(projectDir), projectDir);
53
+ if (artifactStore.error) throw new Error('Project artifact root is unavailable');
54
+ const policies = new WeakMap();
55
+ const sessions = new Map();
56
+ const entries = new Set(); // Includes pending initializes, so concurrent admission is bounded.
57
+ const idleMs = options.idleTimeoutMs ?? 300_000;
58
+ let closing = false;
59
+ let stopPromise;
60
+ const buildServer = async () => {
61
+ const policy = remoteToolPolicy(projectDir, options.tools);
62
+ const mcp = await createServer({ projectDir, artifactStore, toolsets: options.toolsets ?? '', configureTool: policy.configureTool });
63
+ try { policy.validate(); } catch (error) { await mcp.close(); throw error; }
64
+ policies.set(mcp, policy);
65
+ return mcp;
66
+ };
67
+ // Validate tool selection and registration before binding the listener.
68
+ let warmServer = await buildServer();
69
+ function touch(entry) {
70
+ clearTimeout(entry.timer);
71
+ entry.timer = setTimeout(() => {
72
+ if (policies.get(entry.mcp)?.busy()) touch(entry);
73
+ else void dispose(entry);
74
+ }, idleMs);
75
+ entry.timer.unref();
76
+ }
77
+ async function dispose(entry) {
78
+ if (entry.disposing) return entry.disposing;
79
+ sessions.delete(entry.transport?.sessionId);
80
+ clearTimeout(entry.timer);
81
+ entry.disposing = (async () => {
82
+ try {
83
+ await entry.ready?.catch(() => {});
84
+ await entry.mcp?.close();
85
+ await policies.get(entry.mcp)?.drain();
86
+ }
87
+ finally { entries.delete(entry); }
88
+ })();
89
+ return entry.disposing;
90
+ }
91
+ async function newSession(token) {
92
+ const entry = { token };
93
+ entries.add(entry);
94
+ try {
95
+ entry.mcp = warmServer;
96
+ warmServer = undefined;
97
+ entry.ready = entry.mcp ? Promise.resolve(entry.mcp) : buildServer();
98
+ entry.mcp = await entry.ready;
99
+ if (closing) throw new Error('Listener is draining');
100
+ entry.transport = new StreamableHTTPServerTransport({
101
+ sessionIdGenerator: () => randomUUID(),
102
+ onsessioninitialized: id => { sessions.set(id, entry); touch(entry); },
103
+ onsessionclosed: () => { void dispose(entry); },
104
+ });
105
+ await entry.mcp.connect(entry.transport);
106
+ const sdkClose = entry.transport.onclose;
107
+ entry.transport.onclose = () => {
108
+ sdkClose?.();
109
+ sessions.delete(entry.transport?.sessionId);
110
+ clearTimeout(entry.timer);
111
+ entries.delete(entry);
112
+ };
113
+ return entry;
114
+ } catch (error) {
115
+ entries.delete(entry);
116
+ await entry.mcp?.close();
117
+ throw error;
118
+ }
119
+ }
120
+ const listener = http.createServer(async (request, response) => {
121
+ let created;
122
+ try {
123
+ if (closing) return reply(response, 503, 'Listener is draining');
124
+ const token = await authenticate(request.headers.authorization);
125
+ if (!token) return reply(response, 401, 'Unauthorized');
126
+ if (!permittedHost(request.headers)) return reply(response, 403, 'Host or Origin is not allowed');
127
+ if (request.url !== '/mcp') return reply(response, 404, 'Not found');
128
+ if (!['POST', 'GET', 'DELETE'].includes(request.method)) return reply(response, 405, 'Method not allowed');
129
+ const identity = await fs.stat(projectDir);
130
+ if (await fs.realpath(projectDir) !== projectDir || identity.dev !== projectIdentity.dev || identity.ino !== projectIdentity.ino) {
131
+ return reply(response, 503, 'Pinned project changed; restart the listener');
132
+ }
133
+ const id = request.headers['mcp-session-id'];
134
+ let entry = id && sessions.get(id);
135
+ if (id && (!entry || !timingSafeEqual(entry.token, token) || entry.disposing)) {
136
+ return reply(response, 404, 'Unknown session; initialize again');
137
+ }
138
+ if (Number(request.headers['content-length']) > BODY_LIMIT) {
139
+ response.setHeader('Connection', 'close');
140
+ return reply(response, 413, 'Request body exceeds 1 MiB');
141
+ }
142
+ if (request.method !== 'POST' && (request.headers['transfer-encoding'] || Number(request.headers['content-length']) > 0)) {
143
+ response.setHeader('Connection', 'close');
144
+ return reply(response, 400, 'Only POST requests may carry a body');
145
+ }
146
+ const body = request.method === 'POST' ? await readBody(request, response) : undefined;
147
+ if (response.writableEnded || response.destroyed) return;
148
+ if (closing) return reply(response, 503, 'Listener is draining');
149
+ if (entry?.disposing) return reply(response, 404, 'Unknown session; initialize again');
150
+ if (entry && isInitializeRequest(body)) return reply(response, 404, 'Session ID cannot be reused for initialization');
151
+ if (!entry) {
152
+ if (request.method !== 'POST' || !isInitializeRequest(body)) return reply(response, 400, 'Initialize a new session first');
153
+ if (entries.size >= maxSessions) return reply(response, 503, 'Maximum sessions reached');
154
+ entry = created = await newSession(token);
155
+ }
156
+ touch(entry);
157
+ await entry.transport.handleRequest(request, response, body);
158
+ if (created && !entry.transport.sessionId) await dispose(entry);
159
+ } catch {
160
+ if (created) await dispose(created);
161
+ reply(response, 500, 'MCP transport failed'); // Never log credentials, inputs or SDK errors containing them.
162
+ }
163
+ });
164
+ listener.requestTimeout = 30_000;
165
+ listener.headersTimeout = 10_000;
166
+ try {
167
+ await new Promise((resolve, reject) => {
168
+ listener.once('error', reject);
169
+ listener.listen(port, host, resolve);
170
+ });
171
+ } catch (error) { await warmServer?.close(); throw error; }
172
+ if (!loopback) console.error('WARNING: remote MCP bind enabled; use a trusted TLS proxy and firewall.');
173
+ const closed = new Promise(resolve => listener.once('close', resolve));
174
+ function close() {
175
+ stopPromise ??= (async () => {
176
+ closing = true;
177
+ listener.close();
178
+ await Promise.allSettled([...entries].map(dispose));
179
+ await warmServer?.close();
180
+ listener.closeAllConnections();
181
+ await closed;
182
+ })();
183
+ return stopPromise;
184
+ }
185
+ return { listener, close, closed, projectDir, sessionCount: () => entries.size };
186
+ }
187
+
188
+ export async function serveHttp(args) {
189
+ const service = await startHttpServer(parseHttpOptions(args));
190
+ const address = service.listener.address();
191
+ console.error(`AIWG MCP HTTP listening on ${address.address}:${address.port}/mcp`);
192
+ const stop = () => { void service.close(); };
193
+ process.once('SIGTERM', stop);
194
+ process.once('SIGINT', stop);
195
+ try { await service.closed; }
196
+ finally {
197
+ process.removeListener('SIGTERM', stop);
198
+ process.removeListener('SIGINT', stop);
199
+ await service.close();
200
+ }
201
+ }
@@ -58,7 +58,7 @@ function retainToolJsonSchema(schema, seen = new Set()) {
58
58
  /**
59
59
  * Create and configure the AIWG MCP Server
60
60
  */
61
- export async function createServer() {
61
+ export async function createServer(options = {}) {
62
62
  const server = new McpServer({
63
63
  name: 'aiwg',
64
64
  version: '1.0.0'
@@ -73,7 +73,9 @@ export async function createServer() {
73
73
  retainToolJsonSchema(schema);
74
74
  schemas[key] = schema;
75
75
  }
76
- return registerTool(name, { ...config, ...schemas }, handler);
76
+ const projected = options.configureTool?.(name, { ...config, ...schemas }, handler);
77
+ if (options.configureTool && !projected) return;
78
+ return registerTool(name, projected?.config ?? { ...config, ...schemas }, projected?.handler ?? handler);
77
79
  };
78
80
 
79
81
  // ============================================
@@ -107,7 +109,7 @@ export async function createServer() {
107
109
  };
108
110
  });
109
111
  }
110
- registerWriterProfileResources(server);
112
+ registerWriterProfileResources(server, { projectRoot: options.projectDir });
111
113
 
112
114
  // ============================================
113
115
  // Command-run dispatch (#1312) — registers:
@@ -130,7 +132,7 @@ export async function createServer() {
130
132
  // `all` deliberately does not reach it (src/mcp/tools/subsystems.mjs).
131
133
  // Default: none (core only — discovery + command-run)
132
134
  // ============================================
133
- const requested = parseToolsets(process.env.AIWG_MCP_TOOLSETS || '');
135
+ const requested = parseToolsets(options.toolsets ?? process.env.AIWG_MCP_TOOLSETS ?? '');
134
136
  // #2892 B1: the `workers` toolset's served project root is resolved ONCE,
135
137
  // here, at registration time — never lazily from `process.cwd()` inside
136
138
  // the tool handler on first request. A project root that cannot be found
@@ -139,7 +141,7 @@ export async function createServer() {
139
141
  // back to an implicit cwd.
140
142
  let projectRoot;
141
143
  try {
142
- projectRoot = await findProjectRoot();
144
+ projectRoot = options.projectDir ?? await findProjectRoot();
143
145
  } catch {
144
146
  projectRoot = undefined;
145
147
  }
@@ -152,9 +154,9 @@ export async function createServer() {
152
154
  // must pin its own missing default at startup, never adopt the ancestor's
153
155
  // store. Callers select other projects explicitly via `project_dir`.
154
156
  const artifactEnv = { ...process.env };
155
- const trustedProjectRoot = await fs.realpath(process.cwd());
157
+ const trustedProjectRoot = await fs.realpath(options.projectDir ?? process.cwd());
156
158
  const trustedArtifactRoot = await resolveProjectAiwgDir(trustedProjectRoot, { env: artifactEnv });
157
- const startupStore = await pinArtifactRoot(trustedArtifactRoot, trustedProjectRoot);
159
+ const startupStore = options.artifactStore ?? await pinArtifactRoot(trustedArtifactRoot, trustedProjectRoot);
158
160
  const trustedStore = startupStore.root;
159
161
  const projects = new Map();
160
162
  async function trustProject(requested, store) {
@@ -0,0 +1,25 @@
1
+ // Carry trusted project scope and cancellation through existing CLI-backed tools.
2
+ import { AsyncLocalStorage } from 'node:async_hooks';
3
+
4
+ export const toolContext = new AsyncLocalStorage();
5
+
6
+ export function cliExecutionOptions(options) {
7
+ const context = toolContext.getStore();
8
+ return context ? { ...options, cwd: context.projectDir, signal: context.signal } : options;
9
+ }
10
+
11
+ export function bindCliCancellation(child, signal, terminate) {
12
+ if (!signal) return;
13
+ const children = toolContext.getStore()?.children;
14
+ let release;
15
+ const closed = new Promise(resolve => { release = resolve; });
16
+ children?.add(closed);
17
+ const abort = () => terminate(new Error('MCP tool cancelled'));
18
+ signal.addEventListener('abort', abort, { once: true });
19
+ child.once('close', () => {
20
+ signal.removeEventListener('abort', abort);
21
+ children?.delete(closed);
22
+ release();
23
+ });
24
+ if (signal.aborted) abort();
25
+ }
@@ -9,6 +9,7 @@
9
9
  */
10
10
 
11
11
  import { z } from 'zod';
12
+ import { toolContext } from '../tool-context.mjs';
12
13
  import { integer } from '../../schema/zod-validation.mjs';
13
14
  import { showDrillInSchema, showDrillInArgs } from './discovery.mjs';
14
15
  import { parse as parseYaml } from 'yaml';
@@ -19,7 +20,7 @@ import { AIWG_ROOT, mcpError, mcpJson, runAiwgCli } from '../helpers.mjs';
19
20
  function candidateAiwgRoots() {
20
21
  const roots = [
21
22
  AIWG_ROOT,
22
- process.cwd(),
23
+ toolContext.getStore()?.projectDir ?? process.cwd(),
23
24
  ];
24
25
  return [...new Set(roots.map((r) => path.resolve(r)).filter(Boolean))];
25
26
  }
@@ -138,6 +138,7 @@ export function recordDeploymentOutputs(before, roots, opts = {}) {
138
138
  const receiptRoot = (file, receipt) => projectRoot && file === path.join(projectRoot, '.aiwg', SIDECAR) && receipt.scope === 'project'
139
139
  ? projectRoot : path.dirname(file);
140
140
  const declared = new Map();
141
+ const preserved = new Set();
141
142
  for (const [file, bytes] of after) {
142
143
  if (path.basename(file) !== SIDECAR) continue;
143
144
  const receipt = parse(bytes), previous = parse(before.get(file));
@@ -156,12 +157,25 @@ export function recordDeploymentOutputs(before, roots, opts = {}) {
156
157
  const base = receiptRoot(file, receipt);
157
158
  const target = path.resolve(base, name);
158
159
  if (!target.startsWith(`${base}${path.sep}`) || !after.has(target)) continue;
160
+ const prior = previous.managed?.[name];
161
+ // A receipt rewrite is not evidence of a payload write. Preservation can
162
+ // also restore bytes after a writer/binder marked the file as written.
163
+ // Never bless those edited bytes, even with an explicit write hint.
164
+ if (before.get(target)?.equals(after.get(target)) &&
165
+ (prior ? prior.hash !== hash(before.get(target)) : entry.hash === hash(before.get(target)) && !opts.writtenFiles?.includes(target))) {
166
+ if (prior) receipt.managed[name] = prior;
167
+ else delete receipt.managed[name];
168
+ preserved.add(target);
169
+ manifests.set(file, receipt);
170
+ continue;
171
+ }
159
172
  if (stable(previous.managed?.[name]) !== stable(entry)) declared.set(target, { file, name, entry, receipt });
160
173
  }
161
174
  }
162
175
  for (const [file, bytes] of after) {
163
176
  if (path.basename(file) === SIDECAR || /(?:^|[/\\])aiwg\.config$/.test(file)
164
177
  || /(?:\.bak\.|\.aiwg-backup-)/.test(path.basename(file))) continue;
178
+ if (preserved.has(file)) continue;
165
179
  const changed = !before.get(file)?.equals(bytes);
166
180
  const declaration = declared.get(file);
167
181
  if (opts.onlyDeclared && !declaration) continue;
@@ -175,7 +189,7 @@ export function recordDeploymentOutputs(before, roots, opts = {}) {
175
189
  skillRoot = path.dirname(skillRoot);
176
190
  }
177
191
  const skillReceipt = parse(after.get(path.join(skillRoot, SIDECAR)));
178
- const projectScoped = projectRoot && (path.dirname(file) === projectRoot || opts.provider === 'flue' && /[/\\](?:db\.ts|aiwg[/\\](?:tools|specialists)\.ts)$/.test(file));
192
+ const projectScoped = projectRoot && (path.dirname(file) === projectRoot || opts.provider === 'flue' && /[/\\](?:db\.ts|aiwg[/\\](?:(?:tools|specialists|skills)\.ts|remote-specialist\.(?:js|d\.ts)))$/.test(file));
179
193
  const dir = projectScoped ? path.join(projectRoot, '.aiwg') : declaration ? path.dirname(declaration.file) : skillReceipt.managed?.['SKILL.md'] ? skillRoot : path.dirname(file);
180
194
  const name = declaration?.name || portable(path.relative(projectScoped ? projectRoot : dir, file));
181
195
  const existing = manifests.get(path.join(dir, SIDECAR)) || parse(after.get(path.join(dir, SIDECAR)));