spawnfile 0.1.34 → 0.1.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/dist/audit/readAudit.d.ts +3 -3
  2. package/dist/auth/profileStore.d.ts +3 -1
  3. package/dist/auth/profileStore.js +31 -30
  4. package/dist/auth/types.d.ts +16 -0
  5. package/dist/cli/authCommands.d.ts +1 -1
  6. package/dist/cli/authCommands.js +21 -1
  7. package/dist/cli/runCli.d.ts +2 -0
  8. package/dist/cli/runCli.js +2 -1
  9. package/dist/cli/trainingBooted.d.ts +2 -0
  10. package/dist/cli/trainingBooted.js +5 -1
  11. package/dist/compiler/containerDaimonBrokerRender.js +12 -2
  12. package/dist/compiler/containerDaimonGatewayRender.js +4 -0
  13. package/dist/compiler/containerDaimonUidEntrypointRender.js +3 -1
  14. package/dist/compiler/runProject.d.ts +2 -0
  15. package/dist/compiler/runProject.js +6 -5
  16. package/dist/compiler/runProjectAuth.js +4 -1
  17. package/dist/compiler/training/rewind/contract.d.ts +6 -6
  18. package/dist/compiler/training/trial/boot.d.ts +20 -1
  19. package/dist/compiler/training/trial/boot.js +102 -24
  20. package/dist/compiler/training/trial/docker.d.ts +2 -0
  21. package/dist/compiler/training/trial/docker.js +1 -1
  22. package/dist/compiler/training/trial/gateway.d.ts +5 -0
  23. package/dist/compiler/training/trial/gateway.js +18 -3
  24. package/dist/compiler/training/trial/homeLogin.d.ts +31 -0
  25. package/dist/compiler/training/trial/homeLogin.js +69 -0
  26. package/dist/compiler/training/trial/index.d.ts +5 -1
  27. package/dist/compiler/training/trial/index.js +5 -1
  28. package/dist/compiler/training/trial/judge.d.ts +15 -0
  29. package/dist/compiler/training/trial/judge.js +42 -0
  30. package/dist/compiler/training/trial/launcher.d.ts +28 -13
  31. package/dist/compiler/training/trial/launcher.js +168 -24
  32. package/dist/compiler/training/trial/login.d.ts +35 -0
  33. package/dist/compiler/training/trial/login.js +85 -0
  34. package/dist/compiler/training/trial/realmTurns.d.ts +20 -0
  35. package/dist/compiler/training/trial/realmTurns.js +69 -0
  36. package/dist/manifest/renderSpawnfile.js +2 -1
  37. package/dist/runtime/daimon/config.js +3 -3
  38. package/dist/runtime/daimon/engineDescriptors.generated.d.ts +1 -1
  39. package/dist/runtime/daimon/engineDescriptors.generated.js +1 -1
  40. package/dist/runtime/daimon/index.d.ts +1 -1
  41. package/dist/runtime/daimon/index.js +1 -1
  42. package/dist/runtime/daimon/runAuth.js +8 -0
  43. package/dist/runtime/daimon/subscriptionRealms.d.ts +18 -0
  44. package/dist/runtime/daimon/subscriptionRealms.js +14 -1
  45. package/dist/runtime/daimon/training/booted/adapter.d.ts +5 -1
  46. package/dist/runtime/daimon/training/booted/adapter.js +3 -2
  47. package/dist/runtime/daimon/training/booted/adapter.js.map +1 -1
  48. package/dist/runtime/daimon/training/booted/index.d.ts +3 -1
  49. package/dist/runtime/daimon/training/booted/index.js +2 -1
  50. package/dist/runtime/daimon/training/booted/index.js.map +1 -1
  51. package/dist/runtime/daimon/training/booted/judge.d.ts +39 -0
  52. package/dist/runtime/daimon/training/booted/judge.js +122 -0
  53. package/dist/runtime/daimon/training/booted/judge.js.map +1 -0
  54. package/dist/runtime/trainingGraderProviders.js +10 -4
  55. package/dist/runtime/trainingProviders.d.ts +4 -1
  56. package/dist/runtime/trainingProviders.js +13 -6
  57. package/dist/runtime/usageRequestLedger.d.ts +2 -0
  58. package/dist/runtime/usageRequestLedger.js +3 -1
  59. package/dist/shared/trainingLegacy/trainingLegacyHashDomains.d.ts +1 -0
  60. package/dist/shared/trainingLegacy/trainingLegacyHashDomains.js +1 -0
  61. package/dist/shared/trainingLegacy/trainingLegacyHashDomains.js.map +1 -1
  62. package/package.json +1 -1
  63. package/runtimes.yaml +5 -5
  64. package/dist/runtime/daimon/training/providers/codex-subscription/index.d.ts +0 -1
  65. package/dist/runtime/daimon/training/providers/codex-subscription/index.js +0 -2
  66. package/dist/runtime/daimon/training/providers/codex-subscription/index.js.map +0 -1
  67. package/dist/runtime/daimon/training/providers/codex-subscription/protocol.d.ts +0 -17
  68. package/dist/runtime/daimon/training/providers/codex-subscription/protocol.js +0 -80
  69. package/dist/runtime/daimon/training/providers/codex-subscription/protocol.js.map +0 -1
  70. package/dist/runtime/daimon/training/providers/codex-subscription/provider.d.ts +0 -12
  71. package/dist/runtime/daimon/training/providers/codex-subscription/provider.js +0 -125
  72. package/dist/runtime/daimon/training/providers/codex-subscription/provider.js.map +0 -1
  73. package/dist/runtime/daimon/training/providers/codex-subscription/strict-schema.d.ts +0 -6
  74. package/dist/runtime/daimon/training/providers/codex-subscription/strict-schema.js +0 -219
  75. package/dist/runtime/daimon/training/providers/codex-subscription/strict-schema.js.map +0 -1
  76. package/dist/runtime/daimon/training/providers/grok-subscription/cli.d.ts +0 -19
  77. package/dist/runtime/daimon/training/providers/grok-subscription/cli.js +0 -81
  78. package/dist/runtime/daimon/training/providers/grok-subscription/cli.js.map +0 -1
  79. package/dist/runtime/daimon/training/providers/grok-subscription/index.d.ts +0 -3
  80. package/dist/runtime/daimon/training/providers/grok-subscription/index.js +0 -4
  81. package/dist/runtime/daimon/training/providers/grok-subscription/index.js.map +0 -1
  82. package/dist/runtime/daimon/training/providers/grok-subscription/protocol.d.ts +0 -14
  83. package/dist/runtime/daimon/training/providers/grok-subscription/protocol.js +0 -89
  84. package/dist/runtime/daimon/training/providers/grok-subscription/protocol.js.map +0 -1
  85. package/dist/runtime/daimon/training/providers/grok-subscription/provider.d.ts +0 -9
  86. package/dist/runtime/daimon/training/providers/grok-subscription/provider.js +0 -37
  87. package/dist/runtime/daimon/training/providers/grok-subscription/provider.js.map +0 -1
@@ -1,125 +0,0 @@
1
- import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises';
2
- import { homedir, tmpdir } from 'node:os';
3
- import path from 'node:path';
4
- import { runProcess } from '../../../../../training/index.js';
5
- import { InferenceFailure } from '../../../../../training/index.js';
6
- import { validateInferenceResponse, validateInferenceSchema, validateInferenceSchemaData } from '../../../../../training/index.js';
7
- import { codexStrictSchema, normalizeCodexResponse } from './strict-schema.js';
8
- import { classifyCodexFailure, codexEvidence, consumeCodexFrame } from './protocol.js';
9
- export function codexEnvironment(home) {
10
- // Allowlist prevents profile, provider, proxy, shell startup and key overrides.
11
- const env = { HOME: home, CODEX_HOME: path.join(home, '.codex') };
12
- for (const key of ['PATH', 'TMPDIR', 'SystemRoot', 'LANG', 'LC_ALL']) {
13
- if (process.env[key] !== undefined)
14
- env[key] = process.env[key];
15
- }
16
- return env;
17
- }
18
- export function codexArguments(request, effort, schemaFile) {
19
- return ['exec', '--skip-git-repo-check', '--ephemeral', '--sandbox', 'read-only', '--json',
20
- '--ignore-user-config', '--ignore-rules', '--disable', 'memories',
21
- '-c', 'approval_policy="never"', '-c', 'web_search="disabled"', '-c', 'mcp_servers={}',
22
- '-c', 'project_doc_max_bytes=0', '-c', 'model_provider="openai"',
23
- '-c', 'forced_login_method="chatgpt"', '--model', request.model,
24
- ...(schemaFile === undefined ? [] : ['--output-schema', schemaFile]),
25
- ...(effort === undefined ? [] : ['-c', `model_reasoning_effort=${JSON.stringify(effort)}`]),
26
- ...(request.system === undefined ? [] : ['-c', `developer_instructions=${JSON.stringify(request.system)}`]), '-'];
27
- }
28
- function interrupted(result, signal, evidence = {}) {
29
- if (signal?.aborted)
30
- throw new InferenceFailure('cancelled', 'Codex inference cancelled', evidence);
31
- if (result.stop?.reason === 'timeout')
32
- throw new InferenceFailure('timeout', 'Codex native process deadline expired', evidence);
33
- if (result.error === 'Native protocol ended without a line terminator')
34
- throw new InferenceFailure('protocol', 'Truncated Codex event stream', evidence);
35
- if (result.cancelled || result.error !== undefined)
36
- throw new InferenceFailure('transport', 'Codex native process failed', evidence);
37
- }
38
- export function createCodexInference(options = {}) {
39
- return {
40
- id: 'codex-subscription',
41
- capabilities: { tools: 'contained', billing: 'subscription', temperature: false, seed: false },
42
- async generate(request) {
43
- if (request.responseSchema !== undefined)
44
- validateInferenceSchemaData(request.responseSchema);
45
- const schema = request.responseSchema === undefined ? undefined : structuredClone(request.responseSchema);
46
- const transportSchema = schema === undefined ? undefined : codexStrictSchema(schema);
47
- // Dialect admission owns keyword/path errors; generic compilation must not mask them.
48
- validateInferenceSchema(schema);
49
- if (!request.prompt.trim() || !request.model.trim() || request.model.startsWith('-') ||
50
- request.temperature !== undefined || request.seed !== undefined ||
51
- options.reasoningEffort !== undefined && !['none', 'minimal', 'low', 'medium', 'high', 'xhigh'].includes(options.reasoningEffort)) {
52
- throw new InferenceFailure('unsupported', 'Invalid Codex inference controls');
53
- }
54
- if (request.signal?.aborted)
55
- throw new InferenceFailure('cancelled', 'Codex cancelled before launch');
56
- const root = await mkdtemp(path.join(tmpdir(), 'training-codex-inference-'));
57
- const cwd = path.join(root, 'workspace'), home = path.join(root, 'home');
58
- const env = codexEnvironment(home);
59
- const execute = options.process ?? runProcess;
60
- const command = options.command ?? 'codex';
61
- const frames = { started: false, turning: false, completed: false, text: '', usage: null };
62
- let failure;
63
- try {
64
- await mkdir(cwd);
65
- await mkdir(env['CODEX_HOME'], { recursive: true });
66
- const authHome = options.authHome ?? process.env['CODEX_HOME'] ?? path.join(homedir(), '.codex');
67
- await symlink(path.resolve(authHome, 'auth.json'), path.join(env['CODEX_HOME'], 'auth.json'));
68
- let authText = '';
69
- const auth = await execute({ command, args: ['login', 'status'], cwd, env, stdin: '',
70
- timeoutMs: 15_000, signal: request.signal, onLine: line => { authText += `${line}\n`; } }).completion;
71
- interrupted(auth, request.signal);
72
- // Codex prints advisory `WARNING:` lines (e.g. a temporary CODEX_HOME); anything else must be the exact sign-in line.
73
- const status = `${authText}${auth.stderr}`.split('\n').filter(line => !/^WARNING: /u.test(line)).join('\n').trim();
74
- const signedIn = auth.exitCode === 0 && /^Logged in using ChatGPT$/u.test(status);
75
- authText = '';
76
- if (!signedIn)
77
- throw new InferenceFailure('authentication', 'Codex requires a saved ChatGPT subscription sign-in');
78
- const schemaFile = schema === undefined ? undefined : path.join(cwd, 'response-schema.json');
79
- if (schemaFile !== undefined)
80
- await writeFile(schemaFile, JSON.stringify(transportSchema), { mode: 0o600 });
81
- const result = await execute({ command, args: codexArguments(request, options.reasoningEffort, schemaFile), cwd, env,
82
- stdin: request.prompt, timeoutMs: options.timeoutMs ?? 180_000, signal: request.signal,
83
- requireLineTerminator: true,
84
- onLine: line => {
85
- try {
86
- consumeCodexFrame(frames, line);
87
- }
88
- catch (error) {
89
- failure = error;
90
- throw error;
91
- }
92
- } }).completion;
93
- if (failure)
94
- throw failure;
95
- interrupted(result, request.signal, codexEvidence(frames));
96
- if (result.exitCode !== 0)
97
- throw new InferenceFailure(classifyCodexFailure(result.stderr), 'Codex generation failed', codexEvidence(frames));
98
- if (!frames.completed)
99
- throw new InferenceFailure('protocol', 'Codex omitted a completed final answer', codexEvidence(frames));
100
- try {
101
- if (schema !== undefined)
102
- frames.text = normalizeCodexResponse(frames.text, schema, request.responseJsonFence);
103
- validateInferenceResponse(frames.text, schema, request.responseJsonFence);
104
- }
105
- catch {
106
- throw new InferenceFailure('invalid-response', 'Codex answer violated the requested schema', codexEvidence(frames));
107
- }
108
- return { text: frames.text, model: frames.model ?? request.model,
109
- modelBasis: frames.model === undefined ? 'requested-assumption' : 'provider-reported',
110
- usage: frames.usage, route: 'codex-subscription' };
111
- }
112
- catch (error) {
113
- if (failure)
114
- throw failure;
115
- if (error instanceof InferenceFailure)
116
- throw error;
117
- throw new InferenceFailure('transport', 'Codex inference could not complete', codexEvidence(frames));
118
- }
119
- finally {
120
- await rm(root, { recursive: true, force: true });
121
- }
122
- },
123
- };
124
- }
125
- //# sourceMappingURL=provider.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"provider.js","sourceRoot":"","sources":["../../../../../../src/runtime/daimon/training/providers/codex-subscription/provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC1E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AAI,EAAE,MAAM,CAAC,IAAI,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,IAAI,OAAO,CAAC,KAAK;oBAC9D,UAAU,EAAE,MAAM,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,sBAAsB,CAAC,CAAC,CAAC,mBAAmB;oBACrF,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,KAAK,EAAE,oBAAoB,EAAE,CAAC;YACvD,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,IAAI,OAAO;oBAAE,MAAM,OAAO,CAAC;gBAC3B,IAAI,KAAK,YAAY,gBAAgB;oBAAE,MAAM,KAAK,CAAC;gBACnD,MAAM,IAAI,gBAAgB,CAAC,WAAW,EAAE,oCAAoC,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC;YACvG,CAAC;oBAAS,CAAC;gBAAC,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;YAAC,CAAC;QACjE,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -1,6 +0,0 @@
1
- type Schema = Record<string, unknown>;
2
- /** Translate admitted schema nodes only; do not forward arbitrary keywords. */
3
- export declare function codexStrictSchema(schema: Schema): Schema;
4
- /** Remove transport-added null placeholders only; preserve every originally valid null. */
5
- export declare function normalizeCodexResponse(text: string, schema: Schema, jsonFence?: boolean): string;
6
- export {};
@@ -1,219 +0,0 @@
1
- import { Ajv } from 'ajv';
2
- import { isDeepStrictEqual } from 'node:util';
3
- import { InferenceFailure } from '../../../../../training/index.js';
4
- import { validateInferenceResponse } from '../../../../../training/index.js';
5
- // Wire schemas: graders/{labeling/planning,references/protocol,decomposition/transport},
6
- // inference/decision/teacher and evaluation/semantic/protocol, plus local references.
7
- const allowedKeywords = new Set([
8
- 'type', 'properties', 'required', 'additionalProperties', 'items',
9
- 'enum', 'const', 'description', '$schema', '$ref', 'definitions', '$defs',
10
- 'minimum', 'maximum', 'minLength', 'maxLength', 'minItems', 'maxItems', 'uniqueItems',
11
- ]);
12
- // These authored bounds remain enforced on the completed response by the provider.
13
- const transportOmissions = new Set(['minimum', 'maximum', 'minLength', 'maxLength', '$schema']);
14
- const types = new Set(['object', 'array', 'string', 'number', 'integer', 'boolean', 'null']);
15
- function object(value) {
16
- return value !== null && typeof value === 'object' && !Array.isArray(value);
17
- }
18
- function escapePointer(key) {
19
- return key.replaceAll('~', '~0').replaceAll('/', '~1');
20
- }
21
- function refuse(keyword, pointer, reason = 'keyword is not allowlisted') {
22
- throw new InferenceFailure('unsupported', `Codex strict schema refuses ${keyword} at ${pointer}: ${reason}`);
23
- }
24
- /** Admit only the authored dialect. Literal data and property names are not schemas. */
25
- function admit(schema) {
26
- const locations = new Map();
27
- inspect(schema, '#', locations);
28
- for (const [pointer, node] of locations) {
29
- const seen = new Set();
30
- let target = node;
31
- while (typeof target['$ref'] === 'string') {
32
- const reference = target['$ref'];
33
- if (seen.has(reference))
34
- refuse('$ref', `${pointer}/$ref`, 'reference-only cycles are unsupported');
35
- seen.add(reference);
36
- const resolved = locations.get(reference);
37
- if (!resolved)
38
- refuse('$ref', `${pointer}/$ref`, 'target must be a supported schema location');
39
- target = resolved;
40
- }
41
- }
42
- return locations;
43
- }
44
- function inspect(schema, pointer, locations) {
45
- if (!object(schema))
46
- refuse('schema', pointer, 'expected a schema object');
47
- locations.set(pointer, schema);
48
- // Check keys before their values: no unknown construct can hide an unvisited schema.
49
- for (const keyword of Object.keys(schema)) {
50
- if (!allowedKeywords.has(keyword))
51
- refuse(keyword, `${pointer}/${escapePointer(keyword)}`);
52
- }
53
- for (const [keyword, value] of Object.entries(schema)) {
54
- const location = `${pointer}/${keyword}`;
55
- switch (keyword) {
56
- case 'definitions':
57
- case '$defs':
58
- case 'properties':
59
- if (!object(value))
60
- refuse(keyword, location, 'expected a property map');
61
- for (const [name, child] of Object.entries(value))
62
- inspect(child, `${location}/${escapePointer(name)}`, locations);
63
- break;
64
- case 'items':
65
- if (!object(value))
66
- refuse(keyword, location, 'expected a single schema object; tuples are unsupported');
67
- inspect(value, location, locations);
68
- break;
69
- case '$ref':
70
- if (typeof value !== 'string' || (value !== '#' && !value.startsWith('#/')) ||
71
- value.includes('%') || /~(?![01])/u.test(value)) {
72
- refuse(keyword, location, 'expected an unscoped local JSON pointer without URI encoding');
73
- }
74
- if (Object.keys(schema).some(key => !['$ref', '$schema', 'description', 'definitions', '$defs'].includes(key))) {
75
- refuse(keyword, location, 'cannot preserve sibling validation constraints');
76
- }
77
- break;
78
- case 'additionalProperties':
79
- if (value !== false)
80
- refuse(keyword, location, 'free-form objects are unsupported; expected false');
81
- break;
82
- case 'type': {
83
- const valid = (type) => typeof type === 'string' && types.has(type);
84
- if (!valid(value) && !(Array.isArray(value) && value.length === 2 && value.includes('null') &&
85
- new Set(value).size === 2 && value.every(valid))) {
86
- refuse(keyword, location, 'expected a type or a nullable type pair');
87
- }
88
- break;
89
- }
90
- case 'required':
91
- if (!Array.isArray(value) || value.some(name => typeof name !== 'string') || new Set(value).size !== value.length) {
92
- refuse(keyword, location, 'expected distinct property names');
93
- }
94
- break;
95
- case 'description':
96
- if (typeof value !== 'string')
97
- refuse(keyword, location, 'expected text');
98
- break;
99
- case '$schema':
100
- if (value !== 'http://json-schema.org/draft-07/schema#')
101
- refuse(keyword, location, 'only draft-07 is supported');
102
- break;
103
- case 'enum':
104
- if (!Array.isArray(value) || value.length === 0)
105
- refuse(keyword, location, 'expected nonempty literal choices');
106
- break;
107
- case 'minimum':
108
- case 'maximum':
109
- if (typeof value !== 'number' || !Number.isFinite(value))
110
- refuse(keyword, location, 'expected a finite number');
111
- break;
112
- case 'minLength':
113
- case 'maxLength':
114
- case 'minItems':
115
- case 'maxItems':
116
- if (typeof value !== 'number' || !Number.isInteger(value) || value < 0)
117
- refuse(keyword, location, 'expected a nonnegative integer');
118
- break;
119
- case 'uniqueItems':
120
- if (typeof value !== 'boolean')
121
- refuse(keyword, location, 'expected a boolean');
122
- break;
123
- }
124
- }
125
- }
126
- /** Translate admitted schema nodes only; do not forward arbitrary keywords. */
127
- export function codexStrictSchema(schema) {
128
- admit(schema);
129
- return transport(schema, new Set());
130
- }
131
- function transport(schema, nullableSlots) {
132
- const references = [];
133
- const result = translate(schema, nullableSlots, '#', references);
134
- for (const node of references) {
135
- // Optional slots wrap their original target in anyOf[0], including ancestors.
136
- node['$ref'] = node['$ref'].split('/').map((part, index, parts) => nullableSlots.has(parts.slice(0, index + 1).join('/')) ? `${part}/anyOf/0` : part).join('/');
137
- }
138
- return result;
139
- }
140
- function translate(schema, nullableSlots, pointer, references, enclosingLiteral) {
141
- const literal = enclosingLiteral ?? ['enum', 'const', 'uniqueItems'].find(key => Object.hasOwn(schema, key));
142
- if (literal !== undefined && Object.hasOwn(schema, '$ref')) {
143
- refuse(literal, pointer, 'cannot preserve literal constraints with references');
144
- }
145
- const result = Object.fromEntries(Object.entries(schema).filter(([key]) => !transportOmissions.has(key))
146
- .map(([key, value]) => [key, structuredClone(value)]));
147
- if (typeof schema['$ref'] === 'string')
148
- references.push(result);
149
- for (const keyword of ['properties', 'definitions', '$defs']) {
150
- if (object(schema[keyword])) {
151
- result[keyword] = Object.fromEntries(Object.entries(schema[keyword]).map(([name, child]) => [name, translate(child, nullableSlots, `${pointer}/${keyword}/${escapePointer(name)}`, references, literal)]));
152
- }
153
- }
154
- if (object(schema['items']))
155
- result['items'] = translate(schema['items'], nullableSlots, `${pointer}/items`, references, literal);
156
- if (schema['type'] === 'object' || object(schema['properties']) || Object.hasOwn(schema, 'required') ||
157
- Object.hasOwn(schema, 'additionalProperties') || Array.isArray(schema['type']) && schema['type'].includes('object')) {
158
- const properties = (result['properties'] ?? {});
159
- const required = (schema['required'] ?? []);
160
- if (required.some(key => !Object.hasOwn(properties, key))) {
161
- refuse('required', `${pointer}/required`, 'every required name must be declared in properties');
162
- }
163
- if (schema['additionalProperties'] !== false) {
164
- refuse('additionalProperties', `${pointer}/additionalProperties`, 'free-form objects are unsupported; expected false');
165
- }
166
- for (const key of Object.keys(properties)) {
167
- if (!required.includes(key)) {
168
- properties[key] = { anyOf: [properties[key], { type: 'null' }] };
169
- nullableSlots.add(`${pointer}/properties/${escapePointer(key)}`);
170
- }
171
- }
172
- result['properties'] = properties;
173
- result['required'] = Object.keys(properties);
174
- result['additionalProperties'] = false;
175
- }
176
- // Literal equality and uniqueness must not intersect a changed subtree.
177
- for (const keyword of ['enum', 'const', 'uniqueItems']) {
178
- if (Object.hasOwn(schema, keyword) && !isDeepStrictEqual(result, schema)) {
179
- refuse(keyword, `${pointer}/${keyword}`, 'cannot preserve literal constraints when translation changes their subtree');
180
- }
181
- }
182
- return result;
183
- }
184
- /** Remove transport-added null placeholders only; preserve every originally valid null. */
185
- export function normalizeCodexResponse(text, schema, jsonFence = false) {
186
- const locations = admit(schema);
187
- // Check raw JSON first so duplicate keys and infinities cannot disappear.
188
- validateInferenceResponse(text, {}, jsonFence);
189
- const json = jsonFence ? /^```json\r?\n([\s\S]*?)\r?\n```$/u.exec(text.trim())?.[1] ?? text : text;
190
- const nullableSlots = new Set();
191
- transport(schema, nullableSlots);
192
- const ajv = new Ajv({ strict: true, strictRequired: false }).addSchema(schema, 'original');
193
- function visit(value, node, pointer) {
194
- if (typeof node['$ref'] === 'string') {
195
- const reference = node['$ref'];
196
- return visit(value, locations.get(reference), reference);
197
- }
198
- if (Array.isArray(value) && object(node['items'])) {
199
- return value.map(item => visit(item, node['items'], `${pointer}/items`));
200
- }
201
- if (object(value) && object(node['properties'])) {
202
- for (const [key, child] of Object.entries(node['properties'])) {
203
- if (!Object.hasOwn(value, key))
204
- continue;
205
- const location = `${pointer}/properties/${escapePointer(key)}`;
206
- // Encode each pointer segment so percent/hash property names stay literal.
207
- const uri = location.split('/').map(encodeURIComponent).join('/').replace('%23', '#');
208
- if (value[key] === null && nullableSlots.has(location) && !ajv.getSchema(`original${uri}`)(null))
209
- delete value[key];
210
- else
211
- value[key] = visit(value[key], child, location);
212
- }
213
- }
214
- return value;
215
- }
216
- const normalized = JSON.stringify(visit(JSON.parse(json), schema, '#'));
217
- return normalized === JSON.stringify(JSON.parse(json)) ? text : normalized;
218
- }
219
- //# sourceMappingURL=strict-schema.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"strict-schema.js","sourceRoot":"","sources":["../../../../../../src/runtime/daimon/training/providers/codex-subscription/strict-schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAkB,MAAM,KAAK,CAAC;AAC1C,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAC;AACpE,OAAO,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAG7E,yFAAyF;AACzF,sFAAsF;AACtF,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC;IAC9B,MAAM,EAAE,YAAY,EAAE,UAAU,EAAE,sBAAsB,EAAE,OAAO;IACjE,MAAM,EAAE,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,EAAE,aAAa,EAAE,OAAO;IACzE,SAAS,EAAE,SAAS,EAAE,WAAW,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE,aAAa;CACtF,CAAC,CAAC;AACH,mFAAmF;AACnF,MAAM,kBAAkB,GAAG,IAAI,GAAG,CAAC,CAAC,SAAS,EAAE,SAAS,EAAE,WAAW,EAAE,WAAW,EAAE,SAAS,CAAC,CAAC,CAAC;AAChG,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,CAAC,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC,CAAC;AAE7F,SAAS,MAAM,CAAC,KAAc;IAC5B,OAAO,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CA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G,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;gBACtF,IAAI,KAAK,CAAC,GAAG,CAAC,KAAK,IAAI,IAAI,aAAa,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,WAAW,GAAG,EAAE,CAAE,CAAC,IAAI,CAAC;oBAAE,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC;;oBAChH,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,KAAe,EAAE,QAAQ,CAAC,CAAC;YACjE,CAAC;QACH,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IACD,MAAM,UAAU,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC;IACxE,OAAO,UAAU,KAAK,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC;AAC7E,CAAC"}
@@ -1,19 +0,0 @@
1
- import type { InferenceRequest, InferenceResult } from '../../../../../training/index.js';
2
- import { runProcess } from '../../../../../training/index.js';
3
- export type GrokReasoningEffort = 'low' | 'medium' | 'high' | 'xhigh';
4
- export interface GrokCliRun {
5
- command: string;
6
- cwd: string;
7
- promptFile: string;
8
- /** The complete child environment; nothing else is inherited. */
9
- env: NodeJS.ProcessEnv;
10
- timeoutMs: number;
11
- /** `--model` argument: a catalog model. */
12
- cliModel: string;
13
- reasoningEffort: GrokReasoningEffort;
14
- request: InferenceRequest;
15
- responseSchema: InferenceRequest['responseSchema'];
16
- process?: typeof runProcess;
17
- }
18
- /** One tool-free Grok CLI call with init attestation before any further native frame is consumed. */
19
- export declare function runGrokCli(run: GrokCliRun): Promise<InferenceResult>;
@@ -1,81 +0,0 @@
1
- import { runProcess } from '../../../../../training/index.js';
2
- import { captureInferenceDiagnostic } from '../../../../../training/index.js';
3
- import { InferenceFailure } from '../../../../../training/index.js';
4
- import { validateInferenceResponse } from '../../../../../training/index.js';
5
- import { decodeGrok, grokFailureEvidence, validateGrokInitialization } from './protocol.js';
6
- /** One tool-free Grok CLI call with init attestation before any further native frame is consumed. */
7
- export async function runGrokCli(run) {
8
- const { request, responseSchema } = run;
9
- const frames = {};
10
- let malformed = false;
11
- let nativeFailure;
12
- const process = (run.process ?? runProcess)({ command: run.command, cwd: run.cwd,
13
- // Empty --tools means defaults in Grok. Allow one known tool, then remove
14
- // it and the automatically injected lazy-tool discovery pair.
15
- args: ['--prompt-file', run.promptFile, '--model', run.cliModel, '--tools', 'read_file',
16
- '--disallowed-tools', 'read_file,search_tool,use_tool', '--deny', '*', '--permission-mode', 'dontAsk', '--no-plan',
17
- '--no-memory', '--disable-web-search', '--no-subagents', '--max-turns', '1',
18
- '--reasoning-effort', run.reasoningEffort,
19
- '--output-format', 'streaming-messages-json', '--verbatim',
20
- ...(request.system === undefined ? [] : ['--system-prompt-override', request.system]),
21
- ...(responseSchema === undefined ? [] : ['--json-schema', JSON.stringify(responseSchema)])],
22
- env: run.env, stdin: '', timeoutMs: run.timeoutMs, signal: request.signal,
23
- onLine(line) {
24
- let event;
25
- try {
26
- const raw = JSON.parse(line);
27
- if (raw === null || typeof raw !== 'object' || Array.isArray(raw) || frames.result !== undefined)
28
- throw new Error('Invalid frame');
29
- event = raw;
30
- }
31
- catch {
32
- malformed = true;
33
- throw new Error('Malformed Grok protocol');
34
- }
35
- if (event['type'] === 'system' && event['subtype'] === 'init') {
36
- frames.init = event;
37
- try {
38
- validateGrokInitialization(frames);
39
- }
40
- catch (error) {
41
- nativeFailure = error;
42
- throw error;
43
- }
44
- }
45
- if (event['type'] === 'assistant')
46
- frames.assistant = event;
47
- if (event['type'] === 'result' || event['type'] === 'error')
48
- frames.result = event;
49
- if (frames.init === undefined) {
50
- // A refusal may precede init; classify that typed envelope. Every
51
- // other frame must fail before further native work is consumed.
52
- try {
53
- decodeGrok(frames, 1);
54
- }
55
- catch (error) {
56
- nativeFailure = error;
57
- throw error;
58
- }
59
- }
60
- },
61
- });
62
- const completed = await process.completion;
63
- const evidence = grokFailureEvidence(frames);
64
- if (request.signal?.aborted)
65
- throw new InferenceFailure('cancelled', 'Grok inference cancelled', evidence);
66
- if (nativeFailure)
67
- throw nativeFailure;
68
- if (malformed)
69
- throw new InferenceFailure('protocol', 'Malformed Grok protocol', { ...evidence, diagnostic: captureInferenceDiagnostic('transport-framing') });
70
- if (completed.cancelled || completed.error !== undefined)
71
- throw new InferenceFailure('unknown', 'Grok native process did not settle successfully', { ...evidence, diagnostic: captureInferenceDiagnostic('native-process') });
72
- const result = decodeGrok(frames, completed.exitCode);
73
- try {
74
- validateInferenceResponse(result.text, responseSchema);
75
- }
76
- catch {
77
- throw new InferenceFailure('invalid-response', 'Grok response did not match its requested schema', { ...evidence, diagnostic: captureInferenceDiagnostic('response-schema', result.text) });
78
- }
79
- return result;
80
- }
81
- //# sourceMappingURL=cli.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"cli.js","sourceRoot":"","sources":["../../../../../../src/runtime/daimon/training/providers/grok-subscription/cli.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,kCAAkC,CAAC;AAC9D,OAAO,EAAE,0BAA0B,EAAE,MAAM,kCAAkC,CAAC;AAC9E,OAAO,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAC;AACpE,OAAO,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAC7E,OAAO,EAAE,UAAU,EAAE,mBAAmB,EAAE,0BAA0B,EAAmB,MAAM,eAAe,CAAC;AAmB7G,qGAAqG;AACrG,MAAM,CAAC,KAAK,UAAU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QACH,CAAC;KACF,CAAC,CAAC;IACH,MAAM,SAAS,GAAG,MAAM,OAAO,CAAC,UAAU,CAAC;IAC3C,MAAM,QAAQ,GAAG,mBAAmB,CAAC,MAAM,CAAC,CAAC;IAC7C,IAAI,OAAO,CAAC,MAAM,EAAE,OAAO;QAAE,MAAM,IAAI,gBAAgB,CAAC,WAAW,EAAE,0BAA0B,EAAE,QAAQ,CAAC,CAAC;IAC3G,IAAI,aAAa;QAAE,MAAM,aAAa,CAAC;IACvC,IAAI,SAAS;QAAE,MAAM,IAAI,gBAAgB,CAAC,UAAU,EAAE,yBAAyB,EAAE,EAAE,GAAG,QAAQ,EAAE,UAAU,EAAE,0BAA0B,CAAC,mBAAmB,CAAC,EAAE,CAAC,CAAC;IAC/J,IAAI,SAAS,CAAC,SAAS,IAAI,SAAS,CAAC,KAAK,KAAK,SAAS;QAAE,MAAM,IAAI,gBAAgB,CAAC,SAAS,EAAE,iDAAiD,EAAE,EAAE,GAAG,QAAQ,EAAE,UAAU,EAAE,0BAA0B,CAAC,gBAAgB,CAAC,EAAE,CAAC,CAAC;IAC9N,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,EAAE,SAAS,CAAC,QAAQ,CAAC,CAAC;IACtD,IAAI,CAAC;QAAC,yBAAyB,CAAC,MAAM,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;IAAC,CAAC;IAC/D,MAAM,CAAC;QAAC,MAAM,IAAI,gBAAgB,CAAC,kBAAkB,EAAE,kDAAkD,EAAE,EAAE,GAAG,QAAQ,EAAE,UAAU,EAAE,0BAA0B,CAAC,iBAAiB,EAAE,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAAC,CAAC;IACtM,OAAO,MAAM,CAAC;AAChB,CAAC"}
@@ -1,3 +0,0 @@
1
- export { createGrokInference, type GrokInferenceOptions } from './provider.js';
2
- export { runGrokCli } from './cli.js';
3
- export { decodeGrok, grokFailureEvidence, validateGrokInitialization, type GrokFrames } from './protocol.js';
@@ -1,4 +0,0 @@
1
- export { createGrokInference } from './provider.js';
2
- export { runGrokCli } from './cli.js';
3
- export { decodeGrok, grokFailureEvidence, validateGrokInitialization } from './protocol.js';
4
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../src/runtime/daimon/training/providers/grok-subscription/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAA6B,MAAM,eAAe,CAAC;AAC/E,OAAO,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AACtC,OAAO,EAAE,UAAU,EAAE,mBAAmB,EAAE,0BAA0B,EAAmB,MAAM,eAAe,CAAC"}
@@ -1,14 +0,0 @@
1
- import type { InferenceResult } from '../../../../../training/index.js';
2
- import { type InferenceFailureEvidence } from '../../../../../training/index.js';
3
- export interface GrokFrames {
4
- init?: Record<string, unknown>;
5
- assistant?: Record<string, unknown>;
6
- result?: Record<string, unknown>;
7
- }
8
- /** The route of the saved desktop OAuth login, the only way this provider authenticates. */
9
- export declare const GROK_ROUTE = "grok-subscription";
10
- export declare function grokEnvironment(): NodeJS.ProcessEnv;
11
- export declare function grokFailureEvidence({ init, result }: GrokFrames): InferenceFailureEvidence;
12
- /** Validate before generation proceeds; permission denial alone is not tool isolation. */
13
- export declare function validateGrokInitialization(frames: GrokFrames): void;
14
- export declare function decodeGrok(frames: GrokFrames, exitCode: number | null): InferenceResult;
@@ -1,89 +0,0 @@
1
- import { captureInferenceDiagnostic } from '../../../../../training/index.js';
2
- import { InferenceFailure } from '../../../../../training/index.js';
3
- /** The route of the saved desktop OAuth login, the only way this provider authenticates. */
4
- export const GROK_ROUTE = 'grok-subscription';
5
- export function grokEnvironment() {
6
- const env = { ...process.env };
7
- for (const key of Object.keys(env))
8
- if (/^(XAI_|GROK_(API_KEY|BASE_URL|AUTH_TOKEN)|TYPESAFE_API_KEY|OPENAI_API_KEY|ANTHROPIC_API_KEY)/u.test(key))
9
- delete env[key];
10
- return env;
11
- }
12
- function usageOf(result) {
13
- const raw = result['usage'];
14
- const count = (key) => typeof raw?.[key] === 'number' && Number.isSafeInteger(raw[key]) && raw[key] >= 0 ? raw[key] : null;
15
- const input = count('input_tokens'), read = count('cache_read_input_tokens'), write = count('cache_creation_input_tokens');
16
- const output = count('output_tokens');
17
- const total = input === null || read === null || write === null ? null : input + read + write;
18
- if (total === 0 && output === 0)
19
- return null;
20
- return { inputTokens: total !== null && Number.isSafeInteger(total) ? total : null, cachedInputTokens: read,
21
- cacheWriteInputTokens: write, outputTokens: output, reasoningTokens: null, source: 'grok.result.usage.lower-bound' };
22
- }
23
- export function grokFailureEvidence({ init, result }) {
24
- return { usage: result === undefined ? null : usageOf(result), responseModel: reportedModel(init), responseRoute: GROK_ROUTE };
25
- }
26
- function reportedModel(init) {
27
- return typeof init?.['model'] === 'string' && init['model'].trim() ? init['model'] : null;
28
- }
29
- /** Validate before generation proceeds; permission denial alone is not tool isolation. */
30
- export function validateGrokInitialization(frames) {
31
- const { init } = frames, evidence = grokFailureEvidence(frames);
32
- if (init === undefined)
33
- throw new InferenceFailure('protocol', 'Grok omitted initialization', { ...evidence, diagnostic: captureInferenceDiagnostic('initialization') });
34
- if (init['apiKeySource'] !== 'oauth') {
35
- throw new InferenceFailure('authentication', 'Grok did not acknowledge subscription OAuth', { ...evidence, diagnostic: captureInferenceDiagnostic('subscription') });
36
- }
37
- if (!Array.isArray(init['tools']) || init['tools'].length !== 0 ||
38
- !Array.isArray(init['mcp_servers']) || init['mcp_servers'].length !== 0) {
39
- throw new InferenceFailure('protocol', 'Grok tool isolation was not acknowledged', { ...evidence, diagnostic: captureInferenceDiagnostic('tool-isolation') });
40
- }
41
- }
42
- export function decodeGrok(frames, exitCode) {
43
- const { init, assistant, result } = frames;
44
- const evidence = grokFailureEvidence(frames), usage = evidence.usage ?? null;
45
- const model = reportedModel(init);
46
- const status = result?.['status'] ?? result?.['status_code'] ?? refusalStatus(result);
47
- if (status === 402 || status === 429 || status === 503 || status === 401 || status === 403) {
48
- // The number is the only part of a refusal an operator can act on, so it is
49
- // retained as a number rather than left for someone to read back out of prose.
50
- throw new InferenceFailure(status === 402 || status === 429 ? 'quota' : status === 503 ? 'unavailable' : 'authentication', 'Grok refused inference', { ...evidence, detail: 'provider-status', status });
51
- }
52
- validateGrokInitialization(frames);
53
- const message = assistant?.['message'];
54
- const blocks = message?.['content'];
55
- const validBlocks = Array.isArray(blocks) && blocks.every((block) => block !== null && typeof block === 'object' &&
56
- (block['type'] === 'thinking' ||
57
- (block['type'] === 'text' && typeof block['text'] === 'string')));
58
- const text = validBlocks ? blocks.filter((b) => b['type'] === 'text').map((b) => b['text']).join('') : '';
59
- const issue = exitCode !== 0 ? 'native-process'
60
- : result?.['subtype'] !== 'success' || result['is_error'] !== false || (Array.isArray(result['errors']) && result['errors'].length > 0) ? 'terminal-error'
61
- : !['end_turn', 'stop_sequence'].includes(String(result['stop_reason'])) ? 'unfinished-response'
62
- : !validBlocks ? 'content-shape' : !text.trim() ? 'empty-response'
63
- : result['result'] !== text ? 'response-mismatch'
64
- : assistant?.['session_id'] !== result['session_id'] ? 'session-mismatch'
65
- : message?.['stop_reason'] !== result['stop_reason'] ? 'stop-mismatch' : model === null ? 'model-missing' : undefined;
66
- if (issue)
67
- throw new InferenceFailure('protocol', 'Grok omitted a matching completed response', {
68
- ...evidence, diagnostic: captureInferenceDiagnostic(issue),
69
- });
70
- return { text, model: model, modelBasis: 'provider-reported', usage, route: GROK_ROUTE };
71
- }
72
- /** Decode the native error wrapper, never search arbitrary model output for HTTP text. */
73
- function refusalStatus(result) {
74
- if (result?.['is_error'] !== true || !Array.isArray(result['errors']) || result['errors'].length !== 1)
75
- return undefined;
76
- const error = result['errors'][0];
77
- if (typeof error !== 'string' || !error.startsWith('Internal error: '))
78
- return undefined;
79
- try {
80
- const detail = JSON.parse(error.slice('Internal error: '.length));
81
- if (typeof detail === 'string')
82
- return /^Unauthorized \(401\) /u.test(detail) ? 401 : undefined;
83
- return detail !== null && typeof detail === 'object' ? detail['http_status'] : undefined;
84
- }
85
- catch {
86
- return undefined;
87
- }
88
- }
89
- //# sourceMappingURL=protocol.js.map