@aiwg/cli 2026.10.19 → 2026.11.1

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 (143) hide show
  1. package/README.md +1 -0
  2. package/agentic/code/providers/flue/README.md +2 -1
  3. package/dist/src/artifacts/cli.js +3 -2
  4. package/dist/src/artifacts/discover-facets.js +2 -0
  5. package/dist/src/artifacts/discover-session-facets.js +14 -0
  6. package/dist/src/artifacts/fortemi-core-query-adapter.js +4 -4
  7. package/dist/src/artifacts/framework-capabilities.js +7 -3
  8. package/dist/src/artifacts/index-builder.js +2 -3
  9. package/dist/src/artifacts/query-engine-discover-output.js +3 -3
  10. package/dist/src/artifacts/query-engine-discover.js +61 -14
  11. package/dist/src/artifacts/query-engine-entries.js +52 -9
  12. package/dist/src/artifacts/query-engine-installation.js +27 -0
  13. package/dist/src/artifacts/query-engine-rules.js +1 -2
  14. package/dist/src/artifacts/query-engine-scoring.js +33 -31
  15. package/dist/src/artifacts/query-engine-show-card.js +6 -2
  16. package/dist/src/artifacts/query-engine-show.js +2 -2
  17. package/dist/src/artifacts/relations.js +17 -10
  18. package/dist/src/cli/handlers/bundle-declaration.js +55 -0
  19. package/dist/src/cli/handlers/bundle-deployment-mode.js +71 -0
  20. package/dist/src/cli/handlers/bundle-hash-prune.js +37 -0
  21. package/dist/src/cli/handlers/bundle-reconciliation.js +140 -0
  22. package/dist/src/cli/handlers/checkpoint.js +143 -0
  23. package/dist/src/cli/handlers/help.js +1 -0
  24. package/dist/src/cli/handlers/index.js +4 -2
  25. package/dist/src/cli/handlers/models-resource-sample.js +7 -3
  26. package/dist/src/cli/handlers/ralph-launcher.js +1 -1
  27. package/dist/src/cli/handlers/refresh-bundles.js +35 -0
  28. package/dist/src/cli/handlers/refresh-rule-inventory.js +10 -0
  29. package/dist/src/cli/handlers/refresh.js +15 -52
  30. package/dist/src/cli/handlers/remove-bundled.js +7 -4
  31. package/dist/src/cli/handlers/remove-flue-modules.js +19 -0
  32. package/dist/src/cli/handlers/remove-historical-bundle.js +18 -0
  33. package/dist/src/cli/handlers/remove.js +8 -0
  34. package/dist/src/cli/handlers/script-runner.js +12 -1
  35. package/dist/src/cli/handlers/steward-signing.js +44 -0
  36. package/dist/src/cli/handlers/steward.js +5 -0
  37. package/dist/src/cli/handlers/subcommands-list-format.js +4 -4
  38. package/dist/src/cli/handlers/update.js +18 -8
  39. package/dist/src/cli/handlers/use-additive-bundles.js +87 -0
  40. package/dist/src/cli/handlers/use-bundle-counts.js +5 -1
  41. package/dist/src/cli/handlers/use-owned-counts.js +75 -0
  42. package/dist/src/cli/handlers/use-provider-results.js +17 -0
  43. package/dist/src/cli/handlers/use.js +53 -114
  44. package/dist/src/cli/router.js +12 -2
  45. package/dist/src/cli/services/deployment-verification.js +2 -1
  46. package/dist/src/cli/user-scope-mirror.js +3 -1
  47. package/dist/src/config/aiwg-config.js +15 -6
  48. package/dist/src/config/cli.js +1 -0
  49. package/dist/src/config/delivery-validation.js +21 -0
  50. package/dist/src/config/framework-aliases.js +14 -0
  51. package/dist/src/config/host-resource-report.d.mts +1 -1
  52. package/dist/src/config/host-resource-report.mjs +23 -4
  53. package/dist/src/config/host-resource-runtime.d.mts +8 -0
  54. package/dist/src/config/host-resource-runtime.mjs +67 -24
  55. package/dist/src/config/index-graph-overrides.js +4 -0
  56. package/dist/src/config/installed-selection.js +9 -1
  57. package/dist/src/config/installed-validation.js +35 -0
  58. package/dist/src/config/worker-attribution.d.mts +7 -0
  59. package/dist/src/config/worker-attribution.mjs +44 -0
  60. package/dist/src/delivery/git.js +62 -0
  61. package/dist/src/delivery/pr.js +149 -0
  62. package/dist/src/delivery/tracker.js +33 -0
  63. package/dist/src/discovery/interview.js +1 -1
  64. package/dist/src/extensions/claude-hooks-installer.js +1 -0
  65. package/dist/src/extensions/loader.js +2 -1
  66. package/dist/src/extensions/project-local-doctor.js +1 -1
  67. package/dist/src/extensions/project-local-remove.js +3 -3
  68. package/dist/src/issues/cli.js +12 -3
  69. package/dist/src/issues/external-cli.js +76 -0
  70. package/dist/src/issues/live.js +18 -1
  71. package/dist/src/issues/tracker-policy.js +17 -0
  72. package/dist/src/mcp/cli.mjs +12 -7
  73. package/dist/src/mcp/helpers.mjs +5 -1
  74. package/dist/src/mcp/http-options.mjs +101 -0
  75. package/dist/src/mcp/http-tools.mjs +51 -0
  76. package/dist/src/mcp/http-transport.mjs +201 -0
  77. package/dist/src/mcp/server.mjs +9 -7
  78. package/dist/src/mcp/tool-context.mjs +25 -0
  79. package/dist/src/mcp/tools/orchestration.mjs +2 -1
  80. package/dist/src/mcp/tools/worker-invoke.mjs +2 -1
  81. package/dist/src/mcp/tools/worker-stdin-runtime.mjs +12 -0
  82. package/dist/src/models/conductor-data-policy.d.mts +3 -2
  83. package/dist/src/models/conductor-data-policy.mjs +94 -5
  84. package/dist/src/models/worker-plan.js +3 -3
  85. package/dist/src/models/worker-selection-policy.js +2 -1
  86. package/dist/src/providers/deployment-lock.js +77 -0
  87. package/dist/src/providers/deployment-ownership.d.mts +12 -2
  88. package/dist/src/providers/deployment-ownership.mjs +127 -19
  89. package/dist/src/providers/deployment-preservation.d.mts +6 -0
  90. package/dist/src/providers/deployment-preservation.mjs +113 -0
  91. package/dist/src/providers/deployment-removal.js +4 -2
  92. package/dist/src/providers/flue-package-mode.js +19 -0
  93. package/dist/src/providers/provider-definitions.js +4 -0
  94. package/dist/src/providers/skill-ownership.mjs +1 -0
  95. package/dist/src/research/reference-match.js +4 -0
  96. package/dist/src/serve/worker-invocation-preparation.js +3 -1
  97. package/dist/src/serve/worker-invocation.js +2 -0
  98. package/dist/src/skills/run.js +5 -0
  99. package/dist/src/smiths/hook-bridge/codex-translator.js +3 -1
  100. package/dist/src/smiths/hook-bridge/hermes-translator.js +3 -1
  101. package/dist/src/smiths/hook-bridge/prompt-discovery-gaps.js +6 -0
  102. package/package.json +5 -2
  103. package/schemas/models/model-config-compatibility.v1.schema.json +4 -0
  104. package/tools/agents/deploy-agents.mjs +21 -1
  105. package/tools/agents/deploy-options.mjs +2 -0
  106. package/tools/agents/providers/base-contract.mjs +7 -1
  107. package/tools/agents/providers/base-inventory.mjs +41 -14
  108. package/tools/agents/providers/base-kernel-skills.mjs +9 -5
  109. package/tools/agents/providers/base-migrations.mjs +1 -0
  110. package/tools/agents/providers/base-skill-copy.mjs +9 -1
  111. package/tools/agents/providers/base.mjs +1 -1
  112. package/tools/agents/providers/claude.mjs +2 -1
  113. package/tools/agents/providers/codex.mjs +5 -1
  114. package/tools/agents/providers/conductor-data-guard.mjs +35 -11
  115. package/tools/agents/providers/flue-bundles.mjs +42 -0
  116. package/tools/agents/providers/flue-cloudflare.mjs +20 -0
  117. package/tools/agents/providers/flue-project.mjs +45 -6
  118. package/tools/agents/providers/flue-skill-copy.mjs +25 -0
  119. package/tools/agents/providers/flue-skills.mjs +45 -0
  120. package/tools/agents/providers/flue-specialists.mjs +36 -18
  121. package/tools/agents/providers/flue-validation.mjs +14 -0
  122. package/tools/agents/providers/flue.mjs +12 -8
  123. package/tools/agents/providers/hermes-skill-lifecycle.mjs +1 -0
  124. package/tools/agents/providers/muse-hooks.mjs +4 -0
  125. package/tools/agents/providers/muse-prompt-discovery.mjs +22 -0
  126. package/tools/agents/providers/provider-prepare-coordinator.mjs +15 -10
  127. package/tools/agents/providers/rule-delivery-surface.mjs +18 -1
  128. package/tools/agents/providers/rule-deployment-commit.mjs +24 -0
  129. package/tools/agents/providers/rule-deployment-prepare.mjs +4 -0
  130. package/tools/agents/providers/skill-copy-prune.mjs +49 -0
  131. package/tools/agents/providers/stale-artifact-prune.mjs +10 -8
  132. package/tools/ralph-external/lib/worker-capture.mjs +157 -0
  133. package/tools/ralph-external/lib/worker-health.mjs +3 -0
  134. package/tools/ralph-external/lib/worker-invocation-processes.mjs +9 -6
  135. package/tools/ralph-external/lib/worker-launch-cli.mjs +10 -1
  136. package/tools/ralph-external/lib/worker-process-identity.mjs +30 -0
  137. package/tools/ralph-external/lib/worker-retry-evidence.mjs +87 -6
  138. package/tools/ralph-external/lib/worker-termination.mjs +56 -6
  139. package/tools/ralph-external/process-monitor.mjs +12 -18
  140. package/tools/ralph-external/session-launcher.mjs +43 -29
  141. package/tools/skills/codex-skill-metadata.mjs +22 -0
  142. package/tools/skills/deploy-skills-codex.mjs +8 -7
  143. package/vscode-extension/schemas/aiwg.config.v1.json +59 -19
@@ -0,0 +1,33 @@
1
+ import { resolveRemotes } from '../config/aiwg-config.js';
2
+ import { LiveIssueClient } from '../issues/live.js';
3
+ import { trackerToken } from '../issues/tracker-policy.js';
4
+ import { git } from './git.js';
5
+ export async function deliveryTracker(cwd, config, options = {}) {
6
+ const remotes = resolveRemotes(config.remotes);
7
+ if (remotes.issue_provider === 'local' || remotes.issue_tracker === 'local')
8
+ throw new Error('PR and external issue writes require an external tracker');
9
+ let provider = remotes.issue_provider;
10
+ let repo = options.repo;
11
+ let apiUrl = options.apiUrl;
12
+ if (!repo || !apiUrl || !provider) {
13
+ const remote = remotes.issue_tracker;
14
+ const url = remote.includes('://') || remote.includes('@') ? remote : await git(cwd, 'remote', 'get-url', remote);
15
+ const normalized = url.replace(/^([^@]+@)([^:]+):/, 'ssh://$1$2/');
16
+ let parsed;
17
+ try {
18
+ parsed = new URL(normalized);
19
+ }
20
+ catch {
21
+ throw new Error('Cannot resolve tracker remote; supply --repo and --api-url with an explicit issue_provider');
22
+ }
23
+ if ((parsed.protocol === 'https:' || parsed.protocol === 'http:') && (parsed.username || parsed.password))
24
+ throw new Error('Tracker remote URLs must not contain credentials');
25
+ provider ??= parsed.hostname === 'github.com' ? 'github' : 'gitea';
26
+ repo ??= parsed.pathname.replace(/^\//, '').replace(/\.git$/, '');
27
+ const protocol = parsed.protocol === 'http:' ? 'http:' : 'https:';
28
+ apiUrl ??= provider === 'github' ? parsed.hostname === 'github.com' ? 'https://api.github.com' : `${protocol}//${parsed.host}/api/v3` : `${protocol}//${parsed.host}/api/v1`;
29
+ }
30
+ const token = await trackerToken(provider, remotes.tracker_actor, options.source);
31
+ return new LiveIssueClient({ provider, repo, apiUrl, token, actor: remotes.tracker_actor });
32
+ }
33
+ //# sourceMappingURL=tracker.js.map
@@ -137,7 +137,7 @@ export function interviewQuestions(context, answers = {}) {
137
137
  questions[questions.length - 1].questionId = questionId('locations', 'credential-source', project.root, 'jev');
138
138
  add('capabilities', 'jev-options', 'Optional Jev settings as JSON: region, endpoint, verify. Verification sends a billable request at apply.', null, [null], '--region <r> --endpoint <url> --verify', 'policy', project.root, 'jev', true);
139
139
  }
140
- add('capabilities', 'signing', 'Require signed delivery commits?', false, [true, false], '--require-signed-commits --signing-format --signing-key --signing-enforce', 'policy', project.root, undefined, true);
140
+ add('capabilities', 'signing', 'Optional: require signed delivery commits? Signed local merges are recommended where permitted; skip preserves unsigned delivery. Set up with aiwg steward signed-merges.', false, [true, false], '--require-signed-commits --signing-format --signing-key --signing-enforce', 'policy', project.root, undefined, true);
141
141
  add('capabilities', 'delivery', 'Delivery mode and branch protections.', { mode: 'pr-required', force_push_policy: 'never' }, [false, { mode: 'pr-required', force_push_policy: 'never' }], '--delivery-mode --default-branch --require-ci-green --auto-close-issues --issue-comment-on-cycle --force-push-policy', 'policy', project.root, undefined, true);
142
142
  add('capabilities', 'tracker', 'Issue tracker provider and remotes.', null, ['gitea', 'github', 'local'].map(issue_provider => ({ issue_provider })), '--issue-provider gitea|github|local', 'policy', project.root, undefined, !context.unknownRemote, !!context.unknownRemote);
143
143
  }
@@ -38,6 +38,7 @@ import { mergeClaudeAttribution, undoClaudeAttribution } from './claude-attribut
38
38
  const HOOK_SCRIPTS = [
39
39
  { file: 'aiwg-permissions.cjs', events: { PermissionRequest: undefined } },
40
40
  { file: 'aiwg-session.cjs', events: { SessionStart: undefined } },
41
+ { file: 'aiwg-prompt-discovery.cjs', events: { UserPromptSubmit: undefined } },
41
42
  {
42
43
  file: 'aiwg-trace.cjs',
43
44
  events: { SubagentStart: 'start', SubagentStop: 'stop' },
@@ -11,7 +11,6 @@
11
11
  import { getRegistry, createRegistry } from './registry.js';
12
12
  import { CapabilityIndex } from './capability-index.js';
13
13
  import { commandDefinitions } from './commands/definitions.js';
14
- import { allHandlers } from '../cli/handlers/index.js';
15
14
  /**
16
15
  * Load and populate the registry
17
16
  *
@@ -41,6 +40,7 @@ import { allHandlers } from '../cli/handlers/index.js';
41
40
  */
42
41
  export async function loadRegistry(options) {
43
42
  const { registry = createRegistry(), indexCapabilities = false } = options || {};
43
+ const allHandlers = options?.handlers ?? (await import('../cli/handlers/index.js')).allHandlers;
44
44
  // Register all command definitions
45
45
  for (const definition of commandDefinitions) {
46
46
  registry.register(definition);
@@ -100,6 +100,7 @@ export async function getLoadedRegistry() {
100
100
  return loadRegistry({ registry: globalRegistry });
101
101
  }
102
102
  // Already loaded - just build handler map
103
+ const { allHandlers } = await import('../cli/handlers/index.js');
103
104
  const handlerMap = linkHandlers(allHandlers);
104
105
  return {
105
106
  registry: globalRegistry,
@@ -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) {
@@ -12,15 +12,20 @@ import path from 'node:path';
12
12
  import { pathToFileURL } from 'node:url';
13
13
  import { getFrameworkRoot } from '../channel/manager.mjs';
14
14
  import { readAiwgConfig } from '../config/aiwg-config.js';
15
+ import { externalIssues } from './external-cli.js';
16
+ import { trackerToken } from './tracker-policy.js';
15
17
  import { sensitiveInputOptions } from '../auth/sensitive-input.js';
16
- import { LocalIssueProviderCore, buildExternalIssueSnapshotFromLocal, buildLocalIssueConflictReport, createLiveIssueClient, resolveLiveIssueToken, localIssueRoot, parseCommentIdMappings, parseExternalIssueSnapshot, } from './index.js';
18
+ import { LocalIssueProviderCore, buildExternalIssueSnapshotFromLocal, buildLocalIssueConflictReport, createLiveIssueClient, localIssueRoot, parseCommentIdMappings, parseExternalIssueSnapshot, } from './index.js';
17
19
  export async function main(args, cwd = process.cwd()) {
18
20
  const parsed = parseArgs(args);
21
+ parsed.cwd = cwd;
19
22
  const subcommand = parsed.positional[0];
20
23
  const rest = parsed.positional.slice(1);
21
24
  if (parsed.flags.has('backend')) {
22
25
  throw new Error('aiwg issue commands use the local issue provider; --backend is not supported');
23
26
  }
27
+ if (await externalIssues(parsed, cwd, async () => ({ plan: await buildIssuePlan(parsed, cwd), composer: await loadIssueComposer() })))
28
+ return;
24
29
  const provider = stringFlag(parsed, 'provider');
25
30
  if (provider && provider !== 'local') {
26
31
  throw new Error(`aiwg issue is for local issue storage only; configured external trackers use their tracker tools (${provider})`);
@@ -317,8 +322,9 @@ async function handleIndex(issues, rest, args) {
317
322
  }
318
323
  async function liveClient(args, provider) {
319
324
  const repo = requiredStringFlag(args, 'repo');
320
- const token = await resolveLiveIssueToken(provider, sensitiveInputOptions(args.raw, 'token'));
321
- return createLiveIssueClient({ provider, repo, apiUrl: stringFlag(args, 'api-url'), token });
325
+ const actor = (await readAiwgConfig(args.cwd ?? process.cwd()))?.remotes?.tracker_actor;
326
+ const token = await trackerToken(provider, actor, sensitiveInputOptions(args.raw, 'token'));
327
+ return createLiveIssueClient({ provider, repo, apiUrl: stringFlag(args, 'api-url'), token, actor });
322
328
  }
323
329
  function requiredStringFlag(args, flag) {
324
330
  const value = stringFlag(args, flag);
@@ -401,6 +407,9 @@ function csvFlag(args, name) {
401
407
  }
402
408
  function printUsage() {
403
409
  console.log(`Usage:
410
+ aiwg issues create --title "..." --body-file path (configured external tracker)
411
+ aiwg issues comment|close <number> [--body-file path] (configured external tracker)
412
+ Use --provider local for local writes when an external tracker is configured.
404
413
  aiwg issue init [--prefix KEY] [--padding N]
405
414
  aiwg issue plan --title "..." [--body "..."] [--body-file path] [--json]
406
415
  aiwg issue new --title "..." [--body "..."] [--body-file path] [--authorize-policy DIGEST]
@@ -0,0 +1,76 @@
1
+ // Route explicit/configured external issue writes through actor verification and existing issue composition.
2
+ import { readFile } from 'node:fs/promises';
3
+ import { readAiwgConfig } from '../config/aiwg-config.js';
4
+ import { sensitiveInputOptions } from '../auth/sensitive-input.js';
5
+ import { deliveryTracker } from '../delivery/tracker.js';
6
+ export async function externalIssues(args, cwd, composition) {
7
+ const [operation, number] = args.positional;
8
+ if (!['create', 'new', 'comment', 'close'].includes(operation) || args.flags.get('provider') === 'local')
9
+ return false;
10
+ const config = await readAiwgConfig(cwd);
11
+ if (!config || config.remotes?.issue_provider === 'local' || config.remotes?.issue_tracker === 'local')
12
+ return false;
13
+ if (!config.remotes?.issue_tracker && !['gitea', 'github'].includes(String(config.remotes?.issue_provider)))
14
+ return false;
15
+ const value = (key) => typeof args.flags.get(key) === 'string' ? args.flags.get(key) : undefined;
16
+ if (value('provider') && value('provider') !== config.remotes?.issue_provider)
17
+ throw new Error('--provider must match the configured tracker');
18
+ const client = await deliveryTracker(cwd, config, { repo: value('repo'), apiUrl: value('api-url'), source: sensitiveInputOptions(args.raw, 'token') });
19
+ let result;
20
+ if (operation === 'create' || operation === 'new') {
21
+ const { plan, composer } = await composition();
22
+ result = await composer.executeIssuePlan(plan, {
23
+ async findByMarker(marker) {
24
+ for (let page = 1;; page++) {
25
+ const entries = await client.repositoryRequest('GET', `/issues?state=all&per_page=100&limit=100&page=${page}`);
26
+ const entry = entries.find(issue => issue.body?.includes(marker));
27
+ if (entry)
28
+ return { id: String(entry.number), reference: `#${entry.number}`, body: entry.body };
29
+ if (entries.length < 100)
30
+ return null;
31
+ }
32
+ },
33
+ async create(draft) {
34
+ let labels = draft.labels;
35
+ if (client.provider === 'gitea' && labels?.length) {
36
+ const available = [];
37
+ for (let page = 1;; page++) {
38
+ const entries = await client.repositoryRequest('GET', `/labels?limit=100&page=${page}`);
39
+ available.push(...entries);
40
+ if (entries.length < 100)
41
+ break;
42
+ }
43
+ labels = labels.map(name => {
44
+ const id = available.find(label => label.name === name)?.id;
45
+ if (id === undefined)
46
+ throw new Error('Issue label is not defined on the configured tracker');
47
+ return id;
48
+ });
49
+ }
50
+ const issue = await client.repositoryRequest('POST', '/issues', {
51
+ title: draft.title, body: draft.body, labels, assignees: draft.assignees,
52
+ });
53
+ return { id: String(issue.number), reference: `#${issue.number}`, body: issue.body };
54
+ },
55
+ async update(issue, patch) {
56
+ await client.repositoryRequest('PATCH', `/issues/${issue.id}`, patch);
57
+ },
58
+ }, { authorizationDigest: value('authorize-policy') });
59
+ if (result.status !== 'created')
60
+ throw new Error(`Issue creation refused: ${JSON.stringify(result)}`);
61
+ }
62
+ else {
63
+ if (!/^[1-9][0-9]*$/.test(number ?? ''))
64
+ throw new Error(`${operation} requires a positive issue number`);
65
+ const body = value('body-file') ? await readFile(value('body-file'), 'utf8') : value('body') ?? value('reason');
66
+ if (operation === 'comment' && !body)
67
+ throw new Error('comment requires --body or --body-file');
68
+ if (body)
69
+ result = await client.repositoryRequest('POST', `/issues/${number}/comments`, { body });
70
+ if (operation === 'close')
71
+ result = await client.repositoryRequest('PATCH', `/issues/${number}`, { state: 'closed' });
72
+ }
73
+ console.log(JSON.stringify(result, null, 2));
74
+ return true;
75
+ }
76
+ //# sourceMappingURL=external-cli.js.map
@@ -1,4 +1,5 @@
1
1
  import { resolveSensitiveInput } from '../auth/sensitive-input.js';
2
+ import { checkTrackerActor } from './tracker-policy.js';
2
3
  import { isInteractive } from '../cli/env.js';
3
4
  export class LiveIssueClient {
4
5
  options;
@@ -48,6 +49,10 @@ export class LiveIssueClient {
48
49
  const comments = await this.request('GET', this.commentsPath(externalId));
49
50
  return comments.map((comment) => normalizeComment(comment));
50
51
  }
52
+ get provider() { return this.options.provider; }
53
+ repositoryRequest(method, suffix, body) {
54
+ return this.request(method, `${this.issuesPath().replace(/\/issues$/, '')}${suffix}`, body);
55
+ }
51
56
  issuesPath() {
52
57
  return `/repos/${encodeURIComponent(this.owner)}/${encodeURIComponent(this.name)}/issues`;
53
58
  }
@@ -57,7 +62,15 @@ export class LiveIssueClient {
57
62
  commentsPath(externalId) {
58
63
  return `${this.issuePath(externalId)}/comments`;
59
64
  }
65
+ async verifyActor() {
66
+ if (!this.options.actor)
67
+ return;
68
+ const user = await this.request('GET', '/user');
69
+ checkTrackerActor(this.options.actor, user.login);
70
+ }
60
71
  async request(method, path, body) {
72
+ if (method !== 'GET')
73
+ await this.verifyActor();
61
74
  const headers = {
62
75
  Accept: 'application/json',
63
76
  };
@@ -68,6 +81,7 @@ export class LiveIssueClient {
68
81
  try {
69
82
  const response = await this.fetchFn(`${this.baseUrl}${path}`, {
70
83
  method,
84
+ redirect: 'error',
71
85
  headers,
72
86
  body: body === undefined ? undefined : JSON.stringify(body),
73
87
  });
@@ -75,7 +89,10 @@ export class LiveIssueClient {
75
89
  const text = await response.text().catch(() => '');
76
90
  throw new Error(`${this.options.provider} issue API ${method} ${path} failed: ${response.status}${text ? ` ${redactSecrets(text, this.options.token)}` : ''}`);
77
91
  }
78
- const result = await response.json();
92
+ // Native HTTP responses may be empty (for example Gitea merge success).
93
+ // Preserve the injected fetch contract used by existing in-process clients.
94
+ const payload = typeof response.text === 'function' ? await response.text() : undefined;
95
+ const result = (payload === undefined ? await response.json() : payload.trim() ? JSON.parse(payload) : {});
79
96
  // A server can reflect request credentials in issue fields or comments.
80
97
  // Scrub them before they reach local storage or CLI output.
81
98
  if (!this.options.token)
@@ -0,0 +1,17 @@
1
+ import { resolveLiveIssueToken } from './live.js';
2
+ export async function trackerToken(provider, actor, source = {}, dependencies = {}) {
3
+ if (actor?.credential && Object.keys(source).some(key => key !== 'prefix')) {
4
+ throw new Error('Configured tracker_actor.credential cannot be overridden by token flags');
5
+ }
6
+ return resolveLiveIssueToken(provider, actor?.credential ?? source, dependencies);
7
+ }
8
+ export function checkTrackerActor(actor, login) {
9
+ if (typeof login !== 'string' || !login)
10
+ throw new Error('Tracker API did not identify an authenticated actor');
11
+ const normalized = login.toLowerCase();
12
+ if (actor.forbid_actors?.some(value => value.toLowerCase() === normalized))
13
+ throw new Error('Tracker actor is forbidden by remotes.tracker_actor.forbid_actors');
14
+ if (actor.login && actor.login.toLowerCase() !== normalized)
15
+ throw new Error('Tracker API user does not match remotes.tracker_actor.login');
16
+ }
17
+ //# sourceMappingURL=tracker-policy.js.map
@@ -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
+ }