@lumyne/codex-gateway 0.0.0-stage → 0.1.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,229 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+
6
+ const IMAGE = /\.(?:png|jpe?g|webp|gif|avif|bmp)$/i;
7
+ const MARKDOWN_LINK = /\]\((?:<([^<>\r\n]+)>|([^()\r\n]+))\)/g;
8
+ const VIEW = /\btools\.view_image\s*\(\s*\{\s*["']?path["']?\s*:\s*("(?:\\.|[^"\\])*"|'[^'\r\n]*')/g;
9
+ const CAP = 512 * 1024;
10
+
11
+ function workspaceDirectory(items) {
12
+ for (const item of [...items].reverse()) {
13
+ if (item?.role !== 'user') continue;
14
+ const input = Array.isArray(item.content) ? item.content.map(part => part?.text ?? '').join('\n') : item.content;
15
+ if (typeof input !== 'string' || !input.includes('<environment_context>')) continue;
16
+ const cwd = input.match(/<cwd>([^<\r\n]+)<\/cwd>/)?.[1];
17
+ if (cwd && /^[A-Za-z]:[\\/]/.test(cwd)) return cwd;
18
+ }
19
+ return null;
20
+ }
21
+
22
+ function dynamicPreview(script, cwd, paths) {
23
+ if (!cwd) return null;
24
+ const match = script.match(/^\s*const\s+(\w+)\s*=\s*await\s+tools\.exec_command\(\{cmd:\s*("(?:\\.|[^"\\])*"),[^}]*\}\);\s*const\s+(\w+)\s*=\s*\1\.output\.trim\(\);\s*const\s+\w+\s*=\s*await\s+tools\.view_image\(\{(?:path:\s*\3|\3)\s*\}\)/);
25
+ if (!match) return null;
26
+ const command = JSON.parse(match[2]);
27
+ const query = command.match(/^\(Get-Item -LiteralPath (?:'([^']+)'|"([^"]+)"|([^\s()]+))\)\.FullName$/i);
28
+ if (!query) return null;
29
+ const requested = query[1] ?? query[2] ?? query[3];
30
+ return paths.resolve(cwd, requested);
31
+ }
32
+
33
+ function successfulReceipts(value, depth = 0) {
34
+ if (depth > 8 || value == null) return [];
35
+ if (typeof value === 'string') {
36
+ if (value.length > CAP) return [];
37
+ try { return successfulReceipts(JSON.parse(value.trim()), depth + 1); } catch { return []; }
38
+ }
39
+ if (Array.isArray(value)) return value.flatMap(part => successfulReceipts(part, depth + 1));
40
+ if (value.type === 'input_text') return successfulReceipts(value.text, depth + 1);
41
+ if (value.state === 'succeeded' && Array.isArray(value.artifacts)) return value.artifacts;
42
+ return ['output', 'result'].flatMap(key => successfulReceipts(value[key], depth + 1));
43
+ }
44
+
45
+ function verifiedImages(body, files = fs, paths = path.win32) {
46
+ const items = Array.isArray(body?.input) ? body.input : [];
47
+ let start = items.length;
48
+ while (start > 0 && items[start - 1]?.role !== 'user') start--;
49
+ const turn = items.slice(Math.max(start, items.length - 80));
50
+ const outputs = turn.filter(item => /^(?:custom_tool_call_output|function_call_output)$/.test(item?.type));
51
+ const readable = new Set(outputs.filter(item =>
52
+ Array.isArray(item.output) && item.output.some(part =>
53
+ part?.type === 'input_image' && typeof part.image_url === 'string' &&
54
+ /^data:image\/(?:png|jpe?g|webp|gif);base64,/i.test(part.image_url)))
55
+ .map(item => item.call_id).filter(Boolean));
56
+ const filesFound = new Set();
57
+ const cwd = workspaceDirectory(items);
58
+ function previewInProject(file, info) {
59
+ if (!cwd || !/\.jpe?g$/i.test(file)) return false;
60
+ const project = files.realpathSync.native(cwd);
61
+ const relative = paths.relative(project, file);
62
+ if (!relative || relative === '..' || relative.startsWith('..' + paths.sep) || paths.isAbsolute(relative)) return false;
63
+ const fd = files.openSync(file, 'r');
64
+ try {
65
+ const magic = Buffer.alloc(3);
66
+ return info.size >= magic.length && files.readSync(fd, magic, 0, magic.length, 0) === 3 &&
67
+ magic[0] === 0xff && magic[1] === 0xd8 && magic[2] === 0xff;
68
+ } finally { files.closeSync(fd); }
69
+ }
70
+ function check(candidate, expectedSize) {
71
+ if (typeof candidate !== 'string' || !/^[A-Za-z]:[\\/]/.test(candidate) || !IMAGE.test(candidate)) return;
72
+ try {
73
+ const actual = files.realpathSync.native(candidate);
74
+ const info = files.statSync(actual);
75
+ if (!info.isFile() || !info.size || !IMAGE.test(actual) ||
76
+ (expectedSize !== undefined && info.size !== expectedSize)) return;
77
+ const manifest = paths.join(paths.dirname(actual), 'result.json');
78
+ if (!files.existsSync(manifest)) {
79
+ if (expectedSize === undefined && previewInProject(actual, info)) filesFound.add(actual);
80
+ return;
81
+ }
82
+ if (files.statSync(manifest).size > CAP) return;
83
+ const result = JSON.parse(files.readFileSync(manifest, 'utf8').replace(/^\uFEFF/, ''));
84
+ if (result?.state !== 'succeeded' || !Array.isArray(result.artifacts)) return;
85
+ if (result.artifacts.some(item => typeof item?.path === 'string' &&
86
+ paths.normalize(item.path).toLowerCase() === paths.normalize(actual).toLowerCase() &&
87
+ item.bytes === info.size)) filesFound.add(actual);
88
+ } catch {}
89
+ }
90
+ for (const item of outputs) {
91
+ for (const artifact of successfulReceipts(item.output)) {
92
+ if (Number.isSafeInteger(artifact?.bytes) && artifact.bytes > 0) check(artifact.path, artifact.bytes);
93
+ }
94
+ }
95
+ for (const call of turn) {
96
+ if (!readable.has(call?.call_id) || !/^(?:custom_tool_call|function_call)$/.test(call.type)) continue;
97
+ const script = call.input || call.arguments;
98
+ if (typeof script !== 'string' || script.length > CAP) continue;
99
+ for (const [, raw] of script.matchAll(VIEW)) {
100
+ try { check(raw.startsWith('"') ? JSON.parse(raw) : raw.slice(1, -1)); } catch {}
101
+ }
102
+ try { check(dynamicPreview(script, cwd, paths)); } catch {}
103
+ }
104
+ return [...filesFound];
105
+ }
106
+
107
+ function normalize(value) {
108
+ return value.replace(/^\/(?=[A-Za-z]:)/, '').replace(/\\/g, '/');
109
+ }
110
+
111
+ function repairLinks(text, images, exists = fs.existsSync) {
112
+ return text.replace(MARKDOWN_LINK, (link, angled, plain) => {
113
+ const target = normalize(angled ?? plain);
114
+ if (!/^[A-Za-z]:\//.test(target) || !IMAGE.test(target)) return link;
115
+ if (exists(target)) return link;
116
+ const wrong = target.toLowerCase().split('/');
117
+ const matches = images.filter(file => {
118
+ const parts = normalize(file).toLowerCase().split('/');
119
+ const n = Math.min(parts.length, wrong.length);
120
+ return n >= 3 && parts.at(-1) === wrong.at(-1) && parts.at(-2) === wrong.at(-2);
121
+ });
122
+ if (matches.length !== 1) return link;
123
+ const verified = normalize(matches[0]);
124
+ if (/[<>\r\n]/.test(verified)) return link;
125
+ return '](<' + verified + '>)';
126
+ });
127
+ }
128
+
129
+ function eventRecord(raw) {
130
+ const line = raw.split(/\r?\n/).find(line => line.startsWith('data: '));
131
+ if (!line) return null;
132
+ try { return JSON.parse(line.slice(6)); } catch { return null; }
133
+ }
134
+
135
+ function replaceEvent(raw, event) {
136
+ return raw.replace(/^data: [^\r\n]*/m, () => 'data: ' + JSON.stringify(event));
137
+ }
138
+
139
+ function patchEvents(stream, fix) {
140
+ const records = stream.split(/(\r?\n\r?\n)/);
141
+ const groups = new Map();
142
+ const completed = new Map();
143
+ const keyFor = ev => JSON.stringify([ev.item_id ?? ev.item?.id ?? '', ev.output_index ?? 0, ev.content_index ?? 0]);
144
+ const fixPart = (part, field, key) => {
145
+ const original = part?.[field];
146
+ if (typeof original !== 'string') return false;
147
+ const corrected = fix(original);
148
+ if (original === corrected) return false;
149
+ part[field] = corrected;
150
+ completed.set(key, corrected);
151
+ return true;
152
+ };
153
+ const fixItem = (item, outputIndex) => {
154
+ if (item?.type !== 'message' || item.role !== 'assistant' || !Array.isArray(item.content)) return false;
155
+ let changed = false;
156
+ for (const [contentIndex, part] of item.content.entries()) {
157
+ if (part?.type !== 'output_text') continue;
158
+ const key = keyFor({item, output_index:outputIndex, content_index:contentIndex});
159
+ changed = fixPart(part, 'text', key) || changed;
160
+ }
161
+ return changed;
162
+ };
163
+ for (let index = 0; index < records.length; index += 2) {
164
+ const e = eventRecord(records[index]);
165
+ if (!e || typeof e.type !== 'string') continue;
166
+ if (e.type === 'response.output_text.delta' && typeof e.delta === 'string') {
167
+ const id = keyFor(e);
168
+ if (!groups.has(id)) groups.set(id, []);
169
+ groups.get(id).push({index, event: e});
170
+ continue;
171
+ }
172
+ let changed = false;
173
+ if (e.type === 'response.output_text.done') {
174
+ changed = fixPart(e, 'text', keyFor(e));
175
+ } else if (e.type === 'response.content_part.done' && e.part?.type === 'output_text') {
176
+ changed = fixPart(e.part, 'text', keyFor(e));
177
+ } else if (e.type === 'response.output_item.done') {
178
+ changed = fixItem(e.item, e.output_index);
179
+ } else if (e.type === 'response.completed' && Array.isArray(e.response?.output)) {
180
+ for (const [outputIndex, item] of e.response.output.entries()) {
181
+ changed = fixItem(item, outputIndex) || changed;
182
+ }
183
+ }
184
+ if (changed) records[index] = replaceEvent(records[index], e);
185
+ }
186
+ for (const [key, deltas] of groups) {
187
+ const joined = deltas.map(({event}) => event.delta).join('');
188
+ const fixed = completed.get(key) ?? fix(joined);
189
+ if (fixed === joined) continue;
190
+ for (const [i, {index, event}] of deltas.entries()) {
191
+ event.delta = i === deltas.length - 1 ? fixed : '';
192
+ records[index] = replaceEvent(records[index], event);
193
+ }
194
+ }
195
+ return records.join('');
196
+ }
197
+
198
+ async function applyImageLinkGuard(response, body, images = verifiedImages(body)) {
199
+ if (!response.ok || !response.body || !images.length ||
200
+ !response.headers.get('content-type')?.includes('text/event-stream')) return response;
201
+ const reader = response.body.getReader();
202
+ const chunks = [];
203
+ let bytes = 0;
204
+ for (;;) {
205
+ const {done, value} = await reader.read();
206
+ if (done) break;
207
+ chunks.push(value);
208
+ bytes += value.byteLength;
209
+ if (bytes <= CAP) continue;
210
+ const body = new ReadableStream({
211
+ start(controller) { for (const chunk of chunks) controller.enqueue(chunk); },
212
+ async pull(controller) {
213
+ const next = await reader.read();
214
+ if (next.done) controller.close();
215
+ else controller.enqueue(next.value);
216
+ },
217
+ cancel(reason) { return reader.cancel(reason); },
218
+ });
219
+ return new Response(body, {status: response.status, headers: response.headers});
220
+ }
221
+ const initial = Buffer.concat(chunks).toString('utf8');
222
+ const corrected = patchEvents(initial, text => repairLinks(text, images));
223
+ const headers = new Headers(response.headers);
224
+ headers.delete('content-length');
225
+ headers.delete('content-encoding');
226
+ return new Response(corrected, {status: response.status, headers});
227
+ }
228
+
229
+ module.exports = {verifiedImages, repairLinks, patchEvents, applyImageLinkGuard};
@@ -0,0 +1,52 @@
1
+ 'use strict';
2
+ const fs = require('node:fs');
3
+
4
+ const identifier = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/;
5
+ const isObject = value => value && typeof value === 'object' && !Array.isArray(value);
6
+
7
+ function readSettings(file) {
8
+ const input = JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''));
9
+ if (!isObject(input) || input.schemaVersion !== 1 || !isObject(input.channels) ||
10
+ !Array.isArray(input.models) || !input.models.length) {
11
+ throw new Error('Expected gateway configuration schemaVersion 1 with channels and models.');
12
+ }
13
+ const channels = Object.fromEntries(Object.entries(input.channels).map(([id, channel]) => {
14
+ if (!identifier.test(id) || !isObject(channel) || typeof channel.credential !== 'string' ||
15
+ !identifier.test(channel.credential) || typeof channel.endpoint !== 'string') {
16
+ throw new Error('Invalid channel ID or credential reference.');
17
+ }
18
+ let url;
19
+ try { url = new URL(channel.endpoint); } catch { throw new Error('Invalid gateway endpoint.'); }
20
+ if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash) {
21
+ throw new Error('Gateway endpoints must use HTTPS without URL credentials, query parameters or fragments.');
22
+ }
23
+ return [id, {endpoint: url.href.replace(/\/$/, ''), credential: channel.credential}];
24
+ }));
25
+ const seen = new Set();
26
+ const models = input.models.map(model => {
27
+ if (!isObject(model) || typeof model.id !== 'string' || !identifier.test(model.id) ||
28
+ seen.has(model.id) || typeof model.channel !== 'string' || !Object.hasOwn(channels, model.channel) ||
29
+ !['responses', 'anthropic'].includes(model.protocol)) throw new Error('Invalid or duplicate model route.');
30
+ for (const key of ['repairImageLinks','hostedSearch']) {
31
+ if (model[key] !== undefined && typeof model[key] !== 'boolean') throw new Error('Invalid model option: '+key);
32
+ }
33
+ seen.add(model.id);
34
+ return {
35
+ id: model.id, label: label(model.label, model.id), channel: model.channel, protocol: model.protocol,
36
+ repairImageLinks: model.repairImageLinks === true,
37
+ hostedSearch: model.hostedSearch ?? model.protocol === 'responses'
38
+ };
39
+ });
40
+ if (!seen.has(input.defaultModel)) throw new Error('The default model must appear in the model list.');
41
+ return {schemaVersion:1, label:label(input.label, 'Company Gateway'), defaultModel:input.defaultModel, channels, models};
42
+ }
43
+
44
+ function label(value, fallback) {
45
+ if (value === undefined) return fallback;
46
+ if (typeof value !== 'string' || !value.trim() || value.length > 100 || /[\x00-\x1f\x7f]/.test(value)) {
47
+ throw new Error('Invalid display label.');
48
+ }
49
+ return value;
50
+ }
51
+
52
+ module.exports = {readSettings};
package/lib/skill.cjs ADDED
@@ -0,0 +1,113 @@
1
+ 'use strict';
2
+ const fs = require('node:fs');
3
+ const os = require('node:os');
4
+ const path = require('node:path');
5
+ const crypto = require('node:crypto');
6
+ const meta = require('../package.json');
7
+
8
+ const name = 'codex-gateway';
9
+ const sourcePath = path.join(__dirname, '..', 'skills', name);
10
+ const sha = bytes => crypto.createHash('sha256').update(bytes).digest('hex');
11
+ const file = 'SKILL.md';
12
+ const managedFiles = [file,'capabilities.json','adapters/generic.json'];
13
+ const receipt = '.codex-gateway-managed.json';
14
+
15
+ function source() {
16
+ return {ok:true, name, package:meta.name, version:meta.version, path:sourcePath,
17
+ files:managedFiles.map(name=>({path:name,sha256:sha(fs.readFileSync(path.join(sourcePath,name)))}))};
18
+ }
19
+
20
+ function destination(options) {
21
+ if (typeof options.agent !== 'string' || !/^[a-z][a-z0-9-]{0,62}$/i.test(options.agent)) {
22
+ throw new Error('Pass the current Agent name with --agent.');
23
+ }
24
+ if (options.target && options.path) throw new Error('Choose --target or --path.');
25
+ const codex = options.agent.toLowerCase() === 'codex';
26
+ const parent = options.path || (codex ? path.join(process.env.CODEX_HOME || path.join(os.homedir(),'.codex'),'skills') : null);
27
+ const resolved = options.target || (parent && path.join(parent,name));
28
+ if (!resolved || !path.isAbsolute(resolved)) throw new Error('Pass the absolute Skill directory with --target or its parent with --path.');
29
+ const target = path.normalize(resolved);
30
+ if (path.relative(sourcePath,target)==='' || target===path.parse(target).root) throw new Error('Invalid Skill destination.');
31
+ return target;
32
+ }
33
+
34
+ function regular(filePath) {
35
+ try { return fs.lstatSync(filePath).isFile(); }
36
+ catch (error) { if(error.code==='ENOENT')return false; throw error; }
37
+ }
38
+
39
+ function status(target) {
40
+ const canonical = source();
41
+ const state = {ok:true, name, package:meta.name, version:meta.version, target,
42
+ installed:false, managed:false, current:false, edited:false,
43
+ verification:{verified:false,algorithm:'sha256'}, recovery:{}};
44
+ if (!fs.existsSync(target)) return state;
45
+ if (!fs.lstatSync(target).isDirectory()) return {...state, recovery:{reason:'INVALID_TARGET'}};
46
+ const doc = path.join(target,file);
47
+ const marker = path.join(target,receipt);
48
+ state.installed = regular(doc);
49
+ if (!regular(marker)) return {...state,recovery:{reason:'UNMANAGED_TARGET'}};
50
+ let record;
51
+ try { record=JSON.parse(fs.readFileSync(marker,'utf8')); } catch {}
52
+ if (record?.package!==meta.name || record?.name!==name || !record?.files || managedFiles.some(name=>! /^[a-f0-9]{64}$/.test(record.files[name]))) {
53
+ return {...state,recovery:{reason:'INVALID_RECEIPT'}};
54
+ }
55
+ state.managed = true;
56
+ let matched = true;
57
+ for (const expected of canonical.files) {
58
+ const full = path.join(target,expected.path);
59
+ const digest = regular(full) ? sha(fs.readFileSync(full)) : null;
60
+ if (digest!==null && digest!==record.files[expected.path]) state.edited = true;
61
+ if (digest!==expected.sha256) matched=false;
62
+ }
63
+ state.current = !state.edited && matched && record.version===meta.version;
64
+ state.verification.verified = state.current;
65
+ return state;
66
+ }
67
+
68
+ function sync(target) {
69
+ const before = status(target);
70
+ if (before.current) return before;
71
+ if (fs.existsSync(target) && (!before.managed || before.edited)) throw new Error('Skill destination is user-owned or edited. Choose a new destination.');
72
+ fs.mkdirSync(path.dirname(target),{recursive:true});
73
+ const stage = fs.mkdtempSync(path.join(path.dirname(target),'.gateway-skill-'));
74
+ let backup;
75
+ try {
76
+ const copy = (from,to,relative='') => {
77
+ for (const item of fs.readdirSync(from,{withFileTypes:true})) {
78
+ const child = relative ? relative+'/'+item.name : item.name;
79
+ if ([...managedFiles,receipt].includes(child)) continue;
80
+ if (item.isDirectory()) {
81
+ fs.mkdirSync(path.join(to,item.name));
82
+ copy(path.join(from,item.name),path.join(to,item.name),child);
83
+ } else {
84
+ if (item.isSymbolicLink()) throw new Error('Managed Skill directories require independent files.');
85
+ fs.copyFileSync(path.join(from,item.name),path.join(to,item.name),fs.constants.COPYFILE_EXCL);
86
+ }
87
+ }
88
+ };
89
+ if (before.managed) copy(target,stage);
90
+ const hashes = {};
91
+ for(const name of managedFiles) {
92
+ const bytes=fs.readFileSync(path.join(sourcePath,name));
93
+ const dest=path.join(stage,name);
94
+ fs.mkdirSync(path.dirname(dest),{recursive:true});
95
+ fs.writeFileSync(dest,bytes,{flag:'wx'});
96
+ hashes[name]=sha(bytes);
97
+ }
98
+ fs.writeFileSync(path.join(stage,receipt),JSON.stringify({name,package:meta.name,version:meta.version,files:hashes})+'\n',{flag:'wx'});
99
+ if (before.managed) {
100
+ backup=target+'.before-'+crypto.randomUUID();
101
+ fs.renameSync(target,backup);
102
+ }
103
+ try { fs.renameSync(stage,target); }
104
+ catch (error) { if(backup&&!fs.existsSync(target))fs.renameSync(backup,target); throw error; }
105
+ const result = status(target);
106
+ if (!result.current) throw new Error('Skill verification failed.');
107
+ return {...result,recovery:backup?{backup}:{}};
108
+ } finally {
109
+ if (fs.existsSync(stage)) fs.rmSync(stage,{recursive:true,force:true});
110
+ }
111
+ }
112
+
113
+ module.exports = {source,destination,status,sync};