@aiwg/cli 2026.10.11 → 2026.10.14
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/model-catalog.v1.json +62 -12
- package/agentic/code/providers/pi/aiwg-bridge.ts +44 -1
- package/dist/src/artifacts/binding-target-identity.js +51 -0
- package/dist/src/artifacts/checksum-manifest.js +12 -0
- package/dist/src/artifacts/index-builder.js +11 -13
- package/dist/src/artifacts/query-engine.js +5 -11
- package/dist/src/cli/handlers/doctor-help.js +32 -0
- package/dist/src/cli/handlers/gates.js +19 -18
- package/dist/src/cli/handlers/models-help.js +7 -1
- package/dist/src/cli/handlers/models.js +3 -3
- package/dist/src/cli/handlers/script-runner.js +8 -5
- package/dist/src/cli/handlers/sessions-intake.js +104 -0
- package/dist/src/cli/handlers/sessions-tail.js +172 -0
- package/dist/src/cli/handlers/sessions.js +90 -17
- package/dist/src/cli/handlers/skill-lint.js +10 -3
- package/dist/src/cli/handlers/steward-format.js +100 -0
- package/dist/src/cli/handlers/steward-models.js +167 -0
- package/dist/src/cli/handlers/steward.js +14 -248
- package/dist/src/cli/handlers/use-bundle-counts.js +87 -0
- package/dist/src/cli/handlers/use-skill-assets.js +207 -0
- package/dist/src/cli/handlers/use.js +35 -216
- package/dist/src/cli/handlers/utilities.js +1 -24
- package/dist/src/config/aiwg-config.js +7 -0
- package/dist/src/config/authorization-cli.js +97 -0
- package/dist/src/config/cli-help.js +1 -0
- package/dist/src/config/cli.js +10 -1
- package/dist/src/decision/context-pruning-common.js +41 -0
- package/dist/src/decision/context-pruning-evaluation.js +366 -0
- package/dist/src/decision/context-pruning-pilot.js +431 -0
- package/dist/src/decision/context-pruning-types.js +19 -0
- package/dist/src/decision/context-pruning.js +5 -846
- package/dist/src/decision/ensemble/contract.js +17 -26
- package/dist/src/decision/ensemble-study/artifacts.js +5 -0
- package/dist/src/decision/ensemble-study/score.js +4 -3
- package/dist/src/decision/feature-export.js +3 -9
- package/dist/src/decision/heldout/collector.js +2 -2
- package/dist/src/decision/issue-triage/runtime.js +3 -9
- package/dist/src/decision/qualification/gates.js +2 -1
- package/dist/src/decision/qualification/release.js +6 -64
- package/dist/src/decision/routing/report.js +2 -0
- package/dist/src/decision/sdlc-screening.js +3 -5
- package/dist/src/decision/sensitivity/comparative.js +5 -3
- package/dist/src/extensions/manifest.js +8 -1
- package/dist/src/extensions/project-local-doctor.js +78 -2
- package/dist/src/extensions/validation.js +10 -11
- package/dist/src/gates/driver.js +6 -77
- package/dist/src/gates/evaluate.js +6 -23
- package/dist/src/gates/floors.js +4 -4
- package/dist/src/gates/index.js +3 -3
- package/dist/src/gates/lattice.js +26 -0
- package/dist/src/gates/registry.js +2 -1
- package/dist/src/gates/report.js +19 -7
- package/dist/src/gates/upstream-ceiling.js +111 -0
- package/dist/src/issues/audit-cli.js +120 -0
- package/dist/src/issues/audit-contract.js +64 -0
- package/dist/src/issues/audit-local.js +82 -0
- package/dist/src/issues/audit.js +220 -0
- package/dist/src/lint/rule-activation.js +15 -1
- package/dist/src/mission-protocol/canonical-codecs.js +270 -0
- package/dist/src/mission-protocol/codecs.js +22 -550
- package/dist/src/mission-protocol/health-trace-codecs.js +281 -0
- package/dist/src/mission-protocol/health-trace-types.js +43 -0
- package/dist/src/mission-protocol/types.js +2 -42
- package/dist/src/mission-protocol/worker-contract-json.js +10 -0
- package/dist/src/mission-protocol/worker-review-gate.js +100 -0
- package/dist/src/mission-protocol/worker-review-types.js +2 -0
- package/dist/src/models/catalog-policy.js +280 -0
- package/dist/src/models/index.js +1 -1
- package/dist/src/models/model-catalog.v1.json +62 -12
- package/dist/src/models/policy-resources.js +28 -0
- package/dist/src/models/provider-models.js +5 -8
- package/dist/src/models/provider-policy.js +10 -546
- package/dist/src/models/resolver.js +26 -8
- package/dist/src/models/router.js +15 -2
- package/dist/src/models/tiers.js +13 -0
- package/dist/src/models/types.js +0 -6
- package/dist/src/models/worker-ceilings.js +59 -0
- package/dist/src/models/worker-invocation-policy.js +243 -0
- package/dist/src/models/worker-plan.js +16 -20
- package/dist/src/models/worker-review-lineage.js +55 -0
- package/dist/src/models/worker-selection-policy.js +1 -1
- package/dist/src/models/wrapper-definitions.js +14 -0
- package/dist/src/models/wrapper-deployment.js +48 -25
- package/dist/src/models/wrapper-enforcement.js +72 -0
- package/dist/src/models/wrapper-route.js +6 -3
- package/dist/src/policy/authorization.js +1 -0
- package/dist/src/policy/hitl-check.js +80 -0
- package/dist/src/policy/hitl-config.js +63 -0
- package/dist/src/policy/hitl-receipt.js +57 -0
- package/dist/src/policy/hitl-types.js +4 -0
- package/dist/src/policy/hitl-validation.js +39 -0
- package/dist/src/policy/hitl.js +117 -0
- package/dist/src/rules/activation.d.mts +3 -1
- package/dist/src/rules/activation.mjs +23 -2
- package/dist/src/rules/gate-coverage.js +51 -0
- package/dist/src/rules/gate-references.js +16 -0
- package/dist/src/rules/rule-frontmatter.schema.json +7 -1
- package/dist/src/serve/worker-command-request.js +21 -4
- package/dist/src/serve/worker-invocation-preparation.js +3 -1
- package/dist/src/serve/worker-invocation.js +21 -10
- package/dist/src/sessions/adapters/deepseek-harness.js +1 -0
- package/dist/src/sessions/adapters/grok-build-native.js +269 -0
- package/dist/src/sessions/adapters/grok-build.js +57 -15
- package/dist/src/sessions/adapters/hermes-state-db.js +252 -0
- package/dist/src/sessions/adapters/hermes.js +42 -3
- package/dist/src/sessions/adapters/warp.js +1 -1
- package/dist/src/sessions/batch-import.js +10 -0
- package/dist/src/sessions/contracts.js +1 -1
- package/dist/src/sessions/discovery-capability.js +38 -0
- package/dist/src/sessions/importer.js +8 -251
- package/dist/src/sessions/index.js +4 -0
- package/dist/src/sessions/intake-dir.js +71 -0
- package/dist/src/sessions/normalization.js +251 -0
- package/dist/src/sessions/tail.js +91 -0
- package/dist/src/sessions/workspace-discovery.js +83 -7
- package/dist/src/skills/adapters/local.js +32 -9
- package/dist/src/skills/agent-skill-sidecar.js +28 -0
- package/dist/src/skills/agent-skills.js +6 -23
- package/dist/src/skills/claude-surface-projection.js +25 -0
- package/dist/src/skills/cli-display.js +33 -0
- package/dist/src/skills/cli.js +2 -26
- package/dist/src/skills/collision-discovery.js +84 -0
- package/dist/src/skills/deployer.js +26 -361
- package/dist/src/skills/deployment-ownership.js +74 -0
- package/dist/src/skills/deployment-policy.js +114 -0
- package/dist/src/skills/deployment-projection.js +152 -0
- package/dist/src/skills/deployment-types.js +20 -0
- package/dist/src/skills/doctor.js +2 -2
- package/dist/src/skills/exporter.js +8 -31
- package/dist/src/skills/importer.js +4 -26
- package/dist/src/skills/provider-extensions.js +41 -0
- package/dist/src/skills/registry.js +22 -7
- package/dist/src/skills/run.js +6 -0
- package/dist/src/skills/types.js +0 -8
- package/dist/src/skills/validator-resources.js +68 -0
- package/dist/src/skills/validator.js +6 -55
- package/dist/src/smiths/context-pipeline/parallelism-section.js +7 -3
- package/dist/src/storage/cli-migrate-options.js +125 -0
- package/dist/src/storage/cli-migrate.js +111 -0
- package/dist/src/storage/cli.js +4 -279
- package/dist/src/storage/migration-adapter.js +79 -0
- package/dist/src/storage/migration-copy.js +108 -0
- package/dist/src/storage/migration-protocol.js +14 -197
- package/dist/src/storage/migration-records.js +186 -0
- package/dist/src/storage/migration-types.js +12 -0
- package/dist/src/tracker/forge-http.js +2 -1
- package/dist/src/tracker/issue-pages.js +110 -0
- package/package.json +3 -1
- package/schemas/mission-v1.schema.json +335 -0
- package/schemas/models/model-catalog.v1.schema.json +19 -1
- package/schemas/models/model-config-compatibility.v1.schema.json +3 -2
- package/schemas/models/model-policy.v1.schema.json +1 -1
- package/tools/agents/providers/antigravity.mjs +3 -5
- package/tools/agents/providers/base.mjs +3 -3
- package/tools/agents/providers/claude.mjs +3 -5
- package/tools/agents/providers/codex.mjs +3 -5
- package/tools/agents/providers/copilot.mjs +3 -5
- package/tools/agents/providers/cursor.mjs +3 -5
- package/tools/agents/providers/factory.mjs +3 -5
- package/tools/agents/providers/grok-build.mjs +9 -7
- package/tools/agents/providers/model-wrapper.mjs +86 -0
- package/tools/agents/providers/omp.mjs +3 -1
- package/tools/agents/providers/openclaw.mjs +3 -5
- package/tools/agents/providers/opencode.mjs +3 -5
- package/tools/agents/providers/provider-paths-staging.mjs +44 -0
- package/tools/agents/providers/rule-binding-targets.mjs +146 -0
- package/tools/agents/providers/rule-delivery.mjs +9 -128
- package/tools/agents/providers/warp.mjs +3 -5
- package/tools/agents/providers/windsurf.mjs +3 -5
- package/tools/plugin/package-plugins.mjs +2 -2
- package/tools/skills/codex-skill-transform.mjs +232 -0
- package/tools/skills/deploy-skills-codex.mjs +8 -249
- package/tools/warp/warp-content.mjs +548 -0
- package/vscode-extension/schemas/aiwg.config.v1.json +177 -0
|
@@ -44,8 +44,6 @@ export function validateRuleFrontmatter(data) {
|
|
|
44
44
|
}
|
|
45
45
|
if (!tagged) diagnostics.push({ severity: 'warn', code: 'missing-activation',
|
|
46
46
|
message: `Missing activation; inferred ${inferRuleActivation(data.enforcement)} delivery (migration fallback); add explicit activation frontmatter.` });
|
|
47
|
-
if (Object.hasOwn(data, 'enforcedBy')) diagnostics.push({ severity: 'info', code: 'reserved-enforcedBy',
|
|
48
|
-
message: 'enforcedBy is opaque reserved metadata (#2839); it has no effect.' });
|
|
49
47
|
const valid = !diagnostics.some(item => item.severity === 'error');
|
|
50
48
|
return {
|
|
51
49
|
valid, diagnostics,
|
|
@@ -59,6 +57,29 @@ export function validateRuleFrontmatter(data) {
|
|
|
59
57
|
};
|
|
60
58
|
}
|
|
61
59
|
|
|
60
|
+
/** Maximum summary length in Unicode code points after trimming (#3728). */
|
|
61
|
+
export const RULE_SUMMARY_MAX_LENGTH = 240;
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Render a rule frontmatter failure as one line naming the file, the field
|
|
65
|
+
* and the limit. Shared by deployment and `aiwg doctor --project-local`
|
|
66
|
+
* (#3728) so both surfaces report the same reason; the raw Ajv pattern
|
|
67
|
+
* message encodes the limit only as a regex, so a too-long summary gets an
|
|
68
|
+
* explicit sentence.
|
|
69
|
+
*/
|
|
70
|
+
export function formatRuleFrontmatterError(file, data, diagnostics) {
|
|
71
|
+
const detail = diagnostics.map((item) => item.message).join('; ');
|
|
72
|
+
const summary = typeof data?.summary === 'string' ? data.summary.trim() : null;
|
|
73
|
+
if (
|
|
74
|
+
summary !== null
|
|
75
|
+
&& [...summary].length > RULE_SUMMARY_MAX_LENGTH
|
|
76
|
+
&& diagnostics.some((item) => item.message.includes('/summary'))
|
|
77
|
+
) {
|
|
78
|
+
return `${file}: summary is ${[...summary].length} characters; the limit is ${RULE_SUMMARY_MAX_LENGTH} characters (single line). ${detail}`;
|
|
79
|
+
}
|
|
80
|
+
return `${file}: ${detail}`;
|
|
81
|
+
}
|
|
82
|
+
|
|
62
83
|
/** Parse complete Markdown source, preserving authored body and opaque metadata. */
|
|
63
84
|
export function parseRuleFrontmatter(content) {
|
|
64
85
|
const source = content.replace(/^\uFEFF/, '');
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/** Read rule sources and report declared gate coverage without executing gates. */
|
|
2
|
+
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { buildGatesRegistry, installedAiwgRoot } from '../gates/driver.js';
|
|
5
|
+
import { parseRuleFrontmatter } from './activation.mjs';
|
|
6
|
+
import { ruleFiles } from './pin-state.js';
|
|
7
|
+
import { ruleGateReferenceErrors } from './gate-references.js';
|
|
8
|
+
function bundleRuleDirs(root) {
|
|
9
|
+
if (!existsSync(root))
|
|
10
|
+
return [];
|
|
11
|
+
return readdirSync(root, { withFileTypes: true }).filter(entry => entry.isDirectory())
|
|
12
|
+
.map(entry => path.join(root, entry.name, 'rules'));
|
|
13
|
+
}
|
|
14
|
+
export function listRuleGateCoverage(options = {}, ruleId) {
|
|
15
|
+
const cwd = path.resolve(options.cwd ?? process.cwd());
|
|
16
|
+
const root = path.resolve(options.aiwgRoot ?? installedAiwgRoot());
|
|
17
|
+
const dirs = [path.join(cwd, 'rules'), path.join(cwd, '.aiwg/rules')];
|
|
18
|
+
for (const group of ['frameworks', 'addons', 'extensions']) {
|
|
19
|
+
dirs.push(...bundleRuleDirs(path.join(root, 'agentic/code', group)), ...bundleRuleDirs(path.join(cwd, '.aiwg', group)));
|
|
20
|
+
}
|
|
21
|
+
for (const candidate of options.packDirs ?? []) {
|
|
22
|
+
const dir = path.resolve(cwd, candidate);
|
|
23
|
+
if (statSync(dir).isDirectory())
|
|
24
|
+
dirs.push(path.join(dir, 'rules'));
|
|
25
|
+
}
|
|
26
|
+
const files = [...new Set(dirs.flatMap(ruleFiles))].sort().filter(file => !/^(?:README|RULES-INDEX|RULES-ONDEMAND)\.md$/.test(path.basename(file)) && !file.endsWith('.core.md'));
|
|
27
|
+
const { registry } = buildGatesRegistry(options);
|
|
28
|
+
const rules = [];
|
|
29
|
+
for (const file of files) {
|
|
30
|
+
const name = path.basename(file, '.md');
|
|
31
|
+
const id = path.relative(file.startsWith(`${root}${path.sep}`) ? root : cwd, file).split(path.sep).join('/');
|
|
32
|
+
// Match exact names or source identities; suffix guesses can select another rule.
|
|
33
|
+
if (ruleId && ![name, id, file].includes(ruleId))
|
|
34
|
+
continue;
|
|
35
|
+
const parsed = parseRuleFrontmatter(readFileSync(file, 'utf8'));
|
|
36
|
+
if (!parsed.valid)
|
|
37
|
+
throw new Error(`${file}: ${parsed.diagnostics.map(item => item.message).join('; ')}`);
|
|
38
|
+
const enforcedBy = parsed.rule.enforcedBy ?? [];
|
|
39
|
+
const errors = ruleGateReferenceErrors(enforcedBy, registry);
|
|
40
|
+
if (errors.length)
|
|
41
|
+
throw new Error(`${file}: ${errors.join('; ')}`);
|
|
42
|
+
rules.push({ id, name, file, enforcedBy, status: enforcedBy.length ? 'gate-backed' : 'guidance-only' });
|
|
43
|
+
}
|
|
44
|
+
return rules;
|
|
45
|
+
}
|
|
46
|
+
export function formatRuleGateCoverage(rules) {
|
|
47
|
+
if (!rules.length)
|
|
48
|
+
return 'No rules found.';
|
|
49
|
+
return rules.map(rule => `${rule.id}: ${rule.status}${rule.enforcedBy.length ? `\n${rule.enforcedBy.map(gate => ` ${gate}`).join('\n')}` : ''}`).join('\n');
|
|
50
|
+
}
|
|
51
|
+
//# sourceMappingURL=gate-coverage.js.map
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export function ruleGateReferenceErrors(references, registry) {
|
|
2
|
+
const errors = [];
|
|
3
|
+
for (const reference of references) {
|
|
4
|
+
const [packId, gateId] = reference.split('#');
|
|
5
|
+
try {
|
|
6
|
+
const pack = registry.resolvePack(packId).resolved;
|
|
7
|
+
if (!pack.spec.gates.some(gate => gate.id === gateId))
|
|
8
|
+
throw new Error(`unknown gate '${gateId}' in ${packId}`);
|
|
9
|
+
}
|
|
10
|
+
catch (error) {
|
|
11
|
+
errors.push(`enforcedBy '${reference}': ${error instanceof Error ? error.message : String(error)}`);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
return errors;
|
|
15
|
+
}
|
|
16
|
+
//# sourceMappingURL=gate-references.js.map
|
|
@@ -66,7 +66,13 @@
|
|
|
66
66
|
}
|
|
67
67
|
},
|
|
68
68
|
"enforcedBy": {
|
|
69
|
-
"description": "
|
|
69
|
+
"description": "Gate references as <namespaced-pack-id>#<gate-id>. Lint resolves each reference against the gate registry. Declares coverage without changing activation or executing gates.",
|
|
70
|
+
"type": "array",
|
|
71
|
+
"uniqueItems": true,
|
|
72
|
+
"items": {
|
|
73
|
+
"type": "string",
|
|
74
|
+
"pattern": "^(?:(?:aiwg|framework|addon|extension):[^/\\s:#]+/[^/\\s:#]+|project:[^/\\s:#]+)#[^\\s#]+$"
|
|
75
|
+
}
|
|
70
76
|
}
|
|
71
77
|
},
|
|
72
78
|
"allOf": [
|
|
@@ -6,14 +6,18 @@ export class WorkerRequestArgumentError extends WorkerPolicyError {
|
|
|
6
6
|
constructor(key) {
|
|
7
7
|
super('OG_CONFIG_REFERENCE', key === 'task'
|
|
8
8
|
? `Missing required --task. Valid task classes: ${Object.keys(DEFAULT_WORKER_SELECTION.taskClasses).join(', ')}, plus classes configured in defaults.workerSelection.taskClasses.`
|
|
9
|
-
:
|
|
10
|
-
|
|
9
|
+
: key === 'wallSeconds' ? '--timeout-ms must be a positive safe integer multiple of 1000 (whole seconds).'
|
|
10
|
+
: key === 'maxAttempts' || key === 'tokens' ? `--${key === 'tokens' ? 'max-output-tokens' : 'max-attempts'} must be a positive safe integer.`
|
|
11
|
+
: key === 'costUsd' ? '--max-usd must be a finite nonnegative number.'
|
|
12
|
+
: `--${key.replace('_', '-')} must be an absolute path; relative paths are not resolved against cwd or --workdir.`);
|
|
13
|
+
this.pointer = `/request/${['maxAttempts', 'tokens', 'costUsd', 'wallSeconds'].includes(key) ? 'ceilings/' : ''}${key}`;
|
|
11
14
|
}
|
|
12
15
|
}
|
|
13
16
|
/** Reject unsupported syntax before discovery or any path reads. */
|
|
14
17
|
export function parseWorkerCommandArgs(args) {
|
|
15
18
|
const names = { role: 'role', task: 'task', group: 'group', brief: 'brief',
|
|
16
|
-
workdir: 'workdir', 'final-output': 'final_output', transport: 'transport', format: 'format'
|
|
19
|
+
workdir: 'workdir', 'final-output': 'final_output', transport: 'transport', format: 'format',
|
|
20
|
+
'max-attempts': 'maxAttempts', 'timeout-ms': 'wallSeconds', 'max-output-tokens': 'tokens', 'max-usd': 'costUsd' };
|
|
17
21
|
const result = {};
|
|
18
22
|
let json = false;
|
|
19
23
|
let premiumAuthorized = false;
|
|
@@ -63,6 +67,19 @@ export function parseWorkerCommandArgs(args) {
|
|
|
63
67
|
throw new Error('Unsupported transport');
|
|
64
68
|
if (result.format && !['shell', 'json'].includes(result.format))
|
|
65
69
|
throw new Error('Unsupported renderer; use POSIX shell or JSON');
|
|
66
|
-
|
|
70
|
+
const ceilings = {};
|
|
71
|
+
for (const key of ['maxAttempts', 'wallSeconds', 'tokens', 'costUsd']) {
|
|
72
|
+
if (result[key] === undefined)
|
|
73
|
+
continue;
|
|
74
|
+
const value = Number(result[key]);
|
|
75
|
+
if (!result[key].trim() || !Number.isFinite(value) || value < 0
|
|
76
|
+
|| key !== 'costUsd' && (!Number.isSafeInteger(value) || value === 0)
|
|
77
|
+
|| key === 'wallSeconds' && value % 1000 !== 0)
|
|
78
|
+
throw new WorkerRequestArgumentError(key);
|
|
79
|
+
ceilings[key] = key === 'wallSeconds' ? value / 1000 : value;
|
|
80
|
+
delete result[key];
|
|
81
|
+
}
|
|
82
|
+
return { ...result, ...(Object.keys(ceilings).length ? { ceilings } : {}),
|
|
83
|
+
...(premiumAuthorized ? { authority: { premiumAuthorized: true, maxAutoTier: 3 } } : {}) };
|
|
67
84
|
}
|
|
68
85
|
//# sourceMappingURL=worker-command-request.js.map
|
|
@@ -104,7 +104,9 @@ export async function prepareWorkerInvocation(invocation, qualification) {
|
|
|
104
104
|
// The frozen 'closed' value means empty stdin (immediate EOF). 'brief-json'
|
|
105
105
|
// pipes a conductor-built params document framed from the brief file
|
|
106
106
|
// (worker-stdin-frame.mjs), so brief text never enters any argv.
|
|
107
|
-
const
|
|
107
|
+
const deadline = qualification.ceilings?.wallSeconds === undefined ? ''
|
|
108
|
+
: `timeout --signal=KILL ${quote(`${Math.min(result.health?.hardTimeoutSeconds ?? Infinity, result.limits.wallSeconds)}s`)} `;
|
|
109
|
+
const worker = `${deadline}env -i${environment ? ` ${environment}` : ''} ${result.argv.map(quote).join(' ')}`;
|
|
108
110
|
const outputs = `> ${quote(result.stdoutPath)} 2> ${quote(result.stderrPath)}`;
|
|
109
111
|
if (result.stdin === 'brief-json') {
|
|
110
112
|
const framer = fileURLToPath(new URL('./worker-stdin-frame.mjs', import.meta.url));
|
|
@@ -7,6 +7,7 @@ export { inspectWorkerPath } from './worker-invocation-paths.js';
|
|
|
7
7
|
import { createHash, randomUUID } from 'node:crypto';
|
|
8
8
|
import { resolveWorkerPlan } from '../models/resolver.js';
|
|
9
9
|
import { workerConfigDigest, validateWorkerHealthConfig } from '../config/aiwg-config.js';
|
|
10
|
+
import { intersectWorkerCeilings } from '../models/worker-ceilings.js';
|
|
10
11
|
import { assertValidWorkerPayload } from '../mission-protocol/codecs.js';
|
|
11
12
|
import { qualificationDigest } from '../models/qualification-digest.mjs';
|
|
12
13
|
import { prepareWorkerInvocation } from './worker-invocation-preparation.js';
|
|
@@ -180,19 +181,19 @@ export async function resolveWorkerInvocation(snapshot, request, drivers, now =
|
|
|
180
181
|
throw new WorkerPolicyError('OG_PIN_MISMATCH', 'Brief role/task/group/workspace/output differs from request');
|
|
181
182
|
}
|
|
182
183
|
}
|
|
184
|
+
// Brief and parent authority restrict caller ceilings; neither can overwrite them.
|
|
185
|
+
const intent = managedIntent ?? brief?.intent;
|
|
186
|
+
if (intent)
|
|
187
|
+
snapshot.constraints = { ...snapshot.constraints, ceilings: intersectWorkerCeilings(snapshot.constraints?.ceilings, { ...intent.limits, costUsd: intent.limits.costUsd ?? undefined }) };
|
|
183
188
|
plan = resolveWorkerPlan(snapshot, { role: request.role, taskClass: request.task, group: request.group,
|
|
184
189
|
transport: request.transport, authority: request.authority, now, expectedDigests: expected?.digests,
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
} } : {}),
|
|
189
|
-
...(managedIntent ? { dataClass: managedIntent.dataClass, member: managedIntent.pins.member,
|
|
190
|
-
model: managedIntent.pins.model, effort: managedIntent.pins.effort?.value,
|
|
191
|
-
ceilings: { ...managedIntent.limits, costUsd: managedIntent.limits.costUsd ?? undefined } } : {}),
|
|
190
|
+
ceilings: request.ceilings,
|
|
191
|
+
...(intent ? { dataClass: intent.dataClass, member: intent.pins.member,
|
|
192
|
+
model: intent.pins.model, effort: intent.pins.effort?.value } : {}),
|
|
192
193
|
context: { estimator: 'utf8-byte-upper-bound-v1', briefTokens: bytes?.length ?? 0,
|
|
193
194
|
inputTokens: 0, toolOutputAllowance: 1024, reservedOutput: 1024 },
|
|
194
195
|
requiredControls: snapshot.config.parallelism?.health?.requireStepCap ? ['stepCap'] : [],
|
|
195
|
-
});
|
|
196
|
+
}, { tokens: 50000, wallSeconds: 900 });
|
|
196
197
|
plan.request = structuredClone(request);
|
|
197
198
|
if (!plan.selected)
|
|
198
199
|
return plan;
|
|
@@ -246,8 +247,8 @@ export async function resolveWorkerInvocation(snapshot, request, drivers, now =
|
|
|
246
247
|
if (!await inspectPath(path.dirname(output), 'directory'))
|
|
247
248
|
outputParentsExist = false;
|
|
248
249
|
}
|
|
249
|
-
const limits = { tokens:
|
|
250
|
-
wallSeconds:
|
|
250
|
+
const limits = { tokens: plan.ceilings.tokens, costUsd: plan.ceilings.costUsd ?? null,
|
|
251
|
+
wallSeconds: plan.ceilings.wallSeconds, maxAttempts: plan.ceilings.maxAttempts };
|
|
251
252
|
const observation = snapshot.catalog.discovery.instances[tuple.cli].models.find(row => row.id === tuple.model || row.apiModelId === tuple.model).worker;
|
|
252
253
|
const profile = adapter.invocationProfiles[tuple.profile];
|
|
253
254
|
const expiresAt = new Date(Math.min(Date.parse(now) + 300000, Date.parse(tuple.observedAt) + (plan.policy?.freshness?.blockHours ?? DEFAULT_WORKER_SELECTION.freshness.blockHours) * 3600000, Math.min(Date.parse(tuple.verifiedAt), Date.parse(adapter.qualification.verifiedAt), profile.installationQualification ? Date.parse(profile.installationQualification.verifiedAt) : Infinity)
|
|
@@ -290,6 +291,15 @@ export async function resolveWorkerInvocation(snapshot, request, drivers, now =
|
|
|
290
291
|
throw new Error('Installed adapter stdin framer is required');
|
|
291
292
|
if (transport.mcp?.timeoutSeconds !== undefined)
|
|
292
293
|
effectiveHealth = resolveWorkerEffectiveHealth(healthConfig, { ...healthInput, transportSeconds: Math.min(healthInput.transportSeconds ?? Infinity, transport.mcp.timeoutSeconds) });
|
|
294
|
+
if (request.ceilings?.wallSeconds !== undefined && request.ceilings.wallSeconds > effectiveHealth.hardTimeoutSeconds) {
|
|
295
|
+
plan.status = 'blocked';
|
|
296
|
+
plan.selected = null;
|
|
297
|
+
plan.diagnostics.push({ code: 'OG_POLICY_RELAXATION', pointer: '/request/ceilings/wallSeconds',
|
|
298
|
+
message: `Requested wallSeconds ceiling ${request.ceilings.wallSeconds} exceeds resolved policy ceiling ${effectiveHealth.hardTimeoutSeconds}.` });
|
|
299
|
+
return plan;
|
|
300
|
+
}
|
|
301
|
+
if (effectiveHealth.hardTimeoutSeconds === limits.wallSeconds)
|
|
302
|
+
effectiveHealth.origins?.hardTimeoutSeconds.push(...(plan.origins?.['/ceilings/wallSeconds'] ?? []).map(origin => origin.pointer));
|
|
293
303
|
if (workerConfigDigest(driver.qualification) !== qualificationDigest)
|
|
294
304
|
throw new WorkerPolicyError('OG_PIN_MISMATCH', 'Installation profile digest changed during resolution');
|
|
295
305
|
const invocation = { version: 1, mode: managedIntent ? 'managed' : 'direct', transport: tuple.transport, selected,
|
|
@@ -306,6 +316,7 @@ export async function resolveWorkerInvocation(snapshot, request, drivers, now =
|
|
|
306
316
|
controlEvidence: isOperatorQualifiedWorkerAdapter(adapter) ? [adapter.qualification.evidenceRef, ...controls.map(name => profile.controls[name].evidence)] : controls.map(name => profile.controls[name].evidence),
|
|
307
317
|
health: effectiveHealth, };
|
|
308
318
|
const invocationQualification = { ...qualification, now: Date.parse(now),
|
|
319
|
+
ceilings: request.ceilings,
|
|
309
320
|
policy: plan.policy, permissions: tuple.permissions, role: request.role, modelObservation: observation,
|
|
310
321
|
expectedDigests: { policyDigest, catalogDigest: plan.digests.catalogDigest, profileDigest: plan.digests.profileDigest, briefDigest },
|
|
311
322
|
requiredControls: controls };
|
|
@@ -25,6 +25,7 @@ export class DeepSeekHarnessSessionAdapter {
|
|
|
25
25
|
limits;
|
|
26
26
|
maxFiles;
|
|
27
27
|
provider = 'deepseek-harness';
|
|
28
|
+
sourceSchemaMajor = 2;
|
|
28
29
|
adapterVersion = DEEPSEEK_HARNESS_ADAPTER_VERSION;
|
|
29
30
|
disposition = 'implemented';
|
|
30
31
|
supportedOperations = ['discover', 'inspect', 'stream'];
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
// Native Grok Build session-store reader (synthetic schema v1; real stores never inspected).
|
|
2
|
+
import { opendir, readFile } from 'node:fs/promises';
|
|
3
|
+
import { dirname, resolve } from 'node:path';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
import { integer, number } from '../../schema/zod-validation.mjs';
|
|
6
|
+
import { schemaIssueDetail, schemaRejectionDetail, SessionContractError, assertSupportedSchemaMajor, } from '../contracts.js';
|
|
7
|
+
import { matchSessionWorkspace } from '../workspace-matching.js';
|
|
8
|
+
import { authorizeSourceFile } from '../policy.js';
|
|
9
|
+
import { streamBoundedJsonLines, } from '../readers.js';
|
|
10
|
+
export const GROK_BUILD_NATIVE_SCHEMA_VERSION = '1.0.0';
|
|
11
|
+
export const GROK_BUILD_NATIVE_SCHEMA_MAJOR = 1;
|
|
12
|
+
export const GROK_BUILD_NATIVE_LOCATOR_CLASS = 'grok-build-native-chat-history';
|
|
13
|
+
export const GROK_BUILD_NATIVE_SESSION_FILENAME = 'chat_history.jsonl';
|
|
14
|
+
export const GROK_BUILD_ACTIVE_SESSIONS_SCHEMA_VERSION = 1;
|
|
15
|
+
export const GROK_BUILD_ACTIVE_FRESHNESS_MS = 120_000;
|
|
16
|
+
export const GROK_BUILD_NATIVE_DISCOVERY_MAX_FILES = 10_000;
|
|
17
|
+
const ACTIVE_SESSIONS_MAX_BYTES = 1024 * 1024;
|
|
18
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
19
|
+
// Synthetic native record shape (v1): one JSON object per line. Real
|
|
20
|
+
// chat_history.jsonl schemas are unqualified (real stores are never read),
|
|
21
|
+
// so any record outside this shape fails closed with SCHEMA_DRIFT.
|
|
22
|
+
const NativeRecordSchema = z.looseObject({
|
|
23
|
+
schemaVersion: z.union([z.string(), z.number()]),
|
|
24
|
+
sessionId: z.string().regex(UUID),
|
|
25
|
+
seq: integer().nonnegative(),
|
|
26
|
+
role: z.enum(['user', 'assistant', 'tool']),
|
|
27
|
+
content: z.string(),
|
|
28
|
+
timestamp: number().optional(),
|
|
29
|
+
toolName: z.string().min(1).optional(),
|
|
30
|
+
toolCallId: z.string().optional(),
|
|
31
|
+
id: z.string().min(1).optional(),
|
|
32
|
+
});
|
|
33
|
+
const ActiveSessionsSchema = z.looseObject({
|
|
34
|
+
schemaVersion: z.union([z.string(), z.number()]),
|
|
35
|
+
sessions: z.array(z.looseObject({
|
|
36
|
+
sessionId: z.string().regex(UUID),
|
|
37
|
+
cwd: z.string().optional(),
|
|
38
|
+
lastHeartbeatAt: number().optional(),
|
|
39
|
+
})),
|
|
40
|
+
});
|
|
41
|
+
/** Decode a url-encoded cwd directory name exactly once; null means skip. */
|
|
42
|
+
export function decodeGrokBuildWorkspaceDir(name) {
|
|
43
|
+
if (!name || name.includes('/') || name.includes('\\'))
|
|
44
|
+
return null;
|
|
45
|
+
let decoded;
|
|
46
|
+
try {
|
|
47
|
+
decoded = decodeURIComponent(name);
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
if (!decoded.startsWith('/') || decoded.includes('\0'))
|
|
53
|
+
return null;
|
|
54
|
+
return decoded;
|
|
55
|
+
}
|
|
56
|
+
export function grokBuildNativeSessionId(locator) {
|
|
57
|
+
const sessionId = dirname(locator).split('/').pop()?.split('\\').pop() ?? '';
|
|
58
|
+
return UUID.test(sessionId) ? sessionId.toLowerCase() : null;
|
|
59
|
+
}
|
|
60
|
+
/** Enumerate documented `<root>/<url-encoded cwd>/<id>/chat_history.jsonl` paths. */
|
|
61
|
+
export async function* discoverGrokBuildNativeChatHistories(root, maxFiles = GROK_BUILD_NATIVE_DISCOVERY_MAX_FILES) {
|
|
62
|
+
const resolved = resolve(root);
|
|
63
|
+
let workspaces;
|
|
64
|
+
try {
|
|
65
|
+
workspaces = await opendir(resolved);
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
let count = 0;
|
|
71
|
+
for await (const workspace of workspaces) {
|
|
72
|
+
if (!workspace.isDirectory())
|
|
73
|
+
continue;
|
|
74
|
+
const decoded = decodeGrokBuildWorkspaceDir(workspace.name);
|
|
75
|
+
if (!decoded)
|
|
76
|
+
continue;
|
|
77
|
+
const workspacePath = resolve(resolved, workspace.name);
|
|
78
|
+
if (workspacePath !== resolved && !workspacePath.startsWith(`${resolved}/`))
|
|
79
|
+
continue;
|
|
80
|
+
let sessions;
|
|
81
|
+
try {
|
|
82
|
+
sessions = await opendir(workspacePath);
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
for await (const session of sessions) {
|
|
88
|
+
if (!session.isDirectory() || !UUID.test(session.name))
|
|
89
|
+
continue;
|
|
90
|
+
const sessionPath = resolve(workspacePath, session.name);
|
|
91
|
+
if (!sessionPath.startsWith(`${workspacePath}/`))
|
|
92
|
+
continue;
|
|
93
|
+
let entries;
|
|
94
|
+
try {
|
|
95
|
+
entries = await opendir(sessionPath);
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
for await (const entry of entries) {
|
|
101
|
+
if (!entry.isFile() || entry.name !== GROK_BUILD_NATIVE_SESSION_FILENAME)
|
|
102
|
+
continue;
|
|
103
|
+
if (++count > maxFiles) {
|
|
104
|
+
throw new SessionContractError('RESOURCE_LIMIT_EXCEEDED', 'Grok Build native session discovery exceeded the authorized file limit', { limit: 'maxFiles', configured: maxFiles, observed: count });
|
|
105
|
+
}
|
|
106
|
+
yield {
|
|
107
|
+
provider: 'grok-build',
|
|
108
|
+
locator: resolve(sessionPath, entry.name),
|
|
109
|
+
locatorClass: GROK_BUILD_NATIVE_LOCATOR_CLASS,
|
|
110
|
+
nativeSessionId: session.name.toLowerCase(),
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/** Match a native locator against the authorized workspace via its cwd directory. */
|
|
117
|
+
export async function grokBuildSourceWorkspaceMatch(locator, workspacePath) {
|
|
118
|
+
const segments = locator.replace(/\\/g, '/').split('/');
|
|
119
|
+
const encoded = segments.at(-3);
|
|
120
|
+
if (!encoded)
|
|
121
|
+
return null;
|
|
122
|
+
const decoded = decodeGrokBuildWorkspaceDir(encoded);
|
|
123
|
+
if (!decoded)
|
|
124
|
+
return null;
|
|
125
|
+
return matchSessionWorkspace(decoded, workspacePath);
|
|
126
|
+
}
|
|
127
|
+
export async function readGrokBuildNativeChatHistory(source, limits) {
|
|
128
|
+
const sessionId = grokBuildNativeSessionId(source.locator);
|
|
129
|
+
if (source.locatorClass !== GROK_BUILD_NATIVE_LOCATOR_CLASS || !sessionId) {
|
|
130
|
+
throw new SessionContractError('SOURCE_NOT_AUTHORIZED', 'Grok Build native source must be an explicitly authorized chat_history.jsonl path');
|
|
131
|
+
}
|
|
132
|
+
await authorizeSourceFile({
|
|
133
|
+
selectedPath: source.locator,
|
|
134
|
+
allowedRoots: source.authorizedScope.allowedRoots,
|
|
135
|
+
});
|
|
136
|
+
const input = await streamBoundedJsonLines({
|
|
137
|
+
selectedPath: source.locator,
|
|
138
|
+
allowedRoots: source.authorizedScope.allowedRoots,
|
|
139
|
+
}, { consistency: 'provisional', limits });
|
|
140
|
+
const records = [];
|
|
141
|
+
let lastSeq = -1;
|
|
142
|
+
for await (const line of input) {
|
|
143
|
+
const parsed = NativeRecordSchema.safeParse(line.value);
|
|
144
|
+
if (!parsed.success) {
|
|
145
|
+
throw new SessionContractError('SCHEMA_DRIFT', 'unrecognized Grok Build native chat_history.jsonl record', schemaRejectionDetail(parsed.error));
|
|
146
|
+
}
|
|
147
|
+
assertSupportedSchemaMajor(declaredSchema(parsed.data.schemaVersion), GROK_BUILD_NATIVE_SCHEMA_MAJOR);
|
|
148
|
+
if (parsed.data.sessionId.toLowerCase() !== sessionId) {
|
|
149
|
+
throw new SessionContractError('SCHEMA_DRIFT', 'Grok Build native record session does not match its session directory', schemaIssueDetail('sessionId'));
|
|
150
|
+
}
|
|
151
|
+
if (parsed.data.seq <= lastSeq) {
|
|
152
|
+
throw new SessionContractError('SCHEMA_DRIFT', 'Grok Build native chat history sequence is not strictly increasing', schemaIssueDetail('seq'));
|
|
153
|
+
}
|
|
154
|
+
lastSeq = parsed.data.seq;
|
|
155
|
+
if (parsed.data.role === 'tool' && !parsed.data.toolName) {
|
|
156
|
+
throw new SessionContractError('SCHEMA_DRIFT', 'Grok Build native tool record is missing its tool name', schemaIssueDetail('toolName'));
|
|
157
|
+
}
|
|
158
|
+
records.push({ record: parsed.data, line });
|
|
159
|
+
}
|
|
160
|
+
if (records.length === 0) {
|
|
161
|
+
throw new SessionContractError('MALFORMED_SOURCE', 'Grok Build native chat history is empty', schemaIssueDetail('<root>'));
|
|
162
|
+
}
|
|
163
|
+
return { records, incompleteTail: input.incompleteTail };
|
|
164
|
+
}
|
|
165
|
+
export function toGrokBuildNativeRecord(sessionId, entry) {
|
|
166
|
+
const { record, line } = entry;
|
|
167
|
+
const occurredAt = timestamp(record.timestamp);
|
|
168
|
+
const nativeEventId = record.id ?? `${sessionId}:${record.seq}`;
|
|
169
|
+
const common = {
|
|
170
|
+
lifecycle: 'unknown-at-import',
|
|
171
|
+
provenance: {
|
|
172
|
+
product: 'grok-build',
|
|
173
|
+
acquisition: GROK_BUILD_NATIVE_LOCATOR_CLASS,
|
|
174
|
+
sourceSchema: GROK_BUILD_NATIVE_SCHEMA_VERSION,
|
|
175
|
+
nativeStoreInspected: true,
|
|
176
|
+
},
|
|
177
|
+
identity: { nativeSessionIdKnown: true, nativeEventIdKnown: true },
|
|
178
|
+
};
|
|
179
|
+
if (record.role === 'tool') {
|
|
180
|
+
return {
|
|
181
|
+
nativeSessionId: sessionId,
|
|
182
|
+
nativeEventId,
|
|
183
|
+
sequence: line.sequence * 1_000,
|
|
184
|
+
kind: 'tool-call',
|
|
185
|
+
role: 'tool',
|
|
186
|
+
toolName: record.toolName,
|
|
187
|
+
toolCallId: record.toolCallId,
|
|
188
|
+
occurredAt,
|
|
189
|
+
text: record.content,
|
|
190
|
+
rawReference: { locatorClass: GROK_BUILD_NATIVE_LOCATOR_CLASS, sequence: line.sequence },
|
|
191
|
+
extensions: common,
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
return {
|
|
195
|
+
nativeSessionId: sessionId,
|
|
196
|
+
nativeEventId,
|
|
197
|
+
sequence: line.sequence * 1_000,
|
|
198
|
+
kind: 'message',
|
|
199
|
+
role: record.role,
|
|
200
|
+
occurredAt,
|
|
201
|
+
text: record.content,
|
|
202
|
+
rawReference: { locatorClass: GROK_BUILD_NATIVE_LOCATOR_CLASS, sequence: line.sequence },
|
|
203
|
+
extensions: common,
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
/** Read and validate active_sessions.json (read-only, bounded); throws on misuse. */
|
|
207
|
+
export async function readGrokBuildActiveRegistry(selectedPath, allowedRoots) {
|
|
208
|
+
const authorized = await authorizeSourceFile({
|
|
209
|
+
selectedPath, allowedRoots, maxBytes: ACTIVE_SESSIONS_MAX_BYTES,
|
|
210
|
+
});
|
|
211
|
+
const raw = await readFile(authorized.canonicalPath, 'utf8');
|
|
212
|
+
let value;
|
|
213
|
+
try {
|
|
214
|
+
value = JSON.parse(raw);
|
|
215
|
+
}
|
|
216
|
+
catch {
|
|
217
|
+
throw new SessionContractError('SCHEMA_DRIFT', 'Grok Build active_sessions.json is not valid JSON', schemaIssueDetail('<root>'));
|
|
218
|
+
}
|
|
219
|
+
const parsed = ActiveSessionsSchema.safeParse(value);
|
|
220
|
+
if (!parsed.success) {
|
|
221
|
+
throw new SessionContractError('SCHEMA_DRIFT', 'unrecognized Grok Build active_sessions.json shape', schemaRejectionDetail(parsed.error));
|
|
222
|
+
}
|
|
223
|
+
assertSupportedSchemaMajor(declaredSchema(parsed.data.schemaVersion), GROK_BUILD_ACTIVE_SESSIONS_SCHEMA_VERSION);
|
|
224
|
+
return parsed.data;
|
|
225
|
+
}
|
|
226
|
+
/** Provider-reported activity only; never a verified running process. */
|
|
227
|
+
export function grokBuildLiveState(registry, sessionId, nowMs = Date.now()) {
|
|
228
|
+
if (!registry)
|
|
229
|
+
return { state: 'unknown', basis: 'none', reasonCode: 'NO_ACTIVE_SESSIONS_GRANT' };
|
|
230
|
+
const entry = registry.sessions.find((item) => item.sessionId.toLowerCase() === sessionId.toLowerCase());
|
|
231
|
+
if (!entry)
|
|
232
|
+
return { state: 'unknown', basis: 'grok-active-sessions', reasonCode: 'SESSION_NOT_LISTED' };
|
|
233
|
+
if (entry.lastHeartbeatAt === undefined) {
|
|
234
|
+
return { state: 'unknown', basis: 'grok-active-sessions', reasonCode: 'NO_HEARTBEAT' };
|
|
235
|
+
}
|
|
236
|
+
const heartbeatMs = entry.lastHeartbeatAt < 10_000_000_000
|
|
237
|
+
? entry.lastHeartbeatAt * 1_000
|
|
238
|
+
: entry.lastHeartbeatAt;
|
|
239
|
+
if (!Number.isFinite(heartbeatMs)) {
|
|
240
|
+
return { state: 'unknown', basis: 'grok-active-sessions', reasonCode: 'INVALID_HEARTBEAT' };
|
|
241
|
+
}
|
|
242
|
+
if (heartbeatMs > nowMs) {
|
|
243
|
+
return { state: 'unknown', basis: 'grok-active-sessions', reasonCode: 'FUTURE_HEARTBEAT' };
|
|
244
|
+
}
|
|
245
|
+
if (nowMs - heartbeatMs > GROK_BUILD_ACTIVE_FRESHNESS_MS) {
|
|
246
|
+
return { state: 'unknown', basis: 'grok-active-sessions', reasonCode: 'STALE_HEARTBEAT' };
|
|
247
|
+
}
|
|
248
|
+
return { state: 'active', basis: 'grok-active-sessions', reasonCode: 'FRESH_HEARTBEAT' };
|
|
249
|
+
}
|
|
250
|
+
export function parseGrokBuildNativeCursor(value) {
|
|
251
|
+
if (!value)
|
|
252
|
+
return 0;
|
|
253
|
+
if (!/^\d+$/.test(value)) {
|
|
254
|
+
throw new SessionContractError('SCHEMA_DRIFT', 'invalid Grok Build native cursor', schemaIssueDetail('cursor'));
|
|
255
|
+
}
|
|
256
|
+
return Number(value);
|
|
257
|
+
}
|
|
258
|
+
function declaredSchema(value) {
|
|
259
|
+
if (typeof value === 'number')
|
|
260
|
+
return `${value}.0.0`;
|
|
261
|
+
return /^\d+$/.test(String(value)) ? `${value}.0.0` : String(value);
|
|
262
|
+
}
|
|
263
|
+
function timestamp(value) {
|
|
264
|
+
if (value === undefined || value === null)
|
|
265
|
+
return undefined;
|
|
266
|
+
const date = new Date(value < 10_000_000_000 ? value * 1_000 : value);
|
|
267
|
+
return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
|
|
268
|
+
}
|
|
269
|
+
//# sourceMappingURL=grok-build-native.js.map
|
|
@@ -1,31 +1,49 @@
|
|
|
1
1
|
import { basename, extname } from 'node:path';
|
|
2
2
|
import { SessionContractError, schemaIssueDetail, } from '../contracts.js';
|
|
3
3
|
import { readBoundedText } from '../readers.js';
|
|
4
|
+
import { discoverGrokBuildNativeChatHistories, GROK_BUILD_NATIVE_DISCOVERY_MAX_FILES, GROK_BUILD_NATIVE_LOCATOR_CLASS, GROK_BUILD_NATIVE_SCHEMA_VERSION, grokBuildNativeSessionId, parseGrokBuildNativeCursor, readGrokBuildNativeChatHistory, toGrokBuildNativeRecord, } from './grok-build-native.js';
|
|
4
5
|
export const GROK_BUILD_ADAPTER_VERSION = '1.0.0';
|
|
5
6
|
export const GROK_BUILD_CLI_EXPORT_SCHEMA_VERSION = '1.0.0';
|
|
6
7
|
export const GROK_BUILD_CLI_EXPORT_LOCATOR_CLASS = 'grok-build-cli-markdown-export';
|
|
7
8
|
/**
|
|
8
|
-
* Imports the documented `grok export <session-id> <file>` surface
|
|
9
|
+
* Imports the documented `grok export <session-id> <file>` surface plus the
|
|
10
|
+
* native `chat_history.jsonl` store under an explicitly authorized
|
|
11
|
+
* sessions root (`--grok-root`).
|
|
9
12
|
*
|
|
10
|
-
* The public export contract is intentionally lossy.
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
+
* The public export contract is intentionally lossy. Native reads use the
|
|
14
|
+
* synthetic v1 schema in grok-build-native.ts (real stores were never
|
|
15
|
+
* inspected); anything outside it fails closed. AIWG never runs
|
|
16
|
+
* `grok export` itself: export remains an operator-selected fallback.
|
|
13
17
|
*/
|
|
14
18
|
export class GrokBuildSessionAdapter {
|
|
15
19
|
limits;
|
|
20
|
+
maxFiles;
|
|
16
21
|
provider = 'grok-build';
|
|
17
22
|
adapterVersion = GROK_BUILD_ADAPTER_VERSION;
|
|
18
23
|
disposition = 'implemented';
|
|
19
|
-
supportedOperations = ['inspect', 'stream'];
|
|
20
|
-
acquisitionModes = ['manual-export'];
|
|
21
|
-
constructor(limits) {
|
|
24
|
+
supportedOperations = ['discover', 'inspect', 'stream'];
|
|
25
|
+
acquisitionModes = ['manual-export', 'jsonl'];
|
|
26
|
+
constructor(limits, maxFiles = GROK_BUILD_NATIVE_DISCOVERY_MAX_FILES) {
|
|
22
27
|
this.limits = limits;
|
|
28
|
+
this.maxFiles = maxFiles;
|
|
23
29
|
}
|
|
24
|
-
async *discover(
|
|
25
|
-
|
|
26
|
-
|
|
30
|
+
async *discover(scope) {
|
|
31
|
+
if (scope.allowedRoots.length === 0) {
|
|
32
|
+
throw new SessionContractError('SOURCE_NOT_AUTHORIZED', 'Grok Build native discovery requires an explicitly authorized sessions root; pass --grok-root.');
|
|
33
|
+
}
|
|
34
|
+
for (const root of [...scope.allowedRoots].sort()) {
|
|
35
|
+
yield* discoverGrokBuildNativeChatHistories(root, this.maxFiles);
|
|
36
|
+
}
|
|
27
37
|
}
|
|
28
38
|
async inspect(source) {
|
|
39
|
+
if (source.locatorClass === GROK_BUILD_NATIVE_LOCATOR_CLASS) {
|
|
40
|
+
const native = await readGrokBuildNativeChatHistory(source, this.limits);
|
|
41
|
+
return {
|
|
42
|
+
sourceSchemaVersion: GROK_BUILD_NATIVE_SCHEMA_VERSION,
|
|
43
|
+
consistency: native.incompleteTail ? 'provisional' : 'complete',
|
|
44
|
+
operationalState: 'available',
|
|
45
|
+
};
|
|
46
|
+
}
|
|
29
47
|
await this.readSource(source);
|
|
30
48
|
return {
|
|
31
49
|
sourceSchemaVersion: GROK_BUILD_CLI_EXPORT_SCHEMA_VERSION,
|
|
@@ -34,13 +52,33 @@ export class GrokBuildSessionAdapter {
|
|
|
34
52
|
};
|
|
35
53
|
}
|
|
36
54
|
async *stream(source, cursor) {
|
|
55
|
+
if (source.locatorClass === GROK_BUILD_NATIVE_LOCATOR_CLASS) {
|
|
56
|
+
const sessionId = grokBuildNativeSessionId(source.locator);
|
|
57
|
+
if (!sessionId) {
|
|
58
|
+
throw new SessionContractError('SOURCE_NOT_AUTHORIZED', 'Grok Build native source must be an explicitly authorized chat_history.jsonl path');
|
|
59
|
+
}
|
|
60
|
+
const native = await readGrokBuildNativeChatHistory(source, this.limits);
|
|
61
|
+
const start = parseGrokBuildNativeCursor(cursor?.value);
|
|
62
|
+
let outputIndex = 0;
|
|
63
|
+
for (const entry of native.records) {
|
|
64
|
+
const position = outputIndex;
|
|
65
|
+
outputIndex += 1;
|
|
66
|
+
if (position < start)
|
|
67
|
+
continue;
|
|
68
|
+
const record = toGrokBuildNativeRecord(sessionId, entry);
|
|
69
|
+
record.sourceCursor = String(outputIndex);
|
|
70
|
+
yield record;
|
|
71
|
+
}
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
37
74
|
const parsed = await this.readSource(source);
|
|
38
75
|
const start = parseCursor(cursor?.value);
|
|
76
|
+
let outputIndex = 0;
|
|
39
77
|
for (const [sequence, block] of parsed.blocks.entries()) {
|
|
40
|
-
if (sequence < start)
|
|
41
|
-
continue;
|
|
42
78
|
if (block.heading === 'Tools') {
|
|
43
|
-
for (const tool of parseTools(block.text, sequence))
|
|
79
|
+
for (const tool of parseTools(block.text, sequence)) {
|
|
80
|
+
if (outputIndex++ < start)
|
|
81
|
+
continue;
|
|
44
82
|
yield {
|
|
45
83
|
nativeSessionId: parsed.sessionId,
|
|
46
84
|
nativeEventId: undefined,
|
|
@@ -53,8 +91,11 @@ export class GrokBuildSessionAdapter {
|
|
|
53
91
|
rawReference: { locatorClass: source.locatorClass, sequence },
|
|
54
92
|
extensions: provenance(source, parsed.sessionId, 'Tools'),
|
|
55
93
|
};
|
|
94
|
+
}
|
|
56
95
|
continue;
|
|
57
96
|
}
|
|
97
|
+
if (outputIndex++ < start)
|
|
98
|
+
continue;
|
|
58
99
|
yield {
|
|
59
100
|
nativeSessionId: parsed.sessionId,
|
|
60
101
|
nativeEventId: undefined,
|
|
@@ -70,8 +111,9 @@ export class GrokBuildSessionAdapter {
|
|
|
70
111
|
}
|
|
71
112
|
async readSource(source) {
|
|
72
113
|
if (source.locatorClass !== GROK_BUILD_CLI_EXPORT_LOCATOR_CLASS) {
|
|
73
|
-
throw new SessionContractError('UNSUPPORTED_OPERATION', 'Grok Build accepts only a documented `grok export` Markdown transcript
|
|
74
|
-
+
|
|
114
|
+
throw new SessionContractError('UNSUPPORTED_OPERATION', 'Grok Build accepts only a documented `grok export` Markdown transcript or an '
|
|
115
|
+
+ `explicitly authorized \`${GROK_BUILD_NATIVE_LOCATOR_CLASS}\` source; `
|
|
116
|
+
+ 'Grok Bot exports and Cursor stores are not supported.');
|
|
75
117
|
}
|
|
76
118
|
const filename = basename(source.locator, extname(source.locator));
|
|
77
119
|
if (extname(source.locator).toLowerCase() !== '.md' || !UUID.test(filename)) {
|