@aiwg/cli 2026.11.4 → 2026.11.6
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.
- package/agentic/code/providers/capability-matrix.yaml +75 -5
- package/agentic/code/providers/model-capabilities.v1.json +44 -36
- package/bin/aiwg.mjs +6 -4
- package/dist/src/activity-log/cli.js +1 -1
- package/dist/src/agents/agent-deployer.js +1 -1
- package/dist/src/artifacts/audit/types.js +1 -1
- package/dist/src/artifacts/discover-facets.js +1 -1
- package/dist/src/artifacts/enrichment/prompt.js +1 -1
- package/dist/src/artifacts/enrichment/types.js +1 -1
- package/dist/src/artifacts/index-builder.js +4 -2
- package/dist/src/artifacts/query-engine-rules.js +2 -2
- package/dist/src/artifacts/types.js +1 -1
- package/dist/src/artifacts/views/definition.js +1 -1
- package/dist/src/artifacts/views/types.js +1 -1
- package/dist/src/catalog/cli.js +1 -1
- package/dist/src/catalog/cli.mjs +1 -1
- package/dist/src/catalog/loader.js +1 -1
- package/dist/src/catalog/loader.mjs +1 -1
- package/dist/src/catalog/types.js +1 -1
- package/dist/src/cli/cli-extension-loader.js +19 -5
- package/dist/src/cli/cli-extension-paths.js +65 -0
- package/dist/src/cli/handlers/best-practices-audit.js +1 -1
- package/dist/src/cli/handlers/help.js +3 -4
- package/dist/src/cli/handlers/index.js +1 -1
- package/dist/src/cli/handlers/marketplace-plugin-search.js +37 -0
- package/dist/src/cli/handlers/marketplace.js +3 -1
- package/dist/src/cli/handlers/models.js +1 -1
- package/dist/src/cli/handlers/ralph-launcher.js +8 -2
- package/dist/src/cli/handlers/ralph.js +1 -1
- package/dist/src/cli/handlers/runtime-info.js +1 -1
- package/dist/src/cli/handlers/scaffolding.js +2 -2
- package/dist/src/cli/handlers/script-runner.js +8 -5
- package/dist/src/cli/handlers/sdlc-accelerate.js +1 -1
- package/dist/src/cli/handlers/steward-format.js +12 -0
- package/dist/src/cli/handlers/subcommands-bundles.js +1 -1
- package/dist/src/cli/handlers/subcommands-list-format.js +19 -1
- package/dist/src/cli/handlers/types.js +1 -1
- package/dist/src/cli/handlers/use.js +15 -6
- package/dist/src/cli/handlers/utilities.js +1 -1
- package/dist/src/cli/handlers/utility-doctor.js +4 -0
- package/dist/src/cli/handlers/version.js +1 -1
- package/dist/src/cli/handlers/workspace.js +1 -1
- package/dist/src/cli/help-generator.js +9 -11
- package/dist/src/cli/hooks/builtin/activity-log-hook.js +1 -1
- package/dist/src/cli/router.js +1 -1
- package/dist/src/cli/workflow-orchestrator.js +1 -1
- package/dist/src/config/worker-context.js +37 -7
- package/dist/src/config/worker-parallelism.js +11 -0
- package/dist/src/contributors/detect.js +1 -1
- package/dist/src/contributors/discover.js +1 -1
- package/dist/src/contributors/heuristic.js +1 -1
- package/dist/src/contributors/index.js +1 -1
- package/dist/src/contributors/types.js +1 -1
- package/dist/src/contributors/validation.js +1 -1
- package/dist/src/effects/worker-delivery.js +83 -0
- package/dist/src/extensions/capability-index.js +1 -1
- package/dist/src/extensions/commands/definitions.js +2 -2
- package/dist/src/extensions/deployment-registration.js +1 -1
- package/dist/src/extensions/index.js +1 -1
- package/dist/src/extensions/loader.js +1 -1
- package/dist/src/extensions/manifest.js +10 -2
- package/dist/src/extensions/project-local-activity.js +1 -1
- package/dist/src/extensions/project-local-discovery.js +23 -3
- package/dist/src/extensions/project-local-doctor.js +7 -3
- package/dist/src/extensions/project-local-promote.js +3 -3
- package/dist/src/extensions/project-local-remove.js +3 -3
- package/dist/src/extensions/project-local-scaffold.js +20 -8
- package/dist/src/extensions/registry.js +1 -1
- package/dist/src/extensions/shadow-resolver.js +1 -1
- package/dist/src/extensions/types.js +1 -1
- package/dist/src/extensions/upstream-registry.js +1 -1
- package/dist/src/extensions/validation.js +1 -1
- package/dist/src/intake/git-history-analyzer.js +1 -1
- package/dist/src/kb/cli.js +1 -1
- package/dist/src/marketplace/plugin-directory.js +36 -0
- package/dist/src/marketplace/plugin-search.js +180 -0
- package/dist/src/mcp/cli.mjs +2 -2
- package/dist/src/mcp/helpers.mjs +1 -1
- package/dist/src/mcp/http-tools.mjs +8 -6
- package/dist/src/mcp/http-transport.mjs +3 -1
- package/dist/src/mcp/server.mjs +1 -1
- package/dist/src/mcp/tools/command-run.mjs +1 -1
- package/dist/src/mcp/tools/discovery.mjs +1 -1
- package/dist/src/mcp/tools/subsystems.mjs +1 -1
- package/dist/src/mcp/tools/worker-invoke.mjs +68 -22
- package/dist/src/mcp/tools/worker-local-only-preflight.mjs +79 -0
- package/dist/src/mcp/tools/worker-recorded-launch.mjs +26 -0
- package/dist/src/mcp/tools/worker-stdin-runtime.mjs +33 -6
- package/dist/src/mcp/tools/worker-verify-deliver-schema.mjs +33 -0
- package/dist/src/mcp/tools/worker-verify-deliver.mjs +27 -0
- package/dist/src/models/catalog-policy.js +2 -2
- package/dist/src/models/conductor-data-policy.mjs +83 -14
- package/dist/src/models/config-loader.js +2 -2
- package/dist/src/models/factory-models.js +144 -0
- package/dist/src/models/index.js +2 -2
- package/dist/src/models/local-endpoint-models.js +155 -0
- package/dist/src/models/model-capabilities.v1.json +44 -36
- package/dist/src/models/model-discovery.js +16 -8
- package/dist/src/models/opencode-worker-model.mjs +16 -0
- package/dist/src/models/resolver.js +2 -2
- package/dist/src/models/worker-installation.d.mts +2 -0
- package/dist/src/models/worker-installation.mjs +16 -5
- package/dist/src/models/worker-invocation-policy.js +25 -1
- package/dist/src/models/worker-plan.js +1 -1
- package/dist/src/models/wrapper-enforcement.js +1 -1
- package/dist/src/plugin/plugin-installer.js +2 -2
- package/dist/src/plugin/registry-validator.js +2 -2
- package/dist/src/plugin/skill-command-translator.js +1 -1
- package/dist/src/policy/repo-access.js +3 -1
- package/dist/src/providers/capability-matrix.yaml +75 -5
- package/dist/src/providers/deployment-ownership.mjs +8 -1
- package/dist/src/providers/deployment-preservation.mjs +44 -3
- package/dist/src/providers/grok-build-acp.js +13 -5
- package/dist/src/providers/grok-build-dispatch.js +35 -2
- package/dist/src/providers/grok-build-headless.js +2 -1
- package/dist/src/rlm/cache/hash.js +1 -1
- package/dist/src/rlm/cache/store.js +1 -1
- package/dist/src/rlm/cache/types.js +1 -1
- package/dist/src/serve/worker-invocation-preparation.js +13 -0
- package/dist/src/serve/worker-invocation.js +21 -6
- package/dist/src/serve/worker-stdin-frame.mjs +1 -1
- package/dist/src/sessions/adapters/grok-build-native-records.js +77 -7
- package/dist/src/sessions/adapters/grok-build-native.js +148 -1
- package/dist/src/sessions/adapters/grok-build.js +36 -14
- package/dist/src/sessions/normalization.js +1 -1
- package/dist/src/skills/run.js +0 -11
- package/dist/src/smiths/agentsmith/generator.js +1 -1
- package/dist/src/smiths/context-pipeline/index.js +1 -1
- package/dist/src/smiths/context-pipeline/provider-policy.js +1 -1
- package/dist/src/smiths/context-pipeline/types.js +1 -1
- package/dist/src/smiths/context-pipeline/workspace-doctor.js +4 -0
- package/dist/src/smiths/hook-bridge/factory-trust.js +2 -2
- package/dist/src/smiths/hook-bridge/hermes-prompt-discovery.js +10 -7
- package/dist/src/smiths/hook-bridge/hermes-trust.js +65 -0
- package/dist/src/smiths/mcpsmith/analyzers/cli-analyzer.js +2 -2
- package/dist/src/smiths/mcpsmith/generator.js +2 -2
- package/dist/src/smiths/mcpsmith/index.js +2 -2
- package/dist/src/smiths/mcpsmith/types.js +2 -2
- package/dist/src/smiths/skillsmith/collision-detector.js +1 -1
- package/dist/src/smiths/skillsmith/namespace-adapter.js +1 -1
- package/dist/src/smiths/toolsmith/runtime-discovery.mjs +2 -2
- package/dist/src/smiths/toolsmith/types.js +2 -2
- package/dist/src/storage/backends/fortemi.js +1 -1
- package/dist/src/storage/backends/fs.js +1 -1
- package/dist/src/storage/backends/logseq.js +1 -1
- package/dist/src/storage/backends/obsidian.js +1 -1
- package/dist/src/storage/cli.js +2 -2
- package/dist/src/storage/config.js +1 -1
- package/dist/src/storage/index.js +1 -1
- package/dist/src/storage/subsystem-cli.js +1 -1
- package/dist/src/storage/types.js +1 -1
- package/dist/src/testing/generators/test-case-generator.js +1 -1
- package/dist/src/writing/validation-engine.js +1 -1
- package/package.json +11 -1
- package/schemas/models/model-catalog.v1.schema.json +6 -3
- package/tools/agents/deploy-agents.mjs +4 -2
- package/tools/agents/deploy-options.mjs +2 -0
- package/tools/agents/providers/base-inventory.mjs +3 -1
- package/tools/agents/providers/base-kernel-skills.mjs +11 -5
- package/tools/agents/providers/conductor-data-guard.mjs +1 -1
- package/tools/agents/providers/grok-build.mjs +31 -40
- package/tools/agents/providers/model-wrapper.mjs +2 -5
- package/tools/agents/providers/rule-deployment-commit.mjs +3 -0
- package/tools/agents/providers/rule-deployment-prepare.mjs +2 -2
- package/tools/agents/providers/rule-projection.mjs +39 -4
- package/tools/agents/providers/skill-copy-prune.mjs +12 -0
- package/tools/agents/providers/stale-artifact-prune.mjs +24 -10
- package/tools/ralph-external/lib/claude-adapter.mjs +2 -0
- package/tools/ralph-external/lib/factory-adapter.mjs +6 -2
- package/tools/ralph-external/lib/mcp-worker-launch.mjs +67 -0
- package/tools/ralph-external/lib/opencode-adapter.mjs +9 -7
- package/tools/ralph-external/lib/trusted-verification.mjs +1021 -0
- package/tools/ralph-external/lib/typed-stop-delivery.mjs +46 -0
- package/tools/ralph-external/lib/verification-isolation.mjs +509 -0
- package/tools/ralph-external/lib/worker-context.mjs +3 -3
- package/tools/ralph-external/lib/worker-delivery-guards.mjs +95 -0
- package/tools/ralph-external/lib/worker-delivery-record.mjs +15 -0
- package/tools/ralph-external/lib/worker-final.mjs +4 -1
- package/tools/ralph-external/lib/worker-inputs.mjs +20 -1
- package/tools/ralph-external/lib/worker-isolation-status.mjs +3 -0
- package/tools/ralph-external/lib/worker-isolation.mjs +1 -0
- package/tools/ralph-external/lib/worker-launch-cli.mjs +8 -0
- package/tools/ralph-external/lib/worker-local-only-paths.mjs +45 -0
- package/tools/ralph-external/lib/worker-prompt.mjs +4 -1
- package/tools/ralph-external/lib/worker-retry-evidence.mjs +2 -1
- package/tools/ralph-external/lib/worker-run-directory.mjs +45 -0
- package/tools/ralph-external/lib/worker-termination.mjs +21 -12
- package/tools/ralph-external/lib/worker-unit-cleanup.mjs +10 -2
- package/tools/ralph-external/lib/worker-verification-cli.mjs +164 -0
- package/tools/ralph-external/lib/worktree-preparation.mjs +417 -0
- package/tools/ralph-external/session-launcher.mjs +30 -32
- package/vscode-extension/schemas/aiwg.config.v1.json +27 -0
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// Refuse dispatch when a prepared worker tree exposes declared local-only inputs.
|
|
2
|
+
import { stat, realpath, readdir } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { collectLocalOnlyPaths } from '../../models/conductor-data-policy.mjs';
|
|
5
|
+
|
|
6
|
+
const contains = (base, file) => {
|
|
7
|
+
const relative = path.relative(base, file);
|
|
8
|
+
return relative === '' || relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
|
|
9
|
+
};
|
|
10
|
+
async function existing(file) {
|
|
11
|
+
try {
|
|
12
|
+
const info = await stat(file);
|
|
13
|
+
return info.isFile() || info.isDirectory() ? await realpath(file) : null;
|
|
14
|
+
} catch (error) {
|
|
15
|
+
if (error.code === 'ENOENT' || error.code === 'ENOTDIR') return null;
|
|
16
|
+
throw error;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Enumerate aliases without traversing their targets or opening any file contents.
|
|
21
|
+
async function symlinkTargets(tree) {
|
|
22
|
+
const targets = [], pending = [tree];
|
|
23
|
+
while (pending.length) {
|
|
24
|
+
const directory = pending.pop();
|
|
25
|
+
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
|
26
|
+
const file = path.join(directory, entry.name);
|
|
27
|
+
if (entry.isDirectory()) pending.push(file);
|
|
28
|
+
else if (entry.isSymbolicLink()) {
|
|
29
|
+
const target = await existing(file);
|
|
30
|
+
if (target) targets.push(target);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return targets;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function workerLocalOnlyPreflight({ root, snapshot, invocation, drivers }) {
|
|
38
|
+
const paths = collectLocalOnlyPaths(snapshot.models.defaults.workerSelection, snapshot.config.parallelism);
|
|
39
|
+
if (!paths.length) return null;
|
|
40
|
+
const selected = invocation.selected;
|
|
41
|
+
const rows = snapshot.catalog.discovery?.instances?.[selected.cli]?.models ?? [];
|
|
42
|
+
const observation = rows.find(row => (row.id === selected.model || row.apiModelId === selected.model)
|
|
43
|
+
&& row.llmProvider === selected.inferenceProvider)?.worker;
|
|
44
|
+
// Locality is an observed execution-path fact, never inferred from a CLI or class name.
|
|
45
|
+
if (observation?.qualification?.status === 'qualified' && observation.dataUse?.processing === 'local') return null;
|
|
46
|
+
const trees = [invocation.cwd];
|
|
47
|
+
if (invocation.transport === 'mcp') {
|
|
48
|
+
const server = await drivers[selected.cli]?.mcpRegistry?.get(invocation.mcp.serverRef);
|
|
49
|
+
if (server?.cwd) trees.push(server.cwd);
|
|
50
|
+
}
|
|
51
|
+
const exposed = [], protectedTargets = new Map();
|
|
52
|
+
const planned = (invocation.artifacts ?? []).filter(artifact => artifact.location === 'workspace-relative')
|
|
53
|
+
.map(artifact => path.resolve(invocation.cwd, artifact.relativePath));
|
|
54
|
+
for (const file of paths) {
|
|
55
|
+
const projectPath = path.resolve(root, file);
|
|
56
|
+
const projectTarget = await existing(projectPath);
|
|
57
|
+
if (projectTarget) protectedTargets.set(file, projectTarget);
|
|
58
|
+
for (const tree of new Set(trees)) {
|
|
59
|
+
const canonicalTree = await realpath(tree);
|
|
60
|
+
// Check project-relative copies as well as a workdir inside a protected subtree.
|
|
61
|
+
if (await existing(path.resolve(tree, file))
|
|
62
|
+
|| planned.some(target => contains(path.resolve(tree, file), target)) || projectTarget && (
|
|
63
|
+
contains(tree, projectPath) || contains(projectPath, tree)
|
|
64
|
+
|| contains(canonicalTree, projectTarget) || contains(projectTarget, canonicalTree))) {
|
|
65
|
+
exposed.push(file);
|
|
66
|
+
break;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if ([...protectedTargets.keys()].some(file => !exposed.includes(file))) {
|
|
71
|
+
for (const tree of new Set(trees)) for (const target of await symlinkTargets(tree)) {
|
|
72
|
+
for (const [file, protectedTarget] of protectedTargets) {
|
|
73
|
+
if (!exposed.includes(file) && (contains(target, protectedTarget) || contains(protectedTarget, target))) exposed.push(file);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return exposed.length ? { code: 'LOCAL_ONLY_PATH_EXPOSED', paths: exposed.sort(),
|
|
78
|
+
message: `Worker tree exposes local-only paths to a tuple without qualified local processing: ${exposed.sort().join(', ')}; remove them from the worker tree before launch, use a worker with qualified local processing, or deny the task` } : null;
|
|
79
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// Bind resolved MCP shell requests to the installed launcher's capture owner.
|
|
2
|
+
export function recordedShellLauncher({ loadRalphExternal, loadInputs, assertPath, registry, now }) {
|
|
3
|
+
const requests = new WeakMap();
|
|
4
|
+
return {
|
|
5
|
+
async bindPlan(plan, { resolve, snapshot, drivers, at, invocationId, input }) {
|
|
6
|
+
if (plan.invocation?.readiness !== 'launchable'
|
|
7
|
+
|| (plan.invocation.isolation !== 'native-sandbox' && input.run_dir === undefined)) return plan;
|
|
8
|
+
return resolve(snapshot, plan.request, drivers, at, { digests: plan.digests,
|
|
9
|
+
briefDigest: plan.invocation.briefDigest, invocationId });
|
|
10
|
+
},
|
|
11
|
+
requested(invocation) { return invocation.isolation === 'native-sandbox' || requests.get(invocation)?.input.run_dir !== undefined; },
|
|
12
|
+
prepare(invocation, request) { requests.set(invocation, request); },
|
|
13
|
+
async launch(invocation, options) {
|
|
14
|
+
const request = requests.get(invocation);
|
|
15
|
+
try {
|
|
16
|
+
const runDir = request.input.run_dir && await assertPath(request.input.run_dir);
|
|
17
|
+
const { launchMcpShellWorker } = await loadRalphExternal('lib/mcp-worker-launch.mjs');
|
|
18
|
+
return await launchMcpShellWorker(invocation, { ...options, ...request, runDir, loadInputs, now,
|
|
19
|
+
onRunDir: run_dir => registry.update(request.invocationId, { run_dir }) });
|
|
20
|
+
} catch (error) {
|
|
21
|
+
if (!error.launchAttempted) error.workerNotLaunched = true;
|
|
22
|
+
throw error;
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Prepare worker stdin and internal attribution for shell and spawned MCP transports.
|
|
2
2
|
import { directWorkerEnvironment } from '../../config/worker-attribution.mjs';
|
|
3
|
-
import { createHash } from 'node:crypto';
|
|
3
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
4
4
|
import { mkdtemp, mkdir, writeFile, rm, readdir, lstat } from 'node:fs/promises';
|
|
5
5
|
import { tmpdir } from 'node:os';
|
|
6
6
|
import path from 'node:path';
|
|
@@ -60,29 +60,56 @@ export async function launchPreparedShellWorker(invocation, { allowDegraded, con
|
|
|
60
60
|
throw new Error('Worker prompt digest changed');
|
|
61
61
|
}
|
|
62
62
|
const { workerStdinBytes } = await importImpl('serve/worker-stdin-frame.mjs');
|
|
63
|
+
// Same final-output contract the launcher adds (#4156): stdin profiles get the wrapped brief, and
|
|
64
|
+
// file-based profiles get a derived brief through the launcher's own artifact materializer.
|
|
65
|
+
const { workerPromptBrief } = await loadRalphExternal('lib/worker-prompt.mjs');
|
|
66
|
+
if (invocation.stdin === 'closed' && (invocation.argv ?? []).includes(invocation.briefPath)) {
|
|
67
|
+
const { materializeWorkerArtifacts } = await loadRalphExternal('lib/worker-artifacts.mjs');
|
|
68
|
+
// The materializer needs its quarantine outside the worker tree but on the same filesystem
|
|
69
|
+
// (atomic rename; /tmp is often a separate tmpfs), so it sits beside the worker tree.
|
|
70
|
+
const artifactRoot = await mkdtemp(path.join(path.dirname(invocation.cwd), '.aiwg-worker-artifacts-'));
|
|
71
|
+
cleanup = () => rm(artifactRoot, { recursive: true, force: true });
|
|
72
|
+
const materialized = await materializeWorkerArtifacts(invocation, artifactRoot,
|
|
73
|
+
{ brief, invocationId: invocationId ?? invocation.invocationId ?? randomUUID() });
|
|
74
|
+
invocation = { ...invocation, argv: materialized.argv };
|
|
75
|
+
}
|
|
63
76
|
let stdinPath;
|
|
64
|
-
const bytes = workerStdinBytes(invocation, brief, driver);
|
|
77
|
+
const bytes = workerStdinBytes(invocation, workerPromptBrief(brief, invocation.finalPath), driver);
|
|
65
78
|
if (bytes !== null) {
|
|
66
|
-
|
|
79
|
+
const artifactCleanup = cleanup;
|
|
80
|
+
const prepared = await prepareWorkerStdin(bytes, stdinRuntimeRoot);
|
|
81
|
+
stdinPath = prepared.stdinPath;
|
|
82
|
+
cleanup = () => Promise.all([prepared.cleanup(), artifactCleanup()]);
|
|
67
83
|
}
|
|
68
84
|
const markers = directWorkerEnvironment({ ...invocation, ...(invocationId ? { invocationId } : {}) });
|
|
69
85
|
const launch = await planDirectWorkerLaunch({ invocation, config, allowDegraded, name, live, readers,
|
|
70
86
|
env: { ...Object.fromEntries((invocation.envNames ?? []).filter(name => process.env[name] !== undefined)
|
|
71
87
|
.map(name => [name, process.env[name]])), ...markers },
|
|
72
88
|
envNames: [...new Set([...(invocation.envNames ?? []), ...Object.keys(markers)])],
|
|
73
|
-
thresholdOverlay, memoryMaxGb, stdinPath, ownedGroup: true,
|
|
89
|
+
thresholdOverlay, memoryMaxGb, stdinPath, ownedGroup: true,
|
|
90
|
+
isolation: invocation.isolation === 'native-sandbox' ? { mode: 'native-sandbox' } : isolation,
|
|
91
|
+
...(invocation.isolation === 'native-sandbox' ? { attached: true, stdin: bytes === null ? 'closed' : 'open' } : {}),
|
|
92
|
+
admission, invocationId, dispatchGuard,
|
|
74
93
|
spawn, spawnAsync, onSpawnAttempt: value => {
|
|
75
94
|
attempt = value;
|
|
76
95
|
value.child?.once('close', (exitCode, signalCode) => { Object.assign(value, { closed: true, exitCode, signalCode }); });
|
|
77
96
|
},
|
|
78
97
|
});
|
|
98
|
+
if (launch.mode === 'native-sandbox' && launch.child) {
|
|
99
|
+
// The native CLI owns its sandbox; the existing owned-group wrapper
|
|
100
|
+
// supplies stdin and stop authority outside the conductor unit.
|
|
101
|
+
launch.child.stdout?.resume();
|
|
102
|
+
launch.child.stderr?.resume();
|
|
103
|
+
launch.child.stdin?.on('error', () => {});
|
|
104
|
+
launch.child.stdin?.end(bytes ?? undefined);
|
|
105
|
+
}
|
|
79
106
|
const launchAttempted = !!(attempt?.unit || attempt?.pid);
|
|
80
107
|
if (!launch.launched && !launchAttempted) await cleanup();
|
|
81
|
-
return { ...launch, launchAttempted, spawnObservation: attempt, ownedGroup: launch.mode
|
|
108
|
+
return { ...launch, launchAttempted, spawnObservation: attempt, ownedGroup: ['degraded', 'native-sandbox'].includes(launch.mode) && !!launch.pid, cleanup,
|
|
82
109
|
diagnostic: launch.diagnostic ?? describeGateFailures(launch.failures) };
|
|
83
110
|
} catch (error) {
|
|
84
111
|
if (attempt?.unit || attempt?.pid) {
|
|
85
|
-
return { ...attempt, spawnObservation: attempt, ownedGroup:
|
|
112
|
+
return { ...attempt, spawnObservation: attempt, ownedGroup: ['degraded', 'native-sandbox'].includes(attempt.mode), launched: false, launchAttempted: true, cleanup, diagnostic: error.message };
|
|
86
113
|
}
|
|
87
114
|
error.workerNotLaunched = true;
|
|
88
115
|
await cleanup();
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// Own the two mutually exclusive publication request shapes.
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
|
|
4
|
+
const absolute = z.string().startsWith('/').max(4096).refine(value => !value.includes('\0'));
|
|
5
|
+
const check = z.strictObject({
|
|
6
|
+
id: z.string().min(1).max(256), command: absolute,
|
|
7
|
+
args: z.array(z.string().max(65536).refine(value => !value.includes('\0'))).max(256).optional(),
|
|
8
|
+
cwd: absolute.optional(),
|
|
9
|
+
envNames: z.array(z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/)).max(128).optional(),
|
|
10
|
+
timeoutMs: z.number().int().positive().max(86400000).optional(),
|
|
11
|
+
});
|
|
12
|
+
export const typedStopSchema = z.strictObject({
|
|
13
|
+
status: z.enum(['denied', 'blocked']),
|
|
14
|
+
code: z.string().regex(/^[A-Z][A-Z0-9_]{2,63}$/),
|
|
15
|
+
blocking_rule: z.string().min(1).max(2000).refine(value => value.trim().length > 0),
|
|
16
|
+
launch_count: z.literal(0),
|
|
17
|
+
uncertainty_statement: z.string().max(4000).optional(),
|
|
18
|
+
reason: z.string().max(4000).optional(),
|
|
19
|
+
});
|
|
20
|
+
export const typedStopDeliverySchema = z.strictObject({ deliverablePath: absolute, typedStop: typedStopSchema });
|
|
21
|
+
export const publicationSchema = z.union([
|
|
22
|
+
z.strictObject({ run_dir: absolute, artifact_path: absolute.optional(), deliverable_path: absolute, checks: z.array(check).min(1).max(32) }),
|
|
23
|
+
z.strictObject({ deliverable_path: absolute, typed_stop: typedStopSchema }),
|
|
24
|
+
]);
|
|
25
|
+
|
|
26
|
+
// The SDK advertises only object schemas. Preserve the strict union in both
|
|
27
|
+
// its advertised JSON Schema and validation, with a stable refusal code.
|
|
28
|
+
export const publicationInputSchema = z.looseObject({}).superRefine((input, context) => {
|
|
29
|
+
const parsed = publicationSchema.safeParse(input);
|
|
30
|
+
if (!parsed.success) context.addIssue({ code: 'custom', message: `TYPED_STOP_INVALID: ${parsed.error.message}` });
|
|
31
|
+
}).meta({ anyOf: z.toJSONSchema(publicationSchema).anyOf });
|
|
32
|
+
|
|
33
|
+
export const invalidTypedStop = message => Object.assign(new Error(`TYPED_STOP_INVALID: ${message}`), { code: 'TYPED_STOP_INVALID' });
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// Narrow workers-toolset adapter: protected checks and publication share one verifier call.
|
|
2
|
+
import { mcpError, mcpJson } from '../helpers.mjs';
|
|
3
|
+
import { publicationInputSchema, publicationSchema, invalidTypedStop } from './worker-verify-deliver-schema.mjs';
|
|
4
|
+
|
|
5
|
+
export function registerWorkerVerifyDeliverTool(server, { projectRoot, assertPath, verify }) {
|
|
6
|
+
server.registerTool('worker-verify-deliver', {
|
|
7
|
+
title: 'Verify and Deliver a Worker Artifact or Typed Stop',
|
|
8
|
+
description: 'Publish a checked stopped-worker artifact, or a typed denied/blocked stop with launch_count 0 and no run_dir/artifact_path/checks. Both produce signed delivery records. The server must run outside conductor confinement.',
|
|
9
|
+
inputSchema: publicationInputSchema,
|
|
10
|
+
annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false },
|
|
11
|
+
}, async input => {
|
|
12
|
+
try {
|
|
13
|
+
const parsed = publicationSchema.safeParse(input);
|
|
14
|
+
if (!parsed.success) throw invalidTypedStop(parsed.error.message);
|
|
15
|
+
const request = parsed.data;
|
|
16
|
+
const deliverablePath = await assertPath(request.deliverable_path);
|
|
17
|
+
if ('typed_stop' in request) return mcpJson(await verify({ projectDir: projectRoot, deliverablePath, typedStop: request.typed_stop }));
|
|
18
|
+
if (new Set(request.checks.map(entry => entry.id)).size !== request.checks.length) throw new Error('Protected check IDs must be unique');
|
|
19
|
+
const runDir = await assertPath(request.run_dir);
|
|
20
|
+
const artifactPath = request.artifact_path && await assertPath(request.artifact_path);
|
|
21
|
+
return mcpJson(await verify({ projectDir: projectRoot, runDir, artifactPath, deliverablePath, checks: request.checks }));
|
|
22
|
+
} catch (error) {
|
|
23
|
+
if (error.code === 'TYPED_STOP_INVALID') return { ...mcpJson({ status: 'rejected', errorCode: error.code, code: error.code, findings: [error.message] }), isError: true };
|
|
24
|
+
return mcpError(`worker-verify-deliver: ${error.message}`);
|
|
25
|
+
}
|
|
26
|
+
});
|
|
27
|
+
}
|
|
@@ -46,12 +46,12 @@ const DiscoveredWorkerModelSchema = z.looseObject({
|
|
|
46
46
|
context.addIssue({ code: 'custom', path: ['worker', 'efforts'], message: 'Conflicting effort evidence' });
|
|
47
47
|
});
|
|
48
48
|
const ProviderDiscoverySchema = z.looseObject({
|
|
49
|
-
provider: z.string(), source: z.enum(['native', 'cache', 'remote', 'static']), observedAt: dateTime({ offset: true }),
|
|
49
|
+
provider: z.string(), source: z.enum(['native', 'cache', 'remote', 'static', 'local-endpoint']), observedAt: dateTime({ offset: true }),
|
|
50
50
|
runtimeVersion: z.string().optional(), accountScope: z.enum(['local-account', 'local-runtime', 'public-feed', 'static']),
|
|
51
51
|
accountBinding: z.string().min(1).optional(), models: z.array(DiscoveredWorkerModelSchema),
|
|
52
52
|
});
|
|
53
53
|
const DiscoverySchema = z.strictObject({
|
|
54
|
-
source: z.enum(['native', 'cache', 'remote', 'static']), upstreamSource: z.enum(['native', 'remote', 'static']).optional(),
|
|
54
|
+
source: z.enum(['native', 'cache', 'remote', 'static', 'local-endpoint']), upstreamSource: z.enum(['native', 'remote', 'static', 'local-endpoint']).optional(),
|
|
55
55
|
fetchedAt: dateTime({ offset: true }), remoteUrl: url().optional(), remoteError: z.string().optional(),
|
|
56
56
|
inventorySignature: z.string().optional(), providers: z.record(z.string(), ProviderDiscoverySchema),
|
|
57
57
|
instances: z.record(z.string(), ProviderDiscoverySchema).optional(),
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Refuse local-only reads and
|
|
1
|
+
// Refuse local-only reads and unverified worker execution/integration by the conductor.
|
|
2
2
|
import { realpathSync, readFileSync, readdirSync, statSync } from 'node:fs';
|
|
3
3
|
import { resolve, dirname, relative, isAbsolute, sep, matchesGlob, basename } from 'node:path';
|
|
4
4
|
|
|
@@ -27,7 +27,7 @@ const contains = (base, file) => relative(base, file) === ''
|
|
|
27
27
|
|
|
28
28
|
// Retain quoting for glob characters, but never execute shell expansions or substitutions.
|
|
29
29
|
const literalPattern = value => value.replace(/[*?\[\]{}()!+@]/g, char => char === ']' ? ']' : `[${char}]`);
|
|
30
|
-
function shellCommands(command) {
|
|
30
|
+
function shellCommands(command, retainTransfers = false) {
|
|
31
31
|
const commands = [];
|
|
32
32
|
let words = [], value = '', pattern = '', glob = false, quote = null;
|
|
33
33
|
const word = () => {
|
|
@@ -50,7 +50,14 @@ function shellCommands(command) {
|
|
|
50
50
|
if (char === quote) quote = null;
|
|
51
51
|
else append(char, false);
|
|
52
52
|
} else if (char === "'" || char === '"') quote = char;
|
|
53
|
-
else if (/[
|
|
53
|
+
else if (retainTransfers && /[|<>]/.test(char)) {
|
|
54
|
+
word();
|
|
55
|
+
let operator = char;
|
|
56
|
+
if (command[index + 1] === char) operator += command[++index];
|
|
57
|
+
// `2>&1` / `<&3` duplicate a descriptor; the following word is a descriptor, not a path.
|
|
58
|
+
else if (/[<>]/.test(char) && command[index + 1] === '&') operator += command[++index];
|
|
59
|
+
words.push({ value: operator, operator: true });
|
|
60
|
+
} else if (/[;&|<>()`\n]/.test(char)) end();
|
|
54
61
|
else if (/\s/.test(char)) word();
|
|
55
62
|
else append(char, true);
|
|
56
63
|
}
|
|
@@ -166,14 +173,50 @@ export function conductorWorkerTrees(root) {
|
|
|
166
173
|
}
|
|
167
174
|
|
|
168
175
|
const workerExecutionDenial = 'AIWG: conductor must not execute or import worker-written code; use aiwg ralph-external --verify-worker instead';
|
|
176
|
+
const workerIntegrationDenial = 'AIWG: conductor must not integrate unverified worker bytes, execute or import worker-written code, or edit worker paths; use aiwg ralph-external --verify-worker --run-dir ABS_DIR --artifact ABS_FILE --check JSON --deliverable ABS_FILE. Only accepted bytes are delivered; blocked/rejected results never authorize integration. Shell coverage is limited; Write/Edit content copied from a Read is not detected.';
|
|
169
177
|
const runtime = /^(?:node(?:js)?|python(?:\d+(?:\.\d+)*)?|npm|npx|pnpm|yarn|bun|deno|vitest|jest|pytest|py\.test|mocha|ava|tap|tsx|ts-node|make|cmake|ctest|cargo|go|ruby|perl|php|java)$/;
|
|
170
178
|
const shells = new Set(['sh', 'bash', 'dash', 'zsh']);
|
|
171
179
|
const wrappers = new Set(['env', 'nice', 'timeout', 'systemd-run', 'sudo', 'command', 'exec', 'nohup']);
|
|
172
180
|
const wrapperValues = new Set(['-n', '--adjustment', '-p', '--property', '-u', '--user', '-g', '--group',
|
|
173
181
|
'-C', '--chdir', '--working-directory', '--unit', '--description', '--slice', '--kill-after', '-k', '-s', '--signal']);
|
|
174
182
|
|
|
183
|
+
// Recognize transfer operands without interpreting expansions or running worker code.
|
|
184
|
+
function transferPaths(args) {
|
|
185
|
+
const operands = [];
|
|
186
|
+
let target, options = true;
|
|
187
|
+
for (let i = 0; i < args.length; i++) {
|
|
188
|
+
const arg = args[i];
|
|
189
|
+
if (options && arg === '--') { options = false; continue; }
|
|
190
|
+
if (options && arg.startsWith('-')) {
|
|
191
|
+
const [option, assigned] = arg.split('=');
|
|
192
|
+
if (['-t', '--target-directory'].includes(option)) target = assigned ?? args[++i];
|
|
193
|
+
else if (['-m', '--mode', '-o', '--owner', '-g', '--group', '--suffix', '-S', '-e', '--rsh', '--exclude', '--include'].includes(option)
|
|
194
|
+
&& assigned === undefined) i++;
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
operands.push(arg);
|
|
198
|
+
}
|
|
199
|
+
return { sources: target ? operands : operands.slice(0, -1), destination: target ?? operands.at(-1) };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// Preserve command boundaries for execution checks and carry data only across pipes.
|
|
203
|
+
function transferCommands(command) {
|
|
204
|
+
const result = [];
|
|
205
|
+
for (const group of shellCommands(command, true)) {
|
|
206
|
+
let words = [];
|
|
207
|
+
for (const token of group) {
|
|
208
|
+
if (token.operator && ['|', '||'].includes(token.value)) {
|
|
209
|
+
if (words.length) result.push({ words, pipe: token.value === '|' });
|
|
210
|
+
words = [];
|
|
211
|
+
} else words.push(token);
|
|
212
|
+
}
|
|
213
|
+
if (words.length) result.push({ words, pipe: false });
|
|
214
|
+
}
|
|
215
|
+
return result;
|
|
216
|
+
}
|
|
217
|
+
|
|
175
218
|
function workerExecution(command, initialCwd, trees, depth = 0) {
|
|
176
|
-
if (depth > 4) return
|
|
219
|
+
if (depth > 4) return workerExecutionDenial;
|
|
177
220
|
const protectedTrees = trees.flatMap(tree => [resolve(tree), canonical(resolve(tree))]);
|
|
178
221
|
const copies = [];
|
|
179
222
|
let cwd = initialCwd;
|
|
@@ -183,7 +226,8 @@ function workerExecution(command, initialCwd, trees, depth = 0) {
|
|
|
183
226
|
};
|
|
184
227
|
const references = value => (value.match(/[^\s"'`;&|<>()\[\]{},]+/g) ?? [])
|
|
185
228
|
.some(token => untrusted(token.split('=').at(-1)));
|
|
186
|
-
|
|
229
|
+
let pipedSource = false;
|
|
230
|
+
for (const { words, pipe } of transferCommands(command)) {
|
|
187
231
|
let index = 0;
|
|
188
232
|
while (/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[index]?.value ?? '')) index++;
|
|
189
233
|
let name = basename(words[index]?.value ?? '');
|
|
@@ -206,30 +250,49 @@ function workerExecution(command, initialCwd, trees, depth = 0) {
|
|
|
206
250
|
name = basename(words[index]?.value ?? '');
|
|
207
251
|
}
|
|
208
252
|
const args = words.slice(index + 1).map(word => word.value);
|
|
253
|
+
// AIWG's own output (resolve plans, status JSON) is product output even when its
|
|
254
|
+
// arguments name worker-tree paths; only worker file bytes are transfer sources (#4122).
|
|
255
|
+
// The command name and option flags are not paths, even when cwd is inside a worker tree.
|
|
256
|
+
const workerSource = name !== 'aiwg' && (pipedSource || words.some((word, cursor) => !word.operator
|
|
257
|
+
&& cursor > index && !word.value.startsWith('-')
|
|
258
|
+
&& (untrusted(word.value) || globReferences(word, cwd, protectedTrees))
|
|
259
|
+
&& !['>', '>>', '>&', '<&'].includes(words[cursor - 1]?.value)
|
|
260
|
+
&& !(/^\d+$/.test(word.value) && /^[<>]/.test(words[cursor + 1]?.value ?? ''))));
|
|
261
|
+
pipedSource = pipe && workerSource;
|
|
209
262
|
if (name === 'cd') {
|
|
210
263
|
const target = args.find(arg => arg !== '--' && arg !== '-P' && arg !== '-L');
|
|
211
264
|
if (target) cwd = resolve(cwd, target);
|
|
212
265
|
continue;
|
|
213
266
|
}
|
|
214
|
-
if (['cp', 'mv', 'install'].includes(name)) {
|
|
215
|
-
const
|
|
216
|
-
|
|
217
|
-
|
|
267
|
+
if (['cp', 'mv', 'install', 'rsync'].includes(name)) {
|
|
268
|
+
const { sources, destination } = transferPaths(args);
|
|
269
|
+
// Globs and directory operands cannot establish an accepted single-file digest.
|
|
270
|
+
if (destination && !untrusted(destination) && (workerSource || sources.some(source =>
|
|
271
|
+
protectedTrees.some(tree => contains(canonical(resolve(cwd, source)), tree))))) return workerIntegrationDenial;
|
|
272
|
+
for (const source of sources) if (destination && untrusted(source)) {
|
|
218
273
|
copies.push(resolve(cwd, destination), resolve(cwd, destination, basename(source)));
|
|
219
274
|
}
|
|
220
275
|
continue;
|
|
221
276
|
}
|
|
222
|
-
|
|
277
|
+
// Keep a pipeline together so `cat worker | tee dest` and input redirection
|
|
278
|
+
// carry the worker source through to the destination. Never inspect contents.
|
|
279
|
+
const output = words.some((word, cursor) => ['>', '>>'].includes(word.value)
|
|
280
|
+
&& words[cursor + 1] && !untrusted(words[cursor + 1].value));
|
|
281
|
+
const tee = name === 'tee' && words.slice(index + 1)
|
|
282
|
+
.some(arg => !arg.operator && !arg.value.startsWith('-') && !untrusted(arg.value));
|
|
283
|
+
if (workerSource && (output || tee) && !(name === 'aiwg' && args.includes('--verify-worker'))) return workerIntegrationDenial;
|
|
284
|
+
if (words[index]?.value.includes('/') && untrusted(words[index].value)) return workerExecutionDenial;
|
|
223
285
|
if (shells.has(name)) {
|
|
224
286
|
const inline = args.findIndex(arg => /^-[^-]*c/.test(arg));
|
|
225
287
|
if (inline >= 0 && args[inline + 1] !== undefined) {
|
|
226
|
-
|
|
288
|
+
const reason = workerExecution(args[inline + 1], cwd, [...protectedTrees, ...copies], depth + 1);
|
|
289
|
+
if (reason) return reason;
|
|
227
290
|
continue;
|
|
228
291
|
}
|
|
229
292
|
}
|
|
230
|
-
if ((runtime.test(name) || shells.has(name)) && (untrusted('.') || words.some(word => references(word.value)))) return
|
|
293
|
+
if ((runtime.test(name) || shells.has(name)) && (untrusted('.') || words.some(word => references(word.value)))) return workerExecutionDenial;
|
|
231
294
|
}
|
|
232
|
-
return
|
|
295
|
+
return null;
|
|
233
296
|
}
|
|
234
297
|
|
|
235
298
|
export function conductorToolDenial(event, root, paths, workerTrees = conductorWorkerTrees(root)) {
|
|
@@ -242,8 +305,14 @@ export function conductorToolDenial(event, root, paths, workerTrees = conductorW
|
|
|
242
305
|
return protectedPaths.some(base => contains(base, file) || contains(base, canonical(file)));
|
|
243
306
|
};
|
|
244
307
|
if ([input.file_path, input.path].some(denied)) return 'AIWG: local-only task input is unavailable to this conductor';
|
|
308
|
+
if (workerTrees.length && ['Write', 'Edit', 'MultiEdit'].includes(event.tool_name)
|
|
309
|
+
&& [input.file_path, input.path].some(candidate => typeof candidate === 'string'
|
|
310
|
+
&& workerTrees.some(tree => contains(canonical(resolve(tree)), canonical(resolve(cwd, candidate)))
|
|
311
|
+
// Rule 9: the conductor writes the worker brief under the worker tree's .handoff/ before launch.
|
|
312
|
+
&& !contains(canonical(resolve(tree, '.handoff')), canonical(resolve(cwd, candidate)))))) return workerIntegrationDenial;
|
|
245
313
|
if (typeof input.command === 'string') {
|
|
246
|
-
|
|
314
|
+
const reason = workerTrees.length && workerExecution(input.command, cwd, workerTrees);
|
|
315
|
+
if (reason) return reason;
|
|
247
316
|
// Covers literal/quoted paths, compound commands and common redirections. This is
|
|
248
317
|
// deliberately conservative, not a shell interpreter or a filesystem sandbox.
|
|
249
318
|
const command = input.command;
|
|
@@ -3,8 +3,8 @@ import { workerDispatchBlocked, isWorkerMaintenance, workerRecoveryDiagnostic }
|
|
|
3
3
|
* Model Configuration Loader
|
|
4
4
|
* Loads and merges model configurations from multiple sources with proper precedence
|
|
5
5
|
*
|
|
6
|
-
* @implements
|
|
7
|
-
* @architecture
|
|
6
|
+
* @implements @docs/models/supported-models.md
|
|
7
|
+
* @architecture @docs/models/supported-models.md
|
|
8
8
|
*/
|
|
9
9
|
import { readFile } from 'fs/promises';
|
|
10
10
|
import { dirname, resolve } from 'path';
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/** Discover Droid's configured BYOK selectors without retaining credential fields. */
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { open } from 'node:fs/promises';
|
|
4
|
+
import { homedir, tmpdir } from 'node:os';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { readAiwgConfig } from '../config/aiwg-config.js';
|
|
7
|
+
import { buildWorkerObservation, discoveryDigest, runModelDiscoveryCommand } from './model-discovery.js';
|
|
8
|
+
const MAX_CONFIG_BYTES = 1024 * 1024;
|
|
9
|
+
const MODEL_FIELDS = new Set(['', 'customModels', 'model', 'displayName', 'baseUrl', 'provider', 'maxOutputTokens', 'maxContextLimit']);
|
|
10
|
+
async function readSettings(filename) {
|
|
11
|
+
const file = await open(filename, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
12
|
+
try {
|
|
13
|
+
const stat = await file.stat();
|
|
14
|
+
if (!stat.isFile() || stat.size > MAX_CONFIG_BYTES)
|
|
15
|
+
throw new Error('Config exceeds bounds');
|
|
16
|
+
const buffer = Buffer.alloc(MAX_CONFIG_BYTES + 1);
|
|
17
|
+
const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
|
|
18
|
+
if (bytesRead > MAX_CONFIG_BYTES)
|
|
19
|
+
throw new Error('Config exceeds bounds');
|
|
20
|
+
// Drop every unneeded field at parse time, including apiKey/api_key. Never
|
|
21
|
+
// inspect, interpolate or hash their values; parser errors are never echoed.
|
|
22
|
+
return JSON.parse(buffer.toString('utf8', 0, bytesRead), (key, value) => MODEL_FIELDS.has(key) || /^\d+$/.test(key) ? value : undefined);
|
|
23
|
+
}
|
|
24
|
+
finally {
|
|
25
|
+
await file.close();
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function inferenceProvider(provider, baseUrl) {
|
|
29
|
+
if (typeof baseUrl === 'string') {
|
|
30
|
+
try {
|
|
31
|
+
const url = new URL(baseUrl);
|
|
32
|
+
if (!['http:', 'https:'].includes(url.protocol))
|
|
33
|
+
return undefined;
|
|
34
|
+
const host = url.hostname.toLowerCase();
|
|
35
|
+
return { 'openrouter.ai': 'openrouter', 'api.openai.com': 'openai',
|
|
36
|
+
'api.anthropic.com': 'anthropic' }[host] ?? host;
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return undefined;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
// These are backend identities. Generic protocol names are not providers.
|
|
43
|
+
return ['anthropic', 'openai'].includes(provider) ? provider : undefined;
|
|
44
|
+
}
|
|
45
|
+
export async function discoverFactoryModels(options = {}) {
|
|
46
|
+
const observedAt = (options.now?.() ?? new Date()).toISOString();
|
|
47
|
+
const source = join(options.homeDir ?? homedir(), '.factory/settings.json');
|
|
48
|
+
const result = { provider: 'factory', source: 'native', observedAt,
|
|
49
|
+
accountScope: 'local-account', ...(options.accountBinding ? { accountBinding: options.accountBinding } : {}), models: [] };
|
|
50
|
+
let version = options.runtimeVersion;
|
|
51
|
+
if (!version) {
|
|
52
|
+
try {
|
|
53
|
+
const probe = await (options.runner ?? runModelDiscoveryCommand)(options.command ?? 'droid', ['--version'], { cwd: tmpdir(), timeoutMs: 5000 });
|
|
54
|
+
// Accept the known plain and droid-cli banners, never retain arbitrary CLI output.
|
|
55
|
+
if (probe.exitCode === 0)
|
|
56
|
+
version = /^(?:droid-cli\s+)?(\d+\.\d+\.\d+(?:[-+][\w.-]+)?)$/.exec(probe.stdout.trim())?.[1];
|
|
57
|
+
}
|
|
58
|
+
catch { /* A missing runtime cannot establish a current worker observation. */ }
|
|
59
|
+
}
|
|
60
|
+
if (!version)
|
|
61
|
+
return { ...result, errorKind: 'command', error: 'Factory version probe failed; no current custom model observations.' };
|
|
62
|
+
result.runtimeVersion = version;
|
|
63
|
+
let settings;
|
|
64
|
+
try {
|
|
65
|
+
settings = await readSettings(source);
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
return { ...result, errorKind: error.code === 'ENOENT' ? 'unsupported' : 'invalid-output',
|
|
69
|
+
error: 'Factory settings.json could not be read or parsed within bounds; built-in plan models have no non-interactive model-list command.' };
|
|
70
|
+
}
|
|
71
|
+
const rows = settings && typeof settings === 'object' && !Array.isArray(settings)
|
|
72
|
+
? settings.customModels : undefined;
|
|
73
|
+
if (rows === undefined && settings && typeof settings === 'object' && !Array.isArray(settings))
|
|
74
|
+
return result;
|
|
75
|
+
if (!Array.isArray(rows) || rows.length > 1024)
|
|
76
|
+
return { ...result, errorKind: 'invalid-output', error: 'Factory /customModels: expected bounded array.' };
|
|
77
|
+
const diagnostics = [];
|
|
78
|
+
const nameCounts = new Map();
|
|
79
|
+
for (const [index, entry] of rows.entries()) {
|
|
80
|
+
const invalid = () => diagnostics.push(`Factory /customModels/${index}: malformed model fields or unknown inference provider.`);
|
|
81
|
+
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
|
|
82
|
+
invalid();
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
const row = entry;
|
|
86
|
+
const { model, displayName, provider, baseUrl, maxOutputTokens, maxContextLimit } = row;
|
|
87
|
+
// Droid counts prior entries with this normalized name, not array indexes.
|
|
88
|
+
const normalizedName = typeof displayName === 'string' ? displayName.replace(/ /g, '-') : '';
|
|
89
|
+
const occurrence = nameCounts.get(normalizedName) ?? 0;
|
|
90
|
+
nameCounts.set(normalizedName, occurrence + 1);
|
|
91
|
+
if (typeof model !== 'string' || !model.trim() || /\s/.test(model)
|
|
92
|
+
|| typeof displayName !== 'string' || !displayName.trim() || displayName !== displayName.trim()
|
|
93
|
+
|| /[\x00-\x1f\x7f]/.test(displayName) || typeof provider !== 'string'
|
|
94
|
+
|| (maxOutputTokens !== undefined && (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens < 1))
|
|
95
|
+
|| (maxContextLimit !== undefined && (!Number.isSafeInteger(maxContextLimit) || maxContextLimit < 1))) {
|
|
96
|
+
invalid();
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
const llmProvider = inferenceProvider(provider, baseUrl);
|
|
100
|
+
if (!llmProvider) {
|
|
101
|
+
invalid();
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
const id = `custom:${normalizedName}-${occurrence}`;
|
|
105
|
+
const facts = { id, model, displayName, llmProvider, maxOutputTokens: maxOutputTokens ?? null,
|
|
106
|
+
maxContextLimit: maxContextLimit ?? null };
|
|
107
|
+
const worker = buildWorkerObservation({ cliId: options.cliId ?? 'factory', source,
|
|
108
|
+
pointer: `/customModels/${index}`, runtimeVersion: version, observedAt,
|
|
109
|
+
accountScope: 'local-account', accountBinding: options.accountBinding,
|
|
110
|
+
contentDigest: discoveryDigest(JSON.stringify(facts)) }, {
|
|
111
|
+
modelId: id, family: 'unknown', visibility: 'listed', lifecycle: 'active',
|
|
112
|
+
contextTokens: maxContextLimit,
|
|
113
|
+
maxOutputTokens: maxOutputTokens, effortSupport: 'not-applicable',
|
|
114
|
+
provenanceFields: ['/apiModelId', '/llmProvider', '/displayName', '/contextTokens:maxContextLimit'],
|
|
115
|
+
});
|
|
116
|
+
// apiModelId is the executable Droid selector required by qualification and
|
|
117
|
+
// invocation, not the upstream API id. Preserve the latter as config provenance.
|
|
118
|
+
result.models.push({ id, apiModelId: id, displayName, llmProvider, worker });
|
|
119
|
+
result.policy ??= { layers: [{ source, scope: 'user', precedence: 1, policyConstraint: false }],
|
|
120
|
+
selected: {}, constraints: [], diagnostics: [] };
|
|
121
|
+
result.policy.selected[`customModels.${index}.model`] = { value: model, source, scope: 'user', precedence: 1 };
|
|
122
|
+
}
|
|
123
|
+
// Identical display names are numbered; distinct spellings that normalize to
|
|
124
|
+
// the same name remain ambiguous and are withheld together.
|
|
125
|
+
const ambiguousNames = new Set(result.models.filter(row => result.models.some(other => other.displayName !== row.displayName && other.displayName.replace(/ /g, '-') === row.displayName.replace(/ /g, '-')))
|
|
126
|
+
.map(row => row.displayName.replace(/ /g, '-')));
|
|
127
|
+
if (ambiguousNames.size) {
|
|
128
|
+
diagnostics.push('Factory custom model display names produce ambiguous selectors.');
|
|
129
|
+
result.models = result.models.filter(row => !ambiguousNames.has(row.displayName.replace(/ /g, '-')));
|
|
130
|
+
}
|
|
131
|
+
if (diagnostics.length) {
|
|
132
|
+
result.errorKind = 'invalid-output';
|
|
133
|
+
result.error = diagnostics.join('; ');
|
|
134
|
+
}
|
|
135
|
+
return result;
|
|
136
|
+
}
|
|
137
|
+
/** Bind refresh to a single configured Factory installation; doctor binds each target separately. */
|
|
138
|
+
export async function discoverProjectFactoryModels(projectDir, options = {}) {
|
|
139
|
+
const config = await readAiwgConfig(projectDir);
|
|
140
|
+
const clis = Object.entries(config?.parallelism?.clis ?? {}).filter(([id, cli]) => cli.enabled !== false && (cli.adapter ?? `providers:${id}`) === 'providers:factory');
|
|
141
|
+
const [cliId, cli] = clis.length === 1 ? clis[0] : [];
|
|
142
|
+
return discoverFactoryModels({ cliId, command: cli?.executable, accountBinding: cli?.accountScope, ...options });
|
|
143
|
+
}
|
|
144
|
+
//# sourceMappingURL=factory-models.js.map
|
package/dist/src/models/index.js
CHANGED
|
@@ -7,8 +7,8 @@
|
|
|
7
7
|
* - Hierarchical configuration (default < user < project < agent)
|
|
8
8
|
* - Backwards compatibility with v1 configs
|
|
9
9
|
*
|
|
10
|
-
* @implements
|
|
11
|
-
* @architecture
|
|
10
|
+
* @implements @docs/models/supported-models.md
|
|
11
|
+
* @architecture @docs/models/supported-models.md
|
|
12
12
|
*
|
|
13
13
|
* @module models
|
|
14
14
|
*/
|