@sabaiway/agent-workflow-kit 23.2.0 → 23.3.0

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.
@@ -0,0 +1,392 @@
1
+ import { describe, it, after } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { dirname, join, resolve } from 'node:path';
6
+ import { fileURLToPath, pathToFileURL } from 'node:url';
7
+ import { spawn, spawnSync } from 'node:child_process';
8
+ import { createServer } from 'node:http';
9
+ import { once } from 'node:events';
10
+
11
+ const HERE = dirname(fileURLToPath(import.meta.url));
12
+ const BRIDGE = resolve(HERE, '..');
13
+ const REPO = resolve(BRIDGE, '..');
14
+ const HOST = 'api.jev.invalid';
15
+ const ENDPOINT = `https://${HOST}/v1/systemone`;
16
+ const KEY_VARIABLE = 'TYPESAFE_API_KEY';
17
+ const REQUEST_ID = 'req-1';
18
+ const STATE_LIMIT = 30000;
19
+ const BODY_LIMIT = 60000;
20
+ const made = [];
21
+ const client = () => import('./jev-client.mjs');
22
+ const read = (path) => readFileSync(path, 'utf8');
23
+ const readManifest = () => JSON.parse(read(join(BRIDGE, 'capability.json')));
24
+ const getModel = () => { const model = readManifest().posture?.model; assert.ok(model, 'capability.json posture.model is absent'); return model; };
25
+ const getFacts = () => [read(join(REPO, 'codex-cli-bridge/service-facts.txt')).split('\n')[0], `HOST=${HOST}`, `RUN_HOST=${HOST}`, `PASSED_VARIABLE=${KEY_VARIABLE}`, ''].join('\n');
26
+ const makeQuestion = (instructions = 'Choose the supported option.') => ({ type: 'choice', instructions, criteria: { yes: 'Supported', no: 'Unsupported' } });
27
+ const makeRequest = () => ({ state: 'The build passed and the change is ready for review.', questions: { ready: makeQuestion(), safe: { ...makeQuestion(), criteria: { yes: 'Safe', no: 'Unsafe', unsure: 'Unclear' } } } });
28
+ const makeAnswer = (model, request = makeRequest()) => ({ model, answers: Object.fromEntries(Object.entries(request.questions).map(([id, question]) => [id, { type: 'choice', choice: Object.keys(question.criteria)[0], probabilities: Object.fromEntries(Object.keys(question.criteria).map((option, index) => [option, index === 0 ? 1 : 0])), confidence: 0.9 }])) });
29
+ const makeResponse = (body, status = 200, headers = { 'x-typesafe-request-id': REQUEST_ID }) => new Response(typeof body === 'string' ? body : JSON.stringify(body), { status, headers });
30
+ const neverCall = () => assert.fail('transport must not be called');
31
+ const makeFixture = (context, wrapper = false) => {
32
+ if (wrapper) read(join(HERE, 'jev-ask.sh'));
33
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'jev-ask-')));
34
+ made.push(root);
35
+ const home = join(root, 'home');
36
+ mkdirSync(home);
37
+ if (wrapper) cpSync(HERE, join(root, 'bin'), { recursive: true });
38
+ cpSync(join(BRIDGE, 'capability.json'), join(root, 'capability.json'));
39
+ writeFileSync(join(root, 'service-facts.txt'), getFacts());
40
+ const path = join(root, 'request.json');
41
+ writeFileSync(path, JSON.stringify(makeRequest()));
42
+ const key = `tsk-test-${Buffer.from(context.name).toString('hex')}-${'Q7xZp3'.repeat(6)}`;
43
+ const preload = join(root, 'no-network.mjs');
44
+ writeFileSync(preload, "globalThis.fetch = async () => { throw new Error('unexpected transport call'); };\n");
45
+ const env = { PATH: process.env.PATH ?? '', HOME: home, LC_ALL: 'C', [KEY_VARIABLE]: key, NODE_OPTIONS: `--import=${pathToFileURL(preload).href}` };
46
+ return { root, path, key, env, argv: ['--host', HOST, '--key-variable', KEY_VARIABLE, path] };
47
+ };
48
+ after(() => made.forEach((root) => rmSync(root, { recursive: true, force: true })));
49
+ const assertOutcome = (result, key, code, posture = false, shared = false) => {
50
+ assert.equal(result.code, code, result.stderr);
51
+ for (const stream of [result.stdout, result.stderr]) { assert.equal(typeof stream, 'string'); assert.equal(stream.includes(key.trim()), false, 'key leaked'); }
52
+ const lines = result.stderr === '' ? [] : result.stderr.split('\n').slice(0, -1);
53
+ assert.equal(result.stderr, lines.length ? `${lines.join('\n')}\n` : '');
54
+ assert.equal(lines.length, Number(posture) + Number(code !== 0), result.stderr);
55
+ if (posture) assert.match(lines[0], /^judge posture: /);
56
+ if (code !== 0) { assert.equal(result.stdout, ''); assert.match(lines.at(-1), shared ? /^error: / : /^jev-ask: /); }
57
+ return result;
58
+ };
59
+ const runClient = async (cli, fixture, code, options = {}, posture = false) => {
60
+ const calls = [];
61
+ const transport = (...args) => { calls.push(args); return (options.transport ?? neverCall)(...args); };
62
+ const result = await cli.runJudgeCli({ argv: fixture.argv, env: fixture.env, folder: fixture.root, ...options, transport });
63
+ assertOutcome(result, fixture.key, code, posture);
64
+ assert.equal(calls.length, Number(posture), 'one request only after posture');
65
+ return result;
66
+ };
67
+ const runWrapper = (fixture, argv, code, overrides = {}, posture = false, shared = false, bash = 'bash') => {
68
+ const result = spawnSync(bash, [join(fixture.root, 'bin/jev-ask.sh'), ...argv], { cwd: fixture.root, env: { ...fixture.env, ...overrides }, encoding: 'utf8', timeout: 5000 });
69
+ assert.ifError(result.error);
70
+ assert.equal(result.signal, null, result.stderr);
71
+ return assertOutcome({ code: result.status, stdout: result.stdout, stderr: result.stderr }, fixture.key, code, posture, shared);
72
+ };
73
+ const addPreload = (fixture, body, status = 200) => {
74
+ const log = join(fixture.root, 'fetch.log');
75
+ const preload = join(fixture.root, 'preload.mjs');
76
+ writeFileSync(preload, `import { appendFileSync } from 'node:fs';\nglobalThis.fetch = async (url) => { appendFileSync(${JSON.stringify(log)}, String(url) + '\\n'); return new Response(${JSON.stringify(JSON.stringify(body))}, { status: ${status}, headers: { 'x-typesafe-request-id': '${REQUEST_ID}' } }); };\n`);
77
+ return { NODE_OPTIONS: `--import=${pathToFileURL(preload).href}`, log };
78
+ };
79
+ const addRecordingNode = (fixture) => {
80
+ const bin = join(fixture.root, 'recording');
81
+ mkdirSync(bin);
82
+ const argv = join(fixture.root, 'node.argv');
83
+ const env = join(fixture.root, 'node.env');
84
+ const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
85
+ writeFileSync(join(bin, 'node'), `#!/usr/bin/env bash\nprintf '%s\\n' "$@" > ${quote(argv)}\nprintf '%s' "\${TYPESAFE_API_KEY-}" > ${quote(env)}\nexec ${quote(process.execPath)} "$@"\n`);
86
+ chmodSync(join(bin, 'node'), 0o755);
87
+ return { PATH: `${bin}:${fixture.env.PATH}`, argv, env };
88
+ };
89
+ const listFiles = (root, relative = '') => readdirSync(join(root, relative), { withFileTypes: true }).flatMap((entry) => entry.name === 'node_modules' ? [] : entry.isDirectory() ? listFiles(root, join(relative, entry.name)) : [join(relative, entry.name)]).sort();
90
+ const scanFolder = (root) => {
91
+ const files = listFiles(root).filter((file) => !file.endsWith('.test.mjs'));
92
+ const hits = files.flatMap((file) => {
93
+ const text = read(join(root, file));
94
+ return [file !== 'service-facts.txt' && /[a-z0-9.-]*typesafe\.ai\b/i.test(text) ? `${file}: host` : null, file !== 'capability.json' && /\bjev-(?:\d+(?:\.\d+)*|latest)\b/i.test(text) ? `${file}: model` : null].filter(Boolean);
95
+ });
96
+ return { files, hits };
97
+ };
98
+
99
+ it('spec:typesafe-jev-bridge/S1 posts the pinned two-question request and prints only normalized notes', async (context) => {
100
+ const cli = await client();
101
+ const fixture = makeFixture(context);
102
+ const model = getModel();
103
+ for (const requestId of [REQUEST_ID, null]) {
104
+ const calls = [];
105
+ const answer = makeAnswer(model);
106
+ const transport = async (...args) => { calls.push(args); return makeResponse(answer, 200, requestId ? { 'x-typesafe-request-id': requestId } : {}); };
107
+ const result = await runClient(cli, fixture, 0, { env: { [KEY_VARIABLE]: ` ${fixture.key} ` }, transport }, true);
108
+ assert.equal(result.stderr, `judge posture: model=${model} host=${HOST} timeout=10s\n`);
109
+ assert.match(result.stdout, /[^\n]\n$/);
110
+ assert.deepEqual(JSON.parse(result.stdout), { model, requestId, notes: Object.fromEntries(Object.entries(answer.answers).map(([id, { type, ...note }]) => [id, note])) });
111
+ assert.equal(calls.length, 1);
112
+ const [url, init] = calls[0];
113
+ assert.equal(String(url), ENDPOINT);
114
+ assert.equal(init.method, 'POST');
115
+ assert.equal(init.redirect, 'manual');
116
+ const headers = new Headers(init.headers);
117
+ assert.equal(headers.get('authorization'), `Bearer ${fixture.key}`);
118
+ assert.equal(headers.get('content-type'), 'application/json');
119
+ assert.deepEqual(JSON.parse(init.body), { ...makeRequest(), model });
120
+ }
121
+ const request = { ...makeRequest(), questions: { 'a\nb': makeQuestion(), 'a b': makeQuestion() } };
122
+ writeFileSync(fixture.path, JSON.stringify(request));
123
+ const answer = makeAnswer(model, request);
124
+ const result = await runClient(cli, fixture, 0, { transport: async () => makeResponse(answer) }, true);
125
+ assert.deepEqual(Object.keys(JSON.parse(result.stdout).notes).sort(), Object.keys(request.questions).sort());
126
+ });
127
+ it('spec:typesafe-jev-bridge/S2 trims key presence and validates the request before a missing key', async (context) => {
128
+ const cli = await client();
129
+ const fixture = makeFixture(context);
130
+ for (const value of [undefined, '', ' ', '\u00a0']) {
131
+ const env = value === undefined ? {} : { [KEY_VARIABLE]: value };
132
+ assert.equal(cli.keyIsSet(env, KEY_VARIABLE), false);
133
+ await runClient(cli, fixture, 3, { env });
134
+ }
135
+ assert.equal(cli.keyIsSet({ [KEY_VARIABLE]: ' k ' }, KEY_VARIABLE), true);
136
+ writeFileSync(fixture.path, '{not json');
137
+ await runClient(cli, fixture, 2, { env: {} });
138
+ });
139
+ it('spec:typesafe-jev-bridge/S3 bounds a stalled transport and a stalled response body', { timeout: 3000 }, async (context) => {
140
+ const cli = await client();
141
+ assert.equal(cli.JUDGE_TIMEOUT_MS, 10000);
142
+ const fixture = makeFixture(context);
143
+ for (const reply of [() => new Promise(() => {}), async () => new Response(new ReadableStream({ start: () => {} }), { status: 200 })]) {
144
+ const signals = [];
145
+ await runClient(cli, fixture, 4, { transport: (url, init) => { signals.push(init.signal); return reply(); }, timeoutMs: 50 }, true);
146
+ assert.equal(signals[0].aborted, true);
147
+ }
148
+ });
149
+ it('spec:typesafe-jev-bridge/S4 classifies HTTP refusals without following redirects', async (context) => {
150
+ const cli = await client();
151
+ const fixture = makeFixture(context);
152
+ const causes = /key|refused|validation|rate limit|overloaded/i;
153
+ for (const [status, cause] of [[401, /key.*refused|refused.*key/i], [422, /validation/i], [429, /rate limit/i], [529, /overloaded/i], [500, null], [302, null]]) {
154
+ const headers = { ...(status === 401 || status === 302 ? { 'x-typesafe-request-id': REQUEST_ID } : {}), ...(status === 302 ? { Location: 'https://redirect.jev.invalid/' } : {}) };
155
+ const signals = [];
156
+ const result = await runClient(cli, fixture, 5, { transport: async (url, init) => { signals.push(init.signal); return makeResponse('refusal', status, headers); } }, true);
157
+ assert.equal(signals[0].aborted, true, `the ${status} exchange is aborted`);
158
+ const line = result.stderr.split('\n')[1];
159
+ assert.match(line, new RegExp(`\\b${status}\\b`));
160
+ if (headers['x-typesafe-request-id']) assert.ok(line.includes(REQUEST_ID));
161
+ if (cause) assert.match(line, cause); else assert.doesNotMatch(line, causes);
162
+ }
163
+ });
164
+ it('spec:typesafe-jev-bridge/S5 reports a transport rejection before any status', async (context) => {
165
+ const cli = await client();
166
+ await runClient(cli, makeFixture(context), 8, { transport: async () => { throw new TypeError('fetch failed', { cause: new Error('connection failed') }); } }, true);
167
+ });
168
+ it('spec:typesafe-jev-bridge/S6 rejects every malformed answer cell', async (context) => {
169
+ const cli = await client();
170
+ const fixture = makeFixture(context);
171
+ const valid = makeAnswer(getModel());
172
+ const { answers, model } = valid;
173
+ const changeNote = (patch) => ({ ...valid, answers: { ...answers, ready: { ...answers.ready, ...patch } } });
174
+ const invalid = ['not JSON', { model }, { answers }, { ...valid, model: 13 }, { ...valid, answers: { ready: answers.ready } }, { ...valid, answers: { ...answers, extra: answers.ready } },
175
+ changeNote({ choice: 'outside' }), changeNote({ probabilities: { yes: 1 } }), changeNote({ probabilities: { ...answers.ready.probabilities, extra: 0 } }),
176
+ ...[1.5, -0.1].map((yes) => changeNote({ probabilities: { ...answers.ready.probabilities, yes } })), changeNote({ confidence: 1.5 }), changeNote({ type: 'noul' })];
177
+ for (const body of invalid) await runClient(cli, fixture, 6, { transport: async () => makeResponse(body) }, true);
178
+ });
179
+ it('spec:typesafe-jev-bridge/S7 names both models when a well-formed answer uses another pin', async (context) => {
180
+ const cli = await client();
181
+ const fixture = makeFixture(context);
182
+ const other = 'jev-0.0.1';
183
+ const result = await runClient(cli, fixture, 7, { transport: async () => makeResponse(makeAnswer(other)) }, true);
184
+ for (const model of [getModel(), other]) assert.ok(result.stderr.includes(model));
185
+ });
186
+ describe('spec:typesafe-jev-bridge/S8 every refused operand, flag and request exits 2 before any request', () => {
187
+ it('refuses wrapper operands and flags before starting node', (context) => {
188
+ const fixture = makeFixture(context, true);
189
+ const recording = addRecordingNode(fixture);
190
+ for (const argv of [[], [fixture.path, fixture.path], ['--bogus'], ['-x']]) { runWrapper(fixture, argv, 2, { PATH: recording.PATH }); assert.equal(existsSync(recording.argv), false); }
191
+ });
192
+ it('rejects unreadable requests and every invalid request grammar cell', async (context) => {
193
+ const cli = await client();
194
+ const fixture = makeFixture(context);
195
+ for (const path of [join(fixture.root, 'absent'), fixture.root]) await runClient(cli, fixture, 2, { argv: [...fixture.argv.slice(0, -1), path] });
196
+ const request = makeRequest();
197
+ const criteria = (count) => Object.fromEntries(Array.from({ length: count }, (_, index) => [`o${index}`, 'Option']));
198
+ const withQuestion = (patch) => ({ ...request, questions: { ready: { ...makeQuestion(), ...patch } } });
199
+ const invalid = ['{not json', { ...request, model: getModel() }, { questions: request.questions }, { ...request, state: '' }, { ...request, questions: {} },
200
+ ...['noul', 'score'].map((type) => withQuestion({ type })), ...[1, 256].map((count) => withQuestion({ criteria: criteria(count) })), withQuestion({ criteria: { yes: '', no: 'No' } })];
201
+ for (const body of invalid) { writeFileSync(fixture.path, typeof body === 'string' ? body : JSON.stringify(body)); await runClient(cli, fixture, 2); }
202
+ for (const count of [2, 255]) {
203
+ const body = withQuestion({ criteria: criteria(count) });
204
+ writeFileSync(fixture.path, JSON.stringify(body));
205
+ const calls = [];
206
+ await runClient(cli, fixture, 0, { transport: async (...args) => { calls.push(args); return makeResponse(makeAnswer(getModel(), body)); } }, true);
207
+ assert.equal(calls.length, 1);
208
+ }
209
+ });
210
+ });
211
+ it('spec:typesafe-jev-bridge/S9 measures UTF-8 bytes and admits requests exactly at both limits', async (context) => {
212
+ const cli = await client();
213
+ const fixture = makeFixture(context);
214
+ const model = getModel();
215
+ const bytes = (value) => Buffer.byteLength(JSON.stringify(value));
216
+ const measure = ({ state, questions }) => ({ sum: bytes(state) + Math.max(...Object.entries(questions).map(bytes)), body: bytes({ state, model, questions }) });
217
+ const sizeRequest = (sum, body) => {
218
+ const state = '\u00e9'.repeat(10);
219
+ const first = makeQuestion('x'.repeat(sum - bytes(state) - bytes(['ready', makeQuestion('')])));
220
+ const request = { state, questions: { ready: first, safe: makeQuestion('') } };
221
+ return { ...request, questions: { ...request.questions, safe: makeQuestion('x'.repeat(body - measure(request).body)) } };
222
+ };
223
+ for (const [sum, body, code] of [[STATE_LIMIT + 1, BODY_LIMIT, 2], [STATE_LIMIT - 1, BODY_LIMIT + 1, 2], [STATE_LIMIT, BODY_LIMIT, 0]]) {
224
+ const request = sizeRequest(sum, body);
225
+ assert.deepEqual(measure(request), { sum, body });
226
+ writeFileSync(fixture.path, JSON.stringify(request));
227
+ const calls = [];
228
+ const result = await runClient(cli, fixture, code, { transport: async (...args) => { calls.push(args); return makeResponse(makeAnswer(model, request)); } }, code === 0);
229
+ assert.equal(calls.length, code === 0 ? 1 : 0);
230
+ if (code !== 0) for (const number of sum > STATE_LIMIT ? [sum, STATE_LIMIT] : [body, BODY_LIMIT]) assert.match(result.stderr, new RegExp(`\\b${number}\\b`));
231
+ }
232
+ });
233
+ describe('spec:typesafe-jev-bridge/S10 every missing facts line, manifest model and node exits 127 naming its cause', () => {
234
+ it('reads missing facts before even invalid operands', (context) => {
235
+ const fixture = makeFixture(context, true);
236
+ const path = join(fixture.root, 'service-facts.txt');
237
+ rmSync(path);
238
+ for (const argv of [[fixture.path], [fixture.path, fixture.path]]) {
239
+ const result = runWrapper(fixture, argv, 127, {}, false, true);
240
+ for (const text of [path, '/agent-workflow-kit upgrade']) assert.ok(result.stderr.includes(text));
241
+ }
242
+ });
243
+ it('names missing admitted facts fields', (context) => {
244
+ const fixture = makeFixture(context, true);
245
+ const path = join(fixture.root, 'service-facts.txt');
246
+ for (const field of ['RUN_HOST', 'PASSED_VARIABLE']) {
247
+ writeFileSync(path, getFacts().split('\n').filter((line) => !line.startsWith(`${field}=`)).join('\n'));
248
+ const result = runWrapper(fixture, [fixture.path], 127);
249
+ for (const text of [path, field]) assert.ok(result.stderr.includes(text));
250
+ }
251
+ });
252
+ it('reports node absent from a complete PATH farm', (context) => {
253
+ const fixture = makeFixture(context, true);
254
+ const farm = join(fixture.root, 'path');
255
+ mkdirSync(farm);
256
+ const seen = new Set(['node']);
257
+ for (const directory of (process.env.PATH ?? '').split(':').filter((path) => path && existsSync(path) && statSync(path).isDirectory())) {
258
+ for (const name of readdirSync(directory)) if (!seen.has(name)) { seen.add(name); symlinkSync(join(directory, name), join(farm, name)); }
259
+ }
260
+ assert.ok(existsSync(join(farm, 'bash')));
261
+ assert.equal(existsSync(join(farm, 'node')), false);
262
+ const result = runWrapper(fixture, [fixture.path], 127, { PATH: farm }, false, false, join(farm, 'bash'));
263
+ assert.ok(result.stderr.includes('Node.js 22.21'), result.stderr);
264
+ });
265
+ it('refuses absent, unparseable and posture-less manifests', async (context) => {
266
+ const cli = await client();
267
+ const fixture = makeFixture(context);
268
+ const path = join(fixture.root, 'capability.json');
269
+ for (const body of [null, '{not json', '{}', JSON.stringify({ posture: { model: '' } })]) {
270
+ if (body === null) rmSync(path); else writeFileSync(path, body);
271
+ const result = await runClient(cli, fixture, 127);
272
+ assert.ok(result.stderr.includes(path));
273
+ }
274
+ });
275
+ });
276
+ describe('spec:typesafe-jev-bridge/S11 the posture line precedes the request and no byte carries the key', () => {
277
+ it('flattens and redacts a rejection and its cause after the exact posture', async (context) => {
278
+ const cli = await client();
279
+ const fixture = makeFixture(context);
280
+ const result = await runClient(cli, fixture, 8, { transport: async () => { throw new TypeError(`failed ${fixture.key}\nagain`, { cause: new Error(`cause ${fixture.key}\nagain`) }); } }, true);
281
+ assert.equal(result.stderr.split('\n')[0], `judge posture: model=${getModel()} host=${HOST} timeout=10s`);
282
+ });
283
+ it('removes a key of any bytes from outside text before it is made one line or encoded', async (context) => {
284
+ const cli = await client();
285
+ const fixture = makeFixture(context);
286
+ const broken = fixture.key.replace('-Q7', '\nQ7');
287
+ const quoted = fixture.key.replace('-Q7', '"Q7');
288
+ const assertNoKey = (result, key) => {
289
+ for (const part of [...key.split(/["\n]/), JSON.stringify(key).slice(1, -1)]) assert.equal(`${result.stdout}${result.stderr}`.includes(part), false, 'key leaked');
290
+ };
291
+ assertNoKey(await runClient(cli, fixture, 8, { env: { [KEY_VARIABLE]: broken }, transport: async (url, init) => new Headers(init.headers) }, true), broken);
292
+ assertNoKey(await runClient(cli, fixture, 7, { env: { [KEY_VARIABLE]: broken }, transport: async () => makeResponse(makeAnswer(`other-${broken}`)) }, true), broken);
293
+ const result = await runClient(cli, fixture, 0, { env: { [KEY_VARIABLE]: quoted }, transport: async () => makeResponse(makeAnswer(getModel()), 200, { 'x-typesafe-request-id': `id-${quoted}` }) }, true);
294
+ assertNoKey(result, quoted);
295
+ assert.equal(JSON.parse(result.stdout).requestId.includes(quoted), false);
296
+ });
297
+ it('ends a defect inside the client in one scrubbed line', async (context) => {
298
+ const cli = await client();
299
+ const fixture = makeFixture(context);
300
+ const result = await cli.runJudgeCli({ argv: fixture.argv, env: fixture.env, folder: 42, transport: neverCall });
301
+ assertOutcome(result, fixture.key, 8);
302
+ });
303
+ it('gives node the key only through its environment', (context) => {
304
+ const fixture = makeFixture(context, true);
305
+ const recording = addRecordingNode(fixture);
306
+ const preload = addPreload(fixture, makeAnswer(getModel()));
307
+ runWrapper(fixture, [fixture.path], 0, { PATH: recording.PATH, NODE_OPTIONS: preload.NODE_OPTIONS }, true);
308
+ assert.equal(read(recording.env), fixture.key);
309
+ const argv = read(recording.argv);
310
+ assert.equal(argv.includes(fixture.key), false);
311
+ assert.deepEqual(argv.split('\n').slice(0, -1), [join(fixture.root, 'bin/jev-client.mjs'), ...fixture.argv]);
312
+ assert.equal(read(preload.log), `${ENDPOINT}\n`);
313
+ });
314
+ });
315
+ it('spec:typesafe-jev-bridge/S12 prints help and keeps the version and exact bundle consistent', (context) => {
316
+ const fixture = makeFixture(context, true);
317
+ const { version } = readManifest();
318
+ for (const flag of ['--help', '-h']) { const result = runWrapper(fixture, [flag], 0); assert.match(result.stdout, /^Usage:$/m); for (const text of ['jev-ask', version]) assert.ok(result.stdout.includes(text)); }
319
+ assert.equal(read(join(HERE, 'jev-ask.sh')).match(/^AW_BRIDGE_VERSION="([^"]+)"\s+# aw-version-anchor$/m)?.[1], version);
320
+ const frontmatter = read(join(BRIDGE, 'SKILL.md')).match(/^---\r?\n([\s\S]*?)\r?\n---/)?.[1];
321
+ assert.ok(frontmatter);
322
+ assert.match(frontmatter, /^name:\s*['"]?typesafe-jev-bridge['"]?\s*$/m);
323
+ assert.equal(frontmatter.match(/^metadata:\s*\n(?:[ \t]+[^\n]*\n)*?[ \t]+version:\s*['"]?([^\s'"\n]+)['"]?\s*$/m)?.[1], version);
324
+ assert.deepEqual(listFiles(BRIDGE), ['SKILL.md', 'bin/jev-ask.sh', 'bin/jev-ask.test.mjs', 'bin/jev-client.mjs', 'capability.json', 'service-facts.txt', 'setup/README.md']);
325
+ const setup = read(join(BRIDGE, 'setup/README.md'));
326
+ assert.ok(setup.includes('jev-connect.mjs'));
327
+ assert.match(setup, /restart/i);
328
+ assert.match(setup, /Node(?:\.js)? 22\.21 or newer/);
329
+ });
330
+ it('spec:typesafe-jev-bridge/S13 scans every shipped file and catches planted host and model literals', (context) => {
331
+ const fixture = makeFixture(context);
332
+ mkdirSync(join(fixture.root, 'bin'));
333
+ writeFileSync(join(fixture.root, 'SKILL.md'), 'API.TypeSafe.AI');
334
+ writeFileSync(join(fixture.root, 'bin/jev-client.mjs'), 'jev-1.13.0');
335
+ assert.deepEqual(scanFolder(fixture.root).hits, ['SKILL.md: host', 'bin/jev-client.mjs: model']);
336
+ const scanned = scanFolder(BRIDGE);
337
+ assert.deepEqual(scanned.hits, []);
338
+ for (const file of ['SKILL.md', 'bin/jev-ask.sh', 'bin/jev-client.mjs', 'setup/README.md']) assert.ok(scanned.files.includes(file), `scan did not read ${file}`);
339
+ });
340
+ it('spec:typesafe-jev-bridge/S15 forwards client outcomes unchanged for success and HTTP refusal', async (context) => {
341
+ const cli = await client();
342
+ const fixture = makeFixture(context, true);
343
+ for (const status of [200, 401]) {
344
+ const body = status === 200 ? makeAnswer(getModel()) : { error: 'refused' };
345
+ const code = status === 200 ? 0 : 5;
346
+ const preload = addPreload(fixture, body, status);
347
+ const wrapped = runWrapper(fixture, [fixture.path], code, { NODE_OPTIONS: preload.NODE_OPTIONS }, true);
348
+ const direct = await runClient(cli, fixture, code, { transport: async () => makeResponse(body, status) }, true);
349
+ assert.deepEqual(wrapped, direct);
350
+ assert.equal(read(preload.log), `${ENDPOINT}\n`);
351
+ rmSync(preload.log);
352
+ }
353
+ });
354
+ it('spec:typesafe-jev-bridge/S16 the wrapper reaches a loopback CONNECT proxy by its own switch and prints no key or proxy password', async (context) => {
355
+ const fixture = makeFixture(context, true);
356
+ const lines = [];
357
+ const loopback = '127.0.0.1';
358
+ const password = `proxy-${Buffer.from(context.name).toString('hex')}-${fixture.key.slice(-32)}`;
359
+ const server = createServer((req, res) => {
360
+ lines.push(`${req.method} ${req.url}`);
361
+ res.writeHead(403);
362
+ res.end();
363
+ });
364
+ server.on('connect', (req, socket) => {
365
+ lines.push(`${req.method} ${req.url}`);
366
+ socket.end('HTTP/1.1 403 Forbidden\r\n\r\n');
367
+ });
368
+ server.listen(0, loopback);
369
+ try {
370
+ await once(server, 'listening');
371
+ const env = { PATH: process.env.PATH, HOME: fixture.env.HOME, [KEY_VARIABLE]: fixture.key,
372
+ HTTPS_PROXY: `http://proxy-user:${password}@${loopback}:${server.address().port}` };
373
+ const result = await new Promise((resolve, reject) => {
374
+ const child = spawn('bash', [join(fixture.root, 'bin/jev-ask.sh'), fixture.path], { cwd: fixture.root, env });
375
+ const stdout = [];
376
+ const stderr = [];
377
+ const timer = setTimeout(() => child.kill('SIGKILL'), 12000);
378
+ child.stdout.on('data', (chunk) => stdout.push(chunk));
379
+ child.stderr.on('data', (chunk) => stderr.push(chunk));
380
+ child.once('error', (error) => { clearTimeout(timer); reject(error); });
381
+ child.once('close', (code) => {
382
+ clearTimeout(timer);
383
+ resolve({ code, stdout: Buffer.concat(stdout).toString(), stderr: Buffer.concat(stderr).toString() });
384
+ });
385
+ });
386
+ assert.deepEqual(lines, [`CONNECT ${HOST}:443`]);
387
+ assertOutcome(result, fixture.key, 8, true);
388
+ for (const stream of [result.stdout, result.stderr]) assert.equal(stream.includes(password), false, 'proxy password leaked');
389
+ } finally {
390
+ await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
391
+ }
392
+ });
@@ -0,0 +1,155 @@
1
+ // spec:typesafe-jev-bridge — docs/ai/specs/bridges/typesafe-jev-bridge/index.md
2
+ import { readFile } from 'node:fs/promises';
3
+ import { dirname, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ export const JUDGE_TIMEOUT_MS = 10000;
7
+ const EXIT = { OK: 0, REQUEST: 2, KEY: 3, TIMEOUT: 4, HTTP: 5, ANSWER: 6, MODEL: 7, TRANSPORT: 8, INSTALL: 127 };
8
+ const EMPTY = '';
9
+ const NEWLINE = '\n';
10
+ const STRING_TYPE = 'string';
11
+ const OBJECT_TYPE = 'object';
12
+ const CHOICE_TYPE = 'choice';
13
+ const UTF8 = 'utf8';
14
+ const REQUEST_KEYS = ['state', 'questions'];
15
+ const QUESTION_KEYS = ['type', 'instructions', 'criteria'];
16
+ const MIN_OPTIONS = 2;
17
+ const MAX_OPTIONS = 255;
18
+ const MIN_QUESTIONS = 1;
19
+ const EMPTY_BYTE_COUNT = 0;
20
+ const STATE_LIMIT = 30000;
21
+ const BODY_LIMIT = 60000;
22
+ const HTTP_MIN = 200;
23
+ const HTTP_MAX = 299;
24
+ const PROBABILITY_MIN = 0;
25
+ const PROBABILITY_MAX = 1;
26
+ const MILLISECONDS_PER_SECOND = 1000;
27
+ const ARGUMENT_COUNT = 5;
28
+ const HOST_FLAG = '--host';
29
+ const KEY_FLAG = '--key-variable';
30
+ const MANIFEST_FILE = 'capability.json';
31
+ const REQUEST_ID_HEADER = 'x-typesafe-request-id';
32
+ const AUTHORIZATION_HEADER = 'authorization';
33
+ const CONTENT_TYPE_HEADER = 'content-type';
34
+ const JSON_CONTENT_TYPE = 'application/json';
35
+ const REQUEST_METHOD = 'POST';
36
+ const REDIRECT_MODE = 'manual';
37
+ const ENDPOINT_PATH = '/v1/systemone';
38
+ const REMEDY = 'run /agent-workflow-kit upgrade to write it again';
39
+ const HTTP_CAUSES = { 401: 'the key was refused', 422: 'the request failed validation', 429: 'the rate limit was hit', 529: 'the vendor is overloaded' };
40
+ const CONTROL_RUN = /[\x00-\x1f\x7f-\x9f\u2028\u2029]+/gu;
41
+ const flattenText = (text) => String(text).replace(CONTROL_RUN, ' ');
42
+ const isPlainObject = (value) => value !== null && typeof value === OBJECT_TYPE &&
43
+ [Object.prototype, null].includes(Object.getPrototypeOf(value));
44
+ const hasKeys = (value, keys) => isPlainObject(value) && Object.keys(value).length === keys.length &&
45
+ keys.every((key) => Object.hasOwn(value, key));
46
+ const isNonemptyString = (value) => typeof value === STRING_TYPE && value !== EMPTY;
47
+ const isProbability = (value) => Number.isFinite(value) && value >= PROBABILITY_MIN && value <= PROBABILITY_MAX;
48
+ const measureBytes = (value) => Buffer.byteLength(JSON.stringify(value));
49
+ const renderTimeout = (timeoutMs) => Number.isInteger(timeoutMs / MILLISECONDS_PER_SECOND) ?
50
+ `${timeoutMs / MILLISECONDS_PER_SECOND}s` : `${timeoutMs}ms`;
51
+ const REDACTED = '[redacted]';
52
+ const makeFailure = (code, message) => ({ code, stdout: EMPTY, stderr: `jev-ask: ${flattenText(message)}${NEWLINE}` });
53
+ const redactKey = (text, key) => key === EMPTY ? text : text.replaceAll(key, REDACTED);
54
+ const cleanOutsideText = (text, key) => flattenText(redactKey(String(text), key));
55
+ const scrubOutcome = (outcome, key) => Object.fromEntries(Object.entries(outcome).map(([name, value]) =>
56
+ [name, typeof value === STRING_TYPE ? redactKey(value, key) : value]));
57
+ const describeError = (error, key, seen = new Set()) => {
58
+ if (seen.has(error)) return EMPTY;
59
+ seen.add(error);
60
+ return [cleanOutsideText(error?.message ?? error, key), ...(error?.cause === undefined ? [] : [describeError(error.cause, key, seen)])].join(' caused by ');
61
+ };
62
+
63
+ export const keyIsSet = (env, variable) => typeof env[variable] === STRING_TYPE && env[variable].trim() !== EMPTY;
64
+ export const checkRequest = (request) => {
65
+ if (!hasKeys(request, REQUEST_KEYS)) return 'request must contain exactly state and questions';
66
+ if (!isNonemptyString(request.state)) return 'state must be a non-empty string';
67
+ if (!isPlainObject(request.questions) || Object.keys(request.questions).length < MIN_QUESTIONS) return 'questions must be a non-empty object';
68
+ for (const [id, question] of Object.entries(request.questions)) {
69
+ if (!hasKeys(question, QUESTION_KEYS) || question.type !== CHOICE_TYPE || !isNonemptyString(question.instructions)) return `question ${id} must have choice type, non-empty instructions and criteria`;
70
+ if (!isPlainObject(question.criteria)) return `question ${id} criteria must be an object`;
71
+ const options = Object.values(question.criteria);
72
+ if (options.length < MIN_OPTIONS || options.length > MAX_OPTIONS || !options.every(isNonemptyString)) return `question ${id} criteria must have ${MIN_OPTIONS} to ${MAX_OPTIONS} non-empty options`;
73
+ }
74
+ return null;
75
+ };
76
+
77
+ const checkAnswer = (answer, questions) => isPlainObject(answer) && typeof answer.model === STRING_TYPE &&
78
+ hasKeys(answer.answers, Object.keys(questions)) && Object.entries(questions).every(([id, question]) => {
79
+ const note = answer.answers[id];
80
+ return isPlainObject(note) && note.type === CHOICE_TYPE && typeof note.choice === STRING_TYPE &&
81
+ Object.hasOwn(question.criteria, note.choice) && hasKeys(note.probabilities, Object.keys(question.criteria)) &&
82
+ Object.values(note.probabilities).every(isProbability) && isProbability(note.confidence);
83
+ });
84
+ const makeNotes = (answers) => Object.fromEntries(Object.entries(answers).map(([id, { choice, probabilities, confidence }]) =>
85
+ [id, { choice, probabilities, confidence }]));
86
+ const readAnswer = async (response, model, questions, key) => {
87
+ const header = response.headers.get(REQUEST_ID_HEADER);
88
+ const requestId = header === null ? null : cleanOutsideText(header, key);
89
+ if (response.status < HTTP_MIN || response.status > HTTP_MAX) return makeFailure(EXIT.HTTP,
90
+ `HTTP ${response.status}${requestId === null ? EMPTY : ` request ${requestId}`}${HTTP_CAUSES[response.status] ? `: ${HTTP_CAUSES[response.status]}` : EMPTY}`);
91
+ const body = await response.text();
92
+ const answer = (() => { try { return JSON.parse(body); } catch { return null; } })();
93
+ if (!checkAnswer(answer, questions)) return makeFailure(EXIT.ANSWER, 'malformed answer');
94
+ if (answer.model !== model) return makeFailure(EXIT.MODEL, `requested model ${model}; answering model ${cleanOutsideText(answer.model, key)}`);
95
+ return { code: EXIT.OK, stdout: JSON.stringify({ model, requestId, notes: makeNotes(answer.answers) }) + NEWLINE, stderr: EMPTY };
96
+ };
97
+
98
+ export const askJudge = async ({ host, key, model, state, questions, transport, timeoutMs = JUDGE_TIMEOUT_MS }) => {
99
+ const trimmedKey = key.trim();
100
+ const controller = new AbortController();
101
+ const deadline = { timer: null };
102
+ const timeout = new Promise((complete) => {
103
+ deadline.timer = setTimeout(() => complete(makeFailure(EXIT.TIMEOUT, `no complete answer within ${renderTimeout(timeoutMs)}`)), timeoutMs);
104
+ });
105
+ const work = (async () => {
106
+ const response = await transport(`https://${host}${ENDPOINT_PATH}`, {
107
+ method: REQUEST_METHOD, headers: { [AUTHORIZATION_HEADER]: `Bearer ${trimmedKey}`, [CONTENT_TYPE_HEADER]: JSON_CONTENT_TYPE },
108
+ body: JSON.stringify({ state, model, questions }), redirect: REDIRECT_MODE, signal: controller.signal,
109
+ });
110
+ return readAnswer(response, model, questions, trimmedKey);
111
+ })().catch((error) => makeFailure(EXIT.TRANSPORT, describeError(error, trimmedKey)));
112
+ try {
113
+ return scrubOutcome(await Promise.race([timeout, work]), trimmedKey);
114
+ } finally {
115
+ clearTimeout(deadline.timer);
116
+ controller.abort();
117
+ }
118
+ };
119
+
120
+ export const runJudgeCli = async ({ argv, env, folder, transport, timeoutMs = JUDGE_TIMEOUT_MS }) => {
121
+ const [hostFlag, host, keyFlag, variable, path] = Array.isArray(argv) ? argv : [];
122
+ const key = typeof env?.[variable] === STRING_TYPE ? env[variable].trim() : EMPTY;
123
+ const finish = (outcome) => scrubOutcome(outcome, key);
124
+ try {
125
+ if (!Array.isArray(argv) || argv.length !== ARGUMENT_COUNT || hostFlag !== HOST_FLAG || keyFlag !== KEY_FLAG ||
126
+ ![host, variable, path].every(isNonemptyString)) return finish(makeFailure(EXIT.REQUEST, 'usage: --host <host> --key-variable <variable> <request-file>'));
127
+ const manifestPath = resolve(folder, MANIFEST_FILE);
128
+ const model = await readFile(manifestPath, UTF8).then((text) => {
129
+ try { return JSON.parse(text)?.posture?.model; } catch { return null; }
130
+ }, () => null);
131
+ if (!isNonemptyString(model)) return finish(makeFailure(EXIT.INSTALL, `${manifestPath}: no readable posture.model; ${REMEDY}`));
132
+ const text = await readFile(path, UTF8).catch(() => null);
133
+ if (text === null) return finish(makeFailure(EXIT.REQUEST, `${path}: cannot read request file`));
134
+ const parsed = (() => {
135
+ try { return { value: JSON.parse(text) }; } catch { return null; }
136
+ })();
137
+ if (parsed === null) return finish(makeFailure(EXIT.REQUEST, `${path}: request is not JSON`));
138
+ const reason = checkRequest(parsed.value);
139
+ if (reason !== null) return finish(makeFailure(EXIT.REQUEST, reason));
140
+ const { state, questions } = parsed.value;
141
+ const stateBytes = measureBytes(state) + Object.entries(questions).reduce((largest, pair) => Math.max(largest, measureBytes(pair)), EMPTY_BYTE_COUNT);
142
+ if (stateBytes > STATE_LIMIT) return finish(makeFailure(EXIT.REQUEST, `state and largest question measure ${stateBytes} bytes; bound ${STATE_LIMIT}`));
143
+ const bodyBytes = measureBytes({ state, model, questions });
144
+ if (bodyBytes > BODY_LIMIT) return finish(makeFailure(EXIT.REQUEST, `request measures ${bodyBytes} bytes; bound ${BODY_LIMIT}`));
145
+ if (!keyIsSet(env, variable)) return finish(makeFailure(EXIT.KEY, `${variable} is unset or blank`));
146
+ const posture = flattenText(`judge posture: model=${model} host=${host} timeout=${renderTimeout(timeoutMs)}`) + NEWLINE;
147
+ const outcome = await askJudge({ host, key, model, state, questions, transport, timeoutMs });
148
+ return finish({ ...outcome, stderr: posture + outcome.stderr });
149
+ } catch (error) {
150
+ return finish(makeFailure(EXIT.TRANSPORT, describeError(error, key)));
151
+ }
152
+ };
153
+
154
+ const entry = process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url) ? await runJudgeCli({ argv: process.argv.slice(2), env: process.env, folder: dirname(dirname(fileURLToPath(import.meta.url))), transport: fetch }) : null;
155
+ if (entry !== null) { process.stdout.write(entry.stdout); process.stderr.write(entry.stderr); process.exitCode = entry.code; }
@@ -0,0 +1,31 @@
1
+ {
2
+ "family": "agent-workflow",
3
+ "schema": 1,
4
+ "name": "typesafe-jev-bridge",
5
+ "kind": "execution-backend",
6
+ "version": "1.0.0",
7
+ "available": true,
8
+ "provides": ["judge"],
9
+ "roles": {
10
+ "judge": {
11
+ "cmd": "jev-ask",
12
+ "source": "bin/jev-ask.sh",
13
+ "output": "advisory"
14
+ }
15
+ },
16
+ "services": ["jev"],
17
+ "posture": {
18
+ "model": "jev-1.13.0"
19
+ },
20
+ "detect": {
21
+ "installed": {
22
+ "env": "TYPESAFE_JEV_BRIDGE_DIR",
23
+ "default": "~/.claude/skills/typesafe-jev-bridge",
24
+ "file": "SKILL.md"
25
+ }
26
+ },
27
+ "provenance": {
28
+ "author": "sabaiway",
29
+ "source": "github:sabaiway/agent-workflow"
30
+ }
31
+ }
@@ -0,0 +1,6 @@
1
+ # generated from the kit's service fragments (agent-workflow-kit/tools/services/); do not edit
2
+ HOST=api.typesafe.ai
3
+ HOST=docs.typesafe.ai
4
+ RUN_HOST=api.typesafe.ai
5
+ RUN_HOST=docs.typesafe.ai
6
+ PASSED_VARIABLE=TYPESAFE_API_KEY
@@ -0,0 +1,20 @@
1
+ # Setting up the Jev key
2
+
3
+ `jev-ask` needs no binary of its own beyond Node.js 22.21 or newer on `PATH`. It needs one thing from you:
4
+ your TypeSafe key, saved where every new shell of the agent reads it.
5
+
6
+ ## 1. Save the key with the kit's connect command
7
+
8
+ Run the kit's connect command **in a terminal of your own**, not through the agent:
9
+
10
+ ```bash
11
+ node <kit>/tools/jev-connect.mjs
12
+ ```
13
+
14
+ `<kit>` is the folder of the installed `agent-workflow-kit` skill. The command asks for the key with
15
+ no echo, checks it with one request and saves it in your shell's startup file. The key is never
16
+ printed and never put on a command line; never paste it into the chat.
17
+
18
+ ## 2. Restart the agent
19
+
20
+ Restart the agent so its shell reads the saved key, then ask it to check Jev.
package/capability.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "schema": 1,
4
4
  "name": "agent-workflow-kit",
5
5
  "kind": "composition-root",
6
- "version": "23.2.0",
6
+ "version": "23.3.0",
7
7
  "provides": [],
8
8
  "roles": {},
9
9
  "detect": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sabaiway/agent-workflow-kit",
3
- "version": "23.2.0",
3
+ "version": "23.3.0",
4
4
  "description": "Portable, cross-agent memory & workflow for AI coding agents — Claude Code, Codex, Cursor, Devin Desktop. One command deploys an AGENTS.md entry point + docs/ai context with cap/archive/index enforcement into any repo.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -60,7 +60,7 @@
60
60
  "!references/scripts/test-support/**"
61
61
  ],
62
62
  "engines": {
63
- "node": ">=22"
63
+ "node": ">=22.21"
64
64
  },
65
65
  "publishConfig": {
66
66
  "access": "public"