@aiwg/cli 2026.11.6 → 2026.11.7
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/dist/src/artifacts/browser-export.js +1 -0
- package/dist/src/artifacts/fortemi-core-query-adapter.js +2 -0
- package/dist/src/artifacts/index-builder.js +1 -0
- package/dist/src/artifacts/query-engine-discover-output.js +1 -0
- package/dist/src/artifacts/query-engine-discover.js +2 -2
- package/dist/src/artifacts/query-engine-scoring.js +7 -0
- package/dist/src/artifacts/template-output-kind.js +10 -0
- package/dist/src/artifacts/types.js +1 -1
- package/dist/src/cli/handlers/dataset.js +11 -2
- package/dist/src/cli/handlers/update.js +26 -12
- package/dist/src/cli/handlers/use.js +4 -3
- package/dist/src/cli/handlers/writing.js +7 -1
- package/dist/src/dataset/backend-selection.d.ts +3 -0
- package/dist/src/dataset/backend-selection.js +11 -0
- package/dist/src/dataset/contract-range.d.ts +7 -0
- package/dist/src/dataset/contract-range.js +55 -0
- package/dist/src/dataset/fortemi-execution-bridge.d.ts +2 -0
- package/dist/src/dataset/fortemi-execution-bridge.js +12 -1
- package/dist/src/dataset/index.d.ts +2 -0
- package/dist/src/dataset/index.js +2 -0
- package/dist/src/dataset/orchestration-service.d.ts +1 -1
- package/dist/src/dataset/orchestration-service.js +7 -8
- package/dist/src/dataset/orchestration-types.d.ts +2 -0
- package/dist/src/dataset/service-binding-checkpoints.d.ts +10 -0
- package/dist/src/dataset/service-binding-checkpoints.js +26 -0
- package/dist/src/dataset/service-binding-contract.d.ts +46 -0
- package/dist/src/dataset/service-binding-contract.js +25 -0
- package/dist/src/dataset/service-binding-registry.d.ts +12 -0
- package/dist/src/dataset/service-binding-registry.js +118 -0
- package/dist/src/extensions/manifest.js +23 -7
- package/dist/src/extensions/project-local-doctor.js +2 -1
- package/dist/src/extensions/project-quickref-discovery.js +11 -0
- package/dist/src/extensions/project-quickref.js +4 -7
- package/dist/src/mcp/tools/worker-invoke.mjs +6 -4
- package/dist/src/mcp/tools/worker-launch-ledger.mjs +33 -0
- package/dist/src/mcp/tools/worker-verify-deliver-schema.mjs +22 -6
- package/dist/src/mcp/tools/worker-verify-deliver.mjs +4 -6
- package/dist/src/providers/deployment-input-session.d.mts +2 -0
- package/dist/src/providers/deployment-input-session.mjs +38 -0
- package/dist/src/serve/worker-invocation-preparation.js +52 -33
- package/dist/src/serve/worker-invocation.js +4 -2
- package/dist/src/serve/worker-shell-prompt.d.mts +6 -0
- package/dist/src/serve/worker-shell-prompt.mjs +78 -0
- package/dist/src/writing/campaign-patterns.js +96 -0
- package/dist/src/writing/campaign-report.js +41 -0
- package/dist/src/writing/contextual-diagnostics.js +29 -5
- package/dist/src/writing/current-patterns.catalogue.json +87 -0
- package/dist/src/writing/current-patterns.js +99 -0
- package/dist/src/writing/prose-mask.js +80 -0
- package/dist/src/writing/structural-patterns.js +109 -0
- package/dist/src/writing/validation-campaign.js +19 -0
- package/dist/src/writing/validation-engine.js +17 -10
- package/dist/src/writing/validation-rules.js +4 -3
- package/package.json +1 -1
- package/schemas/dataset/service-binding.v1.schema.json +70 -0
- package/tools/agents/providers/base-models-platforms.mjs +87 -48
- package/tools/agents/providers/rule-deployment-corpus-inputs.mjs +19 -0
- package/tools/agents/providers/rule-deployment-input-session.mjs +40 -0
- package/tools/agents/providers/rule-deployment-prepare.mjs +15 -6
- package/tools/plugin/package-plugins.mjs +2 -0
- package/tools/ralph-external/lib/typed-stop-delivery.mjs +10 -1
- package/tools/ralph-external/lib/worker-delivery-guards.mjs +47 -1
- package/tools/ralph-external/lib/worker-run-directory-refusal.mjs +2 -1
- package/tools/ralph-external/lib/worker-verification-cli.mjs +1 -1
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// Admits trusted, preloaded adapter/backend pairs and pins their CLI execution identity.
|
|
2
|
+
import { contractRangeIncludes } from './contract-range.js';
|
|
3
|
+
import { DATASET_ADAPTER_CONTRACT_VERSION } from './adapter-types.js';
|
|
4
|
+
import { validateCheckpoint } from './adapter-sdk.js';
|
|
5
|
+
import { datasetDigest, DatasetContractError } from './contracts.js';
|
|
6
|
+
import { DATASET_CONTRACT_VERSION } from './types.js';
|
|
7
|
+
import { requireDatasetBindingSelection, requireDatasetServiceBinding, } from './service-binding-contract.js';
|
|
8
|
+
const same = (a, b) => datasetDigest(a).value === datasetDigest(b).value;
|
|
9
|
+
const offers = (backend) => [...backend.capabilities()].sort((a, b) => a.name.localeCompare(b.name));
|
|
10
|
+
const expectedOffers = (descriptor) => [...descriptor.capabilities].sort((a, b) => a.name.localeCompare(b.name));
|
|
11
|
+
function assertRegistration({ descriptor: d, adapter, backend, backendIdentity }) {
|
|
12
|
+
const manifest = adapter.describe();
|
|
13
|
+
if (manifest.contractVersion !== DATASET_ADAPTER_CONTRACT_VERSION || !contractRangeIncludes('1.0.0', manifest.datasetContractRange)
|
|
14
|
+
|| d.datasetContractVersion !== DATASET_CONTRACT_VERSION || d.adapterContractVersion !== manifest.contractVersion
|
|
15
|
+
|| manifest.id !== d.adapter.id || manifest.version !== d.adapter.version
|
|
16
|
+
|| !same(manifest.packageDigest, d.adapter.packageDigest) || !same(datasetDigest(manifest), d.adapterManifestDigest)
|
|
17
|
+
|| !backendIdentity || backendIdentity.id !== d.backend.id || backendIdentity.version !== d.backend.version
|
|
18
|
+
|| !same(backendIdentity.packageDigest, d.backend.packageDigest)
|
|
19
|
+
|| backend.id !== d.backend.id || !same(offers(backend), expectedOffers(d)))
|
|
20
|
+
throw new DatasetContractError('DATASET_BINDING_INCOMPATIBLE', 'Registered implementation differs from the qualified binding');
|
|
21
|
+
if (manifest.maturity === 'experimental' || manifest.trust.state === 'untrusted')
|
|
22
|
+
throw new DatasetContractError('DATASET_BINDING_UNQUALIFIED', 'Adapter maturity and trust must permit qualification');
|
|
23
|
+
}
|
|
24
|
+
function boundedAdapter(entry) {
|
|
25
|
+
const adapter = entry.adapter;
|
|
26
|
+
return {
|
|
27
|
+
describe: () => { assertRegistration(entry); return adapter.describe(); },
|
|
28
|
+
configure: config => { assertRegistration(entry); return adapter.configure(config); },
|
|
29
|
+
check: request => { assertRegistration(entry); return adapter.check(request); },
|
|
30
|
+
discover: request => { assertRegistration(entry); return adapter.discover(request); },
|
|
31
|
+
preview: request => { assertRegistration(entry); return adapter.preview({ ...request, limits: { ...request.limits, ...entry.descriptor.limits } }); },
|
|
32
|
+
async *read(request) {
|
|
33
|
+
assertRegistration(entry);
|
|
34
|
+
const limits = entry.descriptor.limits;
|
|
35
|
+
const signal = AbortSignal.any([...(request.signal ? [request.signal] : []), AbortSignal.timeout(limits.timeoutMs)]);
|
|
36
|
+
let count = 0;
|
|
37
|
+
let bytes = 0;
|
|
38
|
+
for await (const event of adapter.read({ ...request, signal, limits: { ...request.limits, ...limits } })) {
|
|
39
|
+
if (request.signal?.aborted)
|
|
40
|
+
return;
|
|
41
|
+
if (signal.aborted)
|
|
42
|
+
throw new DatasetContractError('DATASET_BINDING_RESOURCE_LIMIT', 'Binding read deadline exceeded');
|
|
43
|
+
if (event.kind === 'diagnostic' && event.diagnostic.severity === 'error')
|
|
44
|
+
throw new DatasetContractError(event.diagnostic.code, 'Qualified adapter read failed before execution');
|
|
45
|
+
if (event.kind === 'record') {
|
|
46
|
+
const size = Buffer.byteLength(JSON.stringify(event.record.value));
|
|
47
|
+
bytes += size;
|
|
48
|
+
count++;
|
|
49
|
+
if (count > limits.maxRecords || bytes > limits.maxBytes || size > limits.maxRecordBytes)
|
|
50
|
+
throw new DatasetContractError('DATASET_BINDING_RESOURCE_LIMIT', 'Binding record or byte limit exceeded');
|
|
51
|
+
}
|
|
52
|
+
yield event;
|
|
53
|
+
}
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
export class DatasetBindingRegistry {
|
|
58
|
+
#entries = new Map();
|
|
59
|
+
/** Trusted bootstrap only: registration never imports code or reads evidence paths. */
|
|
60
|
+
register(value, adapter, backend, backendIdentity) {
|
|
61
|
+
const descriptor = requireDatasetServiceBinding(value);
|
|
62
|
+
const key = `${descriptor.id}@${descriptor.version}`;
|
|
63
|
+
if (this.#entries.has(key))
|
|
64
|
+
throw new Error('DATASET_BINDING_DUPLICATE');
|
|
65
|
+
const entry = { descriptor, adapter, backend, backendIdentity: structuredClone(backendIdentity) };
|
|
66
|
+
assertRegistration(entry);
|
|
67
|
+
this.#entries.set(key, entry);
|
|
68
|
+
return {
|
|
69
|
+
contractVersion: descriptor.contractVersion, kind: 'DatasetBindingSelection',
|
|
70
|
+
id: descriptor.id, version: descriptor.version, descriptorDigest: datasetDigest(descriptor),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
select(value) {
|
|
74
|
+
const selection = requireDatasetBindingSelection(value);
|
|
75
|
+
const entry = this.#entries.get(`${selection.id}@${selection.version}`);
|
|
76
|
+
if (!entry)
|
|
77
|
+
throw new Error('DATASET_BINDING_NOT_REGISTERED');
|
|
78
|
+
if (!same(selection.descriptorDigest, datasetDigest(entry.descriptor)))
|
|
79
|
+
throw new Error('DATASET_BINDING_DIGEST_MISMATCH');
|
|
80
|
+
assertRegistration(entry);
|
|
81
|
+
const adapter = boundedAdapter(entry);
|
|
82
|
+
const boundId = `dataset-binding:${selection.id}@${selection.version}:sha256:${selection.descriptorDigest.value}`;
|
|
83
|
+
const backend = {
|
|
84
|
+
id: boundId,
|
|
85
|
+
locality: entry.descriptor.backend.id === 'local' ? 'local' : 'remote',
|
|
86
|
+
capabilities: () => { assertRegistration(entry); return entry.backend.capabilities(); },
|
|
87
|
+
async execute(request) {
|
|
88
|
+
assertRegistration(entry);
|
|
89
|
+
if (request.plan.execution.backend !== boundId)
|
|
90
|
+
throw new Error('DATASET_BINDING_PLAN_MISMATCH');
|
|
91
|
+
if (request.signal?.aborted)
|
|
92
|
+
return { outcome: 'cancelled', attemptedRecords: 0, committedRecords: 0, rejectedRecords: 0, diagnostics: [] };
|
|
93
|
+
const signal = AbortSignal.any([...(request.signal ? [request.signal] : []), AbortSignal.timeout(entry.descriptor.limits.timeoutMs)]);
|
|
94
|
+
const result = await entry.backend.execute({ ...request, signal });
|
|
95
|
+
if (result.checkpoint && validateCheckpoint(result.checkpoint, adapter.describe(), request.plan.source.identity).length)
|
|
96
|
+
throw new Error('DATASET_BINDING_CHECKPOINT_MISMATCH');
|
|
97
|
+
return result;
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
return {
|
|
101
|
+
adapter(id, version) {
|
|
102
|
+
if (id !== entry.descriptor.adapter.id || version !== entry.descriptor.adapter.version)
|
|
103
|
+
throw new Error('DATASET_BINDING_ADAPTER_MISMATCH');
|
|
104
|
+
assertRegistration(entry);
|
|
105
|
+
return adapter;
|
|
106
|
+
},
|
|
107
|
+
selectBackend(id) {
|
|
108
|
+
if (id !== undefined && id !== boundId && id !== entry.descriptor.backend.id)
|
|
109
|
+
throw new DatasetContractError('DATASET_BINDING_BACKEND_MISMATCH', 'The plan requires its explicitly selected binding');
|
|
110
|
+
assertRegistration(entry);
|
|
111
|
+
return backend;
|
|
112
|
+
},
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/** Empty by default. Trusted installed entrypoints register statically imported implementations. */
|
|
117
|
+
export const datasetBindingRegistry = new DatasetBindingRegistry();
|
|
118
|
+
//# sourceMappingURL=service-binding-registry.js.map
|
|
@@ -267,6 +267,19 @@ export const BundleManifestSchema = z.strictObject({
|
|
|
267
267
|
}
|
|
268
268
|
return presentCount === 1 && present[m.type];
|
|
269
269
|
}, { error: 'type must match its corresponding *Config block (addon→addonConfig, framework→frameworkConfig, plugin→pluginConfig, provider→providerConfig; extension may omit extensionConfig)' });
|
|
270
|
+
/** Format a field diagnostic consistently with `aiwg list --project-local`. */
|
|
271
|
+
export function formatManifestValidationError(error) {
|
|
272
|
+
return `${error.field}: expected ${error.expected}, got ${error.actual}`
|
|
273
|
+
+ (error.hint ? `; hint: ${error.hint}` : '');
|
|
274
|
+
}
|
|
275
|
+
function stringifyManifestValue(value) {
|
|
276
|
+
try {
|
|
277
|
+
return JSON.stringify(value) ?? String(value);
|
|
278
|
+
}
|
|
279
|
+
catch {
|
|
280
|
+
return String(value);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
270
283
|
/**
|
|
271
284
|
* Convert a Zod error into the structured ManifestValidationError shape used
|
|
272
285
|
* by discovery and `aiwg validate-metadata`.
|
|
@@ -293,22 +306,25 @@ export function zodErrorToValidationErrors(err, manifestPath, input) {
|
|
|
293
306
|
const keys = issue.keys.map((key) => `"${String(key)}"`).join(', ');
|
|
294
307
|
actual = `unknown key(s): ${keys}`;
|
|
295
308
|
}
|
|
296
|
-
if (issue.code === 'invalid_type' && hasInput) {
|
|
309
|
+
if ((issue.code === 'invalid_type' || issue.code === 'invalid_value') && hasInput) {
|
|
297
310
|
let value = input;
|
|
298
311
|
for (const segment of issue.path) {
|
|
299
312
|
value = value !== null && typeof value === 'object' && Object.hasOwn(value, segment)
|
|
300
313
|
? value[segment] : undefined;
|
|
301
314
|
}
|
|
302
|
-
//
|
|
303
|
-
actual =
|
|
304
|
-
:
|
|
305
|
-
:
|
|
306
|
-
: typeof value
|
|
315
|
+
// Enum diagnostics need the rejected value; type errors retain their classification.
|
|
316
|
+
actual = issue.code === 'invalid_value' ? stringifyManifestValue(value)
|
|
317
|
+
: value === null ? 'null' : Array.isArray(value) ? 'array'
|
|
318
|
+
: typeof value === 'number' && Number.isNaN(value) ? 'nan'
|
|
319
|
+
: issue.expected === 'int' && typeof value === 'number' ? 'float'
|
|
320
|
+
: typeof value;
|
|
307
321
|
}
|
|
308
322
|
return {
|
|
309
323
|
path: manifestPath,
|
|
310
324
|
field: issue.path.join('.') || '(root)',
|
|
311
|
-
expected: issue.
|
|
325
|
+
expected: issue.code === 'invalid_value' && Array.isArray(issue.values)
|
|
326
|
+
? `one of ${issue.values.map(stringifyManifestValue).join('|')}`
|
|
327
|
+
: issue.message,
|
|
312
328
|
actual,
|
|
313
329
|
severity: 'error',
|
|
314
330
|
};
|
|
@@ -21,6 +21,7 @@ import { buildUpstreamRegistry } from './upstream-registry.js';
|
|
|
21
21
|
import { resolveShadows } from './shadow-resolver.js';
|
|
22
22
|
import { checkBundleManifestIgnored } from './project-local-gitignore.js';
|
|
23
23
|
import { sha256OfFileRawAndNormalized } from './managed-marker.js';
|
|
24
|
+
import { formatManifestValidationError } from './manifest.js';
|
|
24
25
|
import { projectAiwgPath } from '../config/project-artifacts.js';
|
|
25
26
|
import { projectRelativePathIfInside } from './project-local-paths.js';
|
|
26
27
|
import { auditProjectQuickref } from './project-quickref.js';
|
|
@@ -171,7 +172,7 @@ export async function buildProjectLocalDoctorSection(opts) {
|
|
|
171
172
|
else {
|
|
172
173
|
lines.push(` Validation: ✗ ${validationErrors} error${validationErrors === 1 ? '' : 's'}`);
|
|
173
174
|
for (const e of discovery.errors.slice(0, 10)) {
|
|
174
|
-
lines.push(` ✗ ${e.path}: ${e
|
|
175
|
+
lines.push(` ✗ ${e.path}: ${formatManifestValidationError(e)}`);
|
|
175
176
|
}
|
|
176
177
|
const quickrefShown = quickrefErrors.slice(0, Math.max(0, 10 - discovery.errors.length));
|
|
177
178
|
for (const error of quickrefShown) {
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// Build quickrefs from validated bundles while retaining rejected sibling diagnostics.
|
|
2
|
+
import { discoverProjectLocalBundles } from './project-local-discovery.js';
|
|
3
|
+
import { formatManifestValidationError } from './manifest.js';
|
|
4
|
+
export async function discoverProjectQuickrefBundles(projectDir) {
|
|
5
|
+
const discovery = await discoverProjectLocalBundles(projectDir);
|
|
6
|
+
return {
|
|
7
|
+
...discovery,
|
|
8
|
+
warnings: discovery.errors.map(error => `${error.path}: ${formatManifestValidationError(error)}`),
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
//# sourceMappingURL=project-quickref-discovery.js.map
|
|
@@ -16,7 +16,7 @@ import { resolveHermesHome } from '../providers/hermes-home.js';
|
|
|
16
16
|
import { OPERATIONAL_SHOW_TYPES } from '../artifacts/types.js';
|
|
17
17
|
import { projectAiwgPath } from '../config/project-artifacts.js';
|
|
18
18
|
import { appendAiwgSourceTrackBlock } from './project-local-gitignore.js';
|
|
19
|
-
import {
|
|
19
|
+
import { discoverProjectQuickrefBundles } from './project-quickref-discovery.js';
|
|
20
20
|
import { enumerateBundleArtifacts } from './shadow-resolver.js';
|
|
21
21
|
const OWNERSHIP_MARKER = '.aiwg-project-quickref.json';
|
|
22
22
|
const ShowHintSchema = z.strictObject({
|
|
@@ -180,16 +180,13 @@ export async function resolveProjectQuickref(projectDir) {
|
|
|
180
180
|
};
|
|
181
181
|
}
|
|
182
182
|
const managed = await loadManagedConfig(projectDir);
|
|
183
|
-
const discovery = await
|
|
184
|
-
if (discovery.errors.length > 0) {
|
|
185
|
-
throw new Error(discovery.errors.map(error => `${error.path}: ${error.field}: ${error.actual}`).join('\n'));
|
|
186
|
-
}
|
|
183
|
+
const discovery = await discoverProjectQuickrefBundles(projectDir);
|
|
187
184
|
if (!managed.config && discovery.bundles.length === 0) {
|
|
188
|
-
return { exists: false, sourcePath: managed.path, provenance: 'managed', warnings:
|
|
185
|
+
return { exists: false, sourcePath: managed.path, provenance: 'managed', warnings: discovery.warnings };
|
|
189
186
|
}
|
|
190
187
|
const config = managed.config ?? ProjectQuickrefConfigSchema.parse({ version: '1' });
|
|
191
188
|
const excluded = new Set(config.discovery.excludeBundles.map(id => id.toLowerCase()));
|
|
192
|
-
const warnings =
|
|
189
|
+
const warnings = discovery.warnings;
|
|
193
190
|
const candidates = [];
|
|
194
191
|
if (config.discovery.enabled) {
|
|
195
192
|
for (const bundle of discovery.bundles) {
|
|
@@ -157,6 +157,7 @@
|
|
|
157
157
|
*/
|
|
158
158
|
|
|
159
159
|
import { registerWorkerVerifyDeliverTool } from './worker-verify-deliver.mjs';
|
|
160
|
+
import { createWorkerLaunchLedger } from './worker-launch-ledger.mjs';
|
|
160
161
|
import { workerFailureDiagnostics } from './worker-failure-diagnostics.mjs';
|
|
161
162
|
import { workerLocalOnlyPreflight } from './worker-local-only-preflight.mjs';
|
|
162
163
|
import { signalChild } from '../../process/signal-child.mjs';
|
|
@@ -1692,9 +1693,10 @@ export async function registerWorkerInvokeToolset(server, options = {}) {
|
|
|
1692
1693
|
return;
|
|
1693
1694
|
}
|
|
1694
1695
|
const servedRootReal = await resolveServedProjectRoot(options.projectRoot);
|
|
1696
|
+
const launches = createWorkerLaunchLedger();
|
|
1695
1697
|
registerWorkerVerifyDeliverTool(server, { projectRoot: servedRootReal,
|
|
1696
1698
|
assertPath: candidate => assertServedPath(servedRootReal, candidate),
|
|
1697
|
-
verify: async input => (await loadRalphExternal('lib/worker-verification-cli.mjs')).verifyWorkerRun(input),
|
|
1699
|
+
verify: async input => (await loadRalphExternal('lib/worker-verification-cli.mjs')).verifyWorkerRun(input, { recordedLaunches: launches.count }),
|
|
1698
1700
|
});
|
|
1699
1701
|
await sweepWorkerStdin(options.stdinRuntimeRoot);
|
|
1700
1702
|
// Pinned once, here, at registration — never re-resolved per request, and
|
|
@@ -1710,9 +1712,9 @@ export async function registerWorkerInvokeToolset(server, options = {}) {
|
|
|
1710
1712
|
const loadWorkerInputsImpl = options.loadWorkerInputs ?? defaultLoadWorkerInputs;
|
|
1711
1713
|
const recordedShell = recordedShellLauncher({ loadRalphExternal, loadInputs: () => loadWorkerInputsImpl(servedRootReal),
|
|
1712
1714
|
assertPath: candidate => assertServedPath(servedRootReal, candidate), registry, now: options.now ?? (() => new Date()) });
|
|
1713
|
-
const launchShellWorkerImpl = options.launchShellWorker ?? ((invocation, context) => recordedShell.requested(invocation)
|
|
1714
|
-
? recordedShell.launch(invocation, context) : defaultLaunchShellWorker(invocation, context));
|
|
1715
|
-
const callMcpWorkerImpl = options.callMcpWorker ?? defaultCallMcpWorker;
|
|
1715
|
+
const launchShellWorkerImpl = launches.track(options.launchShellWorker ?? ((invocation, context) => recordedShell.requested(invocation)
|
|
1716
|
+
? recordedShell.launch(invocation, context) : defaultLaunchShellWorker(invocation, context)), 'shell');
|
|
1717
|
+
const callMcpWorkerImpl = launches.track(options.callMcpWorker ?? defaultCallMcpWorker, 'mcp');
|
|
1716
1718
|
// Both continuations use the audited observer and hardened stop controls.
|
|
1717
1719
|
const waitForUnitTerminationOverride = options.waitForUnitTermination;
|
|
1718
1720
|
// #2915 review 5 ("a second worker over unresolved execution"): the
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// Retain cumulative server-session launch counts independently of registry pruning.
|
|
2
|
+
export function createWorkerLaunchLedger() {
|
|
3
|
+
let count = 0;
|
|
4
|
+
return {
|
|
5
|
+
count: () => count,
|
|
6
|
+
track(launch, transport) {
|
|
7
|
+
return async (...args) => {
|
|
8
|
+
let recorded = false;
|
|
9
|
+
const record = () => { if (!recorded) { recorded = true; count++; } };
|
|
10
|
+
// MCP calls can remain pending long after their process starts.
|
|
11
|
+
// A registered non-null stop control is already launch evidence.
|
|
12
|
+
const context = args[2];
|
|
13
|
+
if (transport === 'mcp' && typeof context?.registerControl === 'function') {
|
|
14
|
+
args[2] = { ...context, registerControl(control) {
|
|
15
|
+
if (control) record();
|
|
16
|
+
return context.registerControl(control);
|
|
17
|
+
} };
|
|
18
|
+
}
|
|
19
|
+
let result;
|
|
20
|
+
try { result = await launch(...args); }
|
|
21
|
+
catch (error) {
|
|
22
|
+
if (error.launchAttempted) record();
|
|
23
|
+
throw error;
|
|
24
|
+
}
|
|
25
|
+
const launched = transport === 'shell'
|
|
26
|
+
? result.launched || result.launchAttempted || result.dispatchState === 'submission-uncertain'
|
|
27
|
+
: result.dispatchState ? result.dispatchState !== 'never-began' : result.outcome !== 'blocked';
|
|
28
|
+
if (launched) record();
|
|
29
|
+
return result;
|
|
30
|
+
};
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
}
|
|
@@ -18,16 +18,32 @@ export const typedStopSchema = z.strictObject({
|
|
|
18
18
|
reason: z.string().max(4000).optional(),
|
|
19
19
|
});
|
|
20
20
|
export const typedStopDeliverySchema = z.strictObject({ deliverablePath: absolute, typedStop: typedStopSchema });
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
21
|
+
const workerPublication = z.strictObject({ run_dir: absolute, artifact_path: absolute.optional(), deliverable_path: absolute, checks: z.array(check).min(1).max(32) });
|
|
22
|
+
const stopPublication = z.strictObject({ deliverable_path: absolute, typed_stop: typedStopSchema });
|
|
23
|
+
export const publicationSchema = z.union([workerPublication, stopPublication]);
|
|
24
|
+
|
|
25
|
+
// Select by presence, including null/undefined stops, so malformed requests
|
|
26
|
+
// receive only the relevant branch's remedies rather than a union dump.
|
|
27
|
+
export function parsePublication(input) {
|
|
28
|
+
const isStop = input !== null && typeof input === 'object' && Object.hasOwn(input, 'typed_stop');
|
|
29
|
+
const parsed = (isStop ? stopPublication : workerPublication).safeParse(input);
|
|
30
|
+
if (parsed.success) return parsed.data;
|
|
31
|
+
const code = isStop ? 'TYPED_STOP_INVALID' : 'PUBLICATION_INVALID';
|
|
32
|
+
const shape = isStop ? 'a typed stop' : 'a worker publication';
|
|
33
|
+
const findings = parsed.error.issues.flatMap(issue => {
|
|
34
|
+
const key = issue.path.join('.');
|
|
35
|
+
if (issue.code === 'unrecognized_keys') return issue.keys.map(unknown => `${code}: ${[...issue.path, unknown].join('.')} is unknown for ${shape}`);
|
|
36
|
+
const missing = issue.path.length && issue.path.reduce((value, part) => value?.[part], input) === undefined;
|
|
37
|
+
return [`${code}: ${key || 'request'} ${missing ? `is required for ${shape}` : issue.message}`];
|
|
38
|
+
});
|
|
39
|
+
throw Object.assign(new Error(findings.join('\n')), { code, findings });
|
|
40
|
+
}
|
|
25
41
|
|
|
26
42
|
// The SDK advertises only object schemas. Preserve the strict union in both
|
|
27
43
|
// its advertised JSON Schema and validation, with a stable refusal code.
|
|
28
44
|
export const publicationInputSchema = z.looseObject({}).superRefine((input, context) => {
|
|
29
|
-
|
|
30
|
-
|
|
45
|
+
try { parsePublication(input); }
|
|
46
|
+
catch (error) { for (const message of error.findings) context.addIssue({ code: 'custom', message }); }
|
|
31
47
|
}).meta({ anyOf: z.toJSONSchema(publicationSchema).anyOf });
|
|
32
48
|
|
|
33
49
|
export const invalidTypedStop = message => Object.assign(new Error(`TYPED_STOP_INVALID: ${message}`), { code: 'TYPED_STOP_INVALID' });
|
|
@@ -1,18 +1,16 @@
|
|
|
1
1
|
// Narrow workers-toolset adapter: protected checks and publication share one verifier call.
|
|
2
2
|
import { mcpError, mcpJson } from '../helpers.mjs';
|
|
3
|
-
import { publicationInputSchema,
|
|
3
|
+
import { publicationInputSchema, parsePublication } from './worker-verify-deliver-schema.mjs';
|
|
4
4
|
|
|
5
5
|
export function registerWorkerVerifyDeliverTool(server, { projectRoot, assertPath, verify }) {
|
|
6
6
|
server.registerTool('worker-verify-deliver', {
|
|
7
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.',
|
|
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. Malformed publications return PUBLICATION_INVALID; malformed typed stops return TYPED_STOP_INVALID. launch_count is checked against this MCP server session\'s recorded worker-invoke launches; undercounts return TYPED_STOP_LAUNCH_MISMATCH. A typed stop can only be published before any worker launch in this session; after a launch, the conductor must retry the worker or publish a verified worker artifact. Both produce signed delivery records. The server must run outside conductor confinement.',
|
|
9
9
|
inputSchema: publicationInputSchema,
|
|
10
10
|
annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false },
|
|
11
11
|
}, async input => {
|
|
12
12
|
try {
|
|
13
|
-
const
|
|
14
|
-
if (!parsed.success) throw invalidTypedStop(parsed.error.message);
|
|
15
|
-
const request = parsed.data;
|
|
13
|
+
const request = parsePublication(input);
|
|
16
14
|
const deliverablePath = await assertPath(request.deliverable_path);
|
|
17
15
|
if ('typed_stop' in request) return mcpJson(await verify({ projectDir: projectRoot, deliverablePath, typedStop: request.typed_stop }));
|
|
18
16
|
if (new Set(request.checks.map(entry => entry.id)).size !== request.checks.length) throw new Error('Protected check IDs must be unique');
|
|
@@ -20,7 +18,7 @@ export function registerWorkerVerifyDeliverTool(server, { projectRoot, assertPat
|
|
|
20
18
|
const artifactPath = request.artifact_path && await assertPath(request.artifact_path);
|
|
21
19
|
return mcpJson(await verify({ projectDir: projectRoot, runDir, artifactPath, deliverablePath, checks: request.checks }));
|
|
22
20
|
} catch (error) {
|
|
23
|
-
if (
|
|
21
|
+
if (['PUBLICATION_INVALID', 'TYPED_STOP_INVALID', 'TYPED_STOP_LAUNCH_MISMATCH'].includes(error.code)) return { ...mcpJson({ status: 'rejected', errorCode: error.code, code: error.code, findings: error.findings ?? [error.message] }), isError: true };
|
|
24
22
|
return mcpError(`worker-verify-deliver: ${error.message}`);
|
|
25
23
|
}
|
|
26
24
|
});
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// Own lazily created immutable inputs for one update, including nested redeploys.
|
|
2
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
3
|
+
|
|
4
|
+
const sessions = new AsyncLocalStorage();
|
|
5
|
+
|
|
6
|
+
export async function withDeploymentInputSession(work) {
|
|
7
|
+
const existing = sessions.getStore();
|
|
8
|
+
if (existing && !existing.closed) return work();
|
|
9
|
+
const session = { inputs: new Map(), closed: false };
|
|
10
|
+
return sessions.run(session, async () => {
|
|
11
|
+
let result, workError, failed = false;
|
|
12
|
+
try { result = await work(); }
|
|
13
|
+
catch (error) { workError = error; failed = true; }
|
|
14
|
+
session.closed = true;
|
|
15
|
+
const errors = [];
|
|
16
|
+
for (const { value, dispose } of session.inputs.values()) {
|
|
17
|
+
try { dispose(value); } catch (error) { errors.push(error); }
|
|
18
|
+
}
|
|
19
|
+
session.inputs.clear();
|
|
20
|
+
if (failed) {
|
|
21
|
+
if (errors.length) {
|
|
22
|
+
// Even a frozen or primitive thrown value must keep its identity.
|
|
23
|
+
try { Object.defineProperty(workError, 'disposeErrors', { value: errors, configurable: true }); } catch {}
|
|
24
|
+
}
|
|
25
|
+
throw workError;
|
|
26
|
+
}
|
|
27
|
+
if (errors.length) throw new AggregateError(errors, 'Failed to dispose deployment inputs');
|
|
28
|
+
return result;
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Outside an update, keep the established standalone deployment lifecycle. */
|
|
33
|
+
export function deploymentSessionInput(key, create, dispose) {
|
|
34
|
+
const session = sessions.getStore();
|
|
35
|
+
if (!session || session.closed) return undefined;
|
|
36
|
+
if (!session.inputs.has(key)) session.inputs.set(key, { value: create(), dispose });
|
|
37
|
+
return session.inputs.get(key).value;
|
|
38
|
+
}
|
|
@@ -4,8 +4,10 @@ import { findPackageRoot } from '../cli/find-package-root.js';
|
|
|
4
4
|
import { workerOutputPaths } from './worker-invocation-paths.js';
|
|
5
5
|
import { directWorkerEnvironment } from '../config/worker-attribution.mjs';
|
|
6
6
|
import { createHash } from 'node:crypto';
|
|
7
|
+
import { existsSync } from 'node:fs';
|
|
7
8
|
import { fileURLToPath } from 'node:url';
|
|
8
9
|
import { validateWorkerArtifacts } from './worker-artifacts.mjs';
|
|
10
|
+
import { shellWorkerPromptPath, shellWorkerArtifactsRefusal } from './worker-shell-prompt.mjs';
|
|
9
11
|
import { assertValidWorkerPayload } from '../mission-protocol/codecs.js';
|
|
10
12
|
import { qualificationDigest } from '../models/qualification-digest.mjs';
|
|
11
13
|
import { qualifyWorkerInvocationProfile, assertOperatorWorkerNativeArgv, assertWorkerSelectionAllowed, assertWorkerLaunchMode, requiresWorkerExternalBoundary, assertWorkerHealthQualification, WorkerPolicyError, DEFAULT_WORKER_SELECTION } from '../models/provider-policy.js';
|
|
@@ -21,6 +23,11 @@ import { qualifyWorkerInvocationProfile, assertOperatorWorkerNativeArgv, assertW
|
|
|
21
23
|
export function mcpToolSchemaDigest(schema) {
|
|
22
24
|
return `sha256:${createHash('sha256').update(JSON.stringify(schema)).digest('hex')}`;
|
|
23
25
|
}
|
|
26
|
+
/** JSON plans retain launcher/MCP support; only raw shell artifact delivery is refused. */
|
|
27
|
+
export class WorkerShellArtifactsError extends WorkerPolicyError {
|
|
28
|
+
pointer = '/request/format';
|
|
29
|
+
constructor() { super('OG_ADAPTER_UNQUALIFIED', shellWorkerArtifactsRefusal); }
|
|
30
|
+
}
|
|
24
31
|
export async function prepareWorkerInvocation(invocation, qualification) {
|
|
25
32
|
const result = structuredClone(invocation);
|
|
26
33
|
validateWorkerArtifacts(result);
|
|
@@ -110,42 +117,54 @@ export async function prepareWorkerInvocation(invocation, qualification) {
|
|
|
110
117
|
const deadline = qualification.ceilings?.wallSeconds === undefined ? ''
|
|
111
118
|
: `timeout --signal=KILL ${quote(`${Math.min(result.health?.hardTimeoutSeconds ?? Infinity, result.limits.wallSeconds)}s`)} `;
|
|
112
119
|
const markers = Object.entries(directWorkerEnvironment(result)).map(([name, value]) => `${name}=${quote(value)}`).join(' ');
|
|
113
|
-
const worker = `${deadline}env -i${environment ? ` ${environment}` : ''} ${markers} ${result.argv.map(quote).join(' ')}`;
|
|
114
|
-
const outputs = `> ${quote(result.stdoutPath)} 2> ${quote(result.stderrPath)}`;
|
|
115
|
-
if (result.stdin === 'brief-json') {
|
|
116
|
-
const framer = fileURLToPath(new URL('./worker-stdin-frame.mjs', import.meta.url));
|
|
117
|
-
const frame = [process.execPath, framer, result.briefPath, result.selected.model, result.cwd].map(quote).join(' ');
|
|
118
|
-
result.shellCommand = `cd ${quote(result.cwd)} && env -i ${frame} | ${worker} ${outputs}`;
|
|
119
|
-
}
|
|
120
|
-
else if (result.stdin === 'adapter-frame') {
|
|
121
|
-
const binding = qualification.stdinFramerBinding;
|
|
122
|
-
if (!binding || !absolute(binding.storePath) || !/^sha256:[a-f0-9]{64}$/.test(binding.storeDigest)) {
|
|
123
|
-
throw new Error('Adapter stdin framer requires a trusted installation binding');
|
|
124
|
-
}
|
|
125
|
-
const framer = fileURLToPath(new URL('./worker-stdin-frame.mjs', import.meta.url));
|
|
126
|
-
const frame = [process.execPath, framer, '--adapter-frame', result.briefPath, result.cwd,
|
|
127
|
-
result.selected.cli, qualification.adapterId, result.selected.qualificationDigest, result.briefDigest,
|
|
128
|
-
binding.storePath, binding.storeDigest, JSON.stringify(qualification.policy ?? null), result.selected.model].map(quote).join(' ');
|
|
129
|
-
result.shellCommand = `cd ${quote(result.cwd)} && env -i${environment ? ` ${environment}` : ''} ${frame} | ${worker} ${outputs}`;
|
|
130
|
-
}
|
|
131
|
-
else if (result.stdin === 'closed' || result.stdin === 'brief-text') {
|
|
132
|
-
const stdin = result.stdin === 'closed' ? '< /dev/null' : `< ${quote(result.briefPath)}`;
|
|
133
|
-
result.shellCommand = `cd ${quote(result.cwd)} && ${worker} ${stdin} ${outputs}`;
|
|
134
|
-
}
|
|
135
|
-
else {
|
|
136
|
-
throw new Error(`Unsupported worker stdin mode: ${result.stdin}`);
|
|
137
|
-
}
|
|
138
120
|
const root = findPackageRoot(path.dirname(fileURLToPath(import.meta.url)));
|
|
139
121
|
if (!root)
|
|
140
122
|
throw new Error('Worker shell handoff requires the installed AIWG package root');
|
|
141
|
-
const
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
123
|
+
const promptPath = shellWorkerPromptPath(result.finalPath);
|
|
124
|
+
// Saved plans must revalidate identically through source and compiled loaders.
|
|
125
|
+
const promptModule = 'src/serve/worker-shell-prompt.mjs';
|
|
126
|
+
const promptRuntime = path.join(root, existsSync(path.join(root, promptModule)) ? promptModule : `dist/${promptModule}`);
|
|
127
|
+
if (result.artifacts?.length) {
|
|
128
|
+
// Raw execution has no launcher-owned artifact cleanup or workspace lifecycle.
|
|
129
|
+
result.shellCommand = [process.execPath, promptRuntime, '--refuse-artifacts', root].map(quote).join(' ');
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
const argv = result.argv.map(token => token === result.briefPath ? promptPath : token);
|
|
133
|
+
const worker = `${deadline}env -i${environment ? ` ${environment}` : ''} ${markers} ${argv.map(quote).join(' ')}`;
|
|
134
|
+
const outputs = `> ${quote(result.stdoutPath)} 2> ${quote(result.stderrPath)}`;
|
|
135
|
+
if (result.stdin === 'brief-json') {
|
|
136
|
+
const frame = [process.execPath, promptRuntime, '--brief-json', root, result.briefPath, result.briefDigest ?? '', result.finalPath, result.selected.model, result.cwd].map(quote).join(' ');
|
|
137
|
+
result.shellCommand = `cd ${quote(result.cwd)} && env -i ${frame} | ${worker} ${outputs}`;
|
|
138
|
+
}
|
|
139
|
+
else if (result.stdin === 'adapter-frame') {
|
|
140
|
+
const binding = qualification.stdinFramerBinding;
|
|
141
|
+
if (!binding || !absolute(binding.storePath) || !/^sha256:[a-f0-9]{64}$/.test(binding.storeDigest)) {
|
|
142
|
+
throw new Error('Adapter stdin framer requires a trusted installation binding');
|
|
143
|
+
}
|
|
144
|
+
const frame = [process.execPath, promptRuntime, '--adapter-frame', root, result.briefPath, result.cwd,
|
|
145
|
+
result.selected.cli, qualification.adapterId, result.selected.qualificationDigest, result.briefDigest,
|
|
146
|
+
binding.storePath, binding.storeDigest, JSON.stringify(qualification.policy ?? null), result.selected.model, result.finalPath].map(quote).join(' ');
|
|
147
|
+
result.shellCommand = `cd ${quote(result.cwd)} && env -i${environment ? ` ${environment}` : ''} ${frame} | ${worker} ${outputs}`;
|
|
148
|
+
}
|
|
149
|
+
else if (result.stdin === 'closed' || result.stdin === 'brief-text') {
|
|
150
|
+
const stdin = result.stdin === 'closed' ? '< /dev/null' : `< ${quote(promptPath)}`;
|
|
151
|
+
result.shellCommand = `cd ${quote(result.cwd)} && ${worker} ${stdin} ${outputs}`;
|
|
152
|
+
}
|
|
153
|
+
else {
|
|
154
|
+
throw new Error(`Unsupported worker stdin mode: ${result.stdin}`);
|
|
155
|
+
}
|
|
156
|
+
const guard = path.join(root, 'tools/ralph-external/lib/worker-shell-capture.mjs');
|
|
157
|
+
// Closed probes with no task input need neither a brief file nor a derived prompt.
|
|
158
|
+
const needsPrompt = result.stdin !== 'closed' || result.argv.includes(result.briefPath);
|
|
159
|
+
const binding = { request: { role: qualification.role, task: qualification.task ?? null,
|
|
160
|
+
group: result.selected.group, workdir: result.cwd },
|
|
161
|
+
invocation: { cwd: result.cwd, briefPath: result.briefPath, briefDigest: result.briefDigest, stdin: result.stdin, selected: result.selected },
|
|
162
|
+
paths: { ...workerOutputPaths(result), ...(needsPrompt ? { workerBrief: promptPath } : {}) } };
|
|
163
|
+
// Reserve every output before shell redirection or vendor-owned final writes.
|
|
164
|
+
// Noclobber also protects stream files created between reservation and exec.
|
|
165
|
+
const stage = needsPrompt ? [process.execPath, promptRuntime, '--stage', root, result.briefPath, result.briefDigest ?? '', result.finalPath].map(quote).join(' ') + ' && ' : '';
|
|
166
|
+
result.shellCommand = `${[process.execPath, guard, JSON.stringify(binding)].map(quote).join(' ')} && ${stage}(set -C; ${result.shellCommand})`;
|
|
167
|
+
}
|
|
149
168
|
}
|
|
150
169
|
else {
|
|
151
170
|
const binding = result.mcp;
|
|
@@ -10,7 +10,7 @@ import { workerConfigDigest, validateWorkerHealthConfig } from '../config/aiwg-c
|
|
|
10
10
|
import { intersectWorkerCeilings } from '../models/worker-ceilings.js';
|
|
11
11
|
import { assertValidWorkerPayload } from '../mission-protocol/codecs.js';
|
|
12
12
|
import { qualificationDigest } from '../models/qualification-digest.mjs';
|
|
13
|
-
import { prepareWorkerInvocation } from './worker-invocation-preparation.js';
|
|
13
|
+
import { prepareWorkerInvocation, WorkerShellArtifactsError } from './worker-invocation-preparation.js';
|
|
14
14
|
export { prepareWorkerInvocation, mcpToolSchemaDigest } from './worker-invocation-preparation.js';
|
|
15
15
|
import { isOperatorQualifiedWorkerAdapter, assertOperatorWorkerNativeArgv, assertWorkerLaunchMode, WorkerRoleEffortError, WorkerQualificationPolicyError, requiredWorkerControls, isCanonicalWorkerModelKey, WorkerPolicyError, DEFAULT_WORKER_SELECTION } from '../models/provider-policy.js';
|
|
16
16
|
/** Frozen per-attempt windows; parent/transport ceilings include time already spent. */
|
|
@@ -367,6 +367,8 @@ export async function resolveWorkerInvocation(snapshot, request, drivers, now =
|
|
|
367
367
|
};
|
|
368
368
|
await driver.mcpRegistry.assertWorkerQualified(profile.mcp.serverRef, input);
|
|
369
369
|
}
|
|
370
|
+
if (request.format === 'shell' && prepared.transport === 'shell' && prepared.artifacts?.length)
|
|
371
|
+
throw new WorkerShellArtifactsError();
|
|
370
372
|
plan.invocation = prepared;
|
|
371
373
|
pointer = '/request/brief';
|
|
372
374
|
const rechecked = await readBrief(request.brief);
|
|
@@ -395,7 +397,7 @@ export function workerInvocationDiagnostic(error, pointer, fallback = 'OG_CONFIG
|
|
|
395
397
|
return { code: error.code, pointer: error.pointer, message: error.message };
|
|
396
398
|
if (error instanceof WorkerRoleEffortError)
|
|
397
399
|
return { code: error.code, pointer: error.pointer, message: error.message };
|
|
398
|
-
if (error instanceof WorkerPathScopeError || error instanceof WorkerRequestArgumentError) {
|
|
400
|
+
if (error instanceof WorkerPathScopeError || error instanceof WorkerRequestArgumentError || error instanceof WorkerShellArtifactsError) {
|
|
399
401
|
return { code: error.code, pointer: error.pointer, message: error.message };
|
|
400
402
|
}
|
|
401
403
|
if (error instanceof WorkerInvocationCheckError)
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Private prompt staging shared by shell rendering and its runtime envelope. */
|
|
2
|
+
export function shellWorkerPromptPath(finalPath: string): string;
|
|
3
|
+
export const shellWorkerArtifactsRefusal: string;
|
|
4
|
+
export function stageShellWorkerPrompt(root: string, briefPath: string, briefDigest: string, finalPath: string): Promise<string>;
|
|
5
|
+
export function frameShellWorkerPrompt(root: string, args: string[]): Promise<Buffer>;
|
|
6
|
+
export function frameShellWorkerJson(root: string, args: string[]): Promise<string>;
|